| 1 |
var openStation=function(or){"use strict";var sr=typeof document<"u"?document.currentScript:null;function Xy(){const t=window;t.wp=t.wp??{};const e=t.wp;e.os||(e.os={});const n=e.os;if(n.myWordpress)return;const o=[],s={registerEntityKind:(i,r)=>{const a={unregister:null},l={kind:i,renderer:r,slot:a};return o.push(l),()=>{if(a.unregister){a.unregister(),a.unregister=null;return}const c=o.indexOf(l);c!==-1&&o.splice(c,1)}},__pendingKinds:o};n.myWordpress=s}Xy();function Tt(){const t=window.wp?.hooks;if(!t)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 t}function Fn(t,e,n,o){Tt().addFilter(t,e,n,o)}function X(t,e,n,o){Tt().addAction(t,e,n,o)}function zc(t,e){return Tt().removeAction(t,e)}function K(t,e,...n){return Tt().applyFilters(t,e,...n)}function L(t,...e){Tt().doAction(t,...e)}function Gc(t){return Tt().didAction(t)}function Zy(){return Tt()}const b={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_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",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 Jy=0;function jc(t){if(Gc(b.INIT)>0){Promise.resolve().then(t);return}const e=`desktop-mode/when-ready-${++Jy}`;X(b.INIT,e,t)}function Qy(){return Gc(b.INIT)>0}const eb=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"];function Vc(t){let e=t;try{e=decodeURIComponent(t)}catch{e=t}return e.replace(/\.php/g,"-php").replace(/[?&=/]/g,"-").replace(/[^a-zA-Z0-9_-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")||"index"}function le(t,e){let n=null;try{n=new URL(t,e)}catch{n=null}if(n){const s=new URL(e).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams;for(const l of eb){const c=n.searchParams.get(l);c&&r.set(l,c)}const a=r.toString();return Vc(a?`${i}?${a}`:i)}let o=t.replace(e,"");return o.startsWith("/")&&(o=o.substring(1)),Vc(o)}function tb(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}function nb(t){t.style.setProperty("--os-file-tile-enter-delay",`${(Math.random()*.25).toFixed(3)}s`),t.style.setProperty("--os-file-tile-enter-duration",`${(.3+Math.random()*.25).toFixed(3)}s`)}function qc(t){try{const e=new URL(t,window.location.origin);return e.searchParams.delete("openstation_chromeless"),e.searchParams.delete("desktop_mode_portal"),e.pathname.replace(/\/+$/,"")+"?"+e.searchParams.toString()}catch{return t}}function Ss(t){try{const e=new URL(t,window.location.origin);return e.searchParams.delete("openstation_chromeless"),e.searchParams.delete("desktop_mode_portal"),e.searchParams.delete("_wp_http_referer"),e.searchParams.sort(),e.pathname.replace(/\/+$/,"")+"?"+e.searchParams.toString()}catch{return t}}function Kc(t){if(typeof t!="string"||t===""||typeof DOMParser>"u")return"";let e;try{e=new DOMParser().parseFromString(t,"image/svg+xml")}catch{return""}const n=e.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||e.getElementsByTagName("parsererror").length>0)return"";const o=new Set(["script","style","foreignobject","iframe","object","embed"]),s=i=>{const r=Array.from(i.children);for(const a of r){if(o.has(a.nodeName.toLowerCase())){a.remove();continue}for(const l of Array.from(a.attributes)){const c=l.name.toLowerCase(),d=l.value.trim().toLowerCase();if(c.startsWith("on")){a.removeAttribute(l.name);continue}d.startsWith("javascript:")&&a.removeAttribute(l.name)}s(a)}};s(n);for(const i of Array.from(n.attributes)){const r=i.name.toLowerCase(),a=i.value.trim().toLowerCase();(r.startsWith("on")||a.startsWith("javascript:"))&&n.removeAttribute(i.name)}return n.outerHTML}let Zt=null;function As(){return!!window.openStationWindowSystem}function Yc(t){return new Promise((e,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(As()){e();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){As()?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=t,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 ob(){return window.openStationConfig?.windowSystemBundleUrl??""}function sb(t){!t||As()||Zt||(Zt=Yc(t).catch(e=>{Zt=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",e)}))}async function ib(t){if(As())return window.openStationWindowSystem;if(!t){const e=window.openStationWindowSystem;if(e)return e;throw new Error("[openstation] ensureWindowSystemLoaded(): no bundle URL configured and `window.openStationWindowSystem` is not pre-registered.")}return Zt||(Zt=Yc(t)),await Zt,window.openStationWindowSystem}const rb="os-confirm-dialog";let Jt=null;function Bn(){return typeof window.customElements<"u"&&!!window.customElements.get(rb)}function Xc(t){return new Promise((e,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(Bn()){e();return}n(new Error("[openstation] shell-overlays bundle loaded but did not register the overlay components."))};if(o){Bn()?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=t,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(t){!t||Bn()||Jt||(Jt=Xc(t).catch(e=>{Jt=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",e)}))}function ir(t){return Bn()||!t?Promise.resolve():(Jt||(Jt=Xc(t)),Jt)}function rr(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function Is(t,e){const n=rr();if(Bn()||!n){e();return}ir(n).then(()=>{t()&&e()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Zc="openstation";function ar(){return window.wp?.i18n}function k(t,e=Zc){return ar()?.__(t,e)??t}function Hn(t,e,n,o=Zc){return ar()?._n(t,e,n,o)??(n===1?t:e)}function ae(t,...e){const n=ar()?.sprintf;if(n)return n(t,...e);let o=0;return t.replace(/%(?:(\d+)\$)?[sd]/g,(s,i)=>{const r=i?Number.parseInt(i,10)-1:o++;return String(e[r]??"")})}function lb(t,e){if(!t||typeof t!="object")return!1;const n=t.cols,o=t.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)>=e}function cb(t){if(!t||typeof t!="object")return!1;const e=t.cellWidth,n=t.cellHeight;return typeof e!="number"||typeof n!="number"||!Number.isFinite(e)||!Number.isFinite(n)?!1:e>0&&n>0}function db(t,e,n){if(t<=1)return{cols:1,rows:1};const o=e/Math.max(1,n),s=6;let i={cols:t,rows:1,score:1/0};for(let r=1;r<=Math.min(s,t);r++){const a=Math.min(s,Math.ceil(t/r));if(r*a<t)continue;const l=e/r/Math.max(1,n/a),c=Math.abs(l-o),d=r*a-t,u=c+d*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function lr(t,e,n=0){const o=t.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,l=34,c=(e.width-r*2-a*(s-1))/s,d=(e.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-l);return t.map((f,p)=>{const m=p%s,g=Math.floor(p/s),h=e.left+r+m*(c+a),w=e.top+n+r+g*(d+a)+l,v=f.element.offsetWidth,R=f.element.offsetHeight,_=Math.min(c/v,u/R),E=v*_,N=R*_;return{win:f,x:h+(c-E)/2,y:w+(u-N)/2,scale:_}})}const Jc=120,Qc=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],cr="osHadFullscreenBeforeOverview";function ed(t){t.state==="minimized"&&(t.element.style.removeProperty("content-visibility"),t.iframe&&(t.iframe.style.visibility=""),t.element.classList.contains("os-window--fullscreen")&&(t.element.classList.remove("os-window--fullscreen"),t.element.dataset[cr]="true"))}function td(t){t.element.dataset[cr]==="true"&&(t.element.classList.add("os-window--fullscreen"),delete t.element.dataset[cr])}function nd(t){td(t),t.state==="minimized"&&(t.element.style.setProperty("content-visibility","hidden"),t.iframe&&(t.iframe.style.visibility="hidden"))}function od(t){const e=document.getElementById("wpbody-content");if(e)for(const n of Array.from(e.children))n.inert=t}function sd(t,e){for(const n of t._stack)for(const o of Array.from(n.element.children))o.inert=e}function ub(t){if(t._overviewActive)return;const e=t._stack.filter(c=>c.config.desktopId===t._activeDesktopId);t._overviewActive=!0,L(b.OVERVIEW_ENTERING,{});for(const c of Qc){const d=document.getElementById(c);d&&(d.inert=!0)}od(!0),sd(t,!0),t._overviewSnapshot.clear();for(const c of e)t._overviewSnapshot.set(c.id,{transform:c.element.style.transform||"",transition:c.element.style.transition||""});for(const c of e)c.state==="fullscreen"&&c.toggleFullscreen(),ed(c);const n=t._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);t._desktop.classList.add("os-area--overview"),document.getElementById("os-shell")?.classList.add("os-shell--overview"),t._overviewTopBar=id(t),t._desktop.appendChild(t._overviewTopBar);const a=lr(e,i,Jc);t._overviewLabels.clear();for(const c of a){const d=c.win.element;d.classList.add("os-window--overview");const u=c.x-d.offsetLeft,f=c.y-d.offsetTop;d.style.transform=`translate(${u}px, ${f}px) scale(${c.scale})`;const p=ur(c);d.insertAdjacentElement("afterend",p),t._overviewLabels.set(c.win.id,p)}const l=c=>{const d=c.target,u=d?.closest(".os-window--overview");return u?{id:u.id.replace(/^wp-window-/,""),element:u}:d===t._desktop?{id:"backdrop",element:t._desktop}:null};t._overviewPointerDownHandler=c=>{if(c.button!==0){t._overviewPressTarget=null;return}t._overviewPressTarget=l(c),t._overviewPressTarget&&(c.preventDefault(),c.stopPropagation())},t._overviewPointerUpHandler=c=>{if(c.button!==0)return;const d=t._overviewPressTarget;if(t._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"){Nt(t);return}const p=t.getById(d.id);L(b.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),Nt(t,p)},t._overviewKeyHandler=c=>{if(c.key==="Escape"){Nt(t);return}if(c.key==="Enter"){const u=c.target?.ownerDocument||document;if(u.activeElement&&u.activeElement.tagName==="BUTTON")return;if(c.preventDefault(),t._overviewAddTileFocused){rd(t);return}Nt(t)}},t._desktop.addEventListener("pointerdown",t._overviewPointerDownHandler,!0),t._desktop.addEventListener("pointerup",t._overviewPointerUpHandler,!0),t._overviewClickBlocker=c=>{c.target?.closest(".os-overview-top-bar")||(c.stopPropagation(),c.preventDefault())},t._desktop.addEventListener("click",t._overviewClickBlocker,!0),document.addEventListener("keydown",t._overviewKeyHandler),t._lastOverviewHoverId=null,t._overviewMouseHandler=c=>{const u=c.target?.closest(".os-window--overview"),f=u?u.id.replace(/^wp-window-/,""):null;f!==t._lastOverviewHoverId&&(t._lastOverviewHoverId&&L(b.OVERVIEW_WINDOW_UNHOVER,{windowId:t._lastOverviewHoverId}),f&&L(b.OVERVIEW_WINDOW_HOVER,{windowId:f}),t._lastOverviewHoverId=f)},t._desktop.addEventListener("mouseover",t._overviewMouseHandler),t._overviewEnterTimeoutId=window.setTimeout(()=>{t._overviewEnterTimeoutId=null,t._overviewActive&&L(b.OVERVIEW_ENTERED,{})},300)}function fb(t){t._overviewEnterTimeoutId!==null&&(window.clearTimeout(t._overviewEnterTimeoutId),t._overviewEnterTimeoutId=null),t._overviewExitTimeoutId!==null&&(window.clearTimeout(t._overviewExitTimeoutId),t._overviewExitTimeoutId=null)}function id(t){const e=document.createElement("div");e.className="os-overview-top-bar";const n=document.createElement("div");n.className="os-overview-top-bar__list",e.appendChild(n);for(const s of t._desktops)n.appendChild(pb(t,s));const o=document.createElement("button");return o.type="button",o.className="os-overview-top-bar__tile os-overview-top-bar__tile--add",t._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(),rd(t)}),n.appendChild(o),e}function rd(t){const e=dd(t);t._overviewAddTileFocused=!1,ad(t,e.id)}function pb(t,e){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=e.id,e.id===t._activeDesktopId&&!t._overviewAddTileFocused&&o.classList.add("os-overview-top-bar__tile--active"),o.setAttribute("aria-label",ae(k("Switch to %s"),e.label));const s=document.createElement("span");s.className="os-overview-top-bar__tile-preview";const i=t._stack.filter(l=>l.config.desktopId===e.id).length;if(i>0){const l=document.createElement("span");l.className="os-overview-top-bar__tile-count",l.textContent=String(i),s.appendChild(l)}o.appendChild(s);const r=document.createElement("span");r.className="os-overview-top-bar__tile-label",r.textContent=e.label,o.appendChild(r),o.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),ad(t,e.id)});const a=document.createElement("button");return a.type="button",a.className="os-overview-top-bar__tile-close",a.setAttribute("aria-label",ae(k("Close %s"),e.label)),a.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>',a.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),fd(t,e.id),dr(t)}),n.appendChild(o),n.appendChild(a),n}function dr(t){if(!t._overviewTopBar)return;const e=id(t);t._overviewTopBar.replaceWith(e),t._overviewTopBar=e}function ad(t,e){ud(t,e),Nt(t)}function ur(t){const e=document.createElement("div");e.className="os-overview-label",e.dataset.windowId=t.win.id;const n=t.win.element.offsetWidth*t.scale;e.style.left=`${t.x}px`,e.style.top=`${t.y-34}px`,e.style.width=`${n}px`;const o=t.win.config.icon||"dashicons-admin-generic",s=document.createElement("span");s.className=`os-overview-label__icon dashicons ${o}`,s.setAttribute("aria-hidden","true"),e.appendChild(s);const i=document.createElement("span");i.className="os-overview-label__title",i.textContent=t.win.config.title,e.appendChild(i);const r=t.win.getExternalTabCount();if(r>0){const a=document.createElement("span");a.className="os-overview-label__meta",a.textContent=ae(Hn("· %d open tab","· %d open tabs",r),r),e.appendChild(a)}return e}function Nt(t,e,n=!1){if(!t._overviewActive)return;t._overviewActive=!1,t._overviewAddTileFocused=!1,L(b.OVERVIEW_EXITING,{windowId:e?e.id:void 0,reason:e?"select":"cancel"}),t._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of Qc){const r=document.getElementById(i);r&&(r.inert=!1)}od(!1),sd(t,!1);for(const[i,r]of t._overviewSnapshot){const a=t.getById(i);a&&(a.element.style.transform=r.transform)}e&&(e.state==="minimized"&&(td(e),e.restore()),t.focus(e),n&&e.maximize());for(const i of t._stack)i.state==="minimized"&&i.element.classList.remove("os-window--overview");for(const i of t._overviewLabels.values())i.classList.add("os-overview-label--out");t._overviewTopBar&&t._overviewTopBar.classList.add("os-overview-top-bar--out");const s=280;t._overviewExitTimeoutId=window.setTimeout(()=>{t._overviewExitTimeoutId=null;for(const i of t._stack)i.element.classList.remove("os-window--overview"),nd(i);for(const i of t._overviewLabels.values())i.remove();t._overviewLabels.clear(),t._overviewSnapshot.clear(),t._overviewTopBar&&(t._overviewTopBar.remove(),t._overviewTopBar=null),t._overviewClickBlocker&&(t._desktop.removeEventListener("click",t._overviewClickBlocker,!0),t._overviewClickBlocker=null),L(b.OVERVIEW_EXITED,{windowId:e?e.id:void 0,reason:e?"select":"cancel"})},s),t._overviewPointerDownHandler&&(t._desktop.removeEventListener("pointerdown",t._overviewPointerDownHandler,!0),t._overviewPointerDownHandler=null),t._overviewPointerUpHandler&&(t._desktop.removeEventListener("pointerup",t._overviewPointerUpHandler,!0),t._overviewPointerUpHandler=null),t._overviewPressTarget=null,t._overviewKeyHandler&&(document.removeEventListener("keydown",t._overviewKeyHandler),t._overviewKeyHandler=null),t._overviewMouseHandler&&(t._desktop.removeEventListener("mouseover",t._overviewMouseHandler),t._overviewMouseHandler=null),t._lastOverviewHoverId&&(L(b.OVERVIEW_WINDOW_UNHOVER,{windowId:t._lastOverviewHoverId}),t._lastOverviewHoverId=null)}function hb(t){return[...t._desktops]}function ld(t){return t._desktops.find(n=>n.id===t._activeDesktopId)??t._desktops[0]}function mb(t){return ld(t).id}function cd(t,e){const n=e.config.desktopId===t._activeDesktopId;e.element.style.display=n?"":"none"}function fr(t){for(const e of t._stack)cd(t,e)}function dd(t){t._desktopSeq++;const e={id:`desktop-${t._desktopSeq}`,label:ae(k("Desktop %d"),t._desktopSeq)};return t._desktops.push(e),L(b.DESKTOP_CREATED,{desktopId:e.id}),e}function ud(t,e,n){if(e===t._activeDesktopId||!t._desktops.some(s=>s.id===e))return;const o=t._activeDesktopId;if(t._activeDesktopId=e,t._overviewActive)pd(t),dr(t);else{fr(t),n?.direction&&gb(t,n.direction);const s=[...t._stack].reverse().find(i=>i.config.desktopId===e&&i.state!=="minimized");s&&t.focus(s)}L(b.DESKTOP_SWITCHED,{from:o,to:e})}function gb(t,e){const n=t._desktop,o=e==="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 fd(t,e){if(t._desktops.length<=1)return;const n=t._desktops.findIndex(r=>r.id===e);if(n===-1)return;const o=n>0?n-1:1,s=t._desktops[o];for(const r of t._stack)r.config.desktopId===e&&(r.config.desktopId=s.id);t._desktops.splice(n,1),t._activeDesktopId===e&&(t._activeDesktopId=s.id),t._overviewActive?pd(t):fr(t),L(b.DESKTOP_CLOSED,{desktopId:e,migratedTo:s.id})}function pd(t){for(const[i,r]of t._overviewSnapshot){const a=t.getById(i);a&&(a.element.style.transform=r.transform,a.element.style.transition=r.transition,a.element.classList.remove("os-window--overview"),nd(a))}for(const i of t._overviewLabels.values())i.remove();t._overviewLabels.clear(),t._overviewSnapshot.clear(),fr(t);const e=t._stack.filter(i=>i.config.desktopId===t._activeDesktopId);if(e.length===0)return;for(const i of e)t._overviewSnapshot.set(i.id,{transform:i.element.style.transform||"",transition:i.element.style.transition||""}),ed(i);const n=t._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=lr(e,o,Jc);for(const i of s){const r=i.win.element;r.classList.add("os-window--overview");const a=i.x-r.offsetLeft,l=i.y-r.offsetTop;r.style.transform=`translate(${a}px, ${l}px) scale(${i.scale})`;const c=ur(i);r.insertAdjacentElement("afterend",c),t._overviewLabels.set(i.win.id,c)}}function wb(t,e,n){if(e.length===0)return;t._desktops=e.map(s=>({...s})),t._activeDesktopId=e.some(s=>s.id===n)?n:e[0].id;let o=0;for(const s of e){const i=s.id.match(/^desktop-(\d+)$/);if(i){const r=parseInt(i[1],10);Number.isFinite(r)&&r>o&&(o=r)}}t._desktopSeq=Math.max(t._desktopSeq,o)}function yb(t){const e=t._stack.filter(u=>u.config.desktopId===t._activeDesktopId);if(e.length===0)return;L(b.ARRANGE_CASCADE_STARTING,{windowCount:e.length});for(const u of e)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=t._desktop.getBoundingClientRect(),o=30,s=30,i=Math.min(Math.round(n.width*.7),1100),r=Math.min(Math.round(n.height*.75),750),a=Math.max(1,Math.floor((n.width-i-o)/s)),l=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(a,l);e.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=t.getFocused();d&&t.focus(d),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"cascade"}})),L(b.ARRANGE_CASCADE_APPLIED,{windowCount:e.length})}function bb(t){const e=t._stack.filter(f=>f.config.desktopId===t._activeDesktopId);if(e.length===0)return;for(const f of e)f.state==="minimized"&&f.restore(),f.state==="fullscreen"&&f.toggleFullscreen(),f.state==="maximized"&&f.toggleMaximize();const n=t._desktop.getBoundingClientRect(),o=db(e.length,n.width,n.height),s=K(b.ARRANGE_TILE_DIMENSIONS,o,{windowCount:e.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=lb(s,e.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;L(b.ARRANGE_TILE_STARTING,{windowCount:e.length,cols:i,rows:r});const a=16,l=12,c=Math.floor((n.width-a*2-l*(i-1))/i),d=Math.floor((n.height-a*2-l*(r-1))/r);e.forEach((f,p)=>{const m=p%i,g=Math.floor(p/i);f.element.style.left=`${a+m*(c+l)}px`,f.element.style.top=`${a+g*(d+l)}px`,f.element.style.width=`${c}px`,f.element.style.height=`${d}px`});const u=t.getFocused();u&&t.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"tile"}})),L(b.ARRANGE_TILE_APPLIED,{windowCount:e.length,cols:i,rows:r})}const hd="desktop-mode-snap-to-grid";function vb(){try{return window.localStorage.getItem(hd)==="1"}catch{return!1}}function _b(t,e){if(t._snapEnabled!==e){t._snapEnabled=e;try{window.localStorage.setItem(hd,e?"1":"0")}catch{}L(b.ARRANGE_SNAP_CHANGED,{enabled:e})}}function Eb(t){if(!t._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const e=t._desktop.getBoundingClientRect(),n=e.width>=e.height?12:8,o={cellWidth:Math.max(40,Math.round(e.width/n)),cellHeight:Math.max(40,Math.round(e.height/Math.round(n*.66)))},s=K(b.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:e.width,areaHeight:e.height}),{cellWidth:i,cellHeight:r}=cb(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function kb(t,e,n){if(t._splitOverviewActive)return;t._splitOverviewActive=!0,t._splitOverviewAnchor=e,t._splitOverviewZone=n;const o=t._stack.filter(a=>a!==e&&a.state!=="minimized"&&a.config.desktopId===t._activeDesktopId);if(o.length===0){md(t);return}t._splitOverviewSnapshot.clear();for(const a of o)t._splitOverviewSnapshot.set(a.id,{transform:a.element.style.transform||"",transition:a.element.style.transition||""});t._desktop.classList.add("os-area--split-overview");const s=xb(t,n),i=lr(o,s,0);t._splitOverviewLabels.clear();for(const a of i){const l=a.win.element;l.classList.add("os-window--overview");const c=a.x-l.offsetLeft,d=a.y-l.offsetTop;l.style.transform=`translate(${c}px, ${d}px) scale(${a.scale})`;const u=ur(a);l.insertAdjacentElement("afterend",u),t._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const l=a.target,c=l?.closest(".os-window--overview");return c?{id:c.id.replace(/^wp-window-/,""),element:c}:l?{id:"dismiss",element:t._desktop}:null};t._splitOverviewPointerDown=a=>{if(a.button!==0){t._splitOverviewPressTarget=null;return}t._splitOverviewPressTarget=r(a),t._splitOverviewPressTarget&&(a.preventDefault(),a.stopPropagation())},t._splitOverviewPointerUp=a=>{if(a.button!==0)return;const l=t._splitOverviewPressTarget;if(t._splitOverviewPressTarget=null,!l)return;const c=l.element.getBoundingClientRect();if(!(a.clientX>=c.left&&a.clientX<=c.right&&a.clientY>=c.top&&a.clientY<=c.bottom))return;if(a.preventDefault(),a.stopPropagation(),l.id==="dismiss"){zn(t);return}const u=t.getById(l.id);if(!u){zn(t);return}Sb(t,u)},t._splitOverviewKey=a=>{a.key==="Escape"&&zn(t)},t._splitOverviewClickBlocker=a=>{a.stopPropagation(),a.preventDefault()},t._desktop.addEventListener("pointerdown",t._splitOverviewPointerDown,!0),t._desktop.addEventListener("pointerup",t._splitOverviewPointerUp,!0),t._desktop.addEventListener("click",t._splitOverviewClickBlocker,!0),document.addEventListener("keydown",t._splitOverviewKey)}function Sb(t,e){const n=t._splitOverviewZone;if(!n){zn(t);return}const o=n==="left"?"right":"left";e.element.style.transform="",e.element.classList.remove("os-window--overview"),e.applySnap(o),t._splitOverviewSnapshot.delete(e.id),t.focus(e),L(b.SNAP_SPLIT_FILLED,{windowId:e.id,zone:o}),zn(t)}function zn(t){if(!t._splitOverviewActive)return;t._splitOverviewActive=!1;for(const[n,o]of t._splitOverviewSnapshot){const s=t.getById(n);s&&(s.element.style.transform=o.transform)}for(const n of t._splitOverviewLabels.values())n.classList.add("os-overview-label--out");t._desktop.classList.remove("os-area--split-overview"),window.setTimeout(()=>{for(const n of t._stack)t._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("os-window--overview");for(const n of t._splitOverviewLabels.values())n.remove();md(t)},260),t._splitOverviewPointerDown&&(t._desktop.removeEventListener("pointerdown",t._splitOverviewPointerDown,!0),t._splitOverviewPointerDown=null),t._splitOverviewPointerUp&&(t._desktop.removeEventListener("pointerup",t._splitOverviewPointerUp,!0),t._splitOverviewPointerUp=null),t._splitOverviewClickBlocker&&(t._desktop.removeEventListener("click",t._splitOverviewClickBlocker,!0),t._splitOverviewClickBlocker=null),t._splitOverviewKey&&(document.removeEventListener("keydown",t._splitOverviewKey),t._splitOverviewKey=null),t._splitOverviewPressTarget=null}function md(t){t._splitOverviewSnapshot.clear(),t._splitOverviewLabels.clear(),t._splitOverviewAnchor=null,t._splitOverviewZone=null,t._splitOverviewActive=!1}const gd=30,Ab=260;function Ib(t,e){return t<=e.left+gd?"left":t>=e.right-gd?"right":null}function Cb(t,e){const n=t._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:e==="left"?0:n.width-o,y:0,width:o,height:s}}function xb(t,e){const n=t._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return e==="left"?new DOMRect(o,0,o,s):new DOMRect(0,0,o,s)}function Lb(t,e){if(t._snapPendingZone===e&&t._snapPreviewEl)return;if(t._snapPendingZone=e,!t._snapPreviewEl){const o=document.createElement("div");o.className="os-snap-preview",o.setAttribute("aria-hidden","true"),t._desktop.appendChild(o),t._snapPreviewEl=o,Promise.resolve().then(()=>{o.classList.add("os-snap-preview--visible")})}const n=Cb(t,e);t._snapPreviewEl.style.left=`${n.x}px`,t._snapPreviewEl.style.top=`${n.y}px`,t._snapPreviewEl.style.width=`${n.width}px`,t._snapPreviewEl.style.height=`${n.height}px`,t._snapPreviewEl.dataset.zone=e}function pr(t){if(!t._snapPreviewEl){t._snapPendingZone=null;return}const e=t._snapPreviewEl;t._snapPreviewEl=null,t._snapPendingZone=null,e.classList.remove("os-snap-preview--visible"),window.setTimeout(()=>{e.remove()},Ab)}function Tb(t,e,n){if(t._splitOverviewActive)return;const o=t._desktop.getBoundingClientRect(),s=Ib(n,o),i=t._snapPendingZone;s?(Lb(t,s),i!==s&&L(b.SNAP_ZONE_PENDING,{windowId:e.id,zone:s})):i&&(pr(t),L(b.SNAP_ZONE_CANCELED,{windowId:e.id}))}function Nb(t,e){const n=t._snapPendingZone;return n?(pr(t),e.state==="normal"&&(e._savedGeometry={x:e.element.offsetLeft,y:e.element.offsetTop,width:e.element.offsetWidth,height:e.element.offsetHeight}),e.applySnap(n),L(b.SNAP_ZONE_COMMITTED,{windowId:e.id,zone:n}),window.requestAnimationFrame(()=>{kb(t,e,n)}),!0):!1}function Db(t){t._snapPendingZone&&pr(t)}const wd="desktop-mode-native-window-geometry",yd=64,Qe=8192;function Cs(){try{const t=window.localStorage.getItem(wd);if(!t)return{};const e=JSON.parse(t);return!e||typeof e!="object"?{}:e}catch{return{}}}function bd(t){try{window.localStorage.setItem(wd,JSON.stringify(t))}catch{}}function vd(t){if(!t)return null;const n=Cs()[t];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>Qe||s>Qe)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),a=Number(n.y),l=Number.isFinite(r)&&Number.isFinite(a)&&r>=0&&a>=0&&r<=Qe&&a<=Qe;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function _d(t,e){if(!t)return;const n=Math.round(Number(e.width)),o=Math.round(Number(e.height));if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0||n>Qe||o>Qe)return;const s=Cs(),i=s[t],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,l=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===l||(Gn(s,t,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),jn(s))}function Ed(t,e){if(!t)return;const n=Math.round(Number(e.x)),o=Math.round(Number(e.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>Qe||o>Qe)return;const s=Cs(),i=s[t];i&&(i.x===n&&i.y===o||(Gn(s,t,{...i,x:n,y:o}),jn(s)))}function kd(t,e,n){if(!t)return;const o=Cs(),s=o[t];if(!s){if(e===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>Qe||r>Qe)return;Gn(o,t,{width:i,height:r,state:e}),jn(o);return}if(e===null){if(!s.state)return;const{state:i,...r}=s;Gn(o,t,r),jn(o);return}s.state!==e&&(Gn(o,t,{...s,state:e}),jn(o))}function Gn(t,e,n){delete t[e],t[e]=n}function jn(t){const e=Object.keys(t);if(e.length>yd){const n={};for(const o of e.slice(-yd))n[o]=t[o];bd(n);return}bd(t)}const Rb=0,hr=40,Sd=250,Ob=120,Mb=250,Vn="os-window__loading",xs="os-window__loading--visible";function Pb(t,e,n,o,s){const i=hr-n,r=o-hr,a=Math.max(i,Math.min(t,r)),l=Rb,c=s-hr,d=Math.max(l,Math.min(e,c));return{x:a,y:d}}const Ad=100,Ls=30;class Wb{constructor(e){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=vb(),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._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=e,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(e)),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const e=this._desktop.ownerDocument?.activeElement??null;if(!e||e.tagName!=="IFRAME")return;const n=e.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 e of this._stack){const n=e.element.parentElement;if(n){if(e.state==="maximized")e.element.classList.add("os-window--reflowing"),e.element.style.width=`${n.clientWidth}px`,e.element.style.height=`${n.clientHeight}px`;else if(e.state==="snapped-left"||e.state==="snapped-right"){e.element.classList.add("os-window--reflowing");const o=Math.floor(n.clientWidth/2),s=n.clientHeight,i=e.state==="snapped-left"?0:o;e.element.style.left=`${i}px`,e.element.style.top="0px",e.element.style.width=`${o}px`,e.element.style.height=`${s}px`}else if(e.state==="normal"){const o=parseInt(e.element.style.left,10)||0,s=parseInt(e.element.style.top,10)||0,i=e.element.offsetWidth||0,r=Pb(o,s,i,n.clientWidth,n.clientHeight);(o!==r.x||s!==r.y)&&(e.element.classList.add("os-window--reflowing"),e.element.style.left=`${r.x}px`,e.element.style.top=`${r.y}px`)}}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const e of this._stack)e.element.classList.remove("os-window--reflowing")},140)}}async open(e){if(!e||typeof e!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(e===null?"null":typeof e));if(typeof e.id!="string"||e.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof e.url!="string"||e.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 e.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=e.baseId||e.id,o=this.getByBaseIdOnActiveDesktop(n);if(o){const i=o.state==="minimized";this.focus(o),i&&o.restore();let r=!1;if(!o.config.native){const l=Ss(e.url);l===Ss(o.getCurrentUrl())||l===Ss(o.config.url||"")||l===Ss(o.config.parentUrl??o.config.url??"")||(r=o.navigateTo(e.url))}e.params&&(o.config.params={...e.params});const a={windowId:o.id,baseId:n,wasMinimized:i,navigated:r,params:o.config.params??{}};return document.dispatchEvent(new CustomEvent("os-window-reopened",{detail:a})),L(b.WINDOW_REOPENED,a),o}const s=this.getByBaseId(n)?this.nextInstanceId(n):e.id;return this.createWindow({...e,id:s,baseId:n})}async openNew(e){const n=e.baseId||e.id,o=e.id!==n&&!this.getById(e.id)?e.id:this.nextInstanceId(n),s=40+this.cascadeIndex%8*Ls,i=40+this.cascadeIndex%8*Ls;return this.createWindow({initialState:"normal",x:s,y:i,...e,id:o,baseId:n})}async createWindow(e){const n=this._pendingRestoreState.get(e.id);n&&(this._pendingRestoreState.delete(e.id),e={...e,...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*Ls,a=40+this.cascadeIndex%8*Ls,l=e.baseId||e.id,c=e.minWidth??320,d=e.minHeight??200,u=typeof e.width=="number",f=typeof e.height=="number",p=typeof e.x=="number",m=typeof e.y=="number",g=typeof e.initialState=="string",h=!u||!f||!g||!p||!m?vd(l):null,w=e.width??(h?Math.max(h.width,c):s),v=e.height??(h?Math.max(h.height,d):i),R=e.initialState??(h?.state==="maximized"?"maximized":void 0);let _,E;if(h&&typeof h.x=="number"&&typeof h.y=="number"){const Y=Math.max(0,o.width-w-12),j=Math.max(0,o.height-v-12);_=Math.max(12,Math.min(h.x,Y)),E=Math.max(12,Math.min(h.y,j))}const N=e.x??_??r,D=e.y??E??a,O=u||f||p||m||g,y=!!h,M={x:N,y:D,width:w,height:v,state:R};let T;try{T=K(b.WINDOW_GEOMETRY,M,{windowId:e.id,baseId:l,hasSavedGeometry:y,callerPinned:O,desktopRect:{width:o.width,height:o.height}})}catch(F){L(b.SHELL_ERROR,{scope:"window-geometry-filter",windowId:e.id,error:F}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${e.id}":`,F),T=M}const x=(F,Y)=>typeof F=="number"&&Number.isFinite(F)?F:Y,I=T&&typeof T=="object"?T:M,W=Math.max(x(I.width,w),c),z=Math.max(x(I.height,v),d),A=x(I.x,N),P=x(I.y,D),B=I.state??R,C={icon:e.icon||"dashicons-admin-generic",...e,x:A,y:P,width:W,height:z,minWidth:c,minHeight:d,...B?{initialState:B}:{},baseId:l,desktopId:e.desktopId||this._activeDesktopId};this.cascadeIndex++;const[$]=await Promise.all([ib(ob()),ir(rr())]),U=$.createWindow(C);U.onFocusRequest=F=>this.focus(F),U.onClose=F=>this.remove(F),U.onMinimize=()=>{const F=this._stack.filter(Y=>Y.state!=="minimized");F.length>0&&this.focus(F[F.length-1])},U.onOpenAnother=F=>{const Y=F.config.baseId||F.id;F.config.native&&window.wp?.os?.openNewWindow?.(Y,{source:"open-another"})||this.openNew({id:Y,baseId:Y,url:F.config.url||"",title:F.config.title,icon:F.config.icon,submenu:F.config.submenu,multi:!0})},U.onOpenInNewWindow=F=>{const Y=F.config.baseId||F.id;if(F.config.native&&window.wp?.os?.openNewWindow?.(Y,{source:"open-in-new-window"}))return;const j=F.getCurrentUrl();this.openNew({id:Y,baseId:Y,url:j||F.config.url||"",title:F.config.title,icon:F.config.icon,submenu:F.config.submenu,multi:!0})},U.onToggleStartup=F=>{this.onToggleStartupRequested?.(F)},U.snapConfigProvider=()=>this.getSnapConfig(),U.onDragMove=(F,Y)=>{Tb(this,F,Y)},U.onDragEnd=F=>this._snapPendingZone?Nb(this,F):(Db(this),!1),this._stack.push(U),this._desktop.appendChild(U.element),cd(this,U),U.hydrateNative(),this.focus(U);const G={windowId:U.id,page:e.url,title:e.title,url:e.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:G})),L(b.WINDOW_OPENED,G),U}nextInstanceId(e){const n=new Set(this._stack.map(s=>s.id));if(!n.has(e))return e;let o=2;for(;n.has(`${e}-${o}`);)o++;return`${e}-${o}`}focus(e){const n=this._stack.length>0?this._stack[this._stack.length-1]:null,o=this._stack.find(r=>r!==e&&r.isFocused()&&r.isFullscreen());o&&K(b.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:o.id,focusedTo:e.id})&&o.toggleFullscreen();const s=this._stack.indexOf(e);if(s>-1&&this._stack.splice(s,1),this._stack.push(e),this._stack.forEach((r,a)=>{r.setZIndex(Ad+a),r.setFocused(a===this._stack.length-1)}),n&&n!==e&&n.id!==e.id){const r={windowId:n.id,focusedTo:e.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:r})),L(b.WINDOW_BLURRED,r)}const i={windowId:e.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:i})),L(b.WINDOW_FOCUSED,i)}raise(e){const n=this.getById(e);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(Ad+i)}))}remove(e){const n=this._stack.indexOf(e);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:e.id,element:e.element};document.dispatchEvent(new CustomEvent("os-window-closing",{detail:o})),L(b.WINDOW_CLOSING,o);const s={windowId:e.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:s})),L(b.WINDOW_CLOSED,s)}getById(e){return this._stack.find(n=>n.id===e)}getByBaseId(e){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===e)return o}}getByBaseIdOnActiveDesktop(e){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==e)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(e){const n=o=>{if(o===e)return 1;const s=`${e}-`;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)===e).sort((o,s)=>n(o.id)-n(s.id))}getAllByBaseIdOnActiveDesktop(e){return this.getAllByBaseId(e).filter(n=>(n.config.desktopId||this._activeDesktopId)===this._activeDesktopId)}getAll(){return[...this._stack]}findByIframeSource(e){if(e)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===e)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(e){const n=this.getById(e);if(!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)return!1;const s=this.getFocused();return!!s&&s.id===e}isActiveByBaseId(e){const n=this.getFocused();return!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId?!1:(n.config.baseId||n.id)===e}getDesktops(){return hb(this)}getActiveDesktop(){return ld(this)}getActiveDesktopId(){return mb(this)}createDesktop(){return dd(this)}switchDesktop(e,n){ud(this,e,n)}closeDesktop(e){fd(this,e)}getPrimaryDesktopId(){const e=this.getDesktops(),n=e.length>0?e[0].id:"desktop-1",o=K(b.PRIMARY_DESKTOP_ID,n,e);return typeof o!="string"||o===""?n:e.some(i=>i.id===o)?o:n}closeAll(e){const n=new Set(e?.exceptIds??[]),o=this._stack.filter(l=>!n.has(l.id));L(b.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=K(b.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(l=>!i.includes(l));let a=0;for(const l of i.slice())try{l.close(),a++}catch(c){typeof console<"u"&&console.error("[openstation] closeAll: window.close() threw for",l.id,c)}return L(b.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r}),a}minimizeAll(){const e=[];for(const n of this._stack.slice())if((n.config.desktopId||this._activeDesktopId)===this._activeDesktopId&&n.state!=="minimized")try{n.minimize(),e.push(n)}catch(s){typeof console<"u"&&console.error("[openstation] minimizeAll: window.minimize() threw for",n.id,s)}return e}restoreFrom(e){if(!Array.isArray(e))return;const n=new Set(this._stack);for(const o of e)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 e=this._stack.filter(o=>(o.config.desktopId||this._activeDesktopId)===this._activeDesktopId);if(e.length===0)return!1;if(e.every(o=>o.state==="minimized")){for(const o of e)try{o.restore()}catch{}return!1}return this.minimizeAll(),!0}cascade(){yb(this)}tile(){bb(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(e){_b(this,e)}getSnapConfig(){return Eb(this)}enterOverview(){ub(this)}exitOverview(e,n=!1){Nt(this,e,n)}destroy(){this._overviewActive&&Nt(this),fb(this)}getVisibleRects(){return this._stack.map(e=>{const n=e.getSnapshot();return{windowId:e.id,rect:{x:n.x,y:n.y,width:n.width,height:n.height},state:n.state,element:e.element}})}sanitizeParams(e){const n={};for(const[o,s]of Object.entries(e))(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 e=this.getFocused(),o=this._stack.filter(i=>!i.config.ephemeral).map(i=>{const r=i.getSnapshot(),a=i.getExternalTabsSnapshot(),l=!!i.config.native,c=i.config.params,d=l&&c?this.sanitizeParams(c):null;return{id:i.id,baseId:i.config.baseId||i.id,desktopId:i.config.desktopId||this._activeDesktopId,...l?{native:!0}:{},...d?{params:d}:{},url:l?i.config.url||`#${i.id}`:i.getCurrentUrl(),title:i.config.title,icon:i.config.icon,state:r.state,x:r.x,y:r.y,width:r.width,height:r.height,...a.length>0?{externalTabs:a}:{}}}),s=e&&!e.config.ephemeral?e.id:"";return{windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Date.now()}}seedWindowRestoreState(e){this._pendingRestoreState=new Map(Object.entries(e))}seedDesktops(e,n){wb(this,e,n)}}function $b(t){const e=t.getActiveDesktopId(),n=Array.from(t._desktop.children);return t.getAll().filter(o=>(o.config.desktopId||e)===e).sort((o,s)=>n.indexOf(o.element)-n.indexOf(s.element))}function Id(t,e){if(t._overviewActive)return;const n=$b(t);if(n.length<2)return;const o=t.getFocused(),r=((o?n.indexOf(o):-1)+(e==="next"?1:-1)+n.length)%n.length,a=n[r];a.state==="minimized"?a.restore():t.focus(a)}let Cd=!1;function xd(t){let e=t.activeElement;for(;e&&e.shadowRoot&&e.shadowRoot.activeElement;)e=e.shadowRoot.activeElement;if(!e)return!1;if(e instanceof HTMLIFrameElement||e instanceof HTMLTextAreaElement)return!0;if(e instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(e.type);if(e instanceof HTMLElement&&e.isContentEditable===!0)return!0;const n=e.getAttribute("contenteditable");return n!==null&&n!=="false"}function Ub(t){if(Cd)return;Cd=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(xd(document)||(n.preventDefault(),Id(t,n.shiftKey?"prev":"next")))},!0);const e=window.location.origin;window.addEventListener("message",n=>{if(n.origin!==e)return;const o=n.data;!o||o.type!=="os-window-switch"||Id(t,o.direction==="prev"?"prev":"next")})}function Ld(t,e){const n=t.getDesktops();if(n.length<2)return!1;const o=t.getActiveDesktopId(),s=n.findIndex(a=>a.id===o);if(s===-1)return!1;const r=(s+(e==="next"?1:-1)+n.length)%n.length;return r===s?!1:(t.switchDesktop(n[r].id,{direction:e}),!0)}function Td(t,e){if(!t._overviewActive)return!1;const n=t.getDesktops(),o=n.length+1,s=n.length,i=t._overviewAddTileFocused?s:n.findIndex(l=>l.id===t.getActiveDesktopId());if(i===-1)return!1;const a=(i+(e==="next"?1:-1)+o)%o;return a===i?!1:a===s?(t._overviewAddTileFocused=!0,dr(t),!0):(t._overviewAddTileFocused=!1,t.switchDesktop(n[a].id,{direction:e}),!0)}function Fb(t){return t._overviewActive?t.exitOverview():t.enterOverview(),!0}function Bb(t){return t._overviewActive||t.getAll().length===0?!1:(t.toggleShowDesktop(),!0)}function Nd(t){return t._overviewActive?(t.exitOverview(),!0):!1}function Hb(t){const e=t.getAll();return e.length===0?!1:e.every(n=>n.state==="minimized")}function zb(t){return Hb(t)?(t.toggleShowDesktop(),!0):!1}let Dd=!1;function Gb(t){Dd||(Dd=!0,document.addEventListener("keydown",e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.code!=="ArrowLeft"&&e.code!=="ArrowRight"&&e.code!=="ArrowUp"&&e.code!=="ArrowDown"||xd(document))return;let n=!1;switch(e.code){case"ArrowLeft":n=t._overviewActive?Td(t,"prev"):Ld(t,"prev");break;case"ArrowRight":n=t._overviewActive?Td(t,"next"):Ld(t,"next");break;case"ArrowUp":n=Nd(t)||zb(t)||Fb(t);break;case"ArrowDown":n=Nd(t)||Bb(t);break}n&&e.preventDefault()},!0))}const Rd="__openStationSharedStores";function jb(){const t=window;let e=t[Rd];return e||(e=new Map,t[Rd]=e),e}function ie(t,e){const n=jb();let o=n.get(t);o||(o={state:e(),listeners:new Set,rebuild:e},n.set(t,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:${t}] 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:${t}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(r,i),s.notify()},reset(){const i=o.rebuild(),r=o.state;if(typeof r=="object"&&r!==null&&typeof i=="object"&&i!==null){const a=r;for(const l of Object.keys(a))delete a[l];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}function Dt(t,e){if(!t||typeof t!="object")return["def (not an object)"];const n=t,o=[];for(const s of e)s.valid(n)||o.push(`${s.field} (${s.message})`);return o}class Vb extends Error{constructor(e,n,o){super(`[openstation] ${e} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=e,this.errors=n,this.def=o}}function Re(t,e,n){if(e.length!==0)throw new Vb(t,e,n)}function Od(t,e,n){typeof console>"u"||console.warn(`[openstation] ${t} registration rejected — fields: `+e.join(", ")+".",n)}const bt=[[0,0],[100,0],[100,100],[0,100]],qb=48,Kb=80,mr=6,gr=8,Md=4,Pd=3,Wd=64,wr=105,vt=2;function $d(t){return`${Math.round(t*1e3)/1e3}%`}function _t(t){return t.slice().reverse()}function qn(t,e,n,o){return[[t,e],[n,e],[n,o],[t,o]]}function Yb(t,e,n,o){const s=[];for(let i=0;i<o;i++){const r=i/o*Math.PI*2;s.push([t+Math.cos(r)*n,e+Math.sin(r)*n])}return s}function et(t,e=[]){const n=[],o=s=>{n.push(`${$d(s[0])} ${$d(s[1])}`)};for(const s of t)o(s);if(e.length>0){o(t[0]);for(const s of e){for(const i of s)o(i);o(s[0]),o(t[0])}}return`polygon( ${n.join(", ")} )`}function Ud(t){return et(bt,[_t(Yb(50,50,t,qb))])}function Fd(t){return et(bt,[_t(qn(50-t,-vt,50+t,100+vt))])}function Bd(t){const e=100/mr,n=[];for(let o=0;o<mr;o++){const s=o*e;n.push(_t(qn(-vt,s,100+vt,s+t)))}return et(bt,n)}function Hd(t){return et(bt,[_t(qn(-vt,50-t,100+vt,50+t))])}function zd(t){const e=100/gr,n=[];for(let o=0;o<gr;o++){const s=o*e;n.push(_t(qn(s,-vt,s+t,100+vt)))}return et(bt,n)}function Gd(t){return et(bt,[_t([[50,50-t],[50+t,50],[50,50+t],[50-t,50]])])}function jd(t){const e=100/Md,n=100/Pd,o=[];for(let s=0;s<Pd;s++)for(let i=0;i<Md;i++){const r=i*e+e/2,a=s*n+n/2,l=e/2*t,c=n/2*t;o.push(_t(qn(r-l,a-c,r+l,a+c)))}return et(bt,o)}function Vd(t){const e=-Math.PI/2,n=t/180*Math.PI,o=[[50,50]];for(let s=0;s<Wd;s++){const i=e+s/(Wd-1)*n;o.push([50+Math.cos(i)*wr,50+Math.sin(i)*wr])}return et(bt,[_t(o)])}function Xb(){return{from:Ud(0),to:Ud(Kb)}}function Zb(){return{from:Fd(0),to:Fd(52)}}function Jb(){return{from:Bd(0),to:Bd(100/mr+.5)}}function Qb(){return{from:Hd(0),to:Hd(52)}}function ev(){return{from:zd(0),to:zd(100/gr+.5)}}function tv(){return{from:Gd(0),to:Gd(wr)}}function nv(){return{from:jd(0),to:jd(1.04)}}function ov(){return{from:Vd(0),to:Vd(360)}}function sv(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function iv(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function rv(){return{from:et([[-60,0],[100,0],[100,100],[0,100]]),to:et([[100,0],[260,0],[260,100],[160,100]])}}const yr=6,br=100,Qt=br/2,Ts=200,qd=90,Kd=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],av="#101014",lv=1.25,en="http://www.w3.org/2000/svg";let cv=0;function Ns(t){return Math.round(t*1e3)/1e3}function vr(t){return t/yr*Math.PI*2-Math.PI/2}function dv(t){const n=vr(t)+Math.PI/yr+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function uv(t){const e=vr(t),n=vr(t+1);return[[Qt,Qt],[Qt+Math.cos(e)*Ts,Qt+Math.sin(e)*Ts],[Qt+Math.cos(n)*Ts,Qt+Math.sin(n)*Ts]]}function Yd(t,e){const n=uv(t),o=document.createElementNS(en,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${Ns(s)} ${Ns(i)}`).join(" L ")} Z`),e?o.setAttribute("fill","#fff"):(o.setAttribute("fill",Kd[t%Kd.length]),o.setAttribute("stroke",av),o.setAttribute("stroke-width",String(lv)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function fv(){const t=`os-iris-${++cv}`,e=document.createElementNS(en,"svg");e.setAttribute("viewBox",`0 0 ${br} ${br}`),e.setAttribute("preserveAspectRatio","none"),e.setAttribute("aria-hidden","true"),e.style.width="100%",e.style.height="100%",e.style.display="block";const n=document.createElementNS(en,"defs"),o=document.createElementNS(en,"mask");o.setAttribute("id",t);const s=document.createElementNS(en,"g"),i=document.createElementNS(en,"g");i.setAttribute("mask",`url(#${t})`);const r=[];for(let l=0;l<yr;l++){const c=Yd(l,!0),d=Yd(l,!1);s.appendChild(c),i.appendChild(d),r.push({el:c,index:l},{el:d,index:l})}o.appendChild(s),n.appendChild(o),e.appendChild(n),e.appendChild(i);const a=document.createElement("div");return a.appendChild(e),{element:a,play:l=>r.map(({el:c,index:d})=>{const u=dv(d),f=Ns(u.x*qd),p=Ns(u.y*qd);return c.animate([{transform:"translate( 0px, 0px )"},{transform:`translate( ${f}px, ${p}px )`}],{duration:l.duration,easing:l.easing,delay:l.delay,fill:"both"})})}}const Kn="none",pv=460,hv="cubic-bezier( 0.33, 0, 0.2, 1 )",Xd=80,Zd=4e3,mv=70,gv=600,Jd=ie("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),Ds=Jd.state.registry,wv=Jd.state.listeners,Qd=/^[a-z0-9_/-]+$/;function eu(t){const e=/^\s*([a-zA-Z-]+)\s*\(/.exec(t);return e?e[1].toLowerCase():""}function yv(t){return typeof t!="number"||!Number.isFinite(t)?pv:Math.min(Zd,Math.max(Xd,t))}const _r=0;function tu(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?_r:Math.min(Zd,Math.max(Xd,t))}function tn(t){return typeof t!="number"||!Number.isFinite(t)?mv:Math.min(gv,Math.max(0,t))}function nu(t){return typeof t.render=="function"?[]:Array.isArray(t.layers)&&t.layers.length>0?t.layers:typeof t.from=="string"&&typeof t.to=="string"?[{from:t.from,to:t.to}]:[]}function ou(t,e){const n=[],o=typeof t.from=="string"&&t.from.trim()!=="",s=typeof t.to=="string"&&t.to.trim()!=="";if(o||n.push(`${e}.from (missing — the clip-path covering the window)`),s||n.push(`${e}.to (missing — the clip-path uncovering the window)`),o&&s){const i=eu(t.from),r=eu(t.to);i===""||r===""?n.push(`${e}.from|to (must be shape functions, e.g. \`inset( … )\` or \`polygon( … )\` — bare keywords like \`none\` cannot be animated)`):i!==r&&n.push(`${e}.from|to (must use the same shape function to interpolate — got \`${i}()\` and \`${r}()\`)`)}return n}function bv(t){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:t}),!0}catch{return!1}}function Ue(t){const e=[];if(!t||typeof t!="object")e.push("def (not an object)");else{typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):Qd.test(t.id.trim().toLowerCase())?t.id.trim().toLowerCase()===Kn&&e.push('id ("none" is reserved)'):e.push(`id (must match ${Qd} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)");const o=t.render!==void 0,s=Array.isArray(t.layers),i=t.from!==void 0||t.to!==void 0;o&&typeof t.render!="function"?e.push("render (not a function)"):o&&(s||i)?e.push("render|layers|from|to (supply exactly one of: a from/to pair, a layers array, or a render function)"):o||(s&&i?e.push("layers|from|to (supply EITHER a single from/to pair OR a layers array, not both)"):s?(t.layers.length===0&&e.push("layers (empty — supply at least one matched pair)"),t.layers.forEach((r,a)=>{if(!r||typeof r!="object"){e.push(`layers[ ${a} ] (not an object)`);return}e.push(...ou(r,`layers[ ${a} ]`))})):e.push(...ou(t,"").map(r=>r.replace(/^\./,"")))),t.easing!==void 0&&(typeof t.easing!="string"||t.easing.trim()===""?e.push("easing (not a non-empty string)"):bv(t.easing)||e.push("easing (not an easing the browser can parse — `Element.animate()` would throw at play time, with the covering surface already over the window)"))}Re("WindowReveal",e,t);const n=t.id.trim().toLowerCase();Ds.set(n,{...t,id:n}),ru()}function vv(t){Ds.delete(t.toLowerCase())&&ru()}function su(){const t=Array.from(Ds.values()),e=K(b.WINDOW_REVEALS,t);return Array.isArray(e)?e:(typeof console<"u"&&console.warn("[openstation] `os.window-reveals` filter returned a non-array; falling back to registry list."),t)}function iu(t){return su().find(e=>e.id===t)}function _v(t){return Ds.has(t)}function ru(){const t=Array.from(wv);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Ue({id:"sweep",label:k("Sweep"),description:k("A straight edge travels across the window, uncovering the page behind it."),...iv(),duration:420}),Ue({id:"iris",label:k("Iris"),description:k("The page opens out from the centre of the window, like a camera shutter."),...Xb(),duration:520}),Ue({id:"curtain",label:k("Curtain"),description:k("Two panels part from the middle of the window and slide off the sides."),...Zb(),duration:480}),Ue({id:"blinds",label:k("Blinds"),description:k("Six horizontal slats retract at once, letting the page through between them."),...Jb(),duration:560}),Ue({id:"diagonal",label:k("Diagonal"),description:k("A slanted edge sweeps off the trailing corner of the window."),...rv(),duration:460}),Ue({id:"rise",label:k("Rise"),description:k("The page rises into the window from the bottom edge upward."),...sv(),duration:440}),Ue({id:"shutter",label:k("Shutter"),description:k("Two panels part from the middle of the window and slide off the top and bottom."),...Qb(),duration:480}),Ue({id:"slats",label:k("Slats"),description:k("Eight vertical slats retract at once, letting the page through between them."),...ev(),duration:560}),Ue({id:"diamond",label:k("Diamond"),description:k("The page opens out from the centre of the window through a growing rhombus."),...tv(),duration:520}),Ue({id:"mosaic",label:k("Mosaic"),description:k("The page arrives as a grid of tiles, each opening out from its own centre."),...nv(),duration:600}),Ue({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:fv,duration:720,edgeLag:0}),Ue({id:"radar",label:k("Radar"),description:k("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...ov(),duration:760});const Rs=ie("desktop-mode/window-reveal-active",()=>({id:Kn,duration:_r}));function au(t){Rs.state.id=typeof t=="string"&&t!==""?t:Kn}function Ev(){const t=Rs.state.id;return!t||t===Kn?null:iu(t)??null}function lu(t){Rs.state.duration=tu(t)}function kv(){return Rs.state.duration}function Sv({osSettings:t}){const e=t.getOsSettingsSnapshot();au(e.windowReveal),lu(e.windowRevealDuration),t.subscribeOsSettings(n=>{au(n.windowReveal),lu(n.windowRevealDuration)})}const nn="os-window__reveal",Yn="os-window__reveal--edge",Av="os-window__reveal--custom",Rt="os-window__body--revealing",Er="data-os-reveal",kr="data-os-reveal-layer",Et=new WeakMap,cu=ie("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function du(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const Iv="--os-window-reveal-duration",Cv="--os-window-reveal-edge-thickness";function uu(t){const e=t.trim();if(e==="")return 0;const n=/^(-?\d*\.?\d+)\s*(ms|s)?$/i.exec(e);if(!n)return 0;const o=Number(n[1]);return Number.isFinite(o)?n[2]?.toLowerCase()==="s"?o*1e3:o:0}function xv(t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return tu(uu(window.getComputedStyle(t).getPropertyValue(Iv)))}catch{return 0}}function Lv(t,e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(t).getPropertyValue(e).trim()}catch{return""}}function Tv(t,e){const n=Lv(t,Cv);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return tn(e*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return tn(e*Number(s[1]));const i=uu(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?tn(i):null}function fu(t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return!1;try{const e=window.getComputedStyle(t),n=e.backgroundImage;if(n&&n!=="none")return!1;const o=/^rgba?\(([^)]+)\)$/.exec(e.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 Nv(t,e){const n=yv(e.duration),o=kv(),s=o!==_r?o:xv(t)||n,i=Tv(t,s);if(i!==null)return{duration:s,edgeLag:i};const r=tn(e.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:tn(r*s/n)}}function pu(t){return t.querySelector(":scope .os-window__body")}function Dv(t){return t.querySelector(`:scope .${nn}:not( .${Yn} )`)}function Rv(t){return t.querySelector(`:scope .${Yn}`)}function hu(t){return Array.from(t.querySelectorAll(`:scope .${nn}:not( .${Yn} )`))}function mu(t){return Array.from(t.querySelectorAll(`:scope .${Yn}`))}function Sr(t){return Array.from(t.querySelectorAll(`:scope .${nn}`))}function gu(t,e,n,o){const s=document.createElement("div");s.className=o?`${nn} ${Yn}`:nn;const i=o?t.edgeColor:e.color??t.surfaceColor;return typeof i=="string"&&i!==""&&(s.style.background=i),s.setAttribute("aria-hidden","true"),s.setAttribute(Er,t.id),s.setAttribute(kr,String(n)),s.style.clipPath=e.from,s}function Ov(){const t=Ev();if(!t)return[];if(typeof t.render=="function"){let o;try{o=t.render()}catch(i){return typeof console<"u"&&console.error(`[openstation] window reveal "${t.id}" render threw:`,i),[]}if(!o?.element||typeof o.play!="function")return[];const s=o.element;return s.classList.add(nn),s.classList.add(Av),s.setAttribute("aria-hidden","true"),s.setAttribute(Er,t.id),s.setAttribute(kr,"0"),cu.set(s,o.play),[s]}const e=nu(t);if(e.length===0)return[];const n=[];return tn(t.edgeLag)>0&&e.forEach((o,s)=>n.push(gu(t,o,s,!0))),e.forEach((o,s)=>n.push(gu(t,o,s,!1))),n}function Mv(t){const e=pu(t);if(e){e.classList.remove(Rt);for(const n of Sr(e))Et.get(n)?.cancel(),Et.delete(n),n.remove();for(const n of Ov())e.appendChild(n)}}function wu(t){const e=pu(t);if(!e)return;const n=Dv(e);if(!n)return;let o;try{o=iu(n.getAttribute(Er)??"")}catch(E){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",E)}if(!o){Sr(e).forEach(E=>E.remove());return}const i=!!e.querySelector(`:scope .${Vn}`)?.classList.contains(xs)?Sd:0,{duration:r,edgeLag:a}=Nv(e,o),l=o.easing??hv,c=cu.get(n);if(c){e.classList.add(Rt);const E=()=>{Et.delete(n),n.remove(),e.classList.remove(Rt)};if(du()||typeof n.animate!="function"){window.setTimeout(E,i);return}let N=[];try{N=c({duration:r,easing:l,delay:i})}catch(D){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,D)}if(N.length===0){E();return}N[0].addEventListener("finish",E),N[0].addEventListener("cancel",()=>{Et.delete(n),e.classList.remove(Rt)}),Et.set(n,N[0]);return}const d=Rv(e);d&&(a<=0||fu(d))&&mu(e).forEach(E=>E.remove()),fu(n)&&hu(e).forEach(E=>E.remove());const u=Sr(e);if(u.length===0)return;e.classList.add(Rt);const f=()=>{for(const E of u)Et.delete(E),E.remove();e.classList.remove(Rt)};if(du()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,m=nu(o),g=(E,N)=>{const D=m[Number(E.getAttribute(kr))];if(!D)return E.remove(),null;E.style.willChange="clip-path";let O;try{O=E.animate([{clipPath:D.from},{clipPath:D.to}],{duration:N,easing:p,delay:i,fill:"both"})}catch(y){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,y),E.remove(),null}return Et.set(E,O),O},h=hu(e).map(E=>g(E,r)).filter(E=>E!==null),w=mu(e).map(E=>g(E,r+a)).filter(E=>E!==null),v=h[0]??null,R=w[0]??null;if(!v&&!R){f();return}(R??v)?.addEventListener("finish",f);const _=()=>{for(const E of u)Et.delete(E);e.classList.remove(Rt)};v?.addEventListener("cancel",_),R?.addEventListener("cancel",_)}function Os(t){if(!t)return 214;let e=5381;for(let n=0;n<t.length;n++)e=Math.imul(e,33)+t.charCodeAt(n);return(e%360+360)%360}const Xn=ie("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),lt=Xn.state.registry,Ar=Xn.state.listeners,Pv=/^[a-z0-9_-]+$/;function yu(t){if(!t||typeof t!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof t.id!="string"||!Pv.test(t.id))throw new TypeError(`[openstation] registerDockRailRenderer: id must match /^[a-z0-9_-]+$/, got: ${String(t.id)}`);if(typeof t.label!="string"||t.label==="")throw new TypeError("[openstation] registerDockRailRenderer: label must be a non-empty string.");if(typeof t.mount!="function")throw new TypeError("[openstation] registerDockRailRenderer: mount must be a function.");if(t.apiVersion!==void 0&&t.apiVersion!==1)throw new TypeError(`[openstation] registerDockRailRenderer: unsupported apiVersion ${t.apiVersion} (this shell speaks v1).`);lt.set(t.id,t),Ms()}function Wv(t){lt.delete(t)&&Ms()}function $v(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(lt.entries()))o.owner===t&&(lt.delete(n),e++);return e>0&&Ms(),e}function Uv(t){return lt.get(t)}function Fv(){return Array.from(lt.values())}function Bv(t){return Ar.add(t),()=>{Ar.delete(t)}}function Hv(t){Xn.state.activeId!==t&&(Xn.state.activeId=t,Ms())}function Ir(){return lt.get(Xn.state.activeId)??lt.get("default")??lt.values().next().value}function Ms(){const t=Array.from(Ar);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}const bu="desktop-mode-os-settings",zv="custom-gradient",vu="custom-image",Cr="galaxy",_u=[{id:"pulse",label:"Pulse",value:"#f252fc"},{id:"nebula",label:"Nebula",value:"#ec9bff"},{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 xr(){const e=window.wp?.os?.config?.accentColors;if(!Array.isArray(e)||e.length===0)return _u;const n=[];for(const o of e)o&&typeof o=="object"&&typeof o.id=="string"&&typeof o.label=="string"&&typeof o.value=="string"&&o.id!==""&&o.label!==""&&/^#[0-9a-f]{3,8}$/i.test(o.value)&&n.push({id:o.id,label:o.label,value:o.value});return n.length>0?n:_u}function Eu(){const e=window.wp?.os?.config?.defaultWallpaper;return typeof e=="string"&&e!==""?e:Cr}const Lr=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],Tr=[{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"}],Gv=[{id:"classic",label:"Classic"},{id:"unified",label:"Unified"},{id:"spatial",label:"Spatial"}],ee={wallpaper:Cr,accent:"pulse",dockSize:"default",windowRadius:"default",adminBarMode:"static",desktopLayout:"classic",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:{}},ku={dockSize:["compact","default","large"],desktopLayout:["classic","unified","spatial"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},Su=["dockRailRenderer","windowReveal","accent"],Au={windowRevealDuration:{min:80,max:4e3}},jv=/^[a-z0-9_-]+$/;[...Object.keys(ku),...Su,...Object.keys(Au)];function Iu(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e=t,n={},o={};for(const[s,i]of Object.entries(ku)){const r=e[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of Su){const i=e[s];typeof i=="string"&&jv.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(Au)){const r=e[s];typeof r=="number"&&Number.isFinite(r)&&(o[s]=Math.min(i.max,Math.max(i.min,Math.round(r))))}return{...n,...o}}function Vv(t){const e=Iu(t);return typeof e.dockRailRenderer=="string"&&Uv(e.dockRailRenderer)===void 0&&delete e.dockRailRenderer,typeof e.windowReveal=="string"&&e.windowReveal!==Kn&&!_v(e.windowReveal)&&delete e.windowReveal,typeof e.accent=="string"&&!xr().some(n=>n.id===e.accent)&&delete e.accent,e}const qv=/^[a-z0-9_-]+$/,Cu=128;function Kv(t){return typeof t!="string"||t===""||t.length>2048?!1:t.startsWith("dashicons-")||t.startsWith("https://")||t.startsWith("http://")||t.startsWith("data:image/")}function xu(t){if(!t||typeof t!="object")return null;const e=t,n=typeof e.slug=="string"?e.slug:"";if(!qv.test(n))return null;const o={};if(e.icons&&typeof e.icons=="object"){let l=0;for(const[c,d]of Object.entries(e.icons)){if(l>=Cu)break;c===""||!Kv(d)||(o[c]=d,l+=1)}}const s={};if(e.tokens&&typeof e.tokens=="object")for(const[l,c]of Object.entries(e.tokens))typeof c=="string"&&(s[l]=c);const i=[];if(Array.isArray(e.fonts))for(const l of e.fonts)typeof l=="string"&&l!==""&&i.push(l);const r={};if(e.iconColors&&typeof e.iconColors=="object"){let l=0;for(const[c,d]of Object.entries(e.iconColors)){if(l>=Cu)break;c===""||typeof d!="string"||d===""||(r[c]=d,l+=1)}}const a=l=>typeof e[l]=="string"?e[l]:"";return{id:a("id")||n,slug:n,name:a("name")||n,version:a("version"),author:a("author"),description:a("description"),previewUrl:a("previewUrl"),cssUrl:a("cssUrl"),cssText:a("cssText"),tokens:s,fonts:i,icons:o,iconColors:r,recommendedOsSettings:Iu(e.recommendedOsSettings),installedAt:typeof e.installedAt=="number"?e.installedAt:0,source:e.source==="code"?"code":"upload"}}function Yv(){const e=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(e))for(const o of e){const s=xu(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const on=ie("desktop-mode/desktop-themes",Yv);function Ws(){return on}function Xv(){return on.getState().themes.slice()}function Lu(t){if(typeof t!="string"||t==="")return null;const e=t.replace(/\//g,"-");return on.getState().themes.find(n=>n.slug===e||n.id===t)??null}function Nr(){return on.getState().activeId}function Zv(t){const e=[];for(const n of t){const o=xu(n);o&&e.push(o)}on.setState({themes:e})}function Jv(t){return on.subscribe(t)}function $s(t){const e=Ws().state;if(e.activeIcons===null||!t)return null;const n=e.activeIcons[t];if(typeof n!="string"||n==="")return null;const o=K(b.DESKTOP_THEME_ICON,n,{slot:t,themeId:e.activeId??""});return typeof o=="string"&&o!==""?o:null}function Dr(t){const e=Ws().state;if(e.activeIconColors===null||!t)return null;const n=e.activeIconColors[t];if(typeof n!="string"||n==="")return null;const o=K(b.DESKTOP_THEME_ICON_COLOR,n,{slot:t,themeId:e.activeId??""});return typeof o=="string"&&o!==""?Qv(o):null}function Qv(t){const e=t.trim();if(e===""||e.length>64||/[;{}<>"'\\]/.test(e))return null;let n=0;for(const o of e)if(o==="(")n+=1;else if(o===")"&&(n-=1,n<0))return null;return n===0?e:null}function e_(t){return typeof t!="string"||t===""||t.length>4096||!/^(https?:\/\/|data:image\/)/i.test(t)?!1:!/['"()\\<>\s]/.test(t)}function Us(t,e,n){if(!e_(e))return!1;const o=`url("${e}") center / contain no-repeat`;return t.style.backgroundImage="none",t.style.backgroundColor=n,t.style.setProperty("-webkit-mask",o),t.style.setProperty("mask",o),!0}const Tu="data:image/svg+xml;base64,",Fs=new Map;function t_(t){const e=Fs.get(t);if(e!==void 0)return e;let n=!1;try{n=atob(t.slice(Tu.length)).includes("currentColor")}catch{}return Fs.size>=256&&Fs.clear(),Fs.set(t,n),n}function Zn(t,e){const n=e.className??"",o=e.title??"";let s=null;if(e.slot){const l=$s(e.slot);l!==null&&(t=l),s=Dr(e.slot)}if(typeof t=="string"&&t.startsWith("dashicons-")){const l=document.createElement("span");return l.className=`dashicons ${t} ${n}`.trim(),l.setAttribute("aria-hidden","true"),s!==null&&(l.style.color=s),l}if(s!==null&&typeof t=="string"){const l=document.createElement("span");if(l.className=n,l.setAttribute("aria-hidden","true"),l.style.display="inline-block",Us(l,t,s))return l}if(typeof t=="string"&&t.startsWith("data:image/svg+xml;base64,")){const l=t.slice(Tu.length);if(/^[A-Za-z0-9+/=]+$/.test(l)){const c=document.createElement("span");return c.className=n,c.setAttribute("aria-hidden","true"),c.style.display="inline-block",t_(t)&&Us(c,t,"currentColor")||(c.style.backgroundImage=`url("${t}")`,c.style.backgroundRepeat="no-repeat",c.style.backgroundPosition="center",c.style.backgroundSize="contain"),c}}if(typeof t=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(t)){const l=t.indexOf(","),c=l>=0?t.slice(l+1):"";if(/^[A-Za-z0-9+/=]+$/.test(c))return Nu(t,n)}if(typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://")))return Nu(t,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=n_(o);i.textContent=r;const a=Os(o);return i.style.backgroundColor=`hsl( ${a}, 60%, 45% )`,i.style.color="#fff",i.style.display="inline-flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.fontWeight="600",i.style.borderRadius="4px",i}function Nu(t,e){const n=document.createElement("img");return n.className=e,n.src=t,n.alt="",n.setAttribute("aria-hidden","true"),n.draggable=!1,n}function n_(t){const e=(t??"").trim();if(e==="")return"?";const n=e.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 Ot={WINDOW_CONTROL_MINIMIZE:"WINDOW_CONTROL_MINIMIZE",WINDOW_CONTROL_MAXIMIZE:"WINDOW_CONTROL_MAXIMIZE",WINDOW_CONTROL_FULLSCREEN:"WINDOW_CONTROL_FULLSCREEN",WINDOW_CONTROL_FULLSCREEN_EXIT:"WINDOW_CONTROL_FULLSCREEN_EXIT",WINDOW_CONTROL_CLOSE:"WINDOW_CONTROL_CLOSE",WINDOW_CONTROL_MENU:"WINDOW_CONTROL_MENU",WINDOW_CONTROL_RELOAD:"WINDOW_CONTROL_RELOAD",WINDOW_CONTROL_DETACH:"WINDOW_CONTROL_DETACH",OS_SETTINGS:"OS_SETTINGS",RECYCLE_BIN:"RECYCLE_BIN",BUG_REPORT:"BUG_REPORT",EXIT_OPENSTATION:"EXIT_OPENSTATION",PWA_INSTALL:"PWA_INSTALL",DEFAULT_APP_ICON:"DEFAULT_APP_ICON",FOLDER:"FOLDER",FILE_SHORTCUT:"FILE_SHORTCUT",FILE_POST:"FILE_POST",FILE_ATTACHMENT:"FILE_ATTACHMENT",FILE_UPLOAD:"FILE_UPLOAD",FILE_USER:"FILE_USER",FILE_TERM:"FILE_TERM",FILE_COMMENT:"FILE_COMMENT",FILE_BOOKMARK:"FILE_BOOKMARK",FILE_LINK:"FILE_LINK",FILE_EMBED:"FILE_EMBED",RECYCLE_RESTORE:"RECYCLE_RESTORE",RECYCLE_DELETE:"RECYCLE_DELETE"},o_={"desktop-mode-os-settings":Ot.OS_SETTINGS,"desktop-mode-recycle-bin":Ot.RECYCLE_BIN,"desktop-mode-bug-report":Ot.BUG_REPORT,"os-exit":Ot.EXIT_OPENSTATION,"os-pwa-install":Ot.PWA_INSTALL};function Bs(t){if(typeof t!="string"||t==="")return"";const e=o_[t];if(e)return e;const n=t.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function s_(t){if(typeof t!="string"||t==="")return"";if(t==="folder")return Ot.FOLDER;const n=`FILE_${t.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Ot?n:""}const Du=new Map,i_=new Map;function Rr(t,e,n,o){let s=t.get(e);if(!s){if(!o)return;s=new Map,t.set(e,s)}let i=s.get(n);if(!i){if(!o)return;i=new Set,s.set(n,i)}return i}function Ru(t,e,n,o){const s={channel:n,windowId:e},i=Rr(t,e,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel subscriber for "${n}" threw:`,l)}const r=Rr(t,e,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel wildcard subscriber for "${e}" threw:`,l)}}function r_(t,e,n){const o=Rr(Du,t,e,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function a_(t,e,n){Ru(Du,t,e,n)}function l_(t,e,n){Ru(i_,t,e,n)}const Ou=new Set,c_=new Set,Mu=new Map;function d_(t){if(!Ou.has(t)){Ou.add(t);const e=Mu.get(t);if(e){Mu.delete(t);for(const n of e)try{n.flush()}catch(o){typeof console<"u"&&console.error(`[openstation] flushing queued window-send for "${n.channel}" threw:`,o)}}}c_.delete(t)&&(L(b.WINDOW_CONTENT_LOADED,{windowId:t}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:t}})))}const Jn="os-window__body--loading",Or="os-window__body--loading-out",Mr="data-os-loading-at",Pu="data-os-loading-cycle";function Hs(t){return t.getAttribute(Pu)??"0"}function u_(t){t.setAttribute(Mr,String(Date.now())),t.setAttribute(Pu,String(Number(Hs(t))+1))}function f_(t,e){const n=Number(t.getAttribute(Mr)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=Ob-o;if(s<=0){e.classList.add(xs);return}window.setTimeout(()=>{e.isConnected&&t.classList.contains(Jn)&&e.classList.add(xs)},s)}const p_=Symbol.for("desktop-mode/window-config");function h_(t){return t[p_]}function Wu(){const t=document.createElement("div");t.className=Vn,t.setAttribute("aria-hidden","true");const e=document.createElement("os-spinner");return e.setAttribute("preset","classic"),e.setAttribute("size","clamp(96px, 14vw, 192px)"),e.setAttribute("label",k("Loading window content")),t.appendChild(e),t}function m_(t){let e=Wu();const n={windowId:t.id,config:t};if(typeof t.loading?.render=="function")try{t.loading.render(e,n)}catch(o){typeof console<"u"&&console.error(`[openstation] loading.render threw for "${t.id}":`,o)}try{const o=K(b.WINDOW_LOADING_OVERLAY,e,n);o instanceof HTMLElement&&(e=o)}catch(o){typeof console<"u"&&console.error(`[openstation] WINDOW_LOADING_OVERLAY filter threw for "${t.id}":`,o)}return e&&!e.classList.contains(Vn)&&e.classList.add(Vn),e}function $u(t){t.querySelector(":scope .os-window__loading")?.remove()}function Uu(t){const e=t.querySelector(":scope .os-window__body");if(!e||e.querySelector(":scope .os-window__loading"))return;const o=h_(t),s=o?m_(o):Wu();e.appendChild(s),f_(e,s)}const Fu=Sd;let Bu=!1;function Hu(t){return t?document.getElementById(`wp-window-${t}`):null}function g_(){Bu||(Bu=!0,w_())}function w_(){X(b.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",t=>{const e=Hu(t?.windowId??"");if(!e)return;const n=e.querySelector(":scope .os-window__body");n&&(n.classList.remove(Or),n.classList.add(Jn),u_(n),Uu(e),Mv(e))}),X(b.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",t=>{const e=Hu(t?.windowId??"");if(!e)return;const n=e.querySelector(":scope .os-window__body");if(!n)return;const o=!!n.querySelector(`:scope .${Vn}`)?.classList.contains(xs);if(n.classList.remove(Jn),n.removeAttribute(Mr),!o){$u(e),wu(e);return}n.classList.add(Or);const s=Hs(n);wu(e),window.setTimeout(()=>{Hs(n)===s&&(n.classList.contains(Jn)||$u(e))},Fu),window.setTimeout(()=>{Hs(n)===s&&(n.classList.contains(Jn)||n.classList.remove(Or))},Fu+Mb)}),X(b.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>zu())})}function zu(){document.querySelectorAll(".os-window__body--loading").forEach(e=>{const n=e.closest(".os-window");n&&(e.querySelector(":scope .os-window__loading")?.remove(),Uu(n))})}const y_="os_person_view";function b_(t){return t.searchParams.has(y_)}const Qn=ie("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function v_(t){Qn.state.deps=t}function sn(t){if(!t||typeof t.id!="string"||t.id.trim()==="")return()=>{};if(typeof t.nativeWindowId!="string"||t.nativeWindowId==="")return()=>{};if(typeof t.matches!="function")return()=>{};const e=Qn.state.remaps,n=e.findIndex(o=>o.id===t.id);return n>=0&&e.splice(n,1),e.push(t),()=>__(t.id)}function __(t){const e=Qn.state.remaps,n=e.findIndex(o=>o.id===t);n>=0&&e.splice(n,1)}function Pr(t){const{deps:e,remaps:n}=Qn.state;if(!e||!t)return null;let o;try{o=new URL(t,e.adminUrl)}catch{return null}const s=e.getSnapshot();for(const i of n)if(i.matches(t,o)&&!(i.enabled&&!i.enabled(s)))return i.nativeWindowId;return null}function ct(t){const{deps:e,remaps:n}=Qn.state;if(!e||!t)return!1;let o;try{o=new URL(t,e.adminUrl)}catch{return!1}const s=e.getSnapshot();for(const i of n){if(!i.matches(t,o)||i.enabled&&!i.enabled(s))continue;if(i.onMatch)try{i.onMatch(t,o)}catch(l){console.warn(`[openstation] URL remap onMatch hook threw for "${i.id}":`,l)}let r;if(i.params)try{r=i.params(t,o)??void 0}catch(l){console.warn(`[openstation] URL remap params hook threw for "${i.id}":`,l)}if(r?e.openById(i.nativeWindowId,{params:r}):e.openById(i.nativeWindowId))return!0}return!1}const E_="os.activity.";function Wr(t){return E_+String(t).replace(/[^a-zA-Z0-9_.-]/g,".")}let k_=0;const Ee={publish(t,e){L(Wr(t),e)},subscribe(t,e){const n=`os/activity-sub/${++k_}`,o=Wr(t);X(o,n,i=>e(i));let s=!1;return()=>{s||(s=!0,zc(o,n))}},filter(t,e,...n){return K(Wr(t),e,...n)}},S_=4e3,A_=200;function Z(t){const e=Ee.filter("os/toast-requested",{...t});if(!e||e.cancel===!0)return()=>{};let n=!1,o=null;return Is(()=>!n,()=>{o=I_(e)}),()=>{n=!0,o&&o()}}function I_(t){const e=C_(),n=document.createElement("os-toast");n.textContent=t.message,t.action&&(n.setAttribute("action",t.action.label),n.addEventListener("os-toast-action",()=>{t.action?.onClick(),i()})),t.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{t.onDismiss?.(),i()})),e.appendChild(n);let o=!1,s=null;const i=()=>{o||(o=!0,s!==null&&(window.clearTimeout(s),s=null),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove()},A_))};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),t.persistent||(s=window.setTimeout(i,t.duration??S_)),Ee.publish("os/toast-shown",{...t}),i}function C_(){const t=document.querySelector("os-toast-container");if(t)return t;const e=document.createElement("os-toast-container");return document.body.appendChild(e),e}const $r=ie("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function x_(t){if(!t||typeof t.id!="string"||t.id.trim()==="")return()=>{};if(typeof t.matches!="function")return()=>{};const e=$r.state.entries,n=e.findIndex(o=>o.id===t.id);return n>=0&&e.splice(n,1),e.push(t),()=>Gu(t.id)}function Gu(t){const e=$r.state.entries,n=e.findIndex(o=>o.id===t);n>=0&&e.splice(n,1)}function L_(){return $r.state.entries.slice()}const T_=32,N_=64,D_=/^[a-z0-9_/-]+$/,fe=ie("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function Mt(t){return`${t.type}:${t.id}`}function ju(t){return t.root?Mt(t.root):Mt(t)}function Vu(t){const e=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&D_.test(o.trim().toLowerCase());return Dt(t,[{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=>e(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)&&e(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)&&e(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 R_(t,e){const n={type:t.type.trim().toLowerCase(),id:t.id,source:e};if(t.root&&(n.root={type:t.root.type.trim().toLowerCase(),id:t.root.id}),Array.isArray(t.links)&&t.links.length>0&&(n.links=t.links.slice(0,T_).map(o=>{const s={type:o.type.trim().toLowerCase(),id:o.id};return o.rel==="child"&&(s.rel="child"),s})),typeof t.label=="string"&&t.label!==""&&(n.label=t.label),typeof t.previewUrl=="string"&&t.previewUrl!=="")try{new URL(t.previewUrl,window.location.origin).origin===window.location.origin&&(n.previewUrl=t.previewUrl)}catch{}return Array.isArray(t.related)&&t.related.length>0&&(n.related=t.related.slice(0,N_).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 qu(t){return!t||!t.related?"":t.related.map(e=>`${e.id}\0${e.group}\0${e.label}\0${e.url}\0${e.groupLabel??""}\0${e.icon??""}\0${e.count??""}`).join("|")}function Ur(t){return t?[Mt(t),ju(t),...(t.links??[]).map(e=>Mt(e)+(e.rel==="child"?"!child":""))].join("|"):""}function zs(t,e,n={}){const o=n.source??"api";if(typeof t!="string"||t===""){Re("WindowContentRef",["windowId (must be a non-empty string)"],e);return}let s=null;if(e!=null){const a=Vu(e);if(a.length>0){o==="api"&&Re("WindowContentRef",a,e),Od("WindowContentRef",a,e);return}s=R_(e,o)}if(s=K(b.WINDOW_LINKS_CONTENT,s,{windowId:t,source:o}),s!==null&&(!s||Vu(s).length>0)){Od("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=fe.state.contentByWindow.get(t)??null;if(s===null&&i===null||s!==null&&i!==null&&Ur(s)===Ur(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&qu(s)===qu(i))return;s===null?fe.state.contentByWindow.delete(t):fe.state.contentByWindow.set(t,s);const r={windowId:t,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("os-window-content-changed",{detail:r})),L(b.WINDOW_CONTENT_CHANGED,r),W_(),M_()}function dt(t){return fe.state.contentByWindow.get(t)}function Gs(){const t=new Map;for(const[s,i]of fe.state.contentByWindow){const r=ju(i);let a=t.get(r);a||(a={key:r,root:i.root?{...i.root}:{type:i.type,id:i.id},rootWindowIds:[],children:[]},t.set(r,a)),i.root?a.children.push({windowId:s,content:i}):a.rootWindowIds.push(s)}const e=fe.state.focusSeq;for(const s of t.values())s.rootWindowIds.sort((i,r)=>(e.get(r)??0)-(e.get(i)??0));const n=Array.from(t.values()),o=K(b.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[openstation] `os.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function Ku(t){return Gs().find(e=>e.rootWindowIds.includes(t)||e.children.some(n=>n.windowId===t))}function Yu(t){const e=new Set,n=Ku(t);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])e.add(o);for(const o of eo())o.fromWindowId===t?e.add(o.toWindowId):o.toWindowId===t&&e.add(o.fromWindowId);return e.delete(t),Array.from(e)}function O_(t){const e=new Set;for(const n of eo())n.fromWindowId===t?e.add(n.toWindowId):n.toWindowId===t&&e.add(n.fromWindowId);return e.delete(t),Array.from(e)}function eo(){const t=fe.state.focusSeq,e=new Map;for(const[a,l]of fe.state.contentByWindow){const c=Mt(l),d=e.get(c);(!d||(t.get(a)??0)>(t.get(d)??0))&&e.set(c,a)}const n=new Map,o=(a,l)=>`${a}→${l}`;for(const[a,l]of fe.state.contentByWindow){if(l.root){const c=e.get(Mt(l.root));c&&c!==a&&n.set(o(a,c),{fromWindowId:a,toWindowId:c,kind:"child-root",bidirectional:!1})}for(const c of l.links??[]){const d=e.get(Mt(c));if(!d||d===a)continue;if(c.rel==="child"){const f=o(d,a),p=n.get(f);(!p||p.kind!=="child-root")&&n.set(f,{fromWindowId:d,toWindowId:a,kind:"child-root",bidirectional:!1});continue}const u=o(a,d);n.has(u)||n.set(u,{fromWindowId:a,toWindowId:d,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[a,l]of n){if(i.has(a))continue;const c=o(l.toWindowId,l.fromWindowId),d=n.get(c);if(d&&l.kind==="reference"){if(d.kind==="reference"){i.add(c),s.push({...l,bidirectional:!0});continue}continue}s.push(l)}const r=K(b.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 Xu(t){return fe.state.listeners.add(t),()=>{fe.state.listeners.delete(t)}}function M_(){for(const t of Array.from(fe.state.listeners))try{t()}catch(e){typeof console<"u"&&console.error("[openstation] window-links listener threw:",e)}}function P_(){return Array.from(fe.state.contentByWindow).map(([t,e])=>`${t}=${Ur(e)}`).sort().join(";")}function W_(){const t=P_();if(t===fe.state.lastGroupsSignature)return;fe.state.lastGroupsSignature=t;const n={groups:Gs()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),L(b.WINDOW_LINK_GROUPS_CHANGED,n)}const $_={get:dt,set:(t,e)=>zs(t,e,{source:"api"}),groups:Gs,edges:eo,groupOf:Ku,related:Yu,subscribe:Xu};function U_({manager:t}){fe.state.manager=t,!fe.state.started&&(fe.state.started=!0,X(b.WINDOW_OPENED,"desktop-mode/window-links-seed",e=>{if(!e?.windowId)return;const o=fe.state.manager?.getById(e.windowId)?.config?.content;o&&zs(e.windowId,o,{source:"config"})}),X(b.WINDOW_CLOSED,"desktop-mode/window-links-clear",e=>{e?.windowId&&(fe.state.focusSeq.delete(e.windowId),zs(e.windowId,null,{source:"config"}))}),X(b.WINDOW_FOCUSED,"desktop-mode/window-links-recency",e=>{e?.windowId&&(fe.state.seq+=1,fe.state.focusSeq.set(e.windowId,fe.state.seq))}),window.addEventListener("message",e=>{if(e.origin!==window.location.origin)return;const n=e.data;if(!n||n.type!=="os-content-identity")return;const o=fe.state.manager?.findByIframeSource?.(e.source);o&&zs(o.id,n.identity??null,{source:"bridge"})}))}const F_=ie("desktop-mode/admin-link-deps",()=>({deps:null}));function B_(t){F_.state.deps=t}const Zu=ie("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),rn=Zu.state.seed,H_=Zu.state.listeners;function to(t){Re("Wallpaper",Dt(t,tf),t);const e=rn.findIndex(n=>n.id===t.id);e>=0?rn[e]=t:rn.push(t),Qu()}function Ju(t){const e=rn.findIndex(n=>n.id===t);e>=0&&(rn.splice(e,1),Qu())}function Qu(){const t=Array.from(H_);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function ef(){const t=rn.slice(),e=K(b.WALLPAPERS,t);return Array.isArray(e)?e.filter(z_):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),t)}function Fr(t){return ef().find(e=>e.id===t)}const tf=[{field:"id",message:"missing or not a non-empty string",valid:t=>typeof t.id=="string"&&t.id!==""},{field:"label",message:"missing or not a non-empty string",valid:t=>typeof t.label=="string"&&t.label!==""},{field:"preview",message:"missing or not a non-empty string",valid:t=>typeof t.preview=="string"&&t.preview!==""},{field:"type",message:'must be "css" or "canvas"',valid:t=>t.type==="css"||t.type==="canvas"},{field:"value/resolveValue/mount",message:"css types need `value` or `resolveValue`; canvas types need `mount`",valid:t=>t.type==="css"?typeof t.value=="string"||typeof t.resolveValue=="function":t.type==="canvas"?typeof t.mount=="function":!0}];function z_(t){return Dt(t,tf).length===0}const nf=ie("desktop-mode/wallpaper-settings",()=>({values:{}}));function G_(t){return{...nf.state.values[t]??{}}}function j_(t){const e=nf.state.values;for(const n of Object.keys(e))delete e[n];for(const[n,o]of Object.entries(t))e[n]={...o}}function of(t){return typeof t=="string"&&/^#[0-9a-f]{3,8}$/i.test(t)}const sf=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","glow","glowBlur","eyeColor","eyeScale"],rf=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function Br(){return{appearance:{},physics:{}}}function V_(t){return typeof t=="boolean"||typeof t=="string"||typeof t=="number"&&Number.isFinite(t)}function js(t,e){const n={};if(!t||typeof t!="object"||Array.isArray(t))return n;const o=t;for(const s of e){const i=o[s];i!==void 0&&V_(i)&&Object.assign(n,{[s]:i})}return n}function af(t){if(!t||typeof t!="object"||Array.isArray(t))return Br();const e=t;return{appearance:js(e.appearance,sf),physics:js(e.physics,rf)}}function q_(t){return{appearance:js(t,sf),physics:js(t,rf)}}const lf="X-WP-Nonce";function cf(t,e){const n=K_();if(!n)return e;const o=Y_(t);if(!o||!X_(o))return e;const s=e?.headers??(typeof Request<"u"&&t instanceof Request?t.headers:void 0),i=new Headers(s??{});return i.has(lf)?e:(i.set(lf,n),{...e??{},headers:i})}function K_(){if(typeof window>"u")return;const e=window.openStationConfig?.restNonce;return typeof e=="string"&&e.length>0?e:void 0}function Y_(t){try{const e=typeof window<"u"&&window.location?window.location.href:void 0;return typeof t=="string"?new URL(t,e):t instanceof URL?t:typeof Request<"u"&&t instanceof Request?new URL(t.url,e):null}catch{return null}}function X_(t){return typeof window>"u"||!window.location||t.origin!==window.location.origin?!1:!!(t.pathname.includes("/wp-json/")||t.searchParams.has("rest_route"))}function Fe(t,e,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(t,e,n);const s=cf(t,e);return fetch(t,s)}function Z_(){const t=J_();if(t){const e=df(t);return zr(e),e}try{const e=window.localStorage.getItem(bu);if(e)return df(JSON.parse(e))}catch{}return lE()}function J_(){const e=window.openStationConfig?.osSettings;return!e||typeof e!="object"||Array.isArray(e)?null:e}function df(t){const e=xr();return{wallpaper:typeof t.wallpaper=="string"&&t.wallpaper!==""?t.wallpaper:Eu(),accent:e.some(n=>n.id===t.accent)?t.accent:ee.accent,dockSize:Lr.some(n=>n.id===t.dockSize)?t.dockSize:ee.dockSize,windowRadius:Tr.some(n=>n.id===t.windowRadius)?t.windowRadius:ee.windowRadius,adminBarMode:Ps.some(n=>n.id===t.adminBarMode)?t.adminBarMode:ee.adminBarMode,desktopLayout:Gv.some(n=>n.id===t.desktopLayout)?t.desktopLayout:ee.desktopLayout,dockRailRenderer:typeof t.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(t.dockRailRenderer)?t.dockRailRenderer:ee.dockRailRenderer,desktopTheme:typeof t.desktopTheme=="string"&&/^[a-z0-9_-]*$/.test(t.desktopTheme)?t.desktopTheme:ee.desktopTheme,appliedThemeRecommendations:Array.isArray(t.appliedThemeRecommendations)?Array.from(new Set(t.appliedThemeRecommendations.filter(n=>typeof n=="string"&&/^[a-z0-9_-]+$/.test(n)))).slice(-64):ee.appliedThemeRecommendations.slice(),unfocusEffect:typeof t.unfocusEffect=="string"&&/^[a-z0-9_/-]+$/.test(t.unfocusEffect)?t.unfocusEffect:ee.unfocusEffect,windowReveal:typeof t.windowReveal=="string"&&/^[a-z0-9_/-]+$/.test(t.windowReveal)?t.windowReveal:ee.windowReveal,windowRevealDuration:typeof t.windowRevealDuration=="number"&&Number.isFinite(t.windowRevealDuration)&&t.windowRevealDuration>0?Math.min(4e3,Math.max(80,Math.round(t.windowRevealDuration))):ee.windowRevealDuration,windowLinkRenderer:typeof t.windowLinkRenderer=="string"&&/^[a-z0-9_/-]+$/.test(t.windowLinkRenderer)?t.windowLinkRenderer:ee.windowLinkRenderer,windowLinkVisibility:t.windowLinkVisibility==="focus"||t.windowLinkVisibility==="always"||t.windowLinkVisibility==="off"?t.windowLinkVisibility:ee.windowLinkVisibility,windowLinksEnabled:typeof t.windowLinksEnabled=="boolean"?t.windowLinksEnabled:ee.windowLinksEnabled,windowLinkRaiseOnFocus:typeof t.windowLinkRaiseOnFocus=="boolean"?t.windowLinkRaiseOnFocus:ee.windowLinkRaiseOnFocus,windowLinkHighlight:typeof t.windowLinkHighlight=="boolean"?t.windowLinkHighlight:ee.windowLinkHighlight,customGradient:dE(t.customGradient),customImage:uE(t.customImage),wallpaperSettings:Q_(t.wallpaperSettings),libraryHdOnly:typeof t.libraryHdOnly=="boolean"?t.libraryHdOnly:ee.libraryHdOnly,ai:cE(t.ai),heartbeatRate:t.heartbeatRate===15||t.heartbeatRate===30||t.heartbeatRate===45||t.heartbeatRate===60?t.heartbeatRate:ee.heartbeatRate,nativePostsEnabled:typeof t.nativePostsEnabled=="boolean"?t.nativePostsEnabled:ee.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(t.nativePostsHiddenColumns)?t.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):ee.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof t.nativePagesEnabled=="boolean"?t.nativePagesEnabled:ee.nativePagesEnabled,nativeUsersEnabled:typeof t.nativeUsersEnabled=="boolean"?t.nativeUsersEnabled:ee.nativeUsersEnabled,nativePluginsEnabled:typeof t.nativePluginsEnabled=="boolean"?t.nativePluginsEnabled:ee.nativePluginsEnabled,nativeCommentsEnabled:typeof t.nativeCommentsEnabled=="boolean"?t.nativeCommentsEnabled:ee.nativeCommentsEnabled,showDesktopOnWallpaperClick:typeof t.showDesktopOnWallpaperClick=="boolean"?t.showDesktopOnWallpaperClick:ee.showDesktopOnWallpaperClick,mioEnabled:typeof t.mioEnabled=="boolean"?t.mioEnabled:ee.mioEnabled,mioStyle:af(t.mioStyle),showPostStatusRibbons:typeof t.showPostStatusRibbons=="boolean"?t.showPostStatusRibbons:ee.showPostStatusRibbons,developerModeEnabled:typeof t.developerModeEnabled=="boolean"?t.developerModeEnabled:ee.developerModeEnabled,foldersSharingEnabled:typeof t.foldersSharingEnabled=="boolean"?t.foldersSharingEnabled:ee.foldersSharingEnabled,itemVisibility:eE(t.itemVisibility),dockOrder:tE(t.dockOrder),dockPromotedPositions:nE(t.dockPromotedPositions)}}function Q_(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};let n=0;for(const[o,s]of Object.entries(t)){if(n>=64)break;if(typeof o!="string"||o===""||!/^[a-z0-9_/-]+$/.test(o)||!s||typeof s!="object"||Array.isArray(s))continue;const i={};let r=0;for(const[a,l]of Object.entries(s)){if(r>=32)break;if(!(typeof a!="string"||a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof l=="boolean")i[a]=l;else if(typeof l=="number"&&Number.isFinite(l))i[a]=l;else if(typeof l=="string")i[a]=l.slice(0,256);else continue;r++}}r!==0&&(e[o]=i,n++)}return e}function eE(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e=["both","dock","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(t)){if(o>=256)break;if(typeof s!="string"||s===""||typeof i!="string")continue;const r=i;e.includes(r)&&(n[s]=r,o++)}return n}function tE(t){if(!Array.isArray(t))return[];const e=[],n=new Set;for(const o of t)if(!(typeof o!="string"||o===""||n.has(o))&&(n.add(o),e.push(o),e.length>=256))break;return e}function nE(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};let n=0;const o=1e5;for(const[s,i]of Object.entries(t)){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||(e[s]={x:r.x,y:r.y},n++)}return e}let Vs=null;const oE=250;let no=null;function sE(t){no=Hr(t)}function Hr(t){return{...t,customGradient:{...t.customGradient},customImage:t.customImage?{...t.customImage}:null,wallpaperSettings:Object.fromEntries(Object.entries(t.wallpaperSettings).map(([e,n])=>[e,{...n}])),ai:{...t.ai},mioStyle:{appearance:{...t.mioStyle.appearance},physics:{...t.mioStyle.physics}},appliedThemeRecommendations:t.appliedThemeRecommendations.slice(),nativePostsHiddenColumns:t.nativePostsHiddenColumns.slice(),itemVisibility:{...t.itemVisibility},dockOrder:t.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(t.dockPromotedPositions).map(([e,n])=>[e,{...n}]))}}function iE(t,e={}){zr(t),rE(t,e.windowId)}function zr(t){try{window.localStorage.setItem(bu,JSON.stringify(t))}catch{}}function rE(t,e){Vs!==null&&clearTimeout(Vs),e&&(Gr=e),an("pending"),Vs=setTimeout(()=>{Vs=null;const n=Gr;Gr=null,aE(t,n)},oE)}let Gr=null;function aE(t,e){const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){an("saved");return}an("saving");const i=e||"desktop-mode-os-settings";Fe(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:t})},{windowId:i}).then(r=>{if(!r.ok)throw new Error(`${r.status} ${r.statusText}`);no=Hr(t),an("saved")}).catch(r=>{no?(zr(no),an("failed",r instanceof Error?r.message:String(r),Hr(no))):an("failed",r instanceof Error?r.message:String(r))})}function an(t,e,n){const o={phase:t};e&&(o.error=e),n&&(o.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:o}))}function lE(){return{...ee,customGradient:{...ee.customGradient},customImage:null,wallpaperSettings:{...ee.wallpaperSettings},ai:{...ee.ai},appliedThemeRecommendations:[...ee.appliedThemeRecommendations],itemVisibility:{...ee.itemVisibility},dockOrder:[...ee.dockOrder],dockPromotedPositions:{...ee.dockPromotedPositions}}}function cE(t){if(!t||typeof t!="object")return{...ee.ai};const{enabled:e}=t;return{enabled:typeof e=="boolean"?e:ee.ai.enabled}}function dE(t){if(!t||typeof t!="object")return{...ee.customGradient};const{from:e,to:n,angle:o}=t;return{from:of(e)?e:ee.customGradient.from,to:of(n)?n:ee.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:ee.customGradient.angle}}function uE(t){if(!t||typeof t!="object")return null;const{id:e,url:n}=t;return typeof e!="number"||!Number.isFinite(e)||e<=0||typeof n!="string"||!/^https?:\/\//i.test(n)?null:{id:e,url:n}}const fE=180,pE=220,uf=32;function ff(t){const{tile:e}=t;let n=null,o=null,s=null,i=!1,r=null;const a=()=>{o!==null&&(window.clearTimeout(o),o=null)},l=()=>{s!==null&&(window.clearTimeout(s),s=null)},c=()=>{a(),l(),e.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),r?.clear(),r=null,t.suppressTooltip(!1)},d=m=>{m.pointerType==="mouse"&&hE(t)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},fE)))},u=m=>{n&&m.relatedTarget instanceof Node&&n.contains(m.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},pE)},p=()=>{t.suppressTooltip(!0),e.setAttribute("data-peek-active",""),r=new Map,n=mE(t,()=>c(),r),document.body.appendChild(n),EE(n),kE(n,e,t.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,l()}),n.addEventListener("pointerleave",m=>{m.relatedTarget instanceof Node&&e.contains(m.relatedTarget)||(i=!1,f())})};return e.addEventListener("pointerenter",d),e.addEventListener("pointerleave",u),()=>{e.removeEventListener("pointerenter",d),e.removeEventListener("pointerleave",u),c()}}function hE(t){return t.getInstances().length>=1}function mE(t,e,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",ae(k("%s — open windows"),t.item.title));const s=document.createElement("div");s.className="os-dock-peek__cards",o.appendChild(s);const i=t.getInstances();let r=0;for(const a of i){const l=gE(a,t,r++,e,n);s.appendChild(l)}if(t.enableGhost!==!1){const a=yE(t,r,e);s.appendChild(a)}return o}function pf(t,e){t.state==="minimized"&&(t.restore(),e&&delete e.dataset.state)}function gE(t,e,n,o,s){const i=document.createElement("button");i.type="button",i.setAttribute("role","menuitem"),i.className="os-dock-peek__card os-dock-peek__card--instance",i.style.setProperty("--peek-card-index",String(n)),i.style.setProperty("--peek-card-delay",`${n*uf}ms`);const r=t.config.title||e.item.title;i.style.setProperty("--peek-card-hue",`${Os(t.id||r)}`),i.style.setProperty("--peek-card-vt-name",`os-peek-card-${t.id}`);const a=document.createElement("span");a.className="os-dock-peek__card-titlebar";const l=document.createElement("span");l.className="os-dock-peek__card-dots",l.setAttribute("aria-hidden","true");for(let v=0;v<3;v++)l.appendChild(document.createElement("i"));a.appendChild(l);const c=document.createElement("span");c.className="os-dock-peek__card-icon",c.setAttribute("aria-hidden","true");const d=t.config.icon||e.item.icon;d.startsWith("dashicons-")?c.classList.add("dashicons",tb(d)):c.classList.add("dashicons","dashicons-admin-generic"),a.appendChild(c);const u=document.createElement("span");u.className="os-dock-peek__card-label",u.textContent=r,a.appendChild(u),i.appendChild(a);const f=document.createElement("span");f.className="os-dock-peek__card-body",f.setAttribute("aria-hidden","true");for(let v=0;v<3;v++){const R=document.createElement("span");R.className="os-dock-peek__card-line",f.appendChild(R)}const p={window:t,item:e.item},m=K(b.DOCK_PEEK_CARD_CONTENT,f,p);m!==f&&m.classList.add("os-dock-peek__card-body--custom"),i.appendChild(m),t.state==="minimized"&&(i.dataset.state="minimized");const g=()=>{s.delete(t.id),delete i.dataset.preview},h=v=>{if(g(),v.wasMinimized)t.minimize(),i.dataset.state="minimized";else if(v.previouslyFocusedId){const R=e.windowManager.getById(v.previouslyFocusedId);R&&e.windowManager.focus(R)}};return i.addEventListener("click",()=>{g(),wE(e,t,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(t.id))return;const v=t.state==="minimized",R=e.windowManager.getFocused(),_=R&&R!==t?R.id:null;(v||_!==null)&&(s.set(t.id,{wasMinimized:v,previouslyFocusedId:_}),i.dataset.preview=""),v?pf(t,i):R&&R!==t&&e.windowManager.focus(t)}),i.addEventListener("pointerleave",()=>{const v=s.get(t.id);v&&h(v)}),K(b.DOCK_PEEK_CARD_ELEMENT,i,p)}function wE(t,e,n,o){const s=document,i=`os-peek-card-${e.id}`,r=()=>{o(),pf(e,n),t.windowManager.focus(e)};if(typeof s.startViewTransition!="function"){r();return}const a=e.element;n.style.setProperty("view-transition-name",i),a.style.setProperty("view-transition-name",i);const l=s.startViewTransition(r),c=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},d=l;d.finished&&typeof d.finished.then=="function"?d.finished.then(c,c):Promise.resolve().then(c)}function yE(t,e,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(e)),o.style.setProperty("--peek-card-delay",`${e*uf}ms`);const s=document.createElement("span");s.className="os-dock-peek__card-plus",s.setAttribute("aria-hidden","true"),s.textContent="+",o.appendChild(s);const i=document.createElement("span");return i.className="os-dock-peek__card-label",i.textContent=ae(k("New %s"),t.item.title),o.appendChild(i),o.addEventListener("click",()=>{bE(t,n)}),o}function bE(t,e){const n=document,o=()=>{e(),t.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const vE=12,_E=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function EE(t){const e=document.querySelector(".os-shell");if(!e)return;const n=window.getComputedStyle(e);for(const o of _E){const s=n.getPropertyValue(o).trim();s&&t.style.setProperty(o,s)}}function kE(t,e,n){const o=e.getBoundingClientRect();t.dataset.orientation=n,n==="bottom"?(t.style.left=`${o.left+o.width/2}px`,t.style.top=`${o.top-12}px`):n==="right"?(t.style.top=`${o.top}px`,t.style.left=`${o.left-12}px`):(t.style.top=`${o.top}px`,t.style.left=`${o.right+12}px`),requestAnimationFrame(()=>SE(t))}function SE(t,e){const n=t.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=vE;let r=0,a=0;n.top<i?r=i-n.top:n.bottom>o-i&&(r=o-i-n.bottom),n.left<i?a=i-n.left:n.right>s-i&&(a=s-i-n.right),!(a===0&&r===0)&&(t.style.setProperty("--peek-clamp-x",`${a}px`),t.style.setProperty("--peek-clamp-y",`${r}px`),t.classList.add("os-dock-peek--clamped"))}function qs(t){try{const e=new URL(t,window.location.origin);return e.origin===window.location.origin?!1:(window.open(e.toString(),"_blank","noopener,noreferrer"),!0)}catch{return!1}}const jr=new Map;function AE(t){let e,n;try{const s=new URL(t,document.baseURI);e=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===e&&i.pathname===n)return s}catch{}return null}function ke(t,e){const n=jr.get(t);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-os-vendor="${IE(t)}"]`,a=document.querySelector(r);if(a){if(a.dataset.loaded==="1"){s();return}a.addEventListener("load",()=>s(),{once:!0}),a.addEventListener("error",()=>i(new Error(`Failed to load ${t}`)),{once:!0});return}const l=AE(t);if(l){l.dataset.osVendor=t,l.dataset.loaded="1",s();return}e?.translations&&Ks(e.translations);for(const d of e?.l10n??[])Ks(d);for(const d of e?.before??[])Ks(d);const c=document.createElement("script");c.src=t,c.async=!0,c.dataset.osVendor=t,c.addEventListener("load",()=>{c.dataset.loaded="1";for(const d of e?.after??[])Ks(d);s()},{once:!0}),c.addEventListener("error",()=>{jr.delete(t),c.remove(),i(new Error(`Failed to load ${t}`))},{once:!0}),document.head.appendChild(c)});return jr.set(t,o),o}function Ks(t){if(!t)return;const e=document.createElement("script");e.textContent=t,e.dataset.osVendorInline="1",document.head.appendChild(e)}function IE(t){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}let hf=0;function mf(){return window.openStationItemVisibilityMenu??null}function CE(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function gf(t){const e=mf();if(e){e.openItemVisibilityMenu(t);return}const n=CE();if(!n)return;const o=++hf;ke(n).then(()=>{o===hf&&mf()?.openItemVisibilityMenu(t)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const We=class We{constructor(e,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=e,this.windowManager=n,this.items=o,this.adminUrl=s,this.orientation=i,this.rail=i==="bottom"?"taskbar":"dock",this.hooksNamespace=`desktop-mode/dock/${++We.instanceCounter}`,this.container.setAttribute("data-os-dock-placement",i);const r=document.createElement("div");r.className="os-dock__scroll";const a=document.createElement("div");a.className="os-dock__pinned",e.appendChild(r),e.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="os-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.render(),this.bindWindowEvents()}buildHookContextBase(){return{rail:this.rail,orientation:this.orientation,dockId:this.container.id,container:this.container}}setOrientation(e){this.orientation!==e&&(this.orientation=e,this.container.setAttribute("data-os-dock-placement",e),this.tooltip.classList.remove("os-dock__tooltip--above","os-dock__tooltip--before","os-dock__tooltip--after"),e==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):e==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"))}replaceItems(e){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=e;const n=this.buildHookContextBase();L(b.DOCK_BEFORE_RENDER,{...n,items:e,tileElements:this.itemElements});let o=!1,s=0;for(const i of e){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 a=this.badgeOverrides.get(i.id);if(a!==void 0){const c=r.querySelector(".os-dock__item-primary");wf(c??r,a)}const l=this.artOverrides.get(i.id);l&&this._paintArt(r,i.id,l),L(b.DOCK_TILE_RENDERED,{...n,item:i,isSystem:!1,el:r})}this.updateActiveStates(),L(b.DOCK_AFTER_RENDER,{...n,items:e,tileElements:this.itemElements})}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(e){const n=this.systemItemElements.get(e);n&&(n.remove(),this.systemItemElements.delete(e),this.systemItems=this.systemItems.filter(o=>o.id!==e),this.badgeOverrides.delete(e),this.artOverrides.delete(e),this.systemItemElements.size===0&&this.systemSeparator&&(this.systemSeparator.remove(),this.systemSeparator=null),L(b.DOCK_ITEM_REMOVED,{id:e,placement:this.rail}))}setBadge(e,n){const o=this._resolveTileElement(e);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(e):this.badgeOverrides.set(e,s);const i=o.querySelector(".os-dock__item-primary");wf(i??o,s),Ee.publish("os/badge-changed",{itemId:e,count:s,rail:this.rail})}clearBadge(e){this.setBadge(e,0)}setArt(e,n){if(!n){if(!this.artOverrides.delete(e))return;const s=this._resolveTileElement(e),i=this._declaredIcon(e);s&&i&&this._paintArt(s,e,i),Ee.publish("os/art-changed",{itemId:e,icon:"",rail:this.rail});return}this.artOverrides.set(e,n);const o=this._resolveTileElement(e);o&&(this._paintArt(o,e,n),Ee.publish("os/art-changed",{itemId:e,icon:n,rail:this.rail}))}_declaredIcon(e){const n=this.items.find(s=>s.id===e);if(n)return n.icon;const o=this.systemItems.find(s=>s.id===e);return o?o.icon:""}_paintArt(e,n,o){const s=e.querySelector(".os-dock__item-primary")??e,i=this.resolveIcon(o,this._declaredTitle(n),void 0,Bs(n)),r=s.querySelector(".os-dock__item-mask, .os-dock__item-svg, .dashicons, img");r?r.replaceWith(i):s.prepend(i)}_declaredTitle(e){const n=this.items.find(s=>s.id===e);if(n)return n.title;const o=this.systemItems.find(s=>s.id===e);return o?o.title:""}setAttention(e,n,o={}){const s=this._resolveTileElement(e);if(!s)return;const i=this.attentionTimers.get(e);if(i!==void 0&&(window.clearTimeout(i),this.attentionTimers.delete(e)),s.classList.remove("os-dock__item--attention-pulse","os-dock__item--attention-shake","os-dock__item--attention-bounce","os-dock__item--intensity-subtle","os-dock__item--intensity-normal","os-dock__item--intensity-strong"),n===null)return;s.classList.add(`os-dock__item--attention-${n}`);const r=o.intensity??"normal";s.classList.add(`os-dock__item--intensity-${r}`);const a=o.durationMs??4e3;if(a>0){const l=window.setTimeout(()=>{this.attentionTimers.delete(e),this.setAttention(e,null)},a);this.attentionTimers.set(e,l)}}_resolveTileElement(e){return this.itemElements.get(e)??this.systemItemElements.get(e)??null}appendSystemItem(e){this.systemItems.push(e),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 n=this.createSystemItemButton(e);this.systemItemElements.set(e.id,n);const o=this.artOverrides.get(e.id);o&&this._paintArt(n,e.id,o),this.systemHost.appendChild(n),this.updateActiveStates(),L(b.DOCK_TILE_RENDERED,{...this.buildHookContextBase(),item:e,isSystem:!0,el:n})}render(){if(We.activeDragReset){const o=We.activeDragReset;We.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="";const e=this.buildHookContextBase();L(b.DOCK_BEFORE_RENDER,{...e,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(b.DOCK_TILE_RENDERED,{...e,item:o,isSystem:!1,el:s})}L(b.DOCK_AFTER_RENDER,{...e,items:this.items,tileElements:this.itemElements})}createSystemItemButton(e){const n={...this.buildHookContextBase(),item:e,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=K(b.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=e.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",e.title),r.appendChild(this.resolveIcon(e.icon,e.title,void 0,Bs(e.id))),r.addEventListener("click",()=>e.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,e.title,n);const a=ff({tile:o,item:{id:e.id,title:e.title,icon:e.icon,url:""},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(e.id),enableGhost:!!e.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(e.onOpenNew??e.onOpen)()},suppressTooltip:l=>{l&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${e.id}`,a),K(b.DOCK_TILE_ELEMENT,o,n)}createItemButton(e){const n={...this.buildHookContextBase(),item:e,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];e.multi&&s.push("os-dock__item--multi");const i=K(b.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=e.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",e.title);const a=this.resolveIcon(e.icon,e.title,e.url,Bs(e.id));if(r.appendChild(a),e.badge>0){const d=e.badge>99?"99+":String(e.badge),u=document.createElement("span");u.className="os-dock__badge",u.textContent=d,u.setAttribute("aria-label",ae(Hn("%d update","%d updates",e.badge),e.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(e)}),o.addEventListener("contextmenu",d=>{d.preventDefault(),gf({x:d.clientX,y:d.clientY,id:e.id,title:e.title,surface:"dock",pluginFile:e.pluginFile??null,pluginName:e.pluginName??null})}),o.appendChild(r),this.bindTooltipFiltered(o,e.title,n);const l=this.resolveItemBaseId(e),c=ff({tile:o,item:{id:e.id,title:e.title,icon:e.icon,url:e.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(l),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(e),suppressTooltip:d=>{d&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(e.id,c),this.attachDragReorder(o,e.id),K(b.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(e,n){let i=!1,r=0,a=0,l=[],c=null,d=-1,u=null,f=!1;const p=()=>{i=!1,e.classList.remove("os-dock__item--dragging"),e.style.transform="",e.style.transition="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",N),document.removeEventListener("pointercancel",D),document.removeEventListener("keydown",O,!0),window.removeEventListener("blur",y),document.removeEventListener("visibilitychange",M),d=-1,u=null},m=T=>!!T&&T instanceof HTMLElement&&T.classList.contains("os-dock__item")&&!T.classList.contains("os-dock__item--system")&&!!T.dataset.menuSlug,g=T=>{for(const x of Array.from(this.itemHost.children))x instanceof HTMLElement&&x!==e&&m(x)&&T(x)},h=()=>{const T=[];for(const x of Array.from(this.itemHost.children))m(x)&&T.push(x.dataset.menuSlug);return T},w=T=>{g(x=>{const I=T.get(x);if(!I)return;const W=x.getBoundingClientRect(),z=I.left-W.left,A=I.top-W.top;if(Math.abs(z)<.5&&Math.abs(A)<.5)return;x.style.transition="none",x.style.transform=`translate(${z}px, ${A}px)`,x.offsetHeight,x.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",x.style.transform="";const P=()=>{x.style.transition="",x.style.transform="",x.removeEventListener("transitionend",P)};x.addEventListener("transitionend",P)})},v=T=>{if(d!==-1&&T.pointerId!==d)return;if(!i){const $=T.clientX-r,U=T.clientY-a;if($*$+U*U<5*5)return;i=!0,l=h(),c=e.nextSibling,u=e.getBoundingClientRect(),e.classList.add("os-dock__item--dragging"),this.tooltip.classList.remove("os-dock__tooltip--visible")}if(!u)return;const x=T.clientX-r,I=T.clientY-a;e.style.transform=`translate(${x}px, ${I}px)`;const z=document.elementFromPoint(T.clientX,T.clientY)?.closest(".os-dock__item");if(!z||z===e||!m(z))return;const A=z.getBoundingClientRect();let P;this.orientation==="bottom"?P=T.clientX<A.left+A.width/2:P=T.clientY<A.top+A.height/2;const B=new Map;g($=>{B.set($,$.getBoundingClientRect())});let C=!1;if(P?z!==e.nextSibling&&(this.itemHost.insertBefore(e,z),C=!0):z.nextSibling!==e&&(this.itemHost.insertBefore(e,z.nextSibling),C=!0),C){e.style.transform="";const $=e.getBoundingClientRect();r=$.left+$.width/2,a=$.top+$.height/2,e.style.transform=`translate(${T.clientX-r}px, ${T.clientY-a}px)`,w(B)}},R=()=>{e.classList.remove("os-dock__item--dragging"),e.style.transform="",e.style.transition="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",N),document.removeEventListener("pointercancel",D),document.removeEventListener("keydown",O,!0),window.removeEventListener("blur",y),document.removeEventListener("visibilitychange",M),d=-1,u=null,i=!1,We.activeDragReset===p&&(We.activeDragReset=null)},_=()=>{e.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",e.style.transform="";const T=()=>{e.style.transition="",e.removeEventListener("transitionend",T)};e.addEventListener("transitionend",T)},E=T=>{const x=window.wp?.os;if(!x?.getOsSettings||!x?.updateOsSettings)return;const I=x.getOsSettings().dockOrder,W=new Set(T),z=[];let A=!1;for(const P of I){if(W.has(P)){A||(z.push(...T),A=!0);continue}z.push(P)}A||z.push(...T),x.updateOsSettings({dockOrder:z})},N=T=>{if(d!==-1&&T.pointerId!==d)return;if(!i){R();return}f=!0;const x=h();_(),R(),x.length===l.length&&x.every((W,z)=>W===l[z])||E(x),setTimeout(()=>{f=!1},200)},D=T=>{if(!(T&&d!==-1&&T.pointerId!==d)){if(i&&c!==void 0){const x=new Map;g(I=>{x.set(I,I.getBoundingClientRect())}),this.itemHost.insertBefore(e,c),w(x)}_(),R()}},O=T=>{T.key==="Escape"&&D()},y=()=>D(),M=()=>{document.visibilityState!=="visible"&&D()};e.addEventListener("pointerdown",T=>{if(T.button===0){if(We.activeDragReset){const x=We.activeDragReset;We.activeDragReset=null,x()}(i||d!==-1)&&p(),r=T.clientX,a=T.clientY,d=T.pointerId,i=!1,We.activeDragReset=p,document.addEventListener("pointermove",v),document.addEventListener("pointerup",N),document.addEventListener("pointercancel",D),document.addEventListener("keydown",O,!0),window.addEventListener("blur",y),document.addEventListener("visibilitychange",M)}}),e.addEventListener("click",T=>{f&&(T.preventDefault(),T.stopImmediatePropagation())},!0)}resolveIcon(e,n,o,s){let i=!1,r=null;if(s){const a=$s(s);a!==null&&(e=a,i=!0),r=Dr(s)}if(r!==null&&!e.startsWith("dashicons-")){const a=this._makeMaskSpan();if(Us(a,e,r))return a}if(e.startsWith("dashicons-")&&(i||e!=="dashicons-admin-generic")){const a=document.createElement("span");return a.className=`dashicons ${e}`,a.setAttribute("aria-hidden","true"),r!==null&&(a.style.color=r),a}if(e.startsWith("data:image/svg+xml;base64,")){const a=e.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(a))return this._makeSvgIcon(e)}if(e.startsWith("url("))return this._makeSvgIcon(e);if(e.startsWith("http://")||e.startsWith("https://")){const a=document.createElement("img");return a.className="os-dock__item-img",a.src=e,a.alt="",a.setAttribute("aria-hidden","true"),a}if(o&&!i){const a=this._extractNativeMenuIcon(o);if(a)return a}if(e==="dashicons-admin-generic"){const a=document.createElement("span");return a.className="dashicons dashicons-admin-generic",a.setAttribute("aria-hidden","true"),a}return this.createLetterBadge(n)}_makeMaskSpan(){const e=document.createElement("span");return e.className="os-dock__item-mask",e.setAttribute("aria-hidden","true"),e.style.width="var( --os-dock-icon-size, 20px )",e.style.height="var( --os-dock-icon-size, 20px )",e.style.display="block",e.style.flexShrink="0",e}_makeSvgIcon(e){const n=/^url\(\s*(['"]?)(.+?)\1\s*\)$/.exec(e),o=n?n[2]:e,s=this._makeMaskSpan();if(Us(s,o,"currentColor"))return s;const i=document.createElement("span");return i.className="os-dock__item-svg",i.style.backgroundImage=e.startsWith("url(")?e:`url("${e}")`,i.style.backgroundSize="contain",i.style.backgroundRepeat="no-repeat",i.style.backgroundPosition="center",i.setAttribute("aria-hidden","true"),i}_extractNativeMenuIcon(e){const n=document.getElementById("adminmenu");if(!n)return null;let o;try{const f=new URL(e,window.location.href);o=(f.pathname.split("/").pop()||"")+f.search}catch{return null}if(!o)return null;const s=n.querySelectorAll("li.menu-top > a");let i=null;for(const f of Array.from(s))if(f.href.endsWith(o)){i=f.closest("li.menu-top");break}if(!i)return null;const r=i.querySelector(".wp-menu-image");if(!r)return null;const a=r.querySelector("img");if(a&&a.src){const f=document.createElement("img");return f.className="os-dock__item-img",f.src=a.src,f.alt="",f.setAttribute("aria-hidden","true"),f}const l=r.className.match(/\bdashicons-[\w-]+\b/);if(l&&l[0]!=="dashicons-before"){const f=document.createElement("span");return f.className=`dashicons ${l[0]}`,f.setAttribute("aria-hidden","true"),f}const d=window.getComputedStyle(r,"::before").backgroundImage;if(d&&d!=="none"&&!d.includes('url("")'))return this._makeSvgIcon(d);const u=window.getComputedStyle(r).backgroundImage;return u&&u!=="none"&&!u.includes('url("")')?this._makeSvgIcon(u):null}createLetterBadge(e){const n=document.createElement("span");n.className="os-dock__item-letter",n.setAttribute("aria-hidden","true");const o=e.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=Os(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(e,n,o){const s=K(b.DOCK_TILE_TOOLTIP,n,o);e.dataset.dockTooltip=s,s!==""&&(e.addEventListener("pointerenter",()=>{this.positionTooltip(e,s),this.tooltip.classList.add("os-dock__tooltip--visible")}),e.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("os-dock__tooltip--visible")}))}positionTooltip(e,n){const o=e.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(e){if(e.id.startsWith("dock:")){const o=e.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(qs(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(qs(e.url)||ct(e.url))return;const n=this.deriveWindowId(e.url);this.windowManager.open({id:n,baseId:n,url:e.url,parentUrl:e.url,title:e.title,icon:e.icon.startsWith("dashicons-")?e.icon:"dashicons-admin-generic",submenu:e.submenu,multi:!!e.multi})}openNewInstance(e){if(qs(e.url))return;const n=window.wp?.os?.openNewWindow;if(e.windowId&&!e.url&&n?.(e.windowId,{source:"dock-peek"}))return;const o=Pr(e.url);if(o&&n?.(o,{source:"dock-peek"}))return;const s=this.deriveWindowId(e.url);this.windowManager.openNew({id:s,baseId:s,url:e.url,parentUrl:e.url,title:e.title,icon:e.icon.startsWith("dashicons-")?e.icon:"dashicons-admin-generic",submenu:e.submenu,multi:!0})}deriveWindowId(e){return le(e,this.adminUrl)}resolveItemBaseId(e){if(e.windowId)return e.windowId;if(e.id.startsWith("dock:")){const o=e.id.slice(5),i=window.openStationConfig?.desktopIcons?.find(r=>r.id===o);if(i?.window)return i.window;if(i?.url)return Pr(i.url)??this.deriveWindowId(i.url)}return Pr(e.url)??this.deriveWindowId(e.url)}bindWindowEvents(){const e=()=>this.updateActiveStates();this.boundRefresh=e,document.addEventListener("os-window-opened",e),document.addEventListener("os-window-closed",e),document.addEventListener("os-window-focused",e),window.wp?.hooks?.addAction?.("os.os.switched",this.hooksNamespace,e),window.wp?.hooks?.addAction?.("os.os.closed",this.hooksNamespace,e),window.wp?.hooks?.addAction?.(b.WINDOW_MINIMIZED,this.hooksNamespace,e),window.wp?.hooks?.addAction?.(b.WINDOW_RESTORED,this.hooksNamespace,e),window.wp?.hooks?.addAction?.(b.DOCK_REFRESH_ACTIVE,this.hooksNamespace,e)}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?.(b.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(b.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(b.WINDOW_RESTORED,this.hooksNamespace);for(const e of this.attentionTimers.values())window.clearTimeout(e);this.attentionTimers.clear();for(const e of this.peekTeardowns.values())e();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 e=this.windowManager.getFocused(),n=this.windowManager.getActiveDesktopId(),o=i=>(i.config.desktopId||n)===n,s=i=>i.state==="minimized";for(const i of this.items){const r=this.itemElements.get(i.id);if(!r)continue;const a=this.resolveItemBaseId(i);let l=this.windowManager.getAllByBaseId(a).filter(o);if(l.length===0&&i.url){const f=this.deriveWindowId(i.url);l=this.windowManager.getAll().filter(p=>{const m=p.config.baseId||p.id;if(m===a||m===f||m===i.id)return!0;if(p.config.url){const g=this.deriveWindowId(p.config.url);return g===a||g===f}return!1}).filter(o)}const c=l.length>0,d=c&&l.every(s),u=!!e&&o(e)&&!s(e)&&l.some(f=>f.id===e.id||(e.config.baseId||e.id)===a);r.classList.toggle("os-dock__item--active",c),r.classList.toggle("os-dock__item--focused",u),r.classList.toggle("os-dock__item--all-minimized",d),r.classList.toggle("os-dock__item--stacked",c&&l.length>1)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const a=this.windowManager.getById(i.id),l=i.isOpen?i.isOpen():!!a,c=!!a&&s(a),d=!!e&&e.id===i.id&&!s(e);r.classList.toggle("os-dock__item--active",l),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",c)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const e=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||e)===e),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("os-show-desktop-active",o)}};We.instanceCounter=0,We.activeDragReset=null;let Ys=We;function wf(t,e){const n=t.querySelector(":scope > .os-dock__badge");if(e<=0){n?.remove();return}const o=e>99?"99+":String(e);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",ae(Hn("%d notification","%d notifications",e),e));return}const s=document.createElement("span");s.className="os-dock__badge",s.textContent=o,s.setAttribute("aria-label",ae(Hn("%d notification","%d notifications",e),e)),t.appendChild(s)}const yf=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),Vr={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(t){const e=new Ys(t.container,t.windowManager,t.items,t.adminUrl,t.orientation);return{[yf]:e,replaceItems:o=>e.replaceItems(o),appendSystemItem:o=>e.appendSystemItem(o),removeSystemItem:o=>e.removeSystemItem(o),setBadge:(o,s)=>e.setBadge(o,s),setAttention:(o,s,i)=>e.setAttention(o,s,i),setOrientation:o=>e.setOrientation(o),destroy:()=>e.destroy()}}};function Xs(t){if(!t)return null;const n=t[yf];return n instanceof Ys?n:null}function xE(){yu(Vr)}const bf="os-desktop-theme-css",LE="os-desktop-theme-inline-css",qr="data-os-desktop-theme-css",vf="os-desktop-theme-changed";function _f(){return document.getElementById("os-shell")}function Ef(){const t=[];for(const e of[bf,LE]){const n=document.getElementById(e);n&&t.push(n)}return document.querySelectorAll(`[${qr}]`).forEach(e=>{t.includes(e)||t.push(e)}),t}function kf(){for(const t of Ef())t.remove()}function TE(t){const e=_f();return!e||e.getAttribute("data-os-desktop-theme")!==t?!1:Ef().length>0}function Sf(t){const e=document.body;if(!e)return;const n=[];e.classList.forEach(o=>{o.startsWith("os-desktop-theme-")&&n.push(o)});for(const o of n)(t===null||o!==`os-desktop-theme-${t}`)&&e.classList.remove(o);t!==null&&e.classList.add(`os-desktop-theme-${t}`)}function Kr(t){const e=Ws(),n=e.state.activeId,o=typeof t=="string"?t.trim():"",s=o===""?null:Lu(o),i=s?s.slug:null;if(i===n)return;const r=_f();if(!s)r?.removeAttribute("data-os-desktop-theme"),Sf(null),kf(),e.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!TE(s.slug)){if(kf(),s.cssUrl!==""){const l=document.createElement("link");l.id=bf,l.rel="stylesheet",l.href=s.cssUrl,l.setAttribute(qr,s.slug),document.head.appendChild(l)}else if(s.cssText!==""){const l=document.createElement("style");l.setAttribute(qr,s.slug),l.textContent=s.cssText,document.head.appendChild(l)}}r?.setAttribute("data-os-desktop-theme",s.slug),Sf(s.slug),e.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};L(b.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(vf,{detail:a}))}function q(t,...e){return{__wpdHtml:!0,strings:t,values:e}}function NE(t){return!!t&&t.__wpdHtml===!0}const DE="$$wpd$$",Te=/\$\$wpd\$\$(\d+)\$\$/g;function RE(t){let e=t[0];for(let n=1;n<t.length;n++)e+=`${DE}${n-1}$$`+t[n];return e}const Af=new WeakMap;function If(t){const e=Af.get(t);if(e)return e;const n=document.createElement("template");n.innerHTML=RE(t);const o=[],s=(a,l)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const f of Array.from(u.attributes)){const p=f.name,m=f.value,g=p[0];if(Te.test(m))if(Te.lastIndex=0,g==="@"){const h=Te.exec(m);Te.lastIndex=0,o.push({path:l,kind:"event",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else if(g==="."){const h=Te.exec(m);Te.lastIndex=0,o.push({path:l,kind:"prop",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else if(g==="?"){const h=Te.exec(m);Te.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else{const h=[],w=[];let v=0,R;for(Te.lastIndex=0;(R=Te.exec(m))!==null;)h.push(m.slice(v,R.index)),w.push(Number(R[1])),v=R.index+R[0].length;h.push(m.slice(v)),o.push({path:l,kind:"attr",name:p,template:h,valueIndices:w}),u.setAttribute(p,"")}}}const c=Array.from(a.childNodes);let d=0;for(let u=0;u<c.length;u++){const f=c[u],p=u+d;if(f.nodeType===Node.TEXT_NODE){const m=f.textContent||"";if(!Te.test(m)){Te.lastIndex=0;continue}Te.lastIndex=0;const g=f.parentNode;let h=0,w;const v=[],R=[];for(Te.lastIndex=0;(w=Te.exec(m))!==null;){w.index>h&&v.push(document.createTextNode(m.slice(h,w.index)));const _=document.createTextNode("");v.push(_),R.push({path:[...l,p+v.length-1],kind:"node",valueIndex:Number(w[1])}),h=w.index+w[0].length}h<m.length&&v.push(document.createTextNode(m.slice(h)));for(const _ of v)g.insertBefore(_,f);g.removeChild(f),d+=v.length-1,o.push(...R)}else s(f,[...l,p])}};s(n.content,[]);const r={template:n,buildParts:a=>{const l=[];for(const c of o){let d=a;for(const u of c.path)d=d.childNodes[u];c.kind==="node"?l.push({kind:"node",valueIndex:c.valueIndex,child:{anchor:d,state:null}}):c.kind==="attr"?l.push({kind:"attr",element:d,name:c.name,template:c.template,valueIndices:c.valueIndices}):c.kind==="event"?l.push({kind:"event",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="prop"?l.push({kind:"prop",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="bool"&&l.push({kind:"bool",valueIndex:c.valueIndex,element:d,name:c.name})}return l}};return Af.set(t,r),r}const Cf=new WeakMap;function OE(t,e){for(const n of t.nodes)if(n.parentNode!==e)return!1;return!0}function ME(t,e){const n=Cf.get(e);if(n&&n.strings===t.strings&&OE(n,e)){Zs(n.parts,t.values);return}const o=If(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(s),Zs(i,t.values),Cf.set(e,{strings:t.strings,parts:i,nodes:r})}function Zs(t,e){for(const n of t)if(n.kind==="node")Yr(n.child,e[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;s<n.valueIndices.length;s++)o+=xf(e[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=e[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=e[n.valueIndex];o!==n.last&&(n.last=o,n.element[n.name]=o)}else if(n.kind==="bool"){const o=!!e[n.valueIndex];o!==n.last&&(n.last=o,o?n.element.setAttribute(n.name,""):n.element.removeAttribute(n.name))}}function Yr(t,e){if(e==null||e===!1){t.state&&(Pt(t.state),t.state=null);return}if(Array.isArray(e)){UE(t,e);return}if(NE(e)){$E(t,e);return}if(e instanceof Node){PE(t,e);return}WE(t,xf(e))}function PE(t,e){const n=t.state;n?.shape==="node"&&n.node===e||(n&&Pt(n),Js(t,[e]),t.state={shape:"node",node:e})}function WE(t,e){const n=t.state;if(n?.shape==="text"){n.text!==e&&(n.node.textContent=e,n.text=e);return}n&&Pt(n);const o=document.createTextNode(e);Js(t,[o]),t.state={shape:"text",node:o,text:e}}function $E(t,e){const n=t.state;if(n?.shape==="template"&&n.strings===e.strings){Zs(n.parts,e.values);return}n&&Pt(n);const o=If(e.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);Js(t,[s]),Zs(i,e.values),t.state={shape:"template",strings:e.strings,parts:i,nodes:r}}function UE(t,e){const n=t.state;if(n?.shape==="array"&&n.entries.length===e.length){for(let s=0;s<e.length;s++)Yr(n.entries[s],e[s]);return}n&&Pt(n);const o=[];for(const s of e){const i=document.createTextNode("");Js(t,[i]);const r={anchor:i,state:null};Yr(r,s),o.push(r)}t.state={shape:"array",entries:o}}function Js(t,e){const n=t.anchor.parentNode;if(n)for(const o of e)n.insertBefore(o,t.anchor)}function Pt(t){if(t.shape==="text"){t.node.remove();return}if(t.shape==="template"){for(const e of t.parts)e.kind==="node"&&e.child.state&&(Pt(e.child.state),e.child.state=null);for(const e of t.nodes)e.parentNode&&e.parentNode.removeChild(e);return}if(t.shape==="node"){t.node.parentNode&&t.node.parentNode.removeChild(t.node);return}for(const e of t.entries)e.state&&Pt(e.state),e.anchor.remove()}function xf(t){return t==null||t===!1?"":String(t)}const Lt=class Lt 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(Lf)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(e,n,o){if(n===o)return;const s=FE(e);this._propValues[s]=o,this.requestUpdate()}get classNames(){return Array.from(this.classList)}set classNames(e){if(e==null){this.removeAttribute("class");return}const o=(Array.isArray(e)?e:String(e).split(/\s+/)).map(s=>String(s).trim()).filter(s=>s!=="");this.className=o.join(" ")}requestUpdate(){this._scheduleRender()}emit(e,n){return this.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,composed:!0}))}_installPropAccessors(){const e=this.constructor;for(const n of e.props){if(Object.getOwnPropertyDescriptor(this,n))continue;const o=Lf(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&&ME(this.render(),this._renderRoot)}))}_adoptStyles(){const e=this.constructor;if(e.styles.length!==0)if(e.shadow&&this.shadowRoot){const n=e.styles.map(o=>o.sheet).filter(o=>o!==null);if(this.shadowRoot.adoptedStyleSheets=n,n.length!==e.styles.length){for(const o of e.styles)if(!o.sheet){const s=document.createElement("style");s.textContent=o.cssText,this.shadowRoot.appendChild(s)}}}else this._adoptLightStyles(e)}_adoptLightStyles(e){if(!Lt._lightStylesAdopted.has(e)){Lt._lightStylesAdopted.add(e);for(const n of e.styles){const o=document.createElement("style");o.dataset.osUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};Lt.props=[],Lt.styles=[],Lt.shadow=!0,Lt._lightStylesAdopted=new WeakSet;let be=Lt;function Se(t,e){customElements.get(t)||customElements.define(t,e)}function Lf(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function FE(t){return t.replace(/-([a-z])/g,(e,n)=>n.toUpperCase())}const BE=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function re(t,...e){let n=t[0];for(let o=1;o<t.length;o++){const s=e[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+=t[o]}if(BE){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function HE(t){const e=[],n=[];let o=null,s=t.parentElement;for(;s&&!(s===document.body||s===document.documentElement);){const r=s.id||"";if(r.startsWith("wp-window-")){o=r.slice(10);break}if(s.tagName.toLowerCase()==="os-tabpanel"){const a=s.getAttribute("for");a&&n.unshift(a)}s=s.parentElement}o&&e.push(Xr(o));for(const r of n)e.push("tab-"+Xr(r));const i=t.getAttribute("label");return i&&e.push(Xr(i)),e.length===0?"os-unnamed":"os-"+e.filter(r=>r!=="").join("-")}function Xr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Tf(t){if(t.id)return t.id;const e=HE(t);return t.id=e,e}const tt=re`: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 ) )}`,zE=re` .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%}}`,Zr=re` .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%}}`,Nf=re` .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}}`,Df=re` .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}}`,Rf=re` .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}}`,Of=re` .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%}}`,GE=re` .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}}`,Jr=re` 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}}`,jE=re` 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-position 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-image:var( --_holo-fill );background-size:220% 220%;background-position:22% 28%;box-shadow:var( --_holo-glow )}input[ type='checkbox' ]:checked:hover:not(:disabled ),input[ type='radio' ]:checked:hover:not(:disabled ){background-position:74% 66%}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( --_holo-ink );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( --_holo-ink );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( --_holo-ink );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}}`,Mf=re` @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}}`;re` ${tt} ${zE} ${Zr} ${Nf} ${Df} ${Rf} ${Of} ${GE} ${Jr} ${jE} ${Mf} `;const VE=re` ${tt}: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}`,Pf='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',as=class as extends be{constructor(){super(...arguments),this._prevFocus=null,this._onKey=e=>{if(e.key==="Escape"&&!this.hasAttribute("mandatory")){e.preventDefault(),this._cancel();return}if(e.key==="Tab"){const n=this._focusables();if(n.length===0)return;const o=n[0],s=n[n.length-1],i=this.ownerDocument,r=i?i.activeElement:null,a=e.composedPath()[0]||r;e.shiftKey&&a===o?(e.preventDefault(),s.focus()):!e.shiftKey&&a===s&&(e.preventDefault(),o.focus())}},this._onBackdrop=e=>{if(this.hasAttribute("mandatory"))return;const n=e.composedPath();(n.length>0?n[0]:e.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(e,n,o){if(super.attributeChangedCallback?.(e,n,o),e==="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 e=this.shadowRoot;if(!e)return[];const n=Array.from(this.querySelectorAll(Pf)),o=Array.from(e.querySelectorAll(Pf));return[...n,...o].filter(s=>s.offsetParent!==null||s.tagName==="BUTTON")}_focusFirst(){const e=this._focusables();e.length>0?e[0].focus():this.shadowRoot?.querySelector(".dialog")?.focus?.()}_cancel(){const e=new CustomEvent("os-modal-cancel",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(e)&&this.hideModal()}render(){const e=this.getAttribute("title")??"",n=this.hasAttribute("mandatory");return q` |
| 2 |
<div part="dialog" class="dialog" tabindex="-1"> |
| 3 |
${e?q` |
| 4 |
<div class="header"> |
| 5 |
<h2 class="title">${e}</h2> |
| 6 |
<div class="header-actions"> |
| 7 |
<slot name="header-actions"></slot> |
| 8 |
${n?q``:q`<button |
| 9 |
type="button" |
| 10 |
class="close" |
| 11 |
aria-label="Close" |
| 12 |
@click=${()=>this._cancel()} |
| 13 |
>×</button>`} |
| 14 |
</div> |
| 15 |
</div> |
| 16 |
`:q``} |
| 17 |
<div class="body"> |
| 18 |
<slot></slot> |
| 19 |
</div> |
| 20 |
<div class="footer"> |
| 21 |
<slot name="footer"></slot> |
| 22 |
</div> |
| 23 |
</div> |
| 24 |
`}};as.props=["open","title","size","mandatory"],as.styles=[VE],as.help=void 0;let Qr=as;Se("os-modal",Qr);const qE=re` ${tt} ${Zr} ${Nf} ${Df} ${Rf} ${Mf}: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 )}}`,ls=class ls extends be{render(){const e=this.disabled!==null,n=this.busy!==null,o=this.type||"button";return q` |
| 25 |
<button |
| 26 |
part="button" |
| 27 |
class="os-holo-edge os-holo-sheen" |
| 28 |
type=${o} |
| 29 |
?disabled=${e||n} |
| 30 |
aria-busy=${n?"true":"false"} |
| 31 |
> |
| 32 |
${n?q`<span class="os-button__spinner" aria-hidden="true"></span>`:""} |
| 33 |
<slot></slot> |
| 34 |
<!-- |
| 35 |
The two motion layers. Elements rather than |
| 36 |
pseudo-elements because the sheen and the hairline |
| 37 |
have already taken this button's ::before and |
| 38 |
::after — see the pseudo-element budget note in |
| 39 |
src/ui/holo.ts. Both are inert and aria-hidden. |
| 40 |
--> |
| 41 |
<span class="os-holo-glint" aria-hidden="true"></span> |
| 42 |
<span class="os-holo-ring" aria-hidden="true"></span> |
| 43 |
</button> |
| 44 |
`}};ls.props=["variant","disabled","type","busy","fill-cell"],ls.styles=[qE],ls.help=void 0;let ea=ls;Se("os-button",ea);function Wf(t){const{from:e,to:n,angle:o}=t.customGradient;return`linear-gradient(${o}deg, ${e}, ${n})`}const KE=()=>k("Mix your own two-colour gradient and set the angle — your desk, your palette.");function YE(t){to({id:zv,label:k("Custom gradient"),type:"css",preview:Wf(t.state),description:KE(),resolveValue:()=>Wf(t.state)})}function XE(t){if(!t.customImage){Ju(vu);return}const n=`url("${encodeURI(t.customImage.url)}") center/cover no-repeat, #1d2327`;to({id:vu,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 Qs=null;function ZE(t){return window.openStationRenderOsSettingsPanel?Promise.resolve(window.openStationRenderOsSettingsPanel):Qs||(Qs=new Promise((e,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}e(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=t,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)}),Qs)}class JE{constructor(e,n){this.activeEditorTeardown=null,this.tabRegistryUnsubscribe=null,this.activeTabId=null,this.osSettingsListeners=new Set,this._lastRenderedBody=null,this.config=e,this.layer=n,this.state=Z_(),sE(this.state),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))}),YE(this),XE(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,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(([e,n])=>[e,{...n}]))}}subscribeOsSettings(e){return this.osSettingsListeners.add(e),()=>{this.osSettingsListeners.delete(e)}}apply(){const e=document.getElementById("os-shell");if(!e)return;j_(this.state.wallpaperSettings);const n=Fr(this.state.wallpaper)||Fr(Eu())||Fr(Cr)||ef()[0];n&&this.layer.apply(n);const o=xr(),s=o.find(c=>c.id===this.state.accent)??o[0],i=Lr.find(c=>c.id===this.state.dockSize)??Lr[1],r=Tr.find(c=>c.id===this.state.windowRadius)??Tr[1],a=document.body;a.style.setProperty("--wp-admin-theme-color",s.value),a.style.setProperty("--os-dock-width",`${i.width}px`),a.style.setProperty("--os-dock-icon-size",`${i.icon}px`),a.style.setProperty("--os-window-radius",`${r.value}px`),e.style.setProperty("--os-window-radius",`${r.value}px`);const l=Ps.find(c=>c.id===this.state.adminBarMode)??Ps[0];for(const c of Ps)document.body.classList.toggle(`os-admin-bar-${c.id}`,c.id===l.id);e.setAttribute("data-os-layout",this.state.desktopLayout),Hv(this.state.dockRailRenderer),Kr(this.state.desktopTheme)}save(e={}){if(iE(this.state,e),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(e){this.activeTabId=e;const n=this._lastRenderedBody;if(!n?.isConnected)return;const o=n.querySelector("os-tabs");o&&(o.value=e)}renderPanel(e){this._lastRenderedBody=e;const n=window.openStationRenderOsSettingsPanel;if(n){n(this,e);return}ZE(this.config.osSettingsPanelBundleUrl??"").then(o=>{e.isConnected&&o(this,e)}).catch(o=>{typeof console<"u"&&console.error("[openstation] OpenStation Preferences panel failed to load:",o)})}}const QE="os-exit";function ek(){return{id:QE,title:k("Exit OpenStation"),icon:"dashicons-exit",onOpen:()=>{tk()}}}async function tk(){const t=window.openStationAdminBar,e=t?.classicUrl||"/wp-admin/";if(!t?.ajaxUrl||!t?.nonce){$f(e);return}const n=new URLSearchParams;n.set("action","save-openstation"),n.set("nonce",t.nonce),n.set("enabled","");let o=e;try{const s=await fetch(t.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{}$f(o)}function $f(t){try{window.top.location.href=t}catch{window.location.href=t}}const nk={userId:null,requestedAt:0,tabRequested:!1};let ei=null;function ok(){if(ei)return ei;const e=window.wp?.os?.createSharedStore;return typeof e!="function"?null:(ei=e("desktop-mode/user-edit/target",()=>({...nk})),ei)}function sk(t){const e=ok();if(e){e.state.userId=t,e.state.requestedAt=Date.now(),e.state.tabRequested=!0,e.notify();return}const n=window;n._wpdUserEditTarget={userId:t,requestedAt:Date.now(),tabRequested:!0}}let ti=null;function ik(){if(ti)return ti;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(ti=t("desktop-mode/comments/post-filter",()=>({postId:0})),ti)}function Uf(t){const e=ik();e&&(e.state.postId=t,e.notify())}function rk(){Uf(0)}const ni=new Map;function Ff(t){if(!t||typeof t.id!="string"||t.id===""){typeof console<"u"&&console.warn("[openstation] Ignored invalid module registration:",t);return}if(typeof t.url!="string"||t.url===""){typeof console<"u"&&console.warn(`[openstation] Module "${t.id}" has no url; ignored.`);return}ni.set(t.id,t)}function ak(){return Array.from(ni.keys())}async function Bf(t){if(!t||t.length===0)return;const e=t.filter(n=>!ni.has(n));if(e.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${e.map(n=>`"${n}"`).join(", ")}. Known modules: ${ak().join(", ")||"(none)"}.`);await Promise.all(t.map(n=>{const o=ni.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():ke(o.url)}))}function Hf(t,e){return{id:t,pluginUrl:e,prefersReducedMotion:lk(),visible:!document.hidden,settings:G_(t)}}function lk(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class zf{constructor(e,n){this.generation=0,this.active=null,this.suspendReasons=new Map,this.freezeOverlay=null,this.frozenCanvas=null,this.boundVisibilityChange=()=>{this.emitEffectiveVisibility()},this.element=e,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(e){const n=++this.generation;if(this.teardownActive(),e.type==="css"){this.applyCss(e);return}this.applyCanvas(e,n)}suspend(e){const n=this.isSuspended();this.suspendReasons.set(e,(this.suspendReasons.get(e)??0)+1),!n&&(this.installFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}resume(e){const n=this.suspendReasons.get(e);if(n!==void 0){if(n>1){this.suspendReasons.set(e,n-1);return}this.suspendReasons.delete(e),!this.isSuspended()&&(this.removeFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}}isSuspended(){return this.suspendReasons.size>0}teardownActive(){if(this.removeFreezeOverlay(),!this.active)return;const{id:e,teardown:n}=this.active;this.active=null,L(b.WALLPAPER_UNMOUNTING,{id:e});try{n()}catch(o){L(b.SHELL_ERROR,{scope:"wallpaper-teardown",id:e,error:o}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${e}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(e){const n=e.resolveValue?e.resolveValue(Hf(e.id,this.pluginUrl)):e.value;typeof n=="string"&&(this.element.style.setProperty("--os-bg",n),document.getElementById("os-shell")?.style.setProperty("--os-bg",n))}applyCanvas(e,n){const o=Hf(e.id,this.pluginUrl);L(b.WALLPAPER_MOUNTING,{id:e.id,container:this.element,ctx:o});const s=e.needs&&e.needs.length>0?Bf(e.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:e.id,teardown:r},L(b.WALLPAPER_MOUNTED,{id:e.id,container:this.element,ctx:o}),this.isEffectivelyHidden()&&this.emitEffectiveVisibility()};s.then(()=>{if(n!==this.generation)return;let r;try{r=e.mount(this.element,o)}catch(a){this.handleMountFailure(e.id,a);return}if(ck(r)){r.then(i,a=>{n===this.generation&&this.handleMountFailure(e.id,a)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(e.id,r)})}isEffectivelyHidden(){return document.hidden||this.isSuspended()}emitEffectiveVisibility(){this.active&&L(b.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){L(b.WALLPAPER_SUSPEND,{id:this.active?.id??null,suspended:this.isSuspended(),reasons:Array.from(this.suspendReasons.keys())})}installFreezeOverlay(){if(this.freezeOverlay||!this.active)return;const e=this.element.querySelector("canvas");if(!(!e||e.width===0||e.height===0))try{const n=document.createElement("canvas");n.width=e.width,n.height=e.height;const o=n.getContext("2d");if(!o)return;o.drawImage(e,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),e.style.visibility="hidden",this.freezeOverlay=n,this.frozenCanvas=e}catch{}}removeFreezeOverlay(){this.freezeOverlay?.remove(),this.freezeOverlay=null,this.frozenCanvas&&(this.frozenCanvas.style.visibility="",this.frozenCanvas=null)}handleMountFailure(e,n){this.element.innerHTML="",L(b.WALLPAPER_MOUNT_FAILED,{id:e,error:n}),L(b.SHELL_ERROR,{scope:"wallpaper-mount",id:e,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${e}" failed to mount:`,n)}}function ck(t){return!!t&&typeof t=="object"&&typeof t.then=="function"}function dk(t){const{osSettings:e}=t,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await ke(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter})}catch(d){L(b.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},a=async c=>{if(n.has(c.id))return;const d=r(c);if(d){to(d),n.add(c.id),e.apply();return}await s(c);let u=i(c.id);if(u&&!u.description&&c.description&&(u={...u,description:c.description}),!u){L(b.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{to(u)}catch(f){L(b.SHELL_ERROR,{scope:"wallpaper-register",id:c.id,error:f});return}n.add(c.id),e.apply()},l=c=>{n.has(c)&&(Ju(c),n.delete(c),e.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)||l(u);for(const u of c)n.has(u.id)||await a(u)}}const Gf=ie("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),ln=Gf.state.seed,ta=Gf.state.listeners;function na(t){Re("Game",Dt(t,Kf),t);const e=ln.findIndex(n=>n.id===t.id);e>=0?ln[e]=t:ln.push(t),Vf()}function jf(t){const e=ln.findIndex(n=>n.id===t);e>=0&&(ln.splice(e,1),Vf())}function uk(t){return ta.add(t),()=>{ta.delete(t)}}function Vf(){const t=Array.from(ta);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function qf(){const t=ln.slice(),e=K(b.GAMES,t);return Array.isArray(e)?e.filter(fk):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),t)}function oi(t){return qf().find(e=>e.id===t)}const Kf=[{field:"id",message:"missing or not a non-empty string",valid:t=>typeof t.id=="string"&&t.id!==""},{field:"title",message:"missing or not a non-empty string",valid:t=>typeof t.title=="string"&&t.title!==""},{field:"scoreColumns",message:"must be an array",valid:t=>Array.isArray(t.scoreColumns)},{field:"render/scriptUrl",message:"needs a `render` callback or a `scriptUrl` to lazily load one",valid:t=>typeof t.render=="function"||typeof t.scriptUrl=="string"&&t.scriptUrl!==""}];function fk(t){return Dt(t,Kf).length===0}function pk(t){return{id:t.id,title:t.title,icon:t.icon,description:t.description||void 0,scoreColumns:Array.isArray(t.scoreColumns)?t.scoreColumns:[],config:t.config??{},scriptUrl:t.scriptUrl,scriptTranslations:t.scriptTranslations,scriptL10n:t.scriptL10n,scriptBefore:t.scriptBefore,scriptAfter:t.scriptAfter}}function hk(){const t=new Set,e=o=>{try{const s=oi(o.id),i=pk(o);na(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}t.add(o.id)},n=o=>{t.has(o)&&(jf(o),t.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(t))s.has(i)||n(i);for(const i of o)s.has(i.id)&&e(i)}}function mk(t={}){const e=t.deactivate??(()=>Kr(""));return function(o){Zv(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=Ws().getState();s!==null&&(i.some(r=>r.slug===s)||e())}}const si=new Map,oa=new Map;let Yf=!1;const Ae={contribute(t,e){return si.set(t,e),()=>{si.get(t)===e&&si.delete(t)}},subscribe(t,e){let n=oa.get(t);return n||(n=new Set,oa.set(t,n)),n.add(e),()=>{n.delete(e)}}};function gk(){if(Yf)return;Yf=!0;const t=window.jQuery;if(!t){console.warn("[desktop-mode/heartbeat] jQuery missing — Heartbeat bus disabled.");return}t(document).on("heartbeat-send",(...e)=>{const n=e[1];if(n)for(const[o,s]of si)try{n[o]=s()}catch(i){console.error(`[desktop-mode/heartbeat] supplier for "${o}" threw:`,i)}}),t(document).on("heartbeat-tick",(...e)=>{const n=e[1];if(n)for(const[o,s]of oa){const i=n[o];if(i!==void 0)for(const r of s)try{r(i)}catch(a){console.error(`[desktop-mode/heartbeat] subscriber for "${o}" threw:`,a)}}})}let ii=null,ri={installHintDismissed:!1,notificationsEnabled:!1};const sa=new Set;function Xf(t){if(!t){ii=null;return}ii=t,ri={...t.state},Jf()}function oo(){return{...ri}}function ia(t){if(ri={...ri,...t},Jf(),!ii)return oo();const e=JSON.stringify(t),n=wk();return fetch(ii.stateUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",...n?{"X-WP-Nonce":n}:{}},body:e}).catch(o=>{typeof console<"u"&&console.warn("[openstation] pwa-state write failed:",o)}),oo()}function Zf(t){return sa.add(t),()=>{sa.delete(t)}}function Jf(){const t=oo();for(const e of Array.from(sa))try{e(t)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function wk(){return window.openStationConfig?.restNonce??""}const yk=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:oo,initPwaState:Xf,subscribePwaState:Zf,updatePwaState:ia},Symbol.toStringTag,{value:"Module"}));function ra(t){const e=Ee.filter("os/notification-requested",{...t});if(!e||e.cancel===!0||!e.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=Z({message:e.body?e.title+" — "+e.body:e.title}),Ee.publish("os/notification-shown",{...e,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=Qf(e),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){ia({notificationsEnabled:!0}),o=Qf(e),o||r();return}r()}}),i)}function Qf(t){let e=null;try{e=new Notification(t.title,{body:t.body,icon:t.icon,tag:t.tag,requireInteraction:t.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[openstation] Notification ctor threw:",n),null}if(t.onClick){const n=t.onClick;e.onclick=()=>{try{n(e)}catch(o){typeof console<"u"&&console.error("[openstation] notification onClick threw:",o)}}}return Ee.publish("os/notification-shown",{...t,fallback:null}),()=>{e&&e.close()}}async function bk(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const t=await Notification.requestPermission();return t==="granted"&&ia({notificationsEnabled:!0}),t}function vk(){return typeof Notification>"u"?"unsupported":Notification.permission}const cn=ie("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function _k(){return cn.state}function aa(t){const e=cn.state;let n=!1;for(const o of t){if(!o||typeof o.id!="number")continue;const s=e.rows.get(o.id);(!s||s.updatedAtMs!==o.updatedAtMs)&&(e.rows.set(o.id,o),n=!0),o.updatedAtMs>e.version&&(e.version=o.updatedAtMs)}n&&kk()}function Ek(t){return cn.state.listeners.add(t),()=>{cn.state.listeners.delete(t)}}function kk(){for(const t of Array.from(cn.state.listeners))try{t()}catch(e){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",e)}}function Sk(){return Array.from(cn.state.rows.values()).sort((t,e)=>e.updatedAtMs-t.updatedAtMs)}const Ak="http://localhost/";function nt(t,e){const n=typeof window<"u"&&window.location?window.location.href:Ak,o=new URL(t,n),s=e.replace(/^\/+/,""),i=s.indexOf("?"),r=i===-1?s:s.slice(0,i),a=i===-1?"":s.slice(i+1);if(o.searchParams.has("rest_route")){const l=o.searchParams.get("rest_route")??"/",c=l.endsWith("/")?l:l+"/";o.searchParams.set("rest_route",c+r)}else{const l=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=l+r}return a&&new URLSearchParams(a).forEach((c,d)=>{o.searchParams.append(d,c)}),o.toString()}const Ik="desktop-mode/games";function Ck(){const e=window.wp?.os?.config;return{restUrl:e?.restUrl||"/wp-json/",restNonce:e?.restNonce||""}}async function so(t,e={},n={}){const{restUrl:o,restNonce:s}=Ck(),i=new Headers(e.headers??{});i.set("X-WP-Nonce",s),e.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Fe(nt(o,t),{...e,headers:i,credentials:"same-origin"},{source:Ik,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok){const l=a?.message||`Games request failed (${r.status})`,c=new Error(l);throw c.status=r.status,c}return a}function xk(t,e,n={}){return so(`desktop-mode/v1/games/${t}/scores`,{method:"POST",body:JSON.stringify({score:e.score,meta:e.meta??{}})},n)}function Lk(){return so("desktop-mode/v1/games/playtime")}function Tk(t,e,n={}){return so(`desktop-mode/v1/games/${t}/playtime`,{method:"POST",body:JSON.stringify({seconds:e})},n)}function Nk(t){return so(`desktop-mode/v1/games/challenges/${t}/accept`,{method:"POST"})}function Dk(t,e,n={}){return so(`desktop-mode/v1/games/challenges/${t}/complete`,{method:"POST",body:JSON.stringify({score:e.score,meta:e.meta??{}})},n)}const Rk=6e4;function Ok(t,e={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const l=Date.now();o+=Math.max(0,l-n),n=l},r=()=>{i();const l=Math.floor(o/1e3);l<1||(o-=l*1e3,Tk(t,l,{windowId:e.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,Rk);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}function ep(){return window.wp?.os??{}}const Mk=760,Pk=560,Wk=480,$k=380;async function Uk(t){if(typeof t.render=="function")return t;const e=ep().loadVendorScript;if(!t.scriptUrl||typeof e!="function")throw new Error(`[openstation] Game "${t.id}" has no render callback and no loadable script.`);await e(t.scriptUrl,{translations:t.scriptTranslations,l10n:t.scriptL10n,before:t.scriptBefore,after:t.scriptAfter});const o=window.openStationGames?.[t.id];if(!o||typeof o.render!="function")throw new Error(`[openstation] No game def on window.openStationGames["${t.id}"]. Script loaded but didn't publish a def — check the plugin's global assignment.`);const s={...t,render:o.render,window:o.window??t.window};return na(s),s}async function tp(t,e={}){const n=ep();let o=oi(t);if(!o)throw new Error(`[openstation] Unknown game "${t}".`);o=await Uk(o);const s=o.render;if(typeof s!="function")throw new Error(`[openstation] Game "${t}" 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-${t}`,r=`game:${i}`,a=n.windowManager,l=a?.getByBaseId?.(i)??a?.getById(i);if(l){const g=l.config?.desktopId;g&&a?.switchDesktop&&g!==a?.getActiveDesktopId?.()&&a.switchDesktop(g),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=(g,h)=>{n.activity?.publish("os/game-score-recorded",{game:t,score:g.score,meta:g.meta??{},windowId:i,challengeId:h})},m=g=>{if(e.challenge){const h=e.challenge.id;return Dk(h,g,{windowId:i}).then(({challenge:w})=>{aa([w]),p(g,h)})}return xk(t,g,{windowId:i}).then(()=>p(g))};try{await n.registerWindow({id:i,title:o.title,icon:o.icon,width:o.window?.width??Mk,height:o.window?.height??Pk,minWidth:o.window?.minWidth??Wk,minHeight:o.window?.minHeight??$k,render:g=>{const h={windowId:i,container:g,config:o.config??{},challenge:e.challenge,submitScore:m,close:()=>{n.windowManager?.getById(i)?.close()}};u=Ok(t,{windowId:i});const w=s(h);return()=>{try{w?.()}finally{f(),d()}}}})}catch(g){throw f(),d(),g}}function Fk(t){return oi(t)?.title||t}const np=new Set,op=new Set;async function Bk(t){const{challenge:e}=await Nk(t.id);aa([e]),await tp(t.game,{challenge:{id:t.id,scoreToBeat:t.scoreToBeat,scoreMeta:t.scoreMeta,challengerName:t.challengerName}})}function Hk(t){const e=ae(k("%1$s challenged you to %2$s — beat %3$s!"),t.challengerName,Fk(t.game),String(t.scoreToBeat));ra({title:k("Game challenge"),body:e,tag:`os-game-challenge-${t.id}`}),Z({message:e,persistent:!0,dismissible:!0,action:{label:k("Accept & Play"),onClick:()=>{Bk(t).catch(n=>{Z({message:n instanceof Error?n.message:k("Could not accept the challenge.")})})}}})}function zk(t){let e;t.result==="beaten"?e=k("%1$s beat your score: %2$s vs your %3$s."):e=k("%1$s did not beat your score: %2$s vs your %3$s.");const n=ae(e,t.recipientName,String(t.resultScore??0),String(t.scoreToBeat));ra({title:k("Challenge finished"),body:n,tag:`os-game-challenge-${t.id}`}),Z({message:n})}function Gk(t){const{currentUserId:e}=t;if(!e)return;Ae.contribute("openstation_games_subscribe",()=>({challengesVersion:_k().version})),Ae.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&aa(o.challenges)});const n=()=>{for(const o of Sk())o.state==="pending"&&o.recipientId===e&&!np.has(o.id)&&(np.add(o.id),Hk(o)),o.state==="completed"&&o.challengerId===e&&!op.has(o.id)&&(op.add(o.id),zk(o))};Ek(n),n()}const sp=/^[a-z0-9_/-]+$/,ip=ie("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),Wt=ip.state.registry,jk=ip.state.listeners;function ai(t){const e=[],n=typeof t?.slug=="string"?t.slug.trim().toLowerCase():"";!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.slug!="string"||t.slug.trim()===""?e.push("slug (missing)"):sp.test(n)||e.push(`slug (must match ${sp} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),typeof t.run!="function"&&e.push("run (must be a function)")),Re("Command",e,t),Wt.set(n,{...t,slug:n}),la()}function rp(t){Wt.delete(t.toLowerCase())&&la()}function li(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(Wt.entries()))o.owner===t&&(Wt.delete(n),e++);return e>0&&la(),e}function ap(){return Array.from(Wt.values())}function Vk(){const t=[];for(const e of Wt.values())e.aiCallable===!0&&t.push({slug:e.slug,label:e.label,description:e.description??"",hint:e.hint??""});return t}function qk(t){return Wt.get(t.toLowerCase())??null}function la(){const t=Array.from(jk);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function Kk(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(b.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.slug)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.slug)}return a},i=r=>{const a=new Set;for(const c of ap())c.owner===r&&a.add(c.slug);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(t))if(!l.has(c)){for(const d of i(c))rp(d);t.delete(c)}for(const c of r)!c.handle||t.has(c.handle)||await o(c);n=s(a)}}const lp=ie("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),io=lp.state.registry,Yk=lp.state.listeners;function cp(t){if(!t||typeof t.id!="string"||t.id.trim()===""||typeof t.label!="string"||t.label.trim()===""||typeof t.render!="function")return;const e=t.id.trim().toLowerCase();if(!/^[a-z0-9_\-]+$/.test(e)){typeof console<"u"&&console.warn("[openstation] registerSettingsTab: id must be [a-z0-9_-]+, got",t.id);return}io.set(e,{...t,id:e}),ca()}function dp(t){io.delete(t.toLowerCase())&&ca()}function Xk(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(io.entries()))o.owner===t&&(io.delete(n),e++);return e>0&&ca(),e}function up(){return Array.from(io.values()).sort((t,e)=>(t.order??100)-(e.order??100))}function ca(){const t=Array.from(Yk);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function Zk(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(b.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{Xk(r);const a=n.get(r);if(a){const l=new Set(up().map(c=>c.id));for(const c of a)l.has(c)&&dp(c)}};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(t))l.has(c)||(i(c),t.delete(c));for(const c of r)!c.handle||t.has(c.handle)||await o(c);n=s(a)}}const fp=ie("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),ro=fp.state.registry,Jk=fp.state.listeners,pp=/^[a-z0-9_/-]+$/;function ci(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):pp.test(t.id.trim().toLowerCase())||e.push(`id (must match ${pp} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),(typeof t.icon!="string"||t.icon.trim()==="")&&e.push("icon (missing)"),typeof t.match!="function"&&e.push("match (must be a function)"),typeof t.onClick!="function"&&typeof t.render!="function"&&e.push("onClick|render (at least one must be a function)")),Re("TitleBarButton",e,t);const n=t.id.trim().toLowerCase();ro.set(n,{...t,id:n}),da()}function Qk(t){ro.delete(t.toLowerCase())&&da()}function e0(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(ro.entries()))o.owner===t&&(ro.delete(n),e++);return e>0&&da(),e}function t0(){return Array.from(ro.values()).sort((t,e)=>(t.order??100)-(e.order??100))}function da(){const t=Array.from(Jk);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] title-bar-button registry listener threw:",n)}}function n0(){const t=new Set,e=new Set,n=async o=>{if(!o.scriptUrl||e.has(o.scriptUrl)){t.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(b.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}e.add(o.scriptUrl),t.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(t))s.has(i)||(e0(i),t.delete(i));for(const i of o)!i.handle||t.has(i.handle)||await n(i)}}const dn="none",ua="svg-splines",hp=ie("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),ao=hp.state.registry,fa=hp.state.listeners,mp=/^[a-z0-9_/-]+$/;function gp(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):mp.test(t.id.trim().toLowerCase())?t.id.trim().toLowerCase()===dn&&e.push('id ("none" is reserved)'):e.push(`id (must match ${mp} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),typeof t.mount!="function"&&e.push("mount (not a function)")),Re("WindowLinkRenderer",e,t);const n=t.id.trim().toLowerCase();ao.set(n,{...t,id:n}),ha()}function o0(t){ao.delete(t.toLowerCase())&&ha()}function s0(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(ao.entries()))o.owner===t&&(ao.delete(n),e++);return e>0&&ha(),e}function wp(){const t=Array.from(ao.values()),e=K(b.WINDOW_LINK_RENDERERS,t);return Array.isArray(e)?e:(typeof console<"u"&&console.warn("[openstation] `os.window-links.renderers` filter returned a non-array; falling back to registry list."),t)}function pa(t){return wp().find(e=>e.id===t)}function i0(t){return fa.add(t),()=>{fa.delete(t)}}function ha(){const t=Array.from(fa);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}const r0=16;function a0(t,e){const n=e.map(i=>({start:Math.max(t.start,i.start),end:Math.min(t.end,i.end)})).filter(i=>i.end>i.start).sort((i,r)=>i.start-r.start),o=[];let s=t.start;for(const i of n)i.start>s&&o.push({start:s,end:i.start}),s=Math.max(s,i.end);return s<t.end&&o.push({start:s,end:t.end}),o}function l0(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,i=e.y-o;if(s===0&&i===0)return{x:n,y:o,side:"right"};const r=s!==0?t.width/2/Math.abs(s):1/0,a=i!==0?t.height/2/Math.abs(i):1/0,l=Math.min(r,a),c=n+s*l,d=o+i*l;let u;return r<=a?u=s>0?"right":"left":u=i>0?"bottom":"top",{x:c,y:d,side:u}}function yp(t,e,n,o){for(const s of n)if(!(s.windowId===o||s.zIndex<=e)&&t.x>=s.rect.x&&t.x<=s.rect.x+s.rect.width&&t.y>=s.rect.y&&t.y<=s.rect.y+s.rect.height)return!1;return!0}function c0(t,e,n,o,s){const i=n.filter(c=>c.windowId!==o&&c.zIndex>e),r=[{side:"top",base:{start:t.x,end:t.x+t.width},at:t.y,horizontal:!0},{side:"bottom",base:{start:t.x,end:t.x+t.width},at:t.y+t.height,horizontal:!0},{side:"left",base:{start:t.y,end:t.y+t.height},at:t.x,horizontal:!1},{side:"right",base:{start:t.y,end:t.y+t.height},at:t.x+t.width,horizontal:!1}];let a=null,l=1/0;for(const{side:c,base:d,at:u,horizontal:f}of r){const p=[];for(const{rect:m}of i)(f?m.y<=u&&u<=m.y+m.height:m.x<=u&&u<=m.x+m.width)&&p.push(f?{start:m.x,end:m.x+m.width}:{start:m.y,end:m.y+m.height});for(const m of a0(d,p)){if(m.end-m.start<r0)continue;const g=(m.start+m.end)/2,h=f?g:u,w=f?u:g,v=Math.hypot(s.x-h,s.y-w);v<l&&(l=v,a={x:h,y:w,side:c})}}return a}function d0(t,e){const n=Math.max(e.x-(t.x+t.width),t.x-(e.x+e.width)),o=Math.max(e.y-(t.y+t.height),t.y-(e.y+e.height));if(n<0&&o<0)return null;const s=Math.max(t.x,e.x),i=Math.min(t.x+t.width,e.x+e.width),r=Math.max(t.y,e.y),a=Math.min(t.y+t.height,e.y+e.height);let l,c;i>=s?l=c=(s+i)/2:e.x>t.x?(l=t.x+t.width,c=e.x):(l=t.x,c=e.x+e.width);let d,u;a>=r?d=u=(r+a)/2:e.y>t.y?(d=t.y+t.height,u=e.y):(d=t.y,u=e.y+e.height);const f=n>=o,p=(m,g,h)=>f?g<=m.x?"left":"right":h<=m.y?"top":"bottom";return{from:{x:l,y:d,side:p(t,l,d)},to:{x:c,y:u,side:p(e,c,u)}}}function bp(t,e){const n=Math.min(160,Math.max(24,.4*e));switch(t.side){case"left":return{x:t.x-n,y:t.y};case"right":return{x:t.x+n,y:t.y};case"top":return{x:t.x,y:t.y-n};default:return{x:t.x,y:t.y+n}}}function u0(t){return{x:t.x+t.width/2,y:t.y+t.height/2}}const un="http://www.w3.org/2000/svg";let f0=0;function vp(t,e,n,o,s){const i=l0(t,s);return e===null||yp(i,e,o,n)?i:c0(t,e,o,n,s)??i}function p0(t,e){const n=document.createElementNS(un,"defs"),o=(a,l,c)=>{const d=`${e}-${a}`,u=document.createElementNS(un,"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(un,"circle");return f.setAttribute("cx","5"),f.setAttribute("cy","5"),f.setAttribute("r","4"),f.classList.add(l),u.appendChild(f),n.appendChild(u),d},s="os-window-link__endpoint",i=`${s}--active`,r={dot:{normal:o("dot",s,"7"),active:o("dot-active",i,"7")},port:{normal:o("port",s,"4.5"),active:o("port-active",i,"4.5")}};return t.appendChild(n),r}gp({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:t=>{const e=++f0,n=(a,l)=>{const c=document.createElementNS(un,"svg");return c.classList.add("os-window-links__svg"),a.appendChild(c),{svg:c,markers:p0(c,`os-window-link-${e}${l}`)}},o={base:n(t.container,""),elevated:n(t.elevatedContainer,"-elevated")},s=new Map,i=a=>{for(const{svg:c}of[o.base,o.elevated])c.setAttribute("width",String(a.container.width)),c.setAttribute("height",String(a.container.height)),c.setAttribute("viewBox",`0 0 ${a.container.width} ${a.container.height}`);const l=new Set;for(const c of a.edges){if(!c.from||!c.to)continue;const d=`${c.fromWindowId}→${c.toWindowId}:${c.kind}`;l.add(d);const u=c.elevated?"elevated":"base";let f=s.get(d);if(f&&f.surface!==u&&(f.group.remove(),s.delete(d),f=void 0),!f){const D=document.createElementNS(un,"g");D.classList.add("os-window-link");const O=document.createElementNS(un,"path");O.classList.add("os-window-link__path"),D.appendChild(O),o[u].svg.appendChild(D),f={group:D,path:O,surface:u},s.set(d,f)}const p=a.obstacles??[],m=d0(c.from,c.to),g=(D,O,y)=>O===null||yp(D,O,p,y);let h=null;m&&g(m.from,c.fromZIndex,c.fromWindowId)&&(h=m.from),h||(h=vp(c.from,c.fromZIndex,c.fromWindowId,p,m?{x:m.to.x,y:m.to.y}:u0(c.to)));let w=null;m&&g(m.to,c.toZIndex,c.toWindowId)&&(w=m.to),w||(w=vp(c.to,c.toZIndex,c.toWindowId,p,{x:h.x,y:h.y}));const v=Math.hypot(w.x-h.x,w.y-h.y),R=bp(h,v),_=bp(w,v);f.path.setAttribute("d",`M ${h.x} ${h.y} C ${R.x} ${R.y}, ${_.x} ${_.y}, ${w.x} ${w.y}`);const E=o[f.surface].markers,N=c.focused?"active":"normal";f.path.setAttribute("marker-end",`url(#${E.dot[N]})`),f.path.setAttribute("marker-start",`url(#${c.bidirectional?E.dot[N]:E.port[N]})`),f.group.classList.toggle("os-window-link--active",c.focused)}for(const[c,d]of Array.from(s))l.has(c)||(d.group.remove(),s.delete(c))},r=t.onFrame(i);return i(t.getFrame()),()=>{r(),s.clear(),o.base.svg.remove(),o.elevated.svg.remove()}}});const _p="os-window-links",Ep="os-window--linked",kp="os-window-links--visible";let Sp=!1;function h0({manager:t,osSettings:e}){if(Sp)return;Sp=!0;let n=e.getOsSettingsSnapshot(),o=null,s=null,i=null,r=null,a=0;const l=new Set;let c=!1;const d=new Set;let u=!1;const f=x=>{const I=x.element;return!I||!I.isConnected||x.state==="minimized"||I.offsetParent===null?null:{x:I.offsetLeft,y:I.offsetTop,width:I.offsetWidth,height:I.offsetHeight}},p=x=>x.state==="snapped-left"||x.state==="snapped-right"?null:f(x),m=()=>{const x=[];for(const P of Gs()){if(P.rootWindowIds.length===0||P.children.length===0)continue;const B=[],C=($,U,G)=>{const F=t.getById($);!F||!G||B.push({windowId:$,role:U,content:G,rect:p(F),focused:F.isFocused(),state:F.state})};for(const $ of P.rootWindowIds)C($,"root",dt($));for(const $ of P.children)C($.windowId,"child",$.content);B.length>0&&x.push({key:P.key,root:P.root,members:B})}const I=P=>{const B=Number.parseInt(P.element?.style.zIndex||"",10);return Number.isFinite(B)?B:null},W=t.getFocused()?.id??null,z=[];for(const P of eo()){const B=t.getById(P.fromWindowId),C=t.getById(P.toWindowId);if(!B||!C)continue;const $=B.isFocused()||C.isFocused();z.push({fromWindowId:P.fromWindowId,toWindowId:P.toWindowId,kind:P.kind,bidirectional:P.bidirectional,focused:$,from:p(B),to:p(C),fromZIndex:I(B),toZIndex:I(C),elevated:W!==null&&(P.fromWindowId===W||P.toWindowId===W)})}const A=[];for(const P of t.getAll()){const B=f(P);B&&A.push({windowId:P.id,rect:B,zIndex:I(P)??0})}return{groups:x,edges:z,obstacles:A,container:{width:o?.offsetWidth??0,height:o?.offsetHeight??0}}},g=()=>{c||l.size===0||(c=!0,requestAnimationFrame(()=>{if(c=!1,!i)return;const x=m();for(const I of Array.from(l))try{I(x)}catch(W){typeof console<"u"&&console.error("[openstation] window-link frame subscriber threw:",W)}}))},h=()=>{if(o&&o.isConnected&&s?.isConnected)return o;const x=document.getElementById("os-area");if(!x)return null;o=document.createElement("div"),o.id=_p,o.className="os-window-links",o.setAttribute("aria-hidden","true"),s=document.createElement("div"),s.id=`${_p}-elevated`,s.className="os-window-links os-window-links--elevated",s.setAttribute("aria-hidden","true");const I=document.getElementById("os-widgets");return I&&I.parentElement===x?(I.insertAdjacentElement("afterend",s),I.insertAdjacentElement("afterend",o)):x.prepend(o,s),o},w=()=>eo().length>0,v=()=>{let x=n.windowLinkRenderer||ua;return x=K(b.WINDOW_LINK_RENDERER,x),x===dn?dn:pa(x)?x:pa(ua)?ua:dn},R=()=>{if(a++,l.clear(),c=!1,r){try{r()}catch(x){L(b.SHELL_ERROR,{scope:"window-link-renderer-teardown",error:x})}r=null}i=null,o?.replaceChildren(),s?.replaceChildren()},_=x=>{const I=pa(x),W=h();if(!I||!W||!s)return;i=x;const z=++a,A={container:W,elevatedContainer:s,getFrame:m,onFrame:P=>(l.add(P),()=>{l.delete(P)})};try{const P=I.mount(A);P instanceof Promise?P.then(B=>{if(z!==a){typeof B=="function"&&B();return}typeof B=="function"&&(r=B)}).catch(B=>{L(b.SHELL_ERROR,{scope:"window-link-renderer-mount",error:B}),z===a&&(i=null)}):typeof P=="function"&&(r=P)}catch(P){L(b.SHELL_ERROR,{scope:"window-link-renderer-mount",error:P}),i=null}g()},E=()=>{const x=t.getFocused();return x?new Set(Yu(x.id)):new Set},N=()=>n.windowLinksEnabled!==!1,D=()=>{if(!o)return;const x=!u&&N()&&(n.windowLinkVisibility==="always"||n.windowLinkVisibility==="focus"&&E().size>0);o.classList.toggle(kp,x),s?.classList.toggle(kp,x)},O=()=>{if(!N()||n.windowLinkRaiseOnFocus===!1||n.windowLinkVisibility==="off")return;const x=t.getFocused();if(x)for(const I of O_(x.id)){const W=t.getById(I);W&&W.state!=="minimized"&&t.raise(I)}},y=()=>{if(!s)return;const x=t.getFocused(),I=E();if(!x||I.size===0||!N()||n.windowLinkVisibility==="off"){s.style.zIndex="";return}let W=-1/0;for(const z of[x.id,...I]){const A=t.getById(z),P=A?.element;if(!P||A.state==="minimized")continue;const B=Number.parseInt(P.style.zIndex||"",10);Number.isFinite(B)&&(W=Math.max(W,B))}s.style.zIndex=Number.isFinite(W)?String(W):""},M=()=>{const x=N()&&n.windowLinkHighlight!==!1&&n.windowLinkVisibility!=="off"?E():new Set;for(const I of d)x.has(I)||t.getById(I)?.element?.classList.remove(Ep);for(const I of x)t.getById(I)?.element?.classList.add(Ep);d.clear();for(const I of x)d.add(I)},T=()=>{const x=N()&&n.windowLinkVisibility!=="off"&&w()?v():dn;x===dn?i&&R():x!==i&&(R(),_(x)),D(),M(),y(),g()};X(b.WINDOW_BOUNDS_CHANGED,"desktop-mode/window-links-frame",()=>g());for(const x of[b.WINDOW_MOVED,b.WINDOW_RESIZED,b.WINDOW_MINIMIZED,b.WINDOW_RESTORED,b.WINDOW_MAXIMIZED,b.WINDOW_UNMAXIMIZED,b.WINDOW_FULLSCREEN_ENTERED,b.WINDOW_FULLSCREEN_EXITED,b.SNAP_ZONE_COMMITTED,b.SNAP_SPLIT_FILLED,b.DESKTOP_SWITCHED,b.SHELL_RESIZED])X(x,"desktop-mode/window-links-frame",()=>g());X(b.WINDOW_FOCUSED,"desktop-mode/window-links-focus",()=>{O(),D(),M(),y(),g()}),X(b.WINDOW_BLURRED,"desktop-mode/window-links-blur",()=>{D(),M(),y(),g()}),X(b.OVERVIEW_ENTERING,"desktop-mode/window-links-overview",()=>{u=!0,D()}),X(b.OVERVIEW_EXITED,"desktop-mode/window-links-overview",()=>{u=!1,D(),g()}),Xu(T),i0(T),e.subscribeOsSettings(x=>{const I=x.windowLinkRenderer!==n.windowLinkRenderer,W=I||x.windowLinkVisibility!==n.windowLinkVisibility||x.windowLinksEnabled!==n.windowLinksEnabled||x.windowLinkRaiseOnFocus!==n.windowLinkRaiseOnFocus||x.windowLinkHighlight!==n.windowLinkHighlight;n=x,W&&(I&&i&&R(),T())}),T()}function Ap(t){return t==="comments"?0:t.startsWith("terms/")?1:t==="media"?2:t==="links"?3:4}function m0({items:t,onPick:e}){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 t){const a=o.get(r.group);a?a.push(r):o.set(r.group,[r])}const s=Array.from(o.entries()).sort((r,a)=>Ap(r[0])-Ap(a[0])),i=[];for(const[,r]of s){const a=r.find(l=>typeof l.groupLabel=="string"&&l.groupLabel!=="")?.groupLabel;if(a){const l=document.createElement("div");l.className="os-window__related-group",l.setAttribute("role","presentation"),l.textContent=a,n.appendChild(l)}for(const l of r){const c=document.createElement("os-menu-item");c.setAttribute("role","menuitem"),c.setAttribute("value",l.id),c.tabIndex=-1,l.icon&&c.setAttribute("icon",l.icon),c.classList.add("os-window__related-item"),c.textContent=typeof l.count=="number"?`${l.label} (${l.count})`:l.label,c.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),e(l)}),i.push(c),n.appendChild(c)}}return n.addEventListener("keydown",r=>{const a=r,l=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const c=a.key==="ArrowDown";let d=i[c?0:i.length-1];l!==-1&&(d=i[(l+(c?1:-1)+i.length)%i.length]),d?.focus()}else if(a.key==="Home"||a.key==="End")a.preventDefault(),a.stopPropagation(),i[a.key==="Home"?0:i.length-1]?.focus();else if(a.key==="Enter"||a.key===" "){const c=i[l];c&&(a.preventDefault(),a.stopPropagation(),c.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function Ip(t){if(!t||typeof t!="object")return!1;const e=t,n=o=>typeof o=="string"&&o.trim()!=="";return n(e.id)&&n(e.group)&&n(e.label)&&n(e.url)&&(e.groupLabel===void 0||typeof e.groupLabel=="string")&&(e.icon===void 0||typeof e.icon=="string")&&(e.count===void 0||typeof e.count=="number"&&Number.isFinite(e.count))}function Cp(t){const e=dt(t)??null,n=e&&Array.isArray(e.related)?e.related.map(s=>({...s})):[],o=K(b.RELATED_ENTITIES_ITEMS,n,{windowId:t,content:e});return Array.isArray(o)?o.filter(Ip):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(Ip))}function ma(t){t?.querySelectorAll(".os-window__related-panel").forEach(e=>{e._wpdRelatedClose?e._wpdRelatedClose():e.remove()})}function g0(t){const e=n=>{n.stopImmediatePropagation()};t.addEventListener("dblclick",e,!0),setTimeout(()=>{t.removeEventListener("dblclick",e,!0)},500)}function w0(t,e,n){const o=t.closest(".os-window__titlebar");if(!o)return;const s=Cp(e.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",a),l.remove(),t.setAttribute("aria-expanded","false")},a=c=>{c.key==="Escape"&&(c.stopPropagation(),r(),t.focus())},l=m0({items:s,onPick:c=>{r(),g0(o),n(c)}});l._wpdRelatedClose=r,o.appendChild(l),o.addEventListener("keydown",a),t.setAttribute("aria-expanded","true"),i=c=>{const d=c.target;!d||l.contains(d)||t.contains(d)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),l.querySelector('[role="menuitem"]')?.focus()}function y0({manager:t,openUrl:e}){ci({id:"desktop-mode/related-entities",label:k("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>Cp(n.id).length>0,render:(n,o)=>{ma(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")){ma(o.element);return}w0(n,o,e)})}}),X(b.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=t.getById(n.windowId);o&&(ma(o.element),o.renderCustomTitleBarButtons?.())})}const ga="os-broadcast",xp="os-broadcast",Lp=window.location.origin;let wa=null;function b0(t){wa=t}function ya(t,e){const n=String(K("os.broadcast.topic",t,{payload:e})??t),o=K("os.broadcast.payload",e,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(ga,{detail:s})),L(b.BROADCAST,s),Ee.publish(n,o),!wa)return;const i={type:xp,topic:n,payload:o};for(const r of wa._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Lp)}catch{}}}function fn(t,e){const n=o=>{const s=o.detail;if(s&&!(t!=="*"&&s.topic!==t))try{e(s.payload,{topic:s.topic})}catch(i){L(b.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(ga,n),()=>document.removeEventListener(ga,n)}function v0(){window.addEventListener("message",t=>{if(t.origin!==Lp)return;const e=t.data;!e||e.type!==xp||e._fromParent||typeof e.topic=="string"&&ya(e.topic,e.payload)})}const _0=new Set(["saved","no-editor","not-dirty","error"]);let Tp=0;function Np(t){if(!(typeof t!="string"||t===""))try{return new URL(t,window.location.origin).origin===window.location.origin?t:void 0}catch{return}}function E0(t,{timeoutMs:e=1e4}={}){const n=t.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Tp+=1;const o=`os-editor-preview-${Date.now()}-${Tp}`;return new Promise(s=>{let i=null,r=!1;const a=c=>{r||(r=!0,window.removeEventListener("message",l),i!==null&&window.clearTimeout(i),s(c))},l=c=>{if(c.origin!==window.location.origin)return;const d=c?.data;if(!d||typeof d!="object"||d.type!=="os-editor-autosave-response"||d.requestId!==o)return;const u=typeof d.status=="string"&&_0.has(d.status)?d.status:"error",f=Np(d.previewUrl);a(f?{status:u,previewUrl:f}:{status:u})};window.addEventListener("message",l),i=window.setTimeout(()=>a({status:"timeout"}),e);try{n.postMessage({type:"os-editor-autosave-request",requestId:o},window.location.origin)}catch{a({status:"no-editor"})}})}const Oe=ie("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),k0=400,Dp=1500;function lo(t){return t?`${t.type}:${t.id}`:""}function S0(t){for(const e of Oe.state.pairings.values())if(e.previewWindowId===t)return e}function A0(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function I0(t){const e=t.getCurrentUrl?.()??"";if(!e)return!1;try{return new URL(e,window.location.origin).pathname.endsWith("/post-new.php")}catch{return!1}}function di(t,e,n,o){Oe.state.pairings.delete(e.editorWindowId),e.reloadTimer!==null&&(window.clearTimeout(e.reloadTimer),e.reloadTimer=null);try{e.unsubscribe()}catch{}if(Op(t,e),o!=="none"){const i=t.getById(e.previewWindowId);i&&(o==="destroy"?i.destroy?.():i.close?.())}const s={editorWindowId:e.editorWindowId,previewWindowId:e.previewWindowId,reason:n};document.dispatchEvent(new CustomEvent("os-editor-preview-closed",{detail:s})),L(b.EDITOR_PREVIEW_CLOSED,s),t.getById(e.editorWindowId)?.renderCustomTitleBarButtons?.()}function ba(t,e,n){e.reloadTimer!==null&&window.clearTimeout(e.reloadTimer),e.reloadTimer=window.setTimeout(()=>{e.reloadTimer=null;const o=t.getById(e.previewWindowId);if(!o)return;const s=n||dt(e.editorWindowId)?.previewUrl,i=s&&s!==e.openUrl?s:void 0;typeof o.swapReload=="function"?(i&&(e.openUrl=i),o.swapReload(i)):i&&o.navigateTo?(e.openUrl=i,o.navigateTo(i)):o.reload?.()},k0)}function C0(t,e,n){const o=`os.${n.type}.changed`,s=String(n.id);e.unsubscribe=fn(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||ba(t,e)})}let Rp=0;function Op(t,e){if(!e.watchId)return;const n=t.getById(e.editorWindowId);try{n?.iframe?.contentWindow?.postMessage({type:"os-editor-live-unwatch",watchId:e.watchId},window.location.origin)}catch{}e.watchId=""}function Mp(t,e,n){Op(t,e);const o=K(b.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:Dp},{editorWindowId:e.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=t.getById(e.editorWindowId)?.iframe?.contentWindow;if(!s)return;Rp+=1;const i=`${e.previewWindowId}-watch-${Rp}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:Dp},window.location.origin),e.watchId=i}catch{}}let x0=E0;async function L0(t,e){const n=Oe.state.pairings.get(e.id);if(n){di(t,n,"toggled","close");return}if(Oe.state.busyEditors.has(e.id)||!t.getById(e.id))return;const o=dt(e.id);if(!o?.previewUrl){Z({message:k("No preview is available for this content.")});return}Oe.state.busyEditors.add(e.id),e.renderCustomTitleBarButtons?.();const s=A0();s||e.applySnap?.("left");const i=x0(e);i.then(f=>{f.status==="error"&&Z({message:k("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{Oe.state.busyEditors.delete(e.id),t.getById(e.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=k("Preview");o.label&&(a=ae(k("Preview: %s"),o.label));let l={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=K(b.EDITOR_PREVIEW_WINDOW_CONFIG,l,{editorWindowId:e.id,content:o});if(c&&typeof c=="object"&&typeof c.id=="string"&&c.id!==""&&typeof c.url=="string"&&c.url!==""?l=c:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await t.open(l),!t.getById(e.id)||lo(dt(e.id))!==lo(o)){t.getById(l.id)?.destroy?.();return}const d={editorWindowId:e.id,previewWindowId:l.id,postKey:lo(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};C0(t,d,o),Mp(t,d,o),Oe.state.pairings.set(e.id,d);const u={editorWindowId:e.id,previewWindowId:l.id,content:o};document.dispatchEvent(new CustomEvent("os-editor-preview-opened",{detail:u})),L(b.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Oe.state.pairings.get(e.id)===d&&f.status==="saved"&&ba(t,d,f.previewUrl)})}function T0({manager:t}){ci({id:"desktop-mode/editor-preview",label:k("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:e=>!e.config.native&&(!!dt(e.id)?.previewUrl||I0(e)),render:(e,n)=>{if(!dt(n.id)?.previewUrl){const i=k("Save the post to enable its preview");e.setAttribute("aria-disabled","true"),e.setAttribute("aria-label",i),e.setAttribute("title",i),e.classList.add("os-window__btn--disabled"),e.addEventListener("click",r=>{r.stopPropagation(),Z({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);e.setAttribute("aria-pressed",String(o)),s&&(e.setAttribute("aria-busy","true"),e.classList.add("os-window__btn--busy")),e.addEventListener("click",i=>{i.stopPropagation(),L0(t,n)})}}),X(b.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",e=>{if(!e?.windowId)return;const n=Oe.state.pairings.get(e.windowId);n&&lo(e.content)!==n.postKey&&di(t,n,"content-changed","close"),t.getById(e.windowId)?.renderCustomTitleBarButtons?.()}),X(b.WINDOW_CLOSED,"desktop-mode/editor-preview",e=>{if(!e?.windowId)return;const n=Oe.state.pairings.get(e.windowId);if(n){di(t,n,"editor-closed","destroy");return}const o=S0(e.windowId);o&&di(t,o,"preview-closed","none")}),X(b.IFRAME_READY,"desktop-mode/editor-preview",e=>{if(!e?.windowId)return;const n=Oe.state.pairings.get(e.windowId);if(n){const o=dt(e.windowId);o&&lo(o)===n.postKey&&Mp(t,n,o)}t.getById(e.windowId)?.renderCustomTitleBarButtons?.()}),window.addEventListener("message",e=>{if(e.origin!==window.location.origin)return;const n=e?.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){ba(t,o,Np(n.previewUrl));return}}})}const Pp="none",Wp=ie("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),co=Wp.state.registry,va=Wp.state.listeners,$p=/^[a-z0-9_/-]+$/;function ui(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):$p.test(t.id.trim().toLowerCase())?t.id.trim().toLowerCase()===Pp&&e.push('id ("none" is reserved)'):e.push(`id (must match ${$p} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),typeof t.className!="string"&&typeof t.apply!="function"&&e.push("className|apply (at least one must be provided — a CSS class to toggle or an apply callback)")),Re("UnfocusEffect",e,t);const n=t.id.trim().toLowerCase();co.set(n,{...t,id:n}),Ea()}function N0(t){co.delete(t.toLowerCase())&&Ea()}function D0(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(co.entries()))o.owner===t&&(co.delete(n),e++);return e>0&&Ea(),e}function _a(){const t=Array.from(co.values()),e=K(b.UNFOCUS_EFFECTS,t);return Array.isArray(e)?e:(typeof console<"u"&&console.warn("[openstation] `os.unfocus-effects` filter returned a non-array; falling back to registry list."),t)}function Up(t){return _a().find(e=>e.id===t)}function R0(t){return va.add(t),()=>{va.delete(t)}}function Ea(){const t=Array.from(va);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}ui({id:"darken",label:k("Darken"),description:k("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),ui({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"}),ui({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 O0(){const t=new Set,e=new Set,n=async o=>{if(!o.scriptUrl||e.has(o.scriptUrl)){t.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(b.SHELL_ERROR,{scope:"unfocus-effect-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}e.add(o.scriptUrl),t.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(t))s.has(i)||(D0(i),t.delete(i));for(const i of o)!i.handle||t.has(i.handle)||await n(i)}}function M0(){const t=new Set,e=new Set,n=async o=>{if(!o.scriptUrl||e.has(o.scriptUrl)){t.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(b.SHELL_ERROR,{scope:"window-link-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}e.add(o.scriptUrl),t.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(t))s.has(i)||(s0(i),t.delete(i));for(const i of o)!i.handle||t.has(i.handle)||await n(i)}}const ka="data-desktop-unfocus-effect",Sa="data-desktop-unfocus-effect-class";let Fp=!1;function P0(t){return t.querySelector("canvas")!==null}function W0({manager:t,osSettings:e}){if(Fp)return;Fp=!0;let n=e.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(Sa);l&&(r.classList.remove(l),r.removeAttribute(Sa));const c=r.getAttribute(ka);c&&Up(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(ka)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Sa,a.className)),r.setAttribute(ka,a.id),a.apply?.(r)},i=()=>{const r=n===Pp?void 0:Up(n),a=_a();for(const l of t.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(P0(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());e.subscribeOsSettings(r=>{n=r.unfocusEffect,i()}),R0(()=>i()),i()}function $0(){const t=new Set,e=new Set,n=async o=>{if(!o.scriptUrl||e.has(o.scriptUrl)){t.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(b.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}e.add(o.scriptUrl),t.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(t))s.has(i)||($v(i),t.delete(i));for(const i of o)!i.handle||t.has(i.handle)||await n(i)}}const Bp=ie("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),uo=Bp.state.registry,U0=Bp.state.listeners,Hp=/^[a-z0-9_/-]+$/;function zp(t){const e=[];if(!t||typeof t!="object")e.push("def (not an object)");else{if(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):Hp.test(t.id.trim().toLowerCase())||e.push(`id (must match ${Hp} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!t.tokens||typeof t.tokens!="object")e.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(t.tokens))if(!o.startsWith("--")){e.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof t.match!="function"&&e.push("match (must be a function)")}Re("WindowTheme",e,t);const n=t.id.trim().toLowerCase();uo.set(n,{...t,id:n}),Aa()}function Gp(t){uo.delete(t.toLowerCase())&&Aa()}function F0(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(uo.entries()))o.owner===t&&(uo.delete(n),e++);return e>0&&Aa(),e}function jp(){return Array.from(uo.values()).sort((t,e)=>(t.priority??100)-(e.priority??100))}function Aa(){const t=Array.from(U0);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function B0(){const t=new Set,e=new Set;let n=new Map;const o=new Set,s=async l=>{if(!l.scriptUrl||e.has(l.scriptUrl)){t.add(l.handle);return}try{await ke(l.scriptUrl,{translations:l.scriptTranslations,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){L(b.SHELL_ERROR,{scope:"window-theme-script-load",handle:l.handle,url:l.scriptUrl,error:c});return}e.add(l.scriptUrl),t.add(l.handle)},i=l=>{const c=new Map;if(!l)return c;for(const d of l){if(!d.scriptHandle||!d.id)continue;let u=c.get(d.scriptHandle);u||(u=new Set,c.set(d.scriptHandle,u)),u.add(d.id)}return c},r=l=>{const c=new Set;for(const u of jp())u.owner===l&&c.add(u.id);const d=n.get(l);if(d)for(const u of d)c.add(u);return c},a=l=>{if(l){for(const c of l)if(!(!c.id||!c.tokens))try{zp({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(b.SHELL_ERROR,{scope:"window-theme-shell-register",id:c.id,error:d})}}};return async(l,c)=>{const d=new Set;for(const u of l)u.handle&&d.add(u.handle);for(const u of Array.from(t)){if(d.has(u))continue;const f=r(u);for(const p of f)Gp(p),o.delete(p);F0(u),t.delete(u)}a(c);for(const u of l)!u.handle||t.has(u.handle)||await s(u);n=i(c)}}const Vp=ie("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),fo=Vp.state.registry,H0=Vp.state.listeners,qp=/^[a-z0-9_/-]+$/;function po(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):qp.test(t.id.trim().toLowerCase())||e.push(`id (must match ${qp} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),typeof t.onClick!="function"&&typeof t.render!="function"&&e.push("onClick|render (at least one must be a function)"),typeof t.render!="function"&&(typeof t.icon!="string"||t.icon.trim()==="")&&e.push("icon (required when render is omitted)"),typeof t.match!="function"&&e.push("match (must be a function)"),t.placement!==void 0&&t.placement!=="left"&&t.placement!=="right"&&t.placement!=="controls"&&e.push('placement (must be "left", "right", or "controls")')),Re("WindowControl",e,t);const n=t.id.trim().toLowerCase();fo.set(n,{...t,id:n}),Ia()}function Kp(t){fo.delete(t.toLowerCase())&&Ia()}function z0(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(fo.entries()))o.owner===t&&(fo.delete(n),e++);return e>0&&Ia(),e}function Yp(){return Array.from(fo.values()).sort((t,e)=>{const n=t.order??100,o=e.order??100;return n!==o?n-o:t.id.localeCompare(e.id)})}function Ia(){const t=Array.from(H0);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function G0(){po({id:"core/minimize",label:k("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:t=>{t.minimize()}}),po({id:"core/maximize",label:k("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:t=>{t.toggleMaximize()}}),po({id:"core/focus-tab",label:k("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:t=>{t.toggleFullscreen()}}),po({id:"core/close",label:k("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:t=>{t.close()}})}function j0(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(b.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of Yp())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(t))if(!l.has(c)){for(const d of i(c))Kp(d);z0(c),t.delete(c)}for(const c of r)!c.handle||t.has(c.handle)||await o(c);n=s(a)}}const Xp=ie("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),ho=Xp.state.registry,V0=Xp.state.listeners,Zp=/^[a-z0-9_/-]+$/,Jp=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Qp(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):Zp.test(t.id.trim().toLowerCase())||e.push(`id (must match ${Zp} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof t.slot!="string"||t.slot.trim()===""?e.push("slot (missing)"):Jp.has(t.slot)||e.push(`slot (must be one of ${Array.from(Jp).join(", ")})`),typeof t.match!="function"&&e.push("match (must be a function)"),typeof t.render!="function"&&e.push("render (must be a function)")),Re("WindowSlot",e,t);const n=t.id.trim().toLowerCase();ho.set(n,{...t,id:n}),xa()}function Ca(t){ho.delete(t.toLowerCase())&&xa()}function q0(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(ho.entries()))o.owner===t&&(ho.delete(n),e++);return e>0&&xa(),e}function eh(){return Array.from(ho.values()).sort((t,e)=>{const n=t.order??100,o=e.order??100;return n!==o?n-o:t.id.localeCompare(e.id)})}function xa(){const t=Array.from(V0);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function K0(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(b.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of eh())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(t))if(!l.has(c)){for(const d of i(c))Ca(d);q0(c),t.delete(c)}for(const c of r)!c.handle||t.has(c.handle)||await o(c);n=s(a)}}const Y0="desktop-mode-notice-dismissed";function X0(){const e=window.wp?.os?.config?.currentUserId;return typeof e=="number"&&e>0?String(e):"anon"}function th(){return`${Y0}:${X0()}`}function La(){try{const t=window.localStorage.getItem(th());if(!t)return{};const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{}}function nh(t){try{window.localStorage.setItem(th(),JSON.stringify(t))}catch{}}function Ta(t){return t?La()[t]===!0:!1}function fi(t){if(!t)return;const e=La();e[t]=!0,nh(e)}function oh(t){if(!t)return;const e=La();e[t]&&(delete e[t],nh(e))}const Z0=re`: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 ) )}`,cs=class cs extends be{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const e=this.getAttribute("notice-id");e&&Ta(e)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const e=this.getAttribute("notice-id");e&&fi(e),this.emit("os-notice-dismiss",{noticeId:e??void 0})}undismiss(){const e=this.getAttribute("notice-id");e&&oh(e),this.hidden=!1}render(){const e=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return q` |
| 45 |
<span |
| 46 |
class="os-notice__icon dashicons ${e??""}" |
| 47 |
?hidden=${!e} |
| 48 |
aria-hidden="true" |
| 49 |
></span> |
| 50 |
<span class="os-notice__label"><slot></slot></span> |
| 51 |
<button |
| 52 |
type="button" |
| 53 |
class="os-notice__close" |
| 54 |
?hidden=${!n} |
| 55 |
aria-label=${k("Dismiss notice")} |
| 56 |
@click=${o=>this._onDismiss(o)} |
| 57 |
> |
| 58 |
<svg viewBox="0 0 14 14" aria-hidden="true"> |
| 59 |
<path |
| 60 |
d="M3 3 L11 11 M11 3 L3 11" |
| 61 |
stroke="currentColor" |
| 62 |
stroke-width="1.6" |
| 63 |
stroke-linecap="round" |
| 64 |
fill="none" |
| 65 |
></path> |
| 66 |
</svg> |
| 67 |
</button> |
| 68 |
`}_onDismiss(e){e.preventDefault(),e.stopPropagation(),this.dismiss()}};cs.props=["tone","notDismissible","icon","noticeId"],cs.styles=[Z0],cs.help=void 0;let Na=cs;Se("os-notice",Na);const mo=ie("desktop-mode/window-notices",()=>({entries:new Map})),J0=/^[a-z0-9_/-]+$/;function sh(t){return`os-notice/${t.toLowerCase()}`}function Q0(t){const e=document.createElement("os-notice");return e.setAttribute("tone",t.tone??"info"),e.setAttribute("notice-id",t.id),t.dismissible===!1&&e.setAttribute("not-dismissible",""),t.icon&&e.setAttribute("icon",t.icon),e.innerHTML=t.message,e}function ih(t){if(!t||typeof t!="object")return()=>{};const e=String(t.id??"").trim().toLowerCase();if(!e||!J0.test(e))return()=>{};if(typeof t.message!="string"||t.message==="")return()=>{};const n={...t,id:e};mo.state.entries.set(e,n);const o=sh(e);return Qp({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=mo.state.entries.get(e);if(!i)return!1;if(typeof i.match!="function")return!0;try{return i.match(s)===!0}catch{return!1}},render:s=>{const i=mo.state.entries.get(e);i&&s.appendChild(Q0(i))}}),()=>Da(e)}function Da(t){const e=String(t??"").trim().toLowerCase();e&&mo.state.entries.delete(e)&&Ca(sh(e))}function rh(){return Array.from(mo.state.entries.values()).sort((t,e)=>{const n=t.order??100,o=e.order??100;return n!==o?n-o:t.id.localeCompare(e.id)})}function eS(t){const e=String(t??"").trim().toLowerCase();e&&fi(e)}function tS(t){const e=String(t??"").trim().toLowerCase();e&&oh(e)}function nS(t){if(!t)return;const e=new Set;if(typeof t.window=="string"&&t.window!==""&&e.add(t.window),Array.isArray(t.windows))for(const o of t.windows)typeof o=="string"&&o!==""&&e.add(o);const n=typeof t.urlContains=="string"&&t.urlContains!==""?t.urlContains.toLowerCase():null;if(!(e.size===0&&n===null))return o=>!(e.size>0&&!e.has(o.id)||n!==null&&!(typeof o.config.url=="string"?o.config.url.toLowerCase():"").includes(n))}function ah(t){const e=new Set;for(const n of t)!n||typeof n.id!="string"||!n.id||(e.add(n.id.toLowerCase()),ih({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:nS(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of rh())n.owner==="__server__"&&(e.has(n.id)||Da(n.id))}const lh=ie("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),go=lh.state.registry,oS=lh.state.listeners,ch=/^[a-z0-9_/-]+$/;function sS(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):ch.test(t.id.trim().toLowerCase())||e.push(`id (must match ${ch} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof t.match!="function"&&e.push("match (must be a function)"),typeof t.render!="function"&&e.push("render (must be a function)")),Re("WindowChrome",e,t);const n=t.id.trim().toLowerCase();go.set(n,{...t,id:n}),Ra()}function dh(t){go.delete(t.toLowerCase())&&Ra()}function iS(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(go.entries()))o.owner===t&&(go.delete(n),e++);return e>0&&Ra(),e}function uh(){return Array.from(go.values()).sort((t,e)=>t.id.localeCompare(e.id))}function Ra(){const t=Array.from(oS);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function rS(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(b.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of uh())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(t))if(!l.has(c)){for(const d of i(c))dh(d);iS(c),t.delete(c)}for(const c of r)!c.handle||t.has(c.handle)||await o(c);n=s(a)}}const Oa=window.location.origin;let aS=0;const pn=new Map,hn=new Map,wo=new Map;function lS(t,e){return wo.set(t,e),()=>{wo.get(t)===e&&wo.delete(t)}}function cS(){return`os-conn-${++aS}`}function dS(t){const e=(l,c)=>{try{l.contentWindow?.postMessage(c,Oa)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=cS(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let m=!1,g=!1;const h=()=>{const D=wo.get(l);return D||(t.getById(l)?.iframe??null)},w=()=>{if(h())return!1;const D=t.getById(l);return!!D&&D.config?.native===!0},v=[],R=()=>{const D=h();if(D)for(;p.length;){const O=p.shift();e(D,{type:"os-bridge-publish",connectionId:d,topic:O.topic,payload:O.payload})}},_={id:d,target:l,isOpen:()=>m,subscribe(D,O){const y=O;if(w()){const T=r_(l,D,(x,I)=>{L(b.CONNECTION_MESSAGE,{connectionId:d,topic:I.channel,direction:"in"});try{y(x,{topic:I.channel})}catch(W){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",W)}});return v.push(T),T}let M=f.get(D);return M||(M=new Set,f.set(D,M)),M.add(y),()=>{M?.delete(y)}},send(D,O){if(g)return;if(L(b.CONNECTION_MESSAGE,{connectionId:d,topic:D,direction:"out"}),w()){l_(l,D,O);return}if(!m){p.push({topic:D,payload:O});return}const y=h();y&&e(y,{type:"os-bridge-publish",connectionId:d,topic:D,payload:O})},disconnect(){_._destroy("disconnect")},_targetWindow:h,_handleIframeMessage(D){if(!D||typeof D!="object")return;const O=D;if(O.type==="os-bridge-handshake-ack"){if(m)return;m=!0,L(b.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:_});try{c.onOpen?.()}catch(y){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",y)}R();return}if(O.type==="os-bridge-publish"){const y=D,M=typeof y.topic=="string"?y.topic:"";if(!M)return;L(b.CONNECTION_MESSAGE,{connectionId:d,topic:M,direction:"in"});const T=f.get(M);if(T)for(const I of Array.from(T))try{I(y.payload,{topic:M})}catch(W){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",W)}const x=f.get("*");if(x)for(const I of Array.from(x))try{I(y.payload,{topic:M})}catch(W){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",W)}return}O.type==="os-bridge-disconnect"&&_._destroy("disconnect")},_destroy(D){if(g)return;g=!0;const O=m;m=!1,pn.delete(d);const y=hn.get(l);y&&(y.delete(d),y.size===0&&hn.delete(l));for(const M of v.splice(0))try{M()}catch{}if(O){const M=h();M&&e(M,{type:"os-bridge-disconnect",connectionId:d})}L(b.CONNECTION_CLOSED,{connectionId:d,reason:D});try{c.onClose?.(D)}catch(M){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",M)}}};pn.set(d,_);let E=hn.get(l);if(E||(E=new Set,hn.set(l,E)),E.add(d),w())return Promise.resolve().then(()=>{if(!(g||m)){m=!0,L(b.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(D){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",D)}}}),_;const N=h();return N&&e(N,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),_},o=(l,c)=>{if(!l||typeof l!="object")return;const d=l;if(typeof d.type!="string"||!d.type.startsWith("os-bridge-"))return;if(d.type==="os-bridge-connection-request"&&typeof d.requestId=="string"&&typeof c=="string"&&c!==""){s(c,d.requestId,Array.isArray(d.topics)?d.topics:[]);return}if(typeof d.connectionId!="string")return;pn.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=wo.get(l)??t.getById(l)?.iframe??null;if(!f)return;const p=K(b.IFRAME_CONNECTION_REQUEST,!0,{windowId:l,requestId:c,topics:d.slice()});if(p===!1){try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!1,reason:"rejected"},Oa)}catch{}return}const m=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,g=n(l,{topics:m});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:g.id},Oa)}catch{}};return{connect:n,getConnection:l=>pn.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=hn.get(l);if(c)for(const d of Array.from(c)){const u=pn.get(d);if(!u||u.isOpen())continue;const f=u._targetWindow();f&&e(f,{type:"os-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:l=>{const c=hn.get(l);if(c)for(const d of Array.from(c))pn.get(d)?._destroy("window-closed")}}}const uS={};function fS(...t){(typeof{url:sr&&sr.tagName.toUpperCase()==="SCRIPT"&&sr.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&uS?"production":void 0)!=="production"&&console.log(...t)}const pS="iframe:";function Ma(t){return pS+t}function fh(t){return t.icon&&typeof t.icon=="string"&&t.icon.startsWith("dashicons-")?t.icon:t.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function hS(t,e){const n=e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}class mS{constructor(e){this.subscribedWindowId=null,this.manager=e.manager,this.adminUrl=e.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"&&(li(Ma(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 e=this.manager.getFocused();e&&this.onFocused(e.id)}onFocused(e){if(this.subscribedWindowId!==e){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{}li(Ma(this.subscribedWindowId))}this.subscribedWindowId=e,this.sendSubscribe(e)}}sendSubscribe(e){const n=this.manager.getById(e);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"os-commands-subscribe"},window.location.origin)}catch(o){fS("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(e,n){const o=Ma(e);li(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=hS(e,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?Kc(s.iconSvg):"",a={slug:i,label:s.label,icon:fh(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,fh(s)):this.runProxy(e,s.name)};try{ai(a)}catch(l){console.error("[openstation] iframe-bridge: dropping bad command",a,l)}}}runNavigate(e,n,o){return(s,i)=>{if(i.close(),ct(e))return;const r=le(e,this.adminUrl);this.manager.open({id:r,baseId:r,url:e,title:n,icon:o})}}runProxy(e,n){return(o,s)=>{s.close();const i=this.manager.getById(e);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 ph="global",gS=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,wS=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,yS=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,bS=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,vS=/getSiteEditorPage\s*\(|site-editor\.php/,_S=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function ES(t){const e=window.__openStationMenuCommands;if(!Array.isArray(e))return null;for(const n of e)if(n&&typeof n=="object"&&n.name===t&&typeof n.url=="string"&&n.url!=="")return{label:typeof n.label=="string"?n.label:"",url:n.url};return null}class kS{constructor(e){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=e.manager,this.adminUrl=e.adminUrl}install(){this.tryMount(0)}tryMount(e){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){e<40&&window.setTimeout(()=>this.tryMount(e+1),150);return}this.mount()}mount(){const e=window.wp,n=e.element,o=e.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,l=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof l!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const c=document.createElement("div");c.setAttribute("aria-hidden","true"),c.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(c),this.host=c;const d={perLoader:{},statics:[],loadersList:[]},u=g=>{if(!Array.isArray(g)||g.length===0)return"";const h=new Array(g.length);for(let w=0;w<g.length;w++){const v=g[w];h[w]=v&&v.name?v.name:""}return h.join("|")},f=()=>{let g=[];for(const h of d.loadersList){const w=d.perLoader[h];Array.isArray(w)&&(g=g.concat(w))}Array.isArray(d.statics)&&(g=g.concat(d.statics)),this.callbackCache=Object.create(null);for(const h of g)h&&h.name&&typeof h.callback=="function"&&(this.callbackCache[h.name]=h.callback);this.publish(g)},p=g=>{const h=g.loader;let w=null;try{w=h.hook({search:""})}catch{}const v=w&&Array.isArray(w.commands)?w.commands:[],R=a(()=>u(v),[v]);return i(()=>{d.perLoader[h.name]=v,f()},[R]),i(()=>()=>{delete d.perLoader[h.name],f()},[]),null},m=()=>{const g=l(E=>{const N=E("core/commands");return!N||typeof N.getCommandLoaders!="function"?[]:[...N.getCommandLoaders(!1)||[],...N.getCommandLoaders(!0)||[]]},[]),h=l(E=>{const N=E("core/commands");return!N||typeof N.getCommands!="function"?[]:[...N.getCommands(!1)||[],...N.getCommands(!0)||[]]},[]),w=a(()=>Array.isArray(g)?g.map(E=>E&&E.name||""):[],[g]),v=w.join("|");i(()=>{d.loadersList=w,f()},[v]);const R=a(()=>u(Array.isArray(h)?h:[]),[h]);if(i(()=>{d.statics=Array.isArray(h)?h:[],f()},[R]),!Array.isArray(g)||g.length===0)return null;const _=[];for(const E of g)!E||typeof E.hook!="function"||_.push(s(p,{key:E.name,loader:E}));return s(n.Fragment||"div",null,_)};try{this.root=n.createRoot(c),this.root.render(s(m))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(e){const n=Object.create(null),o=[];for(const i of e)!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||""} |
| 69 |
`;if(s!==this.lastFingerprint){this.lastFingerprint=s,li(ph);for(const i of o){if(i.kind==="skip")continue;const r=`global-${i.name.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}`,a=this.iconFor(i),l={slug:r,label:i.label,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?Kc(i.iconSvg):void 0,owner:ph,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{ai(l)}catch(c){console.error("[openstation] shell-harvester: dropping bad command",l,c)}}}}classify(e){const n={name:String(e.name),label:String(e.label),icon:typeof e.icon=="string"?e.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof e.callback=="function"?e.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;e.icon&&typeof e.icon!="string"&&(n.iconSvg=this.renderIcon(e.icon));const s=ES(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 e.callback=="function"){let i="";try{i=Function.prototype.toString.call(e.callback)}catch{i=""}const r=i.match(gS)||i.match(wS)||i.match(yS);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(bS.test(i)){const l=vS.test(i)?n.name.match(_S):null;if(l){const c=l[1],d=l[2],u=`/${c}/${d}`;try{const f=new URL("site-editor.php",this.adminUrl);f.searchParams.set("p",u),f.searchParams.set("canvas","edit"),n.url=f.toString(),n.kind="navigate"}catch{n.kind="skip"}}else n.kind="skip"}}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}renderIcon(e){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(e);if(typeof o=="string"&&o.toLowerCase().startsWith("<svg"))return o}catch{}return""}iconFor(e){return e.icon&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}runNavigate(e,n,o){return(s,i)=>{if(i.close(),ct(e))return;const r=le(e,this.adminUrl);this.manager.open({id:r,baseId:r,url:e,title:n,icon:o})}}runInvoke(e,n,o){return(s,i)=>{const r=this.callbackCache[e];if(typeof r!="function"){i.close();return}const a=this.runWithNavCapture(r);if(a){i.close();const l=le(a,this.adminUrl);this.manager.open({id:l,baseId:l,url:a,title:n,icon:o})}}}runWithNavCapture(e){let n=null;const o=l=>{n===null&&typeof l=="string"&&l!==""&&(n=l)},s=window.location,i=new Proxy(s,{get(l,c){const d=l[c];return c==="assign"||c==="replace"?u=>o(u):typeof d=="function"?d.bind(l):d},set(l,c,d){return c==="href"&&o(d),!0}}),r=[],a=l=>{try{Object.defineProperty(l,"location",{configurable:!0,get:()=>i,set:c=>o(c)}),r.push({obj:l,key:"location"})}catch{}};a(document),a(window);try{e({close:()=>{}})}catch{}finally{for(const l of r)try{delete l.obj[l.key]}catch{}}return n}}const mn=[];function Pa(t){Re("Widget",Dt(t,mh),t);const e=mn.findIndex(n=>n.id===t.id);e>=0?mn[e]=t:mn.push(t)}function SS(t){const e=mn.findIndex(n=>n.id===t);e>=0&&mn.splice(e,1)}function hh(){const t=mn.slice(),e=K(b.WIDGETS,t);return Array.isArray(e)?e.filter(AS):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),t)}function yo(t){return hh().find(e=>e.id===t)}const mh=[{field:"id",message:"missing or not a non-empty string",valid:t=>typeof t.id=="string"&&t.id!==""},{field:"label",message:"missing or not a non-empty string",valid:t=>typeof t.label=="string"&&t.label!==""},{field:"description",message:"not a string",valid:t=>typeof t.description=="string"},{field:"icon",message:"missing or not a non-empty string",valid:t=>typeof t.icon=="string"&&t.icon!==""},{field:"mount",message:"not a function",valid:t=>typeof t.mount=="function"}];function AS(t){return Dt(t,mh).length===0}let ot=null;function IS(t){if(ot)return;const e=document.createElement("div");e.className="os-widget-picker",e.setAttribute("role","menu"),e.setAttribute("aria-label",k("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=k("Add widget"),e.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",e.appendChild(o),wh(o,t),document.body.appendChild(e),CS(e,t.anchor);const s=a=>{const l=a.target;l&&(e.contains(l)||t.anchor.contains(l)||gh())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&gh()};document.addEventListener("keydown",i),ot={panel:e,options:t,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function bo(){if(!ot)return;const t=ot.panel.querySelector(".os-widget-picker__list");t&&wh(t,ot.options)}function gh(){ot&&(document.removeEventListener("pointerdown",ot.onOutsidePointerDown,!0),document.removeEventListener("keydown",ot.onKeyDown),ot.panel.remove(),ot=null)}function wh(t,e){t.innerHTML="";const n=new Set(e.enabledIds()),o=e.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."),t.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="os-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("os-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=ae(k("%s (already added)"),s.label):a=ae(k("Add %s"),s.label),i.setAttribute("aria-label",a);const l=document.createElement("span");l.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-widget-picker__entry-text";const d=document.createElement("span");if(d.className="os-widget-picker__entry-label",d.textContent=s.label,c.appendChild(d),s.description){const u=document.createElement("span");u.className="os-widget-picker__entry-description",u.textContent=s.description,c.appendChild(u)}if(i.appendChild(c),r){const u=document.createElement("span");u.className="os-widget-picker__entry-status",u.textContent=k("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),e.onAdd(s.id)}),t.appendChild(i)}}function CS(t,e){const n=e.getBoundingClientRect();t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.style.visibility="hidden";const o=t.getBoundingClientRect(),s=o.width||320,i=o.height||200,r=6;let a=n.right-s,l=n.top-i-r;a<8&&(a=8),l<8&&(l=n.bottom+r),t.style.left=`${Math.round(a)}px`,t.style.top=`${Math.round(l)}px`,t.style.visibility=""}const pi="os-widgets__card--floating",xS="os-widgets__card--movable",LS="os-widgets__card--resizable",yh="os-widgets__card--dragging",bh="os-widgets__card--resizing",TS=160,vh=80,NS=280,DS=180,hi=20,_h=5,RS=_h*_h,OS='input, textarea, select, button, a, [contenteditable="true"]';function MS(t,e,n){const o=document.createElement("div");o.className="os-widgets__card",o.dataset.widgetId=t.id;const s=t.movable===!0,i=t.resizable===!0;s&&o.classList.add(xS),i&&o.classList.add(LS),s?o.appendChild(PS(t,n.onRemove,n.onRedock)):o.appendChild($S(t,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),e.geometry?(Wa(o,GS(e.geometry,e.floatingParent)),o.classList.add(pi)):i&&typeof e.dockedHeight=="number"&&(o.style.height=`${zS(e.dockedHeight,t)}px`);const a=()=>o.classList.contains(pi),l=[];if(i)for(const d of BS()){const u=document.createElement("div");u.className=`os-widgets__resize os-widgets__resize--${d}`,u.setAttribute("aria-hidden","true"),u.dataset.dir=d,o.appendChild(u),l.push(FS(o,u,d,t,e,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=US(o,d,t,e,n))}return{card:o,body:r,dispose:()=>{for(const d of l)try{d()}catch{}if(c)try{c()}catch{}o.remove()}}}function PS(t,e,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=t.label,o.appendChild(i),o.appendChild(WS(t,n));const r=Eh(t,e);return o.appendChild(r),o}function WS(t,e){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",ae(k("Dock %s back to widget column"),t.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(),e()}),n.dataset.noDrag="true",n}function $S(t,e){const n=Eh(t,e);return n.classList.add("os-widgets__card-close--corner"),n}function Eh(t,e){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",ae(k("Remove %s"),t.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(),e()}),n}function US(t,e,n,o,s){let i=null,r=0,a=0,l=0,c=0,d=!1;const u=g=>{if(g.button!==0)return;const h=g.target;h&&h.closest(OS)||(g.preventDefault(),i=g.pointerId,r=g.clientX,a=g.clientY,d=!1,l=parseFloat(t.style.left)||0,c=parseFloat(t.style.top)||0,e.setPointerCapture(i))},f=()=>{if(!t.classList.contains(pi)){const g=o.floatingParent.getBoundingClientRect(),h=t.getBoundingClientRect(),w={x:h.left-g.left,y:h.top-g.top,width:h.width||n.defaultWidth||NS,height:h.height||n.defaultHeight||DS};Wa(t,w),t.classList.add(pi),s.onLiberate(w),l=parseFloat(t.style.left)||0,c=parseFloat(t.style.top)||0}t.classList.add(yh)},p=g=>{if(i===null||g.pointerId!==i)return;const h=g.clientX-r,w=g.clientY-a;if(!d){if(h*h+w*w<RS)return;d=!0,f()}const v=Sh(l+h,c+w,t.offsetWidth,t.offsetHeight,o.floatingParent);t.style.left=`${v.x}px`,t.style.top=`${v.y}px`},m=g=>{if(!(i===null||g.pointerId!==i)){try{e.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,t.classList.remove(yh),s.onGeometryChanged(kh(t)))}};return e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p),e.addEventListener("pointerup",m),e.addEventListener("pointercancel",m),()=>{e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",m),e.removeEventListener("pointercancel",m)}}function FS(t,e,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const m=w=>{if(w.button!==0||!r()&&!HS(n))return;w.preventDefault(),w.stopPropagation(),a=w.pointerId,l=w.clientX,c=w.clientY;const v=t.getBoundingClientRect(),R=s.floatingParent.getBoundingClientRect();d=v.left-R.left,u=v.top-R.top,f=v.width,p=v.height,e.setPointerCapture(a),t.classList.add(bh)},g=w=>{if(a===null||w.pointerId!==a)return;const v=w.clientX-l,R=w.clientY-c,_=jS(n,v,R,d,u,f,p,o,s.floatingParent,r());r()&&(t.style.left=`${_.x}px`,t.style.top=`${_.y}px`,t.style.width=`${_.width}px`),t.style.height=`${_.height}px`},h=w=>{if(!(a===null||w.pointerId!==a)){try{e.releasePointerCapture(a)}catch{}a=null,t.classList.remove(bh),r()?i.onGeometryChanged(kh(t)):i.onDockedHeightChanged(t.offsetHeight)}};return e.addEventListener("pointerdown",m),e.addEventListener("pointermove",g),e.addEventListener("pointerup",h),e.addEventListener("pointercancel",h),()=>{e.removeEventListener("pointerdown",m),e.removeEventListener("pointermove",g),e.removeEventListener("pointerup",h),e.removeEventListener("pointercancel",h)}}function BS(){return["n","e","s","w","ne","nw","se","sw"]}function HS(t){return t==="s"}function Wa(t,e){t.style.left=`${e.x}px`,t.style.top=`${e.y}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`}function kh(t){return{x:parseFloat(t.style.left)||0,y:parseFloat(t.style.top)||0,width:t.offsetWidth,height:t.offsetHeight}}function zS(t,e){return vo(t,e.minHeight??vh,e.maxHeight??1/0)}function GS(t,e){if(!e.clientWidth||!e.clientHeight)return t;const n=Sh(t.x,t.y,t.width,t.height,e);return{...t,x:n.x,y:n.y}}function Sh(t,e,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,a=Math.max(0,i-n-hi),l=Math.max(0,r-o-hi);return{x:Math.min(Math.max(hi,t),a),y:Math.min(Math.max(hi,e),l)}}function jS(t,e,n,o,s,i,r,a,l,c){const d=a.minWidth??TS,u=a.minHeight??vh,f=a.maxWidth??1/0,p=a.maxHeight??1/0,m=l.clientWidth||l.getBoundingClientRect().width,g=l.clientHeight||l.getBoundingClientRect().height;let h=o,w=s,v=i,R=r;if((t==="e"||t==="ne"||t==="se")&&(v=vo(i+e,d,Math.min(f,m-o))),t==="w"||t==="nw"||t==="sw"){const _=vo(i-e,d,Math.min(f,o+i));h=o+(i-_),v=_}if((t==="s"||t==="se"||t==="sw")&&(R=vo(r+n,u,Math.min(p,g-s))),t==="n"||t==="ne"||t==="nw"){const _=vo(r-n,u,Math.min(p,s+r));w=s+(r-_),R=_}return c||(v=i,h=o),{x:h,y:w,width:v,height:R}}function vo(t,e,n){return n<e?e:Math.min(Math.max(t,e),n)}const Ah="desktop-mode-widgets",Ih="desktop-mode-widgets-geometry",Ch="desktop-mode-widgets-docked-heights";function xh(){try{return window.localStorage.getItem(Ah)}catch{return null}}function VS(){const t=xh();if(t===null)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}catch{return[]}}function $a(t){try{window.localStorage.setItem(Ah,JSON.stringify(t))}catch{}}function qS(){try{const t=window.localStorage.getItem(Ih);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[o,s]of Object.entries(e)){const i=YS(s);i&&(n[o]=i)}return n}catch{return{}}}function Ua(t){try{window.localStorage.setItem(Ih,JSON.stringify(t))}catch{}}function KS(){try{const t=window.localStorage.getItem(Ch);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[o,s]of Object.entries(e))typeof s=="number"&&Number.isFinite(s)&&s>0&&(n[o]=s);return n}catch{return{}}}function Lh(t){try{window.localStorage.setItem(Ch,JSON.stringify(t))}catch{}}function YS(t){if(!t||typeof t!="object")return null;const{x:e,y:n,width:o,height:s}=t;return typeof e!="number"||!Number.isFinite(e)||typeof n!="number"||!Number.isFinite(n)||typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||s<=0?null:{x:e,y:n,width:o,height:s}}function XS(t){const e=`os.widget.${t}.`,n=o=>{try{return localStorage.getItem(e+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(e+o,JSON.stringify(s))}catch{}},remove(o){try{localStorage.removeItem(e+o)}catch{}},clear(){try{for(let o=localStorage.length-1;o>=0;o--){const s=localStorage.key(o);s&&s.startsWith(e)&&localStorage.removeItem(s)}}catch{}}}}const ZS=["clock"];class JS{constructor(e,n,o){this.mounted=new Map,this.generation=0,this.root=e,this.pluginUrl=n,this.enabledIds=VS(),this.geometry=qS(),this.dockedHeights=KS(),this.floatingHost=o??e.parentElement??e,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(){xh()===null&&(this.enabledIds=ZS.filter(e=>!!yo(e)),$a(this.enabledIds));for(const e of this.enabledIds)this.mounted.has(e)||this.mountById(e);this.paintEmptyState()}add(e){this.enabledIds.includes(e)||yo(e)&&(this.enabledIds.push(e),$a(this.enabledIds),this.mountById(e),this.paintEmptyState(),L(b.WIDGET_ADDED,{id:e}),bo())}remove(e){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==e),this.enabledIds.length!==n&&($a(this.enabledIds),this.geometry[e]&&(delete this.geometry[e],Ua(this.geometry)),this.dockedHeights[e]!==void 0&&(delete this.dockedHeights[e],Lh(this.dockedHeights)),this.unmountById(e),this.paintEmptyState(),L(b.WIDGET_REMOVED,{id:e}),bo())}getEnabledIds(){return[...this.enabledIds]}mountIfEnabled(e){yo(e)&&this.enabledIds.includes(e)&&(this.mounted.has(e)||(this.mountById(e),this.paintEmptyState()))}unmount(e){this.mounted.has(e)&&(this.unmountById(e),this.paintEmptyState())}ensureMounted(e){return yo(e)?(this.enabledIds.includes(e)||this.add(e),!0):!1}disposeAll(){for(const e of Array.from(this.mounted.keys()))this.unmountById(e)}mountById(e){const n=yo(e);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[e]:void 0,i=MS(n,{floatingParent:this.floatingHost,geometry:s,dockedHeight:this.dockedHeights[e]},{onRemove:()=>this.remove(e),onGeometryChanged:u=>this.persistGeometry(e,u),onDockedHeightChanged:u=>this.persistDockedHeight(e,u),onLiberate:u=>this.liberate(e,u),onRedock:()=>this.redock(e)}),r=!!s,a={id:e,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(e,a),this.placeCard(i.card,r);const l={id:e,pluginUrl:this.pluginUrl,storage:XS(e)};L(b.WIDGET_MOUNTING,{id:e,container:i.body,ctx:l});const c=u=>{const f=this.mounted.get(e);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,L(b.WIDGET_MOUNTED,{id:e,container:i.body,ctx:l})};let d;try{d=n.mount(i.body,l)}catch(u){this.handleMountFailure(e,u);return}if(QS(d)){d.then(c,u=>{this.mounted.get(e)?.generation===o&&this.handleMountFailure(e,u)});return}c(d)}unmountById(e){const n=this.mounted.get(e);if(n){L(b.WIDGET_UNMOUNTING,{id:e});try{n.teardown?.()}catch(o){L(b.SHELL_ERROR,{scope:"widget-teardown",id:e,error:o}),typeof console<"u"&&console.error(`[openstation] Widget "${e}" teardown threw:`,o)}this.generation++,n.frame.dispose(),this.mounted.delete(e)}}handleMountFailure(e,n){const o=this.mounted.get(e);o&&(o.frame.dispose(),this.mounted.delete(e)),L(b.WIDGET_MOUNT_FAILED,{id:e,error:n}),L(b.SHELL_ERROR,{scope:"widget-mount",id:e,error:n}),typeof console<"u"&&console.error(`[openstation] Widget "${e}" failed to mount:`,n)}buildAddTile(){const e=document.createElement("button");e.type="button",e.className="os-widgets__add",e.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"),e.appendChild(n),e.appendChild(o),e.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),IS({anchor:e,registry:()=>hh(),enabledIds:()=>[...this.enabledIds],onAdd:i=>this.add(i)})}),e}placeCard(e,n){n?this.floatingHost.appendChild(e):this.listEl.appendChild(e)}liberate(e,n){const o=this.mounted.get(e);!o||o.floating||(o.floating=!0,this.floatingHost.appendChild(o.frame.card),Wa(o.frame.card,n),this.persistGeometry(e,n),this.paintEmptyState())}redock(e){const n=this.mounted.get(e);if(!n||!n.floating)return;n.floating=!1,this.geometry[e]&&(delete this.geometry[e],Ua(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[e];o.style.height=s!==void 0?`${s}px`:"",this.listEl.appendChild(o),this.paintEmptyState()}persistGeometry(e,n){this.geometry[e]=n,Ua(this.geometry)}persistDockedHeight(e,n){!Number.isFinite(n)||n<=0||(this.dockedHeights[e]=n,Lh(this.dockedHeights))}paintEmptyState(){let e=0;for(const n of this.mounted.values())n.floating||e++;this.root.classList.toggle("os-widgets--has-widgets",e>0)}}function QS(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}const eA=280,tA=220,nA=520,oA=400;function sA(t,e){const o=t.closest('[id^="wp-window-"]')?.id.slice(10);return o||e}function iA(t,e,n){return o=>{const s=sA(o,n),i=document.createElement("iframe");i.style.width="100%",i.style.height="100%",i.style.border="0",i.setAttribute("src",t.url),typeof t.sandbox=="string"&&t.sandbox!==""&&i.setAttribute("sandbox",t.sandbox),o.style.padding="0",o.appendChild(i);const r=lS(s,i);e.push(r);let a;try{a=new URL(t.url,window.location.origin).origin}catch{a=window.location.origin}let l=null;const c=new Promise(f=>{l=f}),d=()=>{if(t.bridge)try{const f=i.contentDocument;if(f&&!f.querySelector("script[data-os-iframe-bridge]")){const p=window.openStationConfig?.iframeBridgeUrl;if(p){const m=f.createElement("script");m.src=p,m.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(m)}}}catch{}d_(s),l?.()};i.addEventListener("load",d);const u=f=>{if(!i.contentWindow||f.source!==i.contentWindow||f.origin!==a&&f.origin!==window.location.origin)return;const p=f.data;p&&typeof p=="object"&&typeof p.type=="string"&&p.type.startsWith("os-bridge-")&&window.__openStationConnectionBridge?.routeIncomingFromIframe(p,s),p&&typeof p=="object"&&p.type==="os-window-publish"&&typeof p.channel=="string"&&p.channel!==""&&a_(s,p.channel,p.payload);try{t.onMessage?.(f.data)}catch(m){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",m)}};return window.addEventListener("message",u),e.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),c}}function rA(t){return async e=>{const n=e.render;let o=n;const s=[];e.iframeContent&&(n&&typeof console<"u"&&console.warn("[openstation] registerWindow: both `render` and `iframeContent` provided — ignoring `render` and using the iframe shorthand. Drop one."),o=iA(e.iframeContent,s,e.id));const i=e.onClose,r=e.iframeContent?()=>{for(const l of s)try{l()}catch{}i?.()}:i;return await t.open({id:e.id,baseId:e.baseId||e.id,native:!0,url:e.url||`#${e.id}`,title:e.title,icon:e.icon,x:e.x??0,y:e.y??0,width:e.width??nA,height:e.height??oA,minWidth:e.minWidth??eA,minHeight:e.minHeight??tA,render:o,onClose:r,onResize:e.onResize,autofocus:e.autofocus,initialState:e.initialState,ownerHandle:e.ownerHandle,multi:e.multi,desktopId:e.desktopId})}}let aA=0;function lA(t,e,n={}){const o=`desktop-mode/on-window/${t}/${++aA}`,s=n.persistent===!0,i=[["opened",b.WINDOW_OPENED],["reopened",b.WINDOW_REOPENED],["focused",b.WINDOW_FOCUSED],["blurred",b.WINDOW_BLURRED],["closing",b.WINDOW_CLOSING],["closed",b.WINDOW_CLOSED],["minimized",b.WINDOW_MINIMIZED],["restored",b.WINDOW_RESTORED],["maximized",b.WINDOW_MAXIMIZED],["unmaximized",b.WINDOW_UNMAXIMIZED],["fullscreenEntered",b.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",b.WINDOW_FULLSCREEN_EXITED],["resized",b.WINDOW_RESIZED],["bodyResized",b.WINDOW_BODY_RESIZED],["boundsChanged",b.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const l=()=>{if(!a){a=!0;for(const c of r)zc(c,o)}};for(const[c,d]of i){const u=e[c];u&&(r.push(d),X(d,o,f=>{const p=f;if(p.windowId!==t)return;const{windowId:m,...g}=p;u(g),c==="closed"&&!s&&l()}))}return l}function Th(){const t=window;return{...t.wpDesktopNativeWindows||{},...t.openStationNativeWindows||{}}}function cA(t){const{manager:e,appendSystemTile:n,removeSystemTile:o}=t,s=new Set,i=new Set,r=new Set,a=new Set,l=new Map,c=_=>{const E=vd(_.id);return E?{width:Math.max(E.width,_.minWidth),height:Math.max(E.height,_.minHeight)}:{width:_.width,height:_.height}},d=_=>{if(i.has(_.templateId))return;if(document.getElementById(_.templateId)){i.add(_.templateId);return}if(!_.templateHtml)return;const E=document.createElement("template");E.id=_.templateId,E.innerHTML=_.templateHtml,document.body.appendChild(E),i.add(_.templateId)},u=_=>{const E=_.styleUrl;if(!E||a.has(E))return;const N=E.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${N}"]`)){const O=document.createElement("link");O.rel="stylesheet",O.href=E,_.styleHandle&&(O.dataset.osStyleHandle=_.styleHandle),document.head.appendChild(O)}if(Array.isArray(_.styleInline))for(const O of _.styleInline){if(typeof O!="string"||O==="")continue;const y=document.createElement("style");_.styleHandle&&(y.dataset.osStyleHandle=_.styleHandle),y.textContent=O,document.head.appendChild(y)}a.add(E)},f=async _=>{if(!(!_.scriptUrl||r.has(_.scriptUrl))){try{await ke(_.scriptUrl,{translations:_.scriptTranslations,l10n:_.scriptL10n,before:_.scriptBefore,after:_.scriptAfter})}catch(E){L(b.SHELL_ERROR,{scope:"native-window-script-load",id:_.id,error:E})}r.add(_.scriptUrl)}},p=(_,E)=>{const N=Th()[_.id],D=(y,M)=>(y.appendChild(Fa(_.templateId)),N?.(y,M)),O=c(_);e.open({id:_.id,baseId:_.id,native:!0,url:`#${_.id}`,title:_.title,icon:_.icon,width:O.width,height:O.height,minWidth:_.minWidth,minHeight:_.minHeight,render:D,autofocus:_.autofocus,ownerHandle:_.ownerHandle||_.scriptHandle,...E?{params:E}:{}})},m=(_,E)=>{const N=Th()[_.id],D=(y,M)=>(y.appendChild(Fa(_.templateId)),N?.(y,M)),O=c(_);e.openNew({id:_.id,baseId:_.id,native:!0,url:`#${_.id}`,title:_.title,icon:_.icon,width:O.width,height:O.height,minWidth:_.minWidth,minHeight:_.minHeight,initialState:"normal",render:D,autofocus:_.autofocus,ownerHandle:_.ownerHandle||_.scriptHandle,...E?{params:E}:{}})},g=async _=>{if(!s.has(_.id)){if(_.placement==="none"){d(_),u(_),await f(_),s.add(_.id);return}d(_),u(_),await f(_),n({id:_.id,title:_.title,icon:_.icon,isOpen:()=>!!e.getById(_.id),onOpen:()=>p(_)}),L(b.DOCK_ITEM_APPENDED,{id:_.id}),s.add(_.id)}},h=_=>{s.has(_)&&(o(_),s.delete(_),l.delete(_))},w=async _=>{const E=new Set;for(const N of _)E.add(N.id),l.set(N.id,N);for(const N of Array.from(s))E.has(N)||h(N);for(const N of _)s.has(N.id)||await g(N)},v=(_,E={})=>{const N=l.get(_);return N?(Ee.publish("os/open-requested",{windowId:_,source:E.source??"api"}),p(N,E.params),!0):!1},R=(_,E={})=>{const N=l.get(_);return N?(Ee.publish("os/open-requested",{windowId:_,source:E.source??"api"}),m(N,E.params),!0):!1};return X(b.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",_=>{const E=_,N=E?.windowId,D=E?.width,O=E?.height;if(!N||typeof D!="number"||typeof O!="number")return;const y=e.getById(N);if(!y||y.state!=="normal")return;const M=y.config.baseId||y.id;_d(M,{width:D,height:O}),y.element&&Ed(M,{x:y.element.offsetLeft,y:y.element.offsetTop})}),X(b.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",_=>{const E=_?.windowId;if(!E)return;const N=e.getById(E);if(!N||N.state!=="normal"||!N.element)return;const D=N.config.baseId||N.id;_d(D,{width:N.element.offsetWidth,height:N.element.offsetHeight}),Ed(D,{x:N.element.offsetLeft,y:N.element.offsetTop})}),X(b.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",_=>{const E=_?.windowId;if(!E)return;const N=e.getById(E);if(!N)return;const D=N.config.baseId||N.id,O=l.get(D),y=O?{width:O.width,height:O.height}:{width:N.config.width,height:N.config.height};kd(D,"maximized",y)}),X(b.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",_=>{const E=_?.windowId;if(!E)return;const N=e.getById(E);if(!N)return;const D=N.config.baseId||N.id;kd(D,null)}),{sync:w,openById:v,openNewById:R}}function Fa(t){let e=null;if(typeof t=="string"){const n=document.getElementById(t);n instanceof HTMLTemplateElement&&(e=n)}else e=t;if(!e)throw new Error(`[openstation] cloneTemplate: no <template> found for ${typeof t=="string"?`#${t}`:"<reference>"}`);return e.content.cloneNode(!0)}function Nh(t){const e=window.wp?.os,n=window.openStationConfig,o=e?.config?.adminUrl??n?.adminUrl;if(!o)return null;const s=e?.getMenuItems?.()??n?.dockItems??[],i=le(t,o);return s.find(r=>le(r.url,o)===i||(r.submenu??[]).some(a=>le(a.url,o)===i))??null}const Dh="os-icon__badge",_o=new Map,Eo=new Map;function dA(t){return Math.max(0,Math.floor(Number(t)||0))}function Rh(t,e){if(!t)return;const n=Ph(t);if(!n)return;const o=dA(e),s=_o.get(t)??0;o!==s&&(o===0?_o.delete(t):_o.set(t,o),Wh(n,o),Ee.publish("os/badge-changed",{itemId:t,count:o,rail:"icon"}),L(b.ICON_BADGE_CHANGED,{iconId:t,count:o,previousCount:s}))}function uA(t){Rh(t,0)}function fA(t){return _o.get(t)??0}function pA(t,e){if(t){if(!e){Eo.delete(t);return}Eo.get(t)!==e&&(Eo.set(t,e),gA(t,e),Ee.publish("os/art-changed",{itemId:t,icon:e,rail:"icon"}))}}function hA(t){return Eo.get(t)??""}function mA(t){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function gA(t,e){const o=Ph(t)?.querySelector(".os-icon__image");if(o){const s=Zn(e,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${mA(t)}"]`).forEach(s=>s.setAttribute("icon",e))}const wA={setBadge:Rh,clearBadge:uA,getBadge:fA,setArt:pA,getArt:hA};function yA(t){return!t||t.length===0?"":`${Nr()??""}::`+t.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let Oh="";function Mh(t,e,n){const o=yA(e);if(o===Oh&&t.querySelector(":scope > .os-icons"))return;Oh=o;const s=t.querySelector(":scope > .os-icons");if(s&&s.remove(),!e||e.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=[...e].sort((l,c)=>{const d=l.pinned?0:1,u=c.pinned?0:1;return d-u}),a=new Map;for(const l of r){const c=vA(l,n),d=_o.get(l.id)??0;d>0&&Wh(c,d);const u=Eo.get(l.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(Zn(u,{className:"os-icon__image",title:""}))}i.appendChild(c),a.set(l.id,c)}t.appendChild(i),L(b.DESKTOP_ICONS_RENDERED,{ids:(e??[]).map(l=>l.id),container:i,tiles:a})}function Ph(t){if(!t)return null;const e=document.querySelector(".os-icons");return e?e.querySelector(`[data-icon-id="${bA(t)}"]`):null}function Wh(t,e){const n=t.querySelector(`:scope > .${Dh}`);if(e<=0){n?.remove();return}const o=e>99?"99+":String(e),s=ae(Hn("%d notification","%d notifications",e),e);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",s);return}const i=document.createElement("span");i.className=Dh,i.textContent=o,i.setAttribute("aria-label",s),t.appendChild(i)}function bA(t){const e=window.CSS;return e?.escape?e.escape(t):t}function vA(t,e){const n=document.createElement("button");n.type="button",n.className=t.pinned?"os-icon os-icon--pinned":"os-icon",n.dataset.iconId=t.id,t.pinned&&(n.dataset.pinned="1"),n.setAttribute("role","listitem"),n.setAttribute("aria-label",t.title);const o=Zn(t.icon,{title:t.title,className:"os-icon__image",slot:Bs(t.id)});n.appendChild(o);const s=document.createElement("span");return s.className="os-icon__label",s.textContent=t.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),L(b.DESKTOP_ICON_CLICKED,{id:t.id,target:t.window?"window":"url"}),_A(t,e)}),n.addEventListener("contextmenu",i=>{t.pinned||(i.preventDefault(),i.stopPropagation(),gf({x:i.clientX,y:i.clientY,id:t.id,title:t.title,surface:"desktop"}))}),n}function _A(t,e){if(t.window)return e.openWindow(t.window),void 0;if(t.url){if(qs(t.url))return;try{const n=new URL(t.url,window.location.origin),o=e.deriveWindowId(n.toString()),s=Nh(n.toString());e.manager.open({id:o,baseId:o,url:n.toString(),parentUrl:s?.url??n.toString(),title:t.title,icon:t.icon,submenu:s?.submenu,multi:!!s?.multi})}catch{}}}function EA(t){return`desktop:${t}`}function kA(t){return`dock:${t}`}function ko(t,e,n){const o=n[t];return o||e}function $h(t){return t==="dock"||t==="both"}function Uh(t){return t==="desktop"||t==="both"}function SA(t,e,n,o){const s=n.itemVisibility,i=n.dockOrder,r=[];for(const a of t){const l=ko(a.id,"dock",s);$h(l)&&r.push(a)}for(const a of e){const l=ko(a.id,"desktop",s);$h(l)&&(a.window&&o&&o.has(a.window)||r.push({id:kA(a.id),title:a.title,icon:a.icon,url:a.url||"",windowId:a.window||void 0,badge:0,submenu:[],isCore:!1}))}return IA(r,i)}function AA(t,e,n){const o=[];for(const i of t){const r=ko(i.id,"desktop",n);Uh(r)&&o.push(i)}let s=0;for(const i of e){const r=ko(i.id,"dock",n);Uh(r)&&o.push({id:EA(i.id),title:i.title,icon:i.icon,window:"",url:i.url||"",position:2e3+s++})}return o}function IA(t,e){if(e.length===0||t.length<=1)return t;const n=new Map;for(const i of t)n.set(i.id,i);const o=[],s=new Set;for(const i of e){const r=n.get(i);r&&(o.push(r),s.add(i))}for(const i of t)s.has(i.id)||o.push(i);return o}const Fh="os-side-dock";function CA(t,e){return{id:`dock-core:${t.id}`,title:t.title,icon:t.icon,window:"",url:t.url,position:1e3+e}}function xA(t,e,n,o){let s=e,i=n,r=o??[],a=null,l=null,c=null,d=null,u=null;const f=new Map,p=new Set,m=I=>I==="core"&&l?l:a,g=()=>{const I=document.getElementById(Fh);if(I)return I;const W=document.createElement("nav");return W.id=Fh,W.className="os-dock",W.setAttribute("role","toolbar"),W.setAttribute("aria-label","Core admin navigation"),t.shellBody.insertBefore(W,t.shellBody.firstChild),W},h=()=>{u&&u.parentNode&&u.parentNode.removeChild(u),u=null},w=()=>t.getSettings?.()??{itemVisibility:{},dockOrder:[]},v=I=>{const W=w().itemVisibility;let z=W[I];for(const A of r)if(A.window===I&&W[A.id]){z=W[A.id];break}return z?z==="dock"||z==="both":!0},R=()=>{for(const[I,W]of f){const z=v(I),A=p.has(I);z&&!A?(m(W.affinity)?.appendSystemItem(W.item),p.add(I)):!z&&A&&(m(W.affinity)?.removeSystemItem(I),p.delete(I))}},_=()=>{const I=new Set;for(const W of f.values())I.add(W.item.id);return SA(i,r,w(),I)},E=()=>{const I=_(),W=[],z=[];for(const A of I)A.isCore?W.push(A):z.push(A);return{core:W,plugin:z}},N=()=>{const I=w();if(s!=="spatial"){t.renderIcons(AA(r,i,I.itemVisibility));return}const{core:W}=E(),z=W.map(CA),A=r.filter(C=>{const $=I.itemVisibility[C.id];return $?$==="desktop"||$==="both":!!C.pinned}),P=[];let B=0;for(const C of i){const $=I.itemVisibility[C.id];($==="desktop"||$==="both")&&P.push({id:`dock:${C.id}`,title:C.title,icon:C.icon,window:"",url:C.url||"",position:2e3+B++})}t.renderIcons([...z,...A,...P])},D=()=>{if(a){try{a.destroy()}catch(I){L(b.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:I})}a=null,c=null}if(l){try{l.destroy()}catch(I){L(b.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:I})}l=null,d=null}},O=I=>{const W=Ir();if(!W)return L(b.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return W.mount(I)}catch(z){if(L(b.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:W.id,error:z}),W===Vr)return null;try{return Vr.mount(I)}catch{return null}}},y=(I,W,z)=>({container:I,items:W,fullMenu:i.slice(),fullSystemTiles:Array.from(f.values()).filter(A=>v(A.item.id)).map(A=>A.item),orientation:z,windowManager:t.windowManager,adminUrl:t.adminUrl,openItem:A=>{const P=le(A.url,t.adminUrl);t.windowManager.open({id:P,baseId:P,url:A.url,parentUrl:A.url,title:A.title,icon:A.icon.startsWith("dashicons-")?A.icon:"dashicons-admin-generic",submenu:A.submenu,multi:!!A.multi})},openSubmenuPick:(A,P)=>{t.windowManager.open({id:le(P.url,t.adminUrl),baseId:le(A.url,t.adminUrl),url:P.url,parentUrl:A.url,title:A.title,icon:A.icon.startsWith("dashicons-")?A.icon:"dashicons-admin-generic",submenu:A.submenu,multi:!!A.multi})},openSystemItem:A=>A.onOpen()}),M=()=>{D();const{core:I,plugin:W}=E();s==="classic"?(u=g(),l=O(y(u,I,"left")),d=Xs(l),a=O(y(t.bottomDockEl,W,"bottom")),c=Xs(a)):s==="unified"?(h(),a=O(y(t.bottomDockEl,_(),"bottom")),c=Xs(a)):(h(),a=O(y(t.bottomDockEl,W,"bottom")),c=Xs(a)),p.clear();for(const[z,A]of f)v(z)&&(m(A.affinity)?.appendSystemItem(A.item),p.add(z))},T={getLayout:()=>s,getPrimary:()=>c,getSide:()=>d,setLayout:I=>{I!==s&&(s=I,t.shellRoot.setAttribute("data-os-layout",I),M(),N(),document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:I,primary:c,side:d}})))},applyDockItems:I=>{i=I;const{core:W,plugin:z}=E();s==="classic"?(l?.replaceItems(W),a?.replaceItems(z)):s==="unified"?a?.replaceItems(_()):a?.replaceItems(z),N()},applyDesktopIcons:I=>{r=I??[],R(),N()},appendSystemTile:(I,W="plugin")=>{f.set(I.id,{item:I,affinity:W}),v(I.id)&&(m(W)?.appendSystemItem(I),p.add(I.id))},removeSystemTile:I=>{const W=f.get(I);W&&(f.delete(I),p.delete(I),m(W.affinity)?.removeSystemItem(I))},listSystemTiles:()=>Array.from(f.values()).map(I=>({id:I.item.id,title:I.item.title,icon:I.item.icon,affinity:I.affinity,placeable:I.item.placeable===!0})),getSystemTile:I=>f.get(I)?.item??null,getMenuItems:()=>i.slice(),refresh:()=>{const{core:I,plugin:W}=E();s==="classic"?(l?.replaceItems(I),a?.replaceItems(W)):s==="unified"?a?.replaceItems(_()):a?.replaceItems(W),R(),N()},destroy:()=>{D(),h()}};t.shellRoot.setAttribute("data-os-layout",s),M(),N();let x=Ir()?.id??null;return Bv(()=>{const I=Ir()?.id??null;I!==x&&(x=I,M(),N(),document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:s,primary:c,side:d}})))}),T}function LA(t){return window.openStationCreateAiAssistant?Promise.resolve(window.openStationCreateAiAssistant):new Promise((e,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}e(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=t,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 TA{constructor(e,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=e,this._scriptUrl=n}_ensure(){return this._loadPromise?this._loadPromise:(this._loadPromise=LA(this._scriptUrl).then(e=>{const n=e(this._config);return this._pendingAsk&&n.attachAsk(this._pendingAsk),this._real=n,n}),this._loadPromise)}open(){this._intendOpen=!0,this._ensure().then(e=>e.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(e){this._pendingAsk=e,this._real&&this._real.attachAsk(e)}}const Bh=t=>!t||typeof t!="object"?!1:t.name==="AbortError",NA=t=>{if(!t)return[];const e=Vk();if(t===!0||t==="aiCallable")return e;if(Array.isArray(t)){const n=new Set(t.map(o=>o.toLowerCase()));return e.filter(o=>n.has(o.slug))}return typeof t=="function"?e.filter(n=>{try{return t(n.slug)===!0}catch{return!1}}):[]},DA=t=>t?typeof t=="string"?{text:t,mode:"append"}:typeof t=="object"&&typeof t.text=="string"&&t.text!==""?{text:t.text,mode:t.mode==="replace"?"replace":"append"}:null:null;function RA(t,e){const n=t??"";return n!==""?n:typeof e=="string"&&e!==""?e:e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?e.message:""}function OA(t){return t===void 0?{value:null}:typeof t=="object"&&t!==null?t:{value:t}}function MA(t){const e=async(s,i)=>{const r=t.config(),a=r.aiSearchUrl??"",l=r.restNonce??"";if(!a||!l)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Fe(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":l},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw Bh(c)?c:new Error(`[openstation] wp.os.ai.ask: network error — ${String(c?.message??c)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",l=qk(r);if(!l)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??t.fallbackContext();let d;try{d=await Promise.resolve(l.run(a,c))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:d}},o=async(s,i,r,a,l,c)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:OA(a)}};l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);let u;try{u=await e(d,c)}catch(m){if(Bh(m))throw m;return null}if(!u.ok)return null;const f=await u.json().catch(()=>({}));return(typeof f.message=="string"?f.message.trim():"")!==""?f.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[openstation] wp.os.ai.ask: empty query passed with non-default options — likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const l=NA(r.tools),c=DA(r.systemPrompt),d={query:a};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),l.length>0&&(d.command_tools=l),c&&(d.system_prompt_text=c.text,d.system_prompt_mode=c.mode);const u=await e(d,r.signal);if(!u.ok){const v=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[openstation] wp.os.ai.ask: HTTP ${u.status} — ${v.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:m,args:g,result:h}=p;let w=RA(f.message,h);if(r.followUp===!0){const v=await o(a,m,g,h,c,r.signal);v!==null&&(w=v)}return{answer_type:"tool_call",message:w,entity:null,admin_links:null,toolCall:{slug:m,args:g,result:h},request_id:f.request_id}}}const Hh="[os-bin badge]";function st(...t){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(Hh,...t)}catch{}}function mi(...t){console.warn(Hh,...t)}const So="desktop-mode-recycle-bin",PA="openstation_recycle_bin_seen_ts";function WA(){return window.wp?.os}const de=ie("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function Ao(t){const e=Math.max(0,Math.floor(t)),n=de.state.current;de.state.current=e,st("setRecycleBinCount",{prev:n,next:e}),Ba(e)}function zh(t){Ao(de.state.current+t)}function $A(){return de.state.current}function Ba(t){const e=t>0?de.state.fullArt:de.state.emptyArt;if(st("paintIconState",{count:t,full:t>0,hasArt:!!e}),!e)return;const n=WA();n?.dock?.setArt?.(So,e),n?.taskbar?.setArt?.(So,e),n?.icons?.setArt?.(So,e)}function UA(t,e=""){const n=Number(t)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;de.state.emptyArt=String(o?.recycleBinIconEmpty??""),de.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;st("startRecycleBinIconState entry",{initial:n,countUrl:e,alreadyStarted:de.state.started,cfgCount:s,cfgUrl:i,cfgDebug:r,readyState:document.readyState});const a=Number(s);if((typeof s=="number"||typeof s=="string")&&Number.isFinite(a)||mi("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),de.state.started){Ao(n);return}de.state.started=!0,de.state.countUrl=e,de.state.seenTs=Date.now(),Ao(n),FA(),BA(),HA(),zA(),GA()}function FA(){X(b.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",t=>{t?.id===So&&Ba(de.state.current)})}function BA(){X(b.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",t=>{t?.ids?.includes(So)&&Ba(de.state.current)})}function HA(){const t=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":zh(+r);break;case"untrashed":case"deleted":zh(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])fn(`os.${s}.changed`,t)}function zA(){const t=window.location.origin;window.addEventListener("message",e=>{if(e.origin!==t)return;const n=e.data;if(!n||n.type!=="os-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=de.state.seenTs){st("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:de.state.seenTs});return}st("postMessage triggers refetch",{ts:o,prevSeenTs:de.state.seenTs}),de.state.seenTs=o,jA()})}function GA(){const t=window.jQuery;if(!t){mi("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}st("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),t(document).on("heartbeat-send",(...e)=>{const n=e[1];n&&(n[PA]=de.state.seenTs)}),t(document).on("heartbeat-tick",(...e)=>{const o=e[1]?.openstation_recycle_bin;st("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>de.state.seenTs&&(de.state.seenTs=o.ts),typeof o.count=="number"&&Ao(o.count))})}async function jA(){if(!de.state.countUrl){st("refetchCount: no countUrl, skip");return}st("refetchCount: hitting",de.state.countUrl);try{const t=await fetch(de.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!t.ok){mi("refetchCount: non-OK",t.status,t.statusText);return}const e=await t.json();st("refetchCount: response",e),typeof e.count=="number"&&Ao(e.count)}catch(t){mi("refetchCount: fetch failed",t)}}const VA="desktop-mode-os-settings",qA="desktop-mode-recycle-bin";function KA(t){const e=ZA();e&&e.addFilter("os.dock.peek-card-content","desktop-mode/built-in-peek-renderers",(n,o)=>{const s=o,i=s.window.id;return i===VA?YA():i===qA?XA(s,t.getRecycleBinCount):n})}function YA(t){const e=document.createElement("span");e.className="os-dock-peek__card-body os-dock-peek__card-body--os-settings",e.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="os-dock-peek__os-hero dashicons dashicons-admin-generic",e.appendChild(n);const o=document.createElement("span");o.className="os-dock-peek__os-subtitle",o.textContent=k("System Preferences"),e.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 e.appendChild(s),e}function XA(t,e){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(e()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="os-dock-peek__bin-stage";const i=document.createElement("span");i.className="os-dock-peek__bin-stack";for(let l=0;l<3;l++){const c=document.createElement("span");c.className="os-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="os-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="os-dock-peek__bin-label",o===0?a.textContent=k("Trash — empty"):o===1?a.textContent=k("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function ZA(){return window.wp?.hooks??null}const gn="desktop-mode-bug-report",JA="WordPress",QA="openstation",Gh=6e3;function eI(t){t.classList.add("desktop-mode-bug-report"),t.replaceChildren();const e=document.createElement("form");e.className="os-bug-report__form",e.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."),e.appendChild(n),e.appendChild(tI()),e.appendChild(nI("title",k("Title"),{placeholder:k("A short summary"),required:!0})),e.appendChild(jh("description",k("What happened? What did you expect?"),{placeholder:k("Describe the issue or the feature you have in mind."),rows:5,required:!0})),e.appendChild(jh("steps",k("Steps to reproduce (bug only)"),{placeholder:k("One step per line"),rows:4}));const o=oI();e.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),e.appendChild(s),e.addEventListener("submit",a=>{a.preventDefault();const l=iI(e);if(!l.title.trim()||!l.description.trim()){sI(e,k("Title and description are both required."));return}const c=rI(l);window.open(c,"_blank","noopener")}),t.appendChild(e)}function tI(){const t=document.createElement("div");t.className="os-bug-report__field os-bug-report__field--type";const e=document.createElement("span");e.className="os-bug-report__label",e.textContent=k("Type"),t.appendChild(e);const n=document.createElement("div");n.className="os-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:k("Bug"),checked:!0},{value:"feature",label:k("Feature request")},{value:"question",label:k("Question")}];for(const s of o){const i=document.createElement("label");i.className="os-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const a=document.createElement("span");a.textContent=s.label,i.appendChild(a),n.appendChild(i)}return t.appendChild(n),t}function nI(t,e,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=e,o.appendChild(s);const i=document.createElement("input");return i.type="text",i.name=t,i.className="os-bug-report__input",n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function jh(t,e,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=e,o.appendChild(s);const i=document.createElement("textarea");return i.name=t,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 oI(){const t=document.createElement("details");t.className="os-bug-report__metadata";const e=document.createElement("summary");e.textContent=k("Environment included with the report"),t.appendChild(e);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=qh(Vh()),t.appendChild(n),t}function sI(t,e){let n=t.querySelector(".os-bug-report__error");n||(n=document.createElement("div"),n.className="os-bug-report__error",n.setAttribute("role","alert"),t.prepend(n)),n.textContent=e}function iI(t){const e=new FormData(t);return{type:e.get("type")??"bug",title:e.get("title")??"",description:e.get("description")??"",steps:e.get("steps")??""}}function rI(t){const e=aI(t.type),n=lI(t),o=new URLSearchParams;return o.set("title",t.title.trim()),o.set("body",n),e.length&&o.set("labels",e.join(",")),`https://github.com/${JA}/${QA}/issues/new?${o.toString()}`}function aI(t){switch(t){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function lI(t){const e=[];e.push(t.description.trim()),t.type==="bug"&&t.steps.trim()&&(e.push(""),e.push("## Steps to reproduce"),e.push(""),e.push(t.steps.trim())),e.push(""),e.push("<details><summary>Environment</summary>"),e.push(""),e.push("```"),e.push(qh(Vh())),e.push("```"),e.push(""),e.push("</details>");let n=e.join(` |
| 70 |
`);return n.length>Gh&&(n=n.slice(0,Gh)+` |
| 71 |
|
| 72 |
…(truncated to fit GitHub URL length limit)`),n}function Vh(){const t=window.wp?.os?.config;return{pluginVersion:t?.pluginVersion??"unknown",wordpressVersion:t?.wordpressVersion??"unknown",userAgent:navigator.userAgent,viewport:`${window.innerWidth}x${window.innerHeight}`,platform:navigator.platform||"unknown",currentUrl:window.location.href}}function qh(t){return[`Plugin version: ${t.pluginVersion}`,`WordPress version: ${t.wordpressVersion}`,`User agent: ${t.userAgent}`,`Viewport: ${t.viewport}`,`Platform: ${t.platform}`,`Current URL: ${t.currentUrl}`].join(` |
| 73 |
`)}let gi=null,Kh=!1,Yh=!1,Xh=!1,$t="pending";function cI(){if(Yh)return;Yh=!0;const t=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{t&&(Xh||uI()||(fI(),Xh=!0,setTimeout(()=>window.location.reload(),0)))})}const Zh="os-sw-reload-ts",dI=3e4;function uI(){try{const t=sessionStorage.getItem(Zh),e=t?Number.parseInt(t,10):0;return!Number.isFinite(e)||e<=0?!1:Date.now()-e<dI}catch{return!1}}function fI(){try{sessionStorage.setItem(Zh,String(Date.now()))}catch{}}async function pI(t,e={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!t?.swUrl||!window.isSecureContext)return $t="unsupported",null;if(gi||Kh)return gi;if(!e.forceReplace){const o=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(s=>{const i=s.active?.scriptURL??s.installing?.scriptURL??"";return i!==""&&i!==t.swUrl});if(o)return $t="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 gi=await navigator.serviceWorker.register(t.swUrl,{scope:"/",updateViaCache:"none"}),$t="registered",cI(),gi}catch(n){return Kh=!0,$t="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",n),null}}function hI(){return $t}const mI="os-pwa-install";function Jh(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Qh(){if(Jh())return!0;const t=window.navigator;if(typeof t.getInstalledRelatedApps!="function")return!1;try{const e=await t.getInstalledRelatedApps();return Array.isArray(e)&&e.length>0}catch{return!1}}let kt=null;function gI(t,e){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,e({message:ae(k("Installed %s as an app."),t)})}}function wI(t,e){return{id:mI,title:ae(k("Install %s as an app"),t),icon:"dashicons-download",onOpen:()=>{yI(t,e)}}}async function yI(t,e){if(kt){const n=kt;kt=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&e({message:k("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await Qh()){e({message:ae(k("%s is already installed. Open it from your apps menu or home screen."),t)});return}if(hI()==="foreign-sw"){e({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}e({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 bI(){if(!kt)return"unavailable";const t=kt;kt=null;try{return await t.prompt(),(await t.userChoice).outcome}catch{return"unavailable"}}function vI(){Promise.resolve().then(()=>yk).then(t=>{t.updatePwaState({installHintDismissed:!1})})}function _I(t,e){t.pwa&&(Xf(t.pwa),gI(t.pwa.appName||"WordPress",e),pI(t.pwa,{forceReplace:!!t.pwa.forceReplaceSw}))}const wn={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function EI(t){return!!t&&typeof t=="object"&&t.type==="os-drag-start"&&!!t.payload&&typeof t.payload=="object"}function kI(t){return!!t&&typeof t=="object"&&t.type==="os-drag-end"}function SI(t){return!!t&&typeof t=="object"&&t.type==="os-drag-payload-request"}function AI(t){const e=t;return e.kind!==void 0&&e.kind!==null?t:typeof e.id=="number"&&typeof e.url=="string"&&typeof e.mime=="string"?{kind:"attachment",id:e.id,url:e.url,title:typeof e.title=="string"?e.title:"",alt:typeof e.alt=="string"?e.alt:"",mime:e.mime,thumbnailUrl:typeof e.thumbnailUrl=="string"?e.thumbnailUrl:void 0,sizes:e.sizes&&typeof e.sizes=="object"?e.sizes:void 0}:t}class II{constructor(){this._payload=null,this._onMessage=e=>{if(e.origin!==this._origin)return;const n=e.data;if(EI(n)){this._startDrag(n.payload);return}if(kI(n)){this._endDrag();return}if(SI(n)&&this._payload&&e.source)try{e.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(e){this._payload!==e&&this._startDrag(e)}end(){this._endDrag()}_startDrag(e){const n=AI(e);this._payload=n,document.dispatchEvent(new CustomEvent(wn.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const e=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(wn.END,{detail:{payload:e}}))}}class CI{constructor(){this._targets=new Map,this._byElement=new Map}register(e){const n=this._targets.get(e.id);return n&&this._byElement.delete(n.element),this._targets.set(e.id,e),this._byElement.set(e.element,e),()=>{this._targets.get(e.id)===e&&(this._targets.delete(e.id),this._byElement.delete(e.element))}}list(){return Array.from(this._targets.values())}clear(){this._targets.clear(),this._byElement.clear()}hitTest(e){let n=e;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(e,n){const o=document.elementFromPoint(e,n);return{target:this.hitTest(o),element:o,accepted:!1}}}const xI="os-drag-ghost",em="os-drag-ghost--accept",tm="os-drag-ghost--reject",LI="os-drag-hint",nm="os-drag-hint--accept",om="os-drag-hint--reject",sm="os-drag-hint--neutral",TI=16,NI=18;function DI(t,e,n){const o=$I(t),s=t.ghost?.offsetX??UI(t.source),i=t.ghost?.offsetY??FI(t.source);o.classList.add(xI),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=OI(t),a=r?RI():null;a&&document.body.appendChild(a);const l={get element(){return o},moveTo(c,d){o.style.transform=`translate3d(${c-s}px, ${d-i}px, 0)`,a&&(a.style.transform=`translate3d(${c+TI}px, ${d+NI}px, 0)`)},setMode(c,d){o.classList.remove(em,tm),c==="accept"?o.classList.add(em):c==="reject"&&o.classList.add(tm),a&&r&&(a.classList.remove(nm,om,sm),c==="accept"?(a.classList.add(nm),a.textContent=d?.acceptLabel??r.accept):c==="reject"?(a.classList.add(om),a.textContent=r.reject):(a.classList.add(sm),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(c){const d=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return c()}finally{o.style.visibility=d,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return l.moveTo(e,n),l.setMode("neutral"),l}function RI(){const t=document.createElement("div");return t.className=LI,t.setAttribute("aria-hidden","true"),t.setAttribute("role","presentation"),t.style.position="fixed",t.style.left="0",t.style.top="0",t.style.margin="0",t.style.pointerEvents="none",t.style.zIndex="2147483647",t.style.willChange="transform",t}function OI(t){const e=t.ghost?.hint;return e?.hidden?null:{accept:e?.accept??MI(t),reject:e?.reject??PI(),neutral:e?.neutral??WI(t)}}function MI(t){return t.type==="shortcut"?k("Drop here to create shortcut","desktop-mode"):t.type==="desktop-file"?k("Drop here to move","desktop-mode"):k("Drop here","desktop-mode")}function PI(t){return k("Can’t drop here","desktop-mode")}function WI(t){return t.type==="shortcut"?k("Drop on the desktop or a folder","desktop-mode"):t.type==="desktop-file"?k("Drop in a folder","desktop-mode"):""}function $I(t){if(t.ghost?.element)return t.ghost.element;const e=t.source.cloneNode(!0);e.removeAttribute("id");const n=t.source.getBoundingClientRect();return e.style.width=`${n.width}px`,e.style.height=`${n.height}px`,e}function UI(t){return t.offsetWidth/2}function FI(t){return t.offsetHeight/2}let im=!1;function BI(t){im||(im=!0,document.addEventListener("keydown",e=>{e.key==="Escape"&&t("escape")}),window.addEventListener("blur",()=>{t("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&t("visibility")}))}const rm=4,he={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"},wi="os-file-tile--dragging",am="os-file-tile--drop-target",lm="data-os-trash-drop-active",cm="data-files-drop-active",dm="data-os-dragging",um="data-os-drag-type",Ha="data-os-drag-mode";class HI{constructor(){this._registry=new CI,this._active=null,this._docListenersAttached=!1,this._lastLiftedEndAt=0,this._onPointerMove=e=>{const n=this._active;if(!n||n._pointerId!==e.pointerId)return;const o=e.clientX-n._origin.clientX,s=e.clientY-n._origin.clientY;if(!n._lifted){if(Math.abs(o)<rm&&Math.abs(s)<rm)return;this._lift(n,e)}n._ghost&&(n._ghost.moveTo(e.clientX,e.clientY),this._updateHover(n,e.clientX,e.clientY),ut(he.MOVE,{payload:n.payload,clientX:e.clientX,clientY:e.clientY}))},this._onPointerUp=e=>{const n=this._active;if(!n||n._pointerId!==e.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,e.clientX,e.clientY);if(o&&o.accepted&&o.target){this._commit(n,o.target,e.clientX,e.clientY);return}this._cancel(n,o&&o.target?"rejected":"no-target")},this._onPointerCancel=e=>{const n=this._active;!n||n._pointerId!==e.pointerId||this._cancel(n,"pointercancel")}}start(e){if(this._active||e.origin.button!==0)return null;const n={payload:e.payload,isFinished:()=>n._finished,cancel:o=>this._cancel(n,o??"caller"),_origin:e.origin,_pointerId:e.origin.pointerId,_lifted:!1,_finished:!1,_callbacks:{onClickOnly:e.onClickOnly,onCancel:e.onCancel,onCommit:e.onCommit},_ghost:null,_currentTarget:null,_currentAccepted:!1};return this._active=n,this._ensureDocListeners(),BI(o=>{this._active&&this._cancel(this._active,o)}),n}registerDropTarget(e){return this._registry.register(e)}isDragging(){return this._active!==null&&this._active._lifted}recentlyEndedDrag(e=500){return this._lastLiftedEndAt===0?!1:Date.now()-this._lastLiftedEndAt<e}getActive(){return this._active}debug(){return{findOrphans:()=>fm(),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(e,n){e._lifted=!0,e.payload.source.classList.add(wi),e._ghost=DI(e.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(dm,""),document.body.setAttribute(um,String(e.payload.type)),document.body.setAttribute(Ha,"neutral")),ut(he.START,{payload:e.payload})}_hitTestNow(e,n,o){const s=()=>{const i=document.elementFromPoint(n,o),r=this._registry.hitTest(i);if(!r)return{target:null,accepted:!1};let a=!1;try{a=r.accept(e.payload)}catch(l){console.error("[openstation] drop target accept() threw:",r.id,l)}return{target:r,accepted:a}};return e._ghost?e._ghost.withHidden(s):s()}_updateHover(e,n,o){const s=this._hitTestNow(e,n,o),i=e._currentTarget;if(s.target===i&&s.accepted===e._currentAccepted)return;i&&za(i,e),e._currentTarget=s.target,e._currentAccepted=s.accepted;let r;s.target?s.accepted?(zI(s.target,e),e._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(e._ghost?.setMode("reject"),ut(he.REJECTED,{payload:e.payload,targetId:s.target.id}),r="reject"):(e._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Ha,r)}_commit(e,n,o,s){e._finished=!0,this._lastLiftedEndAt=Date.now(),za(n,e),this._cleanupDom(e);const i=this._active;this._active=null;try{n.onDrop(e,{clientX:o,clientY:s})}catch(r){console.error("[openstation] drop target onDrop threw:",n.id,r)}try{e._callbacks.onCommit?.(n)}catch(r){console.error("[openstation] drag onCommit threw:",r)}ut(he.COMMIT,{payload:e.payload,targetId:n.id}),ut(he.END,{payload:e.payload,reason:"commit"}),this._active===i&&(this._active=null)}_cancel(e,n){if(!e._finished){e._finished=!0,e._lifted&&(this._lastLiftedEndAt=Date.now()),e._currentTarget&&za(e._currentTarget,e),this._cleanupDom(e),this._active=null;try{e._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}ut(he.CANCEL,{payload:e.payload,reason:n}),ut(he.END,{payload:e.payload,reason:n})}}_cleanupDom(e){try{e.payload.source.classList.remove(wi)}catch{}e._ghost?.dispose(),e._ghost=null,e._currentTarget=null,e._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(dm),document.body.removeAttribute(um),document.body.removeAttribute(Ha)),GI()}}function ut(t,e){typeof document>"u"||document.dispatchEvent(new CustomEvent(t,{detail:e}))}function zI(t,e){try{t.onEnter?.(e)}catch(n){console.error("[openstation] drop target onEnter threw:",t.id,n)}ut(he.ENTER,{payload:e.payload,targetId:t.id})}function za(t,e){try{t.onLeave?.(e)}catch(n){console.error("[openstation] drop target onLeave threw:",t.id,n)}ut(he.LEAVE,{payload:e.payload,targetId:t.id})}function fm(){if(typeof document>"u")return[];const t=[];for(const e of[`.${wi}`,`.${am}`,`[${lm}]`,`[${cm}]`])document.querySelectorAll(e).forEach(n=>t.push(n));return t}function GI(){for(const t of fm())t.classList.remove(wi,am),t.removeAttribute(lm),t.removeAttribute(cm)}const jI=".os-window",pm="wp-window-";function hm(t,e){const n=document.elementFromPoint(t,e);if(!n)return null;const o=n.closest(jI);return o instanceof HTMLElement?o:null}function VI(t){if(!t.id.startsWith(pm))return null;const e=t.id.slice(pm.length);return e.length>0?e:null}const qI="desktop-mode-iframe-drop-",yi="iframe.os-window__iframe",Ga="data-os-iframe-drop-active";let ja=!1,mm=null;const je=new Map,Ut=new Map;let ft=null,Ft=null;function KI(){document.querySelectorAll(yi).forEach(e=>{je.has(e)||(je.set(e,e.style.pointerEvents),e.style.pointerEvents="none")})}function YI(){je.forEach((t,e)=>{e.style.pointerEvents=t}),je.clear()}function gm(t,e){const n=hm(t,e);if(!n)return null;const o=n.querySelector(yi);return o instanceof HTMLIFrameElement?o:null}const wm=t=>{if(!ft)return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy");const e=gm(t.clientX,t.clientY);e!==Ft&&(Ft&&Bt(Ft,{type:"os-drag-leave"}),Ft=e,e&&Bt(e,{type:"os-drag-over",payload:ft}))},ym=t=>{if(!ft)return;t.preventDefault(),t.stopPropagation(),typeof t.stopImmediatePropagation=="function"&&t.stopImmediatePropagation();const e=gm(t.clientX,t.clientY),n=ft;if(Va(),!e)return;const o=e.getBoundingClientRect();Bt(e,{type:"os-drop",payload:n,position:{x:t.clientX-o.left,y:t.clientY-o.top}})},bm=()=>{Va()};function XI(t){if(ft){ft=t;return}ft=t,KI(),document.addEventListener("dragover",wm,!0),document.addEventListener("drop",ym,!0),document.addEventListener("dragend",bm,!0)}function Va(){ft&&(ft=null,Ft&&(Bt(Ft,{type:"os-drag-leave"}),Ft=null),document.removeEventListener("dragover",wm,!0),document.removeEventListener("drop",ym,!0),document.removeEventListener("dragend",bm,!0),YI())}function bi(t){if(!t||typeof t!="object")return;const e=t;return e.type!=="shortcut"&&e.type!=="desktop-file"?void 0:e.data?.bridgePayload}function Bt(t,e){const n=t.contentWindow;if(n)try{n.postMessage(e,window.location.origin)}catch{}}function ZI(t,e,n,o){return t.registerDropTarget({id:`${qI}${o}`,element:n,accept:s=>!!bi(s),onEnter:s=>{const i=bi(s.payload);i&&(n.setAttribute(Ga,""),Bt(e,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(Ga),Bt(e,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(Ga);const r=bi(s.payload);if(!r)return;const a=e.getBoundingClientRect();Bt(e,{type:"os-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function vm(t){let e=t.parentElement;for(;e;){if(e.id.startsWith("wp-window-"))return e.id.slice(10);e=e.parentElement}return`unknown-${Math.random().toString(36).slice(2,10)}`}function JI(t){const e=mm;if(!e)return;const n=document.querySelectorAll(yi),o=!!bi(t);console.info("[openstation] drag-start: suppressing %d iframe(s); bridgeable=%s",n.length,o,t),n.forEach(s=>{if(je.has(s)||(je.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||Ut.has(s))return;const i=s.parentElement;if(!i)return;const r=vm(s),a=ZI(e,s,i,r);Ut.set(s,a)})}function QI(){je.forEach((t,e)=>{e.style.pointerEvents=t}),je.clear(),Ut.forEach(t=>{try{t()}catch{}}),Ut.clear()}function eC(t){ja||(ja=!0,mm=t,document.addEventListener(he.START,e=>{const n=e.detail;JI(n?.payload)}),document.addEventListener(he.END,()=>{QI()}),document.addEventListener(wn.START,e=>{const n=e.detail;n?.payload&&XI(n.payload)}),document.addEventListener(wn.END,()=>{Va()}),X(b.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[e]of Array.from(je))e.isConnected||je.delete(e);for(const[e,n]of Array.from(Ut))if(!e.isConnected){try{n()}catch{}Ut.delete(e)}}),window.__openStationIframeDropDebug=()=>({installed:ja,iframesInDom:document.querySelectorAll(yi).length,suppressedCount:je.size,registeredCount:Ut.size,suppressedIframeIds:Array.from(je.keys()).map(vm)}))}const tC=250,nC=1e3,oC="os-drag-hover";let _m=!1,qa=null,Ka=null,Io=null,Co=null,Ya=null;function Em(){Io!==null&&(clearTimeout(Io),Io=null)}function km(){Co!==null&&(clearTimeout(Co),Co=null)}function xo(){Em(),km(),Ka=null}function Sm(){km(),Co=setTimeout(()=>{Co=null,xo()},nC)}function sC(t,e){const n=qa?.getById(t);if(!(!n||n.isFocused()||!K(b.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:t,payloadType:e})))try{qa?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",t,s)}}function Am(t,e){t!==Ka&&(Em(),Ka=t,t!==null&&(Io=setTimeout(()=>{Io=null,sC(t,e)},tC)))}function Im(t,e,n){const o=hm(t,e);Am(o?VI(o):null,n)}const iC=t=>{const e=t.detail;typeof e?.clientX!="number"||typeof e?.clientY!="number"||Im(e.clientX,e.clientY,e.payload?.type??"")},rC=()=>{xo()};function aC(t){const e=t.dataTransfer?.types;if(!e)return!1;const n=e;return typeof n.includes=="function"?n.includes("Files"):typeof n.contains=="function"&&n.contains("Files")}const lC=t=>{Sm();const e=Ya??(aC(t)?"os-file":"external");Im(t.clientX,t.clientY,e)},Cm=()=>{xo()},cC=t=>{t.relatedTarget===null&&xo()};function dC(t){if(!t)return null;const e=document.querySelectorAll("iframe");for(const n of Array.from(e))if(n.contentWindow===t)return n.closest("[data-window-id]")?.getAttribute("data-window-id")||null;return null}const uC=t=>{if(t.origin!==window.location.origin)return;const e=t.data;if(!e||e.type!==oC)return;const n=dC(t.source);n&&(Sm(),Am(n,typeof e.payloadType=="string"?e.payloadType:"external"))},fC=t=>{const e=t.detail;e?.payload&&(Ya=e.payload.kind??"")},pC=()=>{Ya=null,xo()};function hC(t){_m||(_m=!0,qa=t,document.addEventListener(he.MOVE,iC),document.addEventListener(he.END,rC),document.addEventListener(wn.START,fC),document.addEventListener(wn.END,pC),document.addEventListener("dragover",lC,!0),document.addEventListener("drop",Cm,!0),document.addEventListener("dragend",Cm,!0),document.addEventListener("dragleave",cC,!0),window.addEventListener("message",uC))}function xm(){const t=window.wp?.os;if(!t)return[];const e=t.windowManager,n=t.config;if(!e||!n)return[];const o=[],s=(r,a)=>({id:r.id,label:r.title,description:a,icon:r.icon,open:()=>e.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=K("os.open-command.items",o);return Array.isArray(i)?i:o}const mC={slug:"open",label:"Open",description:"Open an admin page or registered window.",hint:"[window]",icon:"dashicons-external",suggest(t){const e=t.trim().toLowerCase(),n=xm();return(e===""?n:n.filter(s=>s.label.toLowerCase().includes(e)||s.id.toLowerCase().includes(e))).slice(0,12).map(s=>({value:s.label,label:s.label,description:s.description,icon:s.icon??"dashicons-external"}))},run(t,e){const n=t.trim();if(!n)return"Type the name of a window to open, for example `/open Posts`.";const o=xm(),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(),e.close()}};function gC(){ai(mC)}const xe=[],wC=new Set;function Lm(t){if(!t||typeof t.id!="string"||t.id==="")return()=>{};if(typeof t.open!="function"||typeof t.close!="function"||typeof t.isOpen!="function")return()=>{};const e=xe.findIndex(n=>n.id===t.id);return e>=0?xe[e]=t:xe.push(t),Xa(),()=>{const n=xe.findIndex(o=>o.id===t.id);n>=0&&(xe.splice(n,1),Xa())}}function yC(t){const e=xe.findIndex(n=>n.id===t);e>=0&&(xe.splice(e,1),Xa())}function bC(){return xe.slice()}function Xa(){for(const t of Array.from(wC))try{t()}catch(e){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",e)}}function Tm(){if(xe.length===0)return;const t=xe.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(t===-1){try{xe[0].open()}catch{}return}try{xe[t].close()}catch{}const e=t+1;if(e<xe.length)try{xe[e].open()}catch{}}function Za(t){const e=xe.find(n=>n.id===t);if(e){for(const n of xe)if(n.id!==t)try{n.isOpen()&&n.close()}catch{}try{e.open()}catch{}}}let Nm=!1;function vC(){if(Nm)return;Nm=!0,document.addEventListener("keydown",e=>{!(e.metaKey||e.ctrlKey)||e.key!=="k"||e.shiftKey||e.altKey||(e.preventDefault(),e.stopImmediatePropagation(),Tm())},!0);const t=window.location.origin;window.addEventListener("message",e=>{if(e.origin!==t)return;const n=e.data;n&&n.type==="os-palette-cycle"&&Tm()})}const Ye=ie("os/presence",()=>({byUser:new Map,serverTimeMs:0})),_C=5*60*1e3;let Dm=Date.now(),Rm=!1;function vi(){Dm=Date.now()}function EC(t){if(!t||!t.snapshot)return;const e=Ye.state.byUser,n=new Map(e),o=[];for(const[s,i]of Object.entries(t.snapshot)){const r=Number(s);if(!Number.isFinite(r)||r<=0)continue;const l={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=e.get(r);n.set(r,l),(!c||c.status!==l.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:l.status,entry:l})}Ye.state.byUser=n,typeof t.serverTimeMs=="number"&&(Ye.state.serverTimeMs=t.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})),Ee.publish("os/presence-changed",i)}Ee.publish("os/presence-snapshot-applied",{applied:Object.keys(t.snapshot).length,transitions:o.length})}function kC(){Rm||(Rm=!0,document.addEventListener("pointerdown",vi,{capture:!0,passive:!0}),document.addEventListener("keydown",vi,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||vi()}),Ae.contribute("openstation_presence_active",()=>!0),Ae.contribute("openstation_user_active",()=>Date.now()-Dm<_C),Ae.subscribe("openstation_presence",t=>{EC(t)}))}function SC(t){const e=Ye.state.byUser.get(t);return e?e.status:"offline"}function AC(){return new Map(Ye.state.byUser)}function IC(t){return Ye.state.byUser.get(t)??null}function CC(t){return Ye.subscribe(e=>t(e))}function xC(){vi()}function LC(t){if(!Array.isArray(t)||t.length===0)return;const e=Ye.state.byUser,n=new Map(e),o=[];for(const s of t){const i=Number(s.userId);if(!Number.isFinite(i)||i<=0)continue;const r=e.get(i),a={status:s.status,lastSeenMs:typeof s.lastSeenMs=="number"?s.lastSeenMs:r?.lastSeenMs??0,lastActiveMs:typeof s.lastActiveMs=="number"?s.lastActiveMs:r?.lastActiveMs??0};n.set(i,a),(!r||r.status!==a.status)&&o.push({userId:i,oldStatus:r?r.status:null,newStatus:a.status,entry:a})}if(!(o.length===0&&n.size===e.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})),Ee.publish("os/presence-changed",i)}Ee.publish("os/presence-snapshot-applied",{applied:t.length,transitions:o.length})}}const TC=Object.freeze({getStatus:SC,getAll:AC,getEntry:IC,subscribe:CC,markActive:xC,applyBatch:LC});function Om(t){const e=new Set;let n=null;const o=new Set;t.onChange&&o.add(t.onChange);const s=()=>t.order().filter(a=>e.has(a)),i=()=>{const a=s();for(const l of o)try{l(a)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=a=>{const l=e.size,c=Array.from(e);a(),!(e.size===l&&c.every(d=>e.has(d)))&&i()};return{keys:s,has:a=>e.has(a),size:()=>e.size,anchor:()=>n,set(a){r(()=>{e.clear();for(const l of a)e.add(l)}),n=a.length>0?a[a.length-1]:null},add(a){r(()=>{e.add(a)}),n=a},remove(a){r(()=>{e.delete(a)}),n===a&&(n=null)},toggle(a){r(()=>{e.has(a)?e.delete(a):e.add(a)}),n=a},selectRange(a,l=!1){const c=t.order(),d=c.indexOf(a),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{l||e.clear(),e.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{l||e.clear();for(let m=f;m<=p;m+=1)e.add(c[m])})},selectAll(){const a=t.order();r(()=>{for(const l of a)e.add(l)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{e.clear()}),n=null},prune(){const a=new Set(t.order());let l=!1;return r(()=>{for(const c of Array.from(e))a.has(c)||(e.delete(c),l=!0)}),n!==null&&!a.has(n)&&(n=null),l},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const NC=".os-file-tile",DC="os-file-tile--selected",RC="os-selection-marquee",Mm=4,Pm=36,Wm=12,$m="data-os-marquee";function OC(t){if(t.scrollHeight<=t.clientHeight)return!1;const e=t.ownerDocument?.defaultView?.getComputedStyle(t)?.overflowY;return e==="auto"||e==="scroll"||e==="overlay"}function MC(t){const e=t.ownerDocument;if(!e)return()=>{};const n=o=>{o.preventDefault()};e.addEventListener("selectstart",n,!0),e.body?.setAttribute($m,"");try{e.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{e.removeEventListener("selectstart",n,!0),e.body?.removeAttribute($m)}}const PC=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add";function WC(t,e){const n=e.itemSelector??NC,o=e.background??t,s=e.marquee!==!1,i=e.marqueeExclude??PC,r=()=>Array.from(t.querySelectorAll(n)).filter(C=>e.keyOf(C)!==null),a=()=>{const C=[],$=new Map;r().forEach((G,F)=>{const Y=G.parentElement??t;let j=$.get(Y);j||(j=[],$.set(Y,j),C.push(Y)),j.push({key:e.keyOf(G),top:parseFloat(G.style.top)||0,left:parseFloat(G.style.left)||0,index:F})});const U=[];for(const G of C){const F=$.get(G)??[];F.sort((Y,j)=>Y.top!==j.top?Y.top-j.top:Y.left!==j.left?Y.left-j.left:Y.index-j.index);for(const Y of F)U.push(Y.key)}return U},l=e.order??a,c=Om({order:l,onChange:C=>{p(),e.onChange?.(C),u(C)}}),d={},u=C=>{typeof document>"u"||(yn={surface:e.surface??"",scope:e.scope??"",keys:C.slice(),count:C.length},Qa=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:yn})))},f=C=>r().find($=>e.keyOf($)===C)??null,p=()=>{for(const C of r()){const $=e.keyOf(C),U=c.has($);U!==C.hasAttribute("selected")&&(U?C.setAttribute("selected",""):C.removeAttribute("selected")),C.classList.toggle(DC,U),C.hasAttribute("selectable")||C.setAttribute("selectable","");const G=U?"true":"false";C.getAttribute("aria-selected")!==G&&C.setAttribute("aria-selected",G)}};t.setAttribute("role","listbox"),t.setAttribute("aria-multiselectable","true"),e.ariaLabel&&t.setAttribute("aria-label",e.ariaLabel);let m=null;const g=C=>{if(!(C.target instanceof Element))return;const $=C.target.closest(n);if($&&t.contains($)){const U=e.keyOf($);if(U===null)return;if(m=U,C.stopPropagation(),C.shiftKey){c.selectRange(U,C.ctrlKey||C.metaKey);return}if(C.ctrlKey||C.metaKey){c.toggle(U);return}c.set([U]);return}if(_){_=!1;return}c.clear()};o.addEventListener("click",g);let h=null,w=null,v=null,R=[],_=!1,E=0,N=null,D=null;const O=C=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(C),D=C}catch{}},y=()=>{if(D===null||typeof o.releasePointerCapture!="function"){D=null;return}try{o.hasPointerCapture?.(D)&&o.releasePointerCapture(D)}catch{}D=null},M=(C,$)=>{const U=o.getBoundingClientRect();return{x:C-U.left+o.scrollLeft,y:$-U.top+o.scrollTop}},T=()=>{h?.remove(),h=null,w=null,v=null,N?.(),N=null,y(),E&&(cancelAnimationFrame(E),E=0),document.removeEventListener("pointermove",W),document.removeEventListener("pointerup",z),document.removeEventListener("pointercancel",A),o.removeEventListener("lostpointercapture",A),o.removeEventListener("scroll",x),window.removeEventListener("blur",A)};function x(){if(!w||!v)return;const C=M(v.x,v.y),$=C.x-w.x,U=C.y-w.y;if(!h&&Math.abs($)<Mm&&Math.abs(U)<Mm)return;h||(h=document.createElement("div"),h.className=RC,h.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(h),_=!0,N=MC(o),I());const G=Math.min(w.x,C.x),F=Math.min(w.y,C.y),Y=Math.abs($),j=Math.abs(U);h.style.left=`${G}px`,h.style.top=`${F}px`,h.style.width=`${Y}px`,h.style.height=`${j}px`;const se=o.getBoundingClientRect(),ge=se.left-o.scrollLeft,we=se.top-o.scrollTop,pe={left:G+ge,top:F+we,right:G+Y+ge,bottom:F+j+we},_e=[];for(const Ce of r()){const $e=Ce.getBoundingClientRect();$e.left<pe.right&&$e.right>pe.left&&$e.top<pe.bottom&&$e.bottom>pe.top&&_e.push(e.keyOf(Ce))}c.set(Array.from(new Set([...R,..._e])))}function I(){if(E||typeof requestAnimationFrame!="function")return;const C=()=>{if(E=0,!h||!v)return;const $=o.getBoundingClientRect();if(OC(o)){let G=0;if(v.y<$.top+Pm?G=-Wm:v.y>$.bottom-Pm&&(G=Wm),G!==0){const F=o.scrollTop;o.scrollTop+=G,o.scrollTop!==F&&x()}}E=requestAnimationFrame(C)};E=requestAnimationFrame(C)}const W=C=>{w&&(v={x:C.clientX,y:C.clientY},x())},z=()=>{h&&(Ja=Date.now()),T()},A=()=>{T()},P=C=>{if(!s||C.button!==0||!(C.target instanceof Element)||C.target.closest(n))return;const $=C.target.closest(i);$&&$!==o&&o.contains($)||(w=M(C.clientX,C.clientY),v={x:C.clientX,y:C.clientY},typeof C.pointerId=="number"&&O(C.pointerId),R=C.ctrlKey||C.metaKey||C.shiftKey?c.keys():[],R.length===0&&c.clear(),document.addEventListener("pointermove",W),document.addEventListener("pointerup",z),document.addEventListener("pointercancel",A),o.addEventListener("lostpointercapture",A),window.addEventListener("blur",A),o.addEventListener("scroll",x,{passive:!0}))};o.addEventListener("pointerdown",P);const B=C=>{if(C.key==="a"&&(C.ctrlKey||C.metaKey)){C.preventDefault(),c.selectAll();return}if(C.key==="Escape"){if(h||w){T();return}c.size()>0&&c.clear();return}const $=C.key==="ArrowRight"||C.key==="ArrowDown",U=C.key==="ArrowLeft"||C.key==="ArrowUp";if(!$&&!U)return;const G=$?1:-1,F=l();if(F.length===0)return;const Y=m??c.anchor(),j=Y===null?-1:F.indexOf(Y),se=Math.min(F.length-1,Math.max(0,j<0?0:j+G));C.preventDefault();const ge=F[se];m=ge,C.shiftKey?c.selectRange(ge):c.set([ge]),f(ge)?.focus()};return t.addEventListener("keydown",B),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){T(),o.removeEventListener("click",g),o.removeEventListener("pointerdown",P),t.removeEventListener("keydown",B),Qa===d&&(yn=null,Qa=null)}}}let Ja=0;function $C(){return Ja>0&&Date.now()-Ja<500}let yn=null,Qa=null;function UC(){return yn?{...yn,keys:yn.keys.slice()}:null}function el(t){return typeof t.sort=="number"?t.sort:100}function FC(t,e){return ae(k("%1$s (%2$d items)","desktop-mode"),t,e)}function Um(t,e){if(t.length===0)return[];const n=t.map(a=>{const l=e(a);return Array.isArray(l)?l:[]});if(t.length===1)return n[0];const o=t.length,s=[],i=a=>a.multiId??a.id;for(const a of n[0]){const l=i(a),c=[];let d=!1;for(const p of n){const m=p.find(g=>i(g)===l);if(!m||m.multi!==!0){d=!0;break}c.push(m)}if(d||s.some(p=>p.id===l))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):FC(u.label,o);s.push({id:l,label:f,icon:u.icon,disabled:c.some(p=>p.disabled===!0),danger:c.some(p=>p.danger===!0),sort:Math.min(...c.map(el)),multi:!0,onClick:async p=>{const m=new Map,g=[];c.forEach((h,w)=>{const v=h.bulk;if(typeof v!="function"){g.push(h);return}const R=m.get(v);R?R.push(t[w]):m.set(v,[t[w]])});for(const[h,w]of m)try{await h(w)}catch(v){console.error(`[openstation] selection action '${l}' failed for a batch:`,v)}for(const h of g)try{await h.onClick(p)}catch(w){console.error(`[openstation] selection action '${l}' failed for one item:`,w)}}})}s.sort((a,l)=>{const c=el(a),d=el(l);return c!==d?c-d:a.label.localeCompare(l.label)});const r=K("os.selection.actions",s,{items:t,count:o});return Array.isArray(r)?r:s}function Fm(t,e){const n=s=>{if(!(s.target instanceof Node&&t.contains(s.target))){if(s.target instanceof Node)for(const i of e.siblingSelectors??[]){const r=Array.from(document.querySelectorAll(i));for(const a of r)if(a.contains(s.target))return}e.excludeOutsideTarget&&s.target instanceof Node&&e.excludeOutsideTarget.contains(s.target)||e.close()}},o=s=>{s.key==="Escape"&&e.close()};return document.addEventListener("mousedown",n,{capture:!0}),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",n,{capture:!0}),document.removeEventListener("keydown",o)}}const tl=8;function Bm(t,e){t.style.visibility="hidden";const n=()=>{t.isConnected&&(e(t.getBoundingClientRect()),t.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function nl(t){Bm(t,e=>{e.right>window.innerWidth&&(t.style.left=`${Math.max(0,window.innerWidth-e.width-tl)}px`),e.bottom>window.innerHeight&&(t.style.top=`${Math.max(0,window.innerHeight-e.height-tl)}px`)})}function Hm(t,e){const n=e.getBoundingClientRect();t.style.position="fixed",t.style.left=`${n.right}px`,t.style.top=`${n.top}px`,Bm(t,o=>{o.right>window.innerWidth&&(t.style.left=`${Math.max(0,n.left-o.width)}px`),o.bottom>window.innerHeight&&(t.style.top=`${Math.max(0,window.innerHeight-o.height-tl)}px`)})}const BC="os-wallpaper-menu";let bn=null,ol=null,zm=0;function sl(){if(!bn)return;const t=bn.dataset.menuScope??"selection",e=ol;bn.dispatchEvent(new CustomEvent("tile-menu-closed")),bn.remove(),bn=null,ol=null,e?.(),L(`os.${t}.menu.closed`,{})}function HC(t,e){sl();const n=++zm;Is(()=>n===zm,()=>zC(t,e))}function zC(t,{actions:e,dataset:n,className:o,scope:s="selection",onOpened:i,onClosed:r}){if(e.length===0)return;const a=document.createElement("os-context-menu");a.setAttribute("open",""),a.classList.add(BC),o&&a.classList.add(o),a.dataset.menuScope=s;for(const[u,f]of Object.entries(n??{}))a.dataset[u]=f;a.style.left=`${t.x}px`,a.style.top=`${t.y}px`;const l=new Map;for(const u of e){l.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.danger&&f.setAttribute("danger",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",GC(u.icon)),f.textContent=u.label,a.appendChild(f)}a.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=l.get(f.id);p&&(sl(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(m=>{console.error(`[openstation] menu action '${p.id}' threw:`,m)}))}),document.body.appendChild(a),bn=a,ol=r??null,nl(a);const c=Fm(a,{close:()=>sl()});a.addEventListener("tile-menu-closed",c);const d=e.map(u=>u.id);i?.(d),L(`os.${s}.menu.opened`,{items:d,count:e.length})}function GC(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}const jC={active:UC,resolveCommonActions:Um,createModel:Om};let Lo=null;function VC(){Ae.contribute("openstation_content_changes_seen_ts",()=>Lo===null?0:Lo),Ae.subscribe("openstation_content_changes",t=>{if(!t||typeof t.ts!="number")return;const e=Lo===null,n=Lo??0;let o=Math.max(n,t.ts);if(!e&&Array.isArray(t.entries))for(const s of t.entries)!s||typeof s.ts!="number"||s.ts<=n||typeof s.type!="string"||s.type===""||(ya(`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));Lo=o})}const qC="desktop_mode_nonces",il=new Map;let Gm=!1;function rl(t,e){if(typeof t!="string"||t==="")return()=>{};let n=il.get(t);return n||(n=new Set,il.set(t,n)),n.add(e),()=>{n.delete(e)}}function KC(){Gm||(Gm=!0,Ae.subscribe(qC,t=>{if(!(!t||typeof t!="object"))for(const[e,n]of Object.entries(t)){if(typeof n!="string"||n==="")continue;const o=il.get(e);if(o)for(const s of o)try{s(n)}catch(i){console.error(`[desktop-mode/nonce-refresh] updater for "${e}" threw:`,i)}}}),YC())}function YC(){rl("wp_rest",XC),rl("desktop-mode-plugins",t=>{jm("desktop-mode-plugins","ajaxNonce",t)}),rl("updates",t=>{jm("desktop-mode-plugins","updatesNonce",t)})}function XC(t){const e=ZC();e&&typeof e.restNonce=="string"&&(e.restNonce=t);const n=Vm();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=t)}function jm(t,e,n){const s=Vm()?.[t];s&&typeof s=="object"&&(s[e]=n)}function ZC(){if(!(typeof window>"u"))return window.openStationConfig}function Vm(){if(!(typeof window>"u"))return window.openStationWindowConfig}const JC="desktop_mode_auth",QC=5e3,qm=1e3,ex=1e4;let Km=!1,_i=!1,al=!1,Ei=0,Ym=0,To=0,vn=null,Xm=0,Zm=null,Jm=null,Qm=()=>{try{window.location.reload()}catch{}};function ll(){try{const t=window.wp?.heartbeat;t&&typeof t.connectNow=="function"&&t.connectNow()}catch{}}function cl(t=qm){const e=Date.now();if(e<To){vn===null&&(vn=window.setTimeout(()=>{vn=null,To=Date.now()+qm,ll()},To-e));return}To=e+t,ll()}function tx(){_i=!0,!al&&(al=!0,L(b.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function nx(){for(const t of ox())try{t.contentWindow?.location.reload()}catch{}}function ox(){let t;try{t=document.querySelectorAll("iframe")}catch{return[]}return Array.from(t).filter(e=>e.id!=="wp-auth-check-frame"&&!e.closest("#wp-auth-check-wrap"))}function dl(){const t=Date.now();t-Xm<ex||(Xm=t,_i=!1,al=!1,vn!==null&&(window.clearTimeout(vn),vn=null),To=0,cl(),nx(),L(b.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function sx(t){const e=t&&typeof t=="object"?Number(t.uid):NaN;if(!(!Number.isFinite(e)||e<=0)){if(Ei<=0){Ei=e;return}e!==Ei&&Qm()}}function ix(t,e){if(t!==401&&t!==403)return;let n;try{n=new URL(String(e||""),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<Ym||(Ym=o+QC,ll())}function rx(){const t=document.getElementById("wp-auth-check-wrap");if(!t||typeof MutationObserver>"u")return;let e=!t.classList.contains("hidden");Jm=new MutationObserver(()=>{const n=!t.classList.contains("hidden");e&&!n&&cl(),e=n}),Jm.observe(t,{attributes:!0,attributeFilter:["class"]})}function ax(t={}){Km||(Km=!0,Ei=Number(t.currentUserId)>0?Number(t.currentUserId):0,t.reloadShell&&(Qm=t.reloadShell),Ae.subscribe("wp-auth-check",e=>{if(e===!1){tx();return}e===!0&&_i&&dl()}),Ae.subscribe("nonces_expired",()=>{if(_i){dl();return}cl()}),Ae.subscribe(JC,sx),Zm=e=>{if(e.origin!==window.location.origin)return;const n=e.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&dl()},window.addEventListener("message",Zm),rx())}const _n=12;function ul(t,e){const n=le(t,e.adminUrl);return(e.dockItems||[]).find(o=>le(o.url,e.adminUrl)===n||(o.submenu||[]).some(s=>le(s.url,e.adminUrl)===n))}function fl(t,e){const n=Math.max(200,e.width-_n*2),o=Math.max(200,e.height-_n*2),s=Math.min(t.width,n),i=Math.min(t.height,o),r=Math.max(0,e.width-s-_n),a=Math.max(0,e.height-i-_n),l=Math.max(_n,Math.min(t.x,r)),c=Math.max(_n,Math.min(t.y,a));return{x:l,y:c,width:s,height:i}}const eg=window.location.origin;function lx(t,e){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let l;try{l=new URL(a,window.location.href)}catch(g){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",a,g);return}if(l.origin!==eg)return;let c;try{c=new URL(e.adminUrl).pathname}catch(g){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",e.adminUrl,g),c="/wp-admin/"}if(!l.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(l.pathname)||l.searchParams.has("action")&&l.searchParams.get("action")==="logout"||l.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),ct(l.href)))return;const d=le(l.href,e.adminUrl),u=ul(l.href,e),f=(i.textContent||"").trim()||u?.title||"",p=!!i.closest("#wp-admin-bar-new-content"),m={id:d,baseId:d,multi:!!u?.multi||p,url:l.href,parentUrl:u?.url??l.href,title:u?.title||f,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu};if(p){t.openNew(m);return}t.open(m)},!0)}function cx(t){if(!t||typeof t!="object")return null;const e=t;return typeof e.total!="number"||!Number.isFinite(e.total)?null:{total:Math.max(0,Math.floor(e.total)),formatted:typeof e.formatted=="string"&&e.formatted!==""?e.formatted:String(e.total),text:typeof e.text=="string"?e.text:"",url:typeof e.url=="string"?e.url:""}}function dx(t){if(!t.url)return null;const e=document.createElement("li");e.id="wp-admin-bar-updates";const n=document.createElement("a");n.className="ab-item",n.href=t.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),e.appendChild(n),e}function ux(t){const e=cx(t);if(!e)return;let n=document.getElementById("wp-admin-bar-updates");if(e.total<=0){n&&(n.style.display="none");return}if(!n){const i=document.getElementById("wp-admin-bar-root-default");if(!i||(n=dx(e),!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=e.formatted);const s=n.querySelector(".updates-available-text");s&&(s.textContent=e.text)}const fx="os-registry-changed";function px(t,e){const n=new Set;if(Array.isArray(t))for(const r of t)r&&typeof r.id=="string"&&n.add(r.id);const o=new Set;for(const r of e)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 pl(t,e,n){const{added:o,removed:s}=px(e,n);if(o.length===0&&s.length===0||typeof document>"u")return;const i={registry:t,added:o,removed:s};document.dispatchEvent(new CustomEvent(fx,{detail:i}))}function hx(t){const{applyDockItems:e,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:l,syncServerUnfocusEffects:c,syncServerWindowLinkRenderers:d,syncServerDockRailRenderers:u,syncServerGames:f,syncServerDesktopThemes:p,renderIcons:m,syncShortcuts:g}=t;return function(w){const v=w.dockItems,R=w.nativeWindows,_=w.serverWidgets,E=w.serverWallpapers,N=w.serverCommandScripts,D=w.serverCommands,O=w.serverSettingsTabScripts,y=w.serverSettingsTabs,M=w.serverDockRailRendererScripts,T=w.serverTitleBarButtonScripts,x=w.serverUnfocusEffectScripts,I=w.serverWindowLinkRendererScripts,W=w.serverWindowNotices,z=w.serverGames,A=w.serverDesktopThemes,P=w.desktopIcons;if(!Array.isArray(v)||v.length===0)return;const B=n.dockItems;if(e(v),n.dockItems=v,pl("dock-items",B,v),g?.(),Array.isArray(R)){const C=n.nativeWindows;o(R),n.nativeWindows=R,pl("native-windows",C,R)}if(Array.isArray(_)&&(s(_),n.serverWidgets=_),Array.isArray(E)&&(i(E),n.serverWallpapers=E),Array.isArray(z)&&(f(z),n.serverGames=z),Array.isArray(A)&&(p?.(A),n.serverDesktopThemes=A),Array.isArray(N)&&(r(N,Array.isArray(D)?D:void 0),n.serverCommandScripts=N,Array.isArray(D)&&(n.serverCommands=D)),Array.isArray(O)&&(a(O,Array.isArray(y)?y:void 0),n.serverSettingsTabScripts=O,Array.isArray(y)&&(n.serverSettingsTabs=y)),Array.isArray(T)&&(l(T),n.serverTitleBarButtonScripts=T),Array.isArray(x)&&(c(x),n.serverUnfocusEffectScripts=x),Array.isArray(I)&&(d(I),n.serverWindowLinkRendererScripts=I),Array.isArray(M)&&(u(M),n.serverDockRailRendererScripts=M),Array.isArray(W)&&(ah(W),n.serverWindowNotices=W),Array.isArray(P)){const C=n.desktopIcons;m(P),n.desktopIcons=P,pl("desktop-icons",C,P)}ux(w.updateCounts)}}const mx=8e3,gx=600;function wx(t){const{layoutDispatcher:e,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:m,renderIcons:g,syncShortcuts:h}=t,w=hx({applyDockItems:M=>e?.applyDockItems(M),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:m,renderIcons:g,syncShortcuts:h});let v=typeof o.menuSig=="string"?o.menuSig:"",R=!1,_=null,E=!1,N=!1;const D=()=>{if(!o.adminUrl)return Promise.resolve();const M=(()=>{try{const T=new URL("admin.php",o.adminUrl);return T.searchParams.set("openstation_chromeless","1"),T.searchParams.set("openstation_menu_refresh","1"),T.toString()}catch{return null}})();return M?new Promise(T=>{const x=document.createElement("iframe");x.setAttribute("aria-hidden","true"),x.tabIndex=-1,x.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",x.src=M;let I=!1;const W=()=>{I||(I=!0,window.clearTimeout(A),window.removeEventListener("message",z),x.parentNode&&x.parentNode.removeChild(x),T())},z=P=>{if(P.source!==x.contentWindow)return;const B=P.data;!B||B.type!=="os-plugins-changed"||W()},A=window.setTimeout(()=>{L(b.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),W()},mx);window.addEventListener("message",z),document.body.appendChild(x)}):Promise.resolve()},O=()=>{if(E){N=!0;return}E=!0,D().finally(()=>{E=!1,N&&(N=!1,O())})},y=()=>{_!==null&&window.clearTimeout(_),_=window.setTimeout(()=>{_=null,O()},gx)};return window.addEventListener("message",M=>{if(M.origin!==eg)return;const T=M.data;if(T){if(T.type==="os-plugins-changed"){T.payload&&(w(T.payload),typeof T.payload.menuSig=="string"&&(v=T.payload.menuSig));return}if(T.type==="os-updates-changed"){y();return}if(T.type==="os-menu-signature"){const x=T.sig;typeof x=="string"&&x!==""&&x!==v&&!R&&(R=!0,D().finally(()=>{R=!1}))}}}),D}function yx(t){if(!t)return!1;if(Array.isArray(t.windows)&&t.windows.length>0)return!0;if(typeof t.updated!="number"||t.updated<=0||!Array.isArray(t.desktops)||t.desktops.length===0)return!1;if(t.desktops.length>1)return!0;const e=t.desktops[0];return e?.id&&e.id!=="desktop-1"?!0:!!t.activeDesktop&&t.activeDesktop!=="desktop-1"}function bx(t,e,n=5e3){const o=t.getById(e);return o?Promise.resolve(o):new Promise(s=>{const i=l=>{window.clearTimeout(a),document.removeEventListener("os-window-opened",r),s(l)},r=l=>{l.detail?.windowId===e&&i(t.getById(e)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function vx(t,e,n,o){const s=n.getBoundingClientRect();Array.isArray(e.session.desktops)&&e.session.desktops.length>0&&t.seedDesktops(e.session.desktops,e.session.activeDesktop||e.session.desktops[0].id);const i={};for(const r of e.session.windows){if(!r.native)continue;const a=fl(r,s);i[r.id]={desktopId:r.desktopId,initialState:r.state,x:a.x,y:a.y,width:a.width,height:a.height,...r.params?{params:r.params}:{}}}Object.keys(i).length>0&&t.seedWindowRestoreState(i);for(const r of e.session.windows){if(r.native){if(!o?.(r.id))continue;await bx(t,r.id);continue}const a=fl(r,s),l=ul(r.url,e),c=await t.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!l?.multi,url:r.url,parentUrl:l?.url??r.url,title:r.title,icon:r.icon||"dashicons-admin-generic",x:a.x,y:a.y,width:a.width,height:a.height,initialState:r.state,submenu:l?.submenu});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(e.session.focused){const r=t.getById(e.session.focused);r&&t.focus(r)}}async function _x(t,e){if(ct(e.currentPage))return;const n=le(e.currentPage,e.adminUrl),o=ul(e.currentPage,e);await t.open({id:n,baseId:n,multi:!!o?.multi,url:e.currentPage,parentUrl:o?.url??e.currentPage,title:e.currentTitle,icon:e.currentIcon,submenu:o?.submenu})}function Ex(t){return!(t.fromPortal&&!t.fromPortalIntent&&(t.hasSession||!t.defaultEnabled||t.isNativeDefault))}function hl(t,e,n,o){const s=cf(e,n),i=window.fetch(e,s);if(i.then(a=>{if(a.status===401||a.status===403){let l;typeof e=="string"?l=e:e instanceof URL?l=e.href:l=e.url,ix(a.status,l)}},()=>{}),o?.silent)return i;let r=o?.window;return!r&&o?.windowId&&(r=t.getById(o.windowId)??null),r||(r=t.getFocused()),r&&typeof r.trackActivity=="function"&&r.trackActivity(i).catch(()=>{}),i}const kx=500,Sx=1500;function Ax(t,e){let n=null,o=!1,s=!1,i=0;const r=async()=>{if(o){s=!0;return}o=!0,i=Date.now();const c=t.snapshot();try{await hl(t,e.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({session:c}),keepalive:!0},{silent:!0})}catch(d){L(b.SHELL_ERROR,{scope:"session-save",error:d})}finally{o=!1,s&&(s=!1,l())}},a=()=>{n!==null&&(clearTimeout(n),n=null),s=!1;const c=t.snapshot(),d=new Blob([JSON.stringify({session:c})],{type:"application/json"}),u=e.sessionUrl+(e.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(e.restNonce);navigator.sendBeacon&&navigator.sendBeacon(u,d)||r()},l=()=>{n!==null&&clearTimeout(n);let c=kx;if(i!==0){const d=Date.now()-i;c=Math.max(c,Sx-d)}n=window.setTimeout(()=>{n=null,r()},c)};return window.addEventListener("pagehide",a),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&a()}),l}const Ix=120;function Cx(t){document.addEventListener("os-window-opened",t),document.addEventListener("os-window-closed",t),document.addEventListener("os-window-focused",t),document.addEventListener("os-window-changed",t),X(b.DESKTOP_CREATED,"desktop-mode/session-save",t),X(b.DESKTOP_CLOSED,"desktop-mode/session-save",t),X(b.DESKTOP_SWITCHED,"desktop-mode/session-save",t)}function xx(){const t=document.getElementById("os-shell");let e=null;const n=()=>{e=null;const o=t?t.getBoundingClientRect():null;L(b.SHELL_RESIZED,{width:o?Math.round(o.width):window.innerWidth,height:o?Math.round(o.height):window.innerHeight})};window.addEventListener("resize",()=>{e!==null&&window.clearTimeout(e),e=window.setTimeout(n,Ix)}),document.addEventListener("visibilitychange",()=>{L(b.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function Lx(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};return K(b.DOCK_TILE_CLASS,t,o)}function Tx(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};return K(b.DOCK_TILE_ELEMENT,t,o)}function Nx(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};return K(b.DOCK_TILE_TOOLTIP,t,o)}function Dx(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};L(b.DOCK_TILE_RENDERED,{...o,el:t})}const Rx=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),ml=new Set;function Ox(t){if(!t||typeof t.closest!="function")return!1;const e=t;if(e.closest(Rx))return!0;for(const n of ml)if(e.closest(n))return!0;return!1}function Mx(t){return typeof t!="string"||t.trim()===""?()=>{}:(ml.add(t),()=>{ml.delete(t)})}const pt=new Map,Px=window.location.origin;function tg(t){let e=pt.get(t);return e||(e={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},pt.set(t,e)),Wx(t,e),e}function Wx(t,e){const n=gl(t);if(!n||e.loadHandlerTarget===n&&e.loadHandler||(e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),typeof n.addEventListener!="function"))return;const o=()=>{queueMicrotask(()=>En(t))};n.addEventListener("load",o),e.loadHandler=o,e.loadHandlerTarget=n}function $x(t){t.loadHandlerTarget&&t.loadHandler&&typeof t.loadHandlerTarget.removeEventListener=="function"&&t.loadHandlerTarget.removeEventListener("load",t.loadHandler),t.loadHandler=null,t.loadHandlerTarget=null}function gl(t){const e=window.wp?.os?.windowManager;if(e&&typeof e.getById=="function"){const o=e.getById(t);if(o?.iframe)return o.iframe;if(o?.element){const s=o.element.querySelector("iframe");if(s)return s}}return document.getElementById(`wp-window-${t}`)?.querySelector("iframe")??null}function Ux(t){const e={};for(const[n,o]of t.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&&(e[n]=s.join(", "))}return e}function En(t){const e=gl(t);if(!e||!e.contentWindow)return;const n=pt.get(t),o=n?Ux(n):{},s=!!n&&n.observeCount>0;try{e.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},Px)}catch{}}X(b.IFRAME_READY,"desktop-mode/devtools/replay",t=>{const e=t;e&&typeof e.windowId=="string"&&pt.has(e.windowId)&&En(e.windowId)}),X(b.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",t=>{const e=t;if(!e||typeof e.windowId!="string")return;const n=pt.get(e.windowId);if(n)for(const o of n.observers)try{o(e)}catch{}});const St=new Map,Fx=1e3;function ng(t,e,n){const o=St.get(t);if(!o||o.inflight)return;o.inflight=!0;const s=new URL(e+"desktop-mode/v1/debug",window.location.origin);s.searchParams.set("sessionId",t),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(t)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const l=o.channels.get(a.channel);if(l)for(const c of l)try{c(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=St.get(t);r&&r.channels.size>0&&(r.timer=setTimeout(()=>ng(t,e,n),Fx))})}function Bx(){const t=window.openStationConfig;return!t||!t.restUrl||!t.restNonce?null:{restUrl:t.restUrl,restNonce:t.restNonce}}function Hx(t,e){const n=St.get(t);if(!n)return;const o=n.channels.get(e.channel);if(o)for(const s of o)try{s(e)}catch{}}let zx=0;const og={addRequestHeader(t,e,n){if(typeof t!="string"||t==="")return()=>{};if(typeof e!="string"||e==="")return()=>{};const o=tg(t),s={value:n};let i=o.headers.get(e);return i||(i=[],o.headers.set(e,i)),i.push(s),En(t),()=>{const r=pt.get(t);if(!r)return;const a=r.headers.get(e);if(!a)return;const l=a.indexOf(s);l>=0&&a.splice(l,1),a.length===0&&r.headers.delete(e),En(t),sg(t)}},onRequest(t,e,n){if(typeof t!="string"||t==="")return()=>{};if(typeof e!="function")return()=>{};const o=tg(t);o.observers.add(e);const s=!!n?.observe;return s&&(o.observeCount++,En(t)),()=>{const i=pt.get(t);i&&(i.observers.delete(e),s&&(i.observeCount=Math.max(0,i.observeCount-1),En(t)),sg(t))}},reloadWithDebugSession(t,e,n){if(typeof t!="string"||t===""||typeof e!="string"||e==="")return null;const o=gl(t);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=og.addRequestHeader(t,s,e);try{const a=o.getAttribute("src")||o.src||"",l=new URL(a,window.location.origin);l.searchParams.set(i,e),o.src=l.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const t=window.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(t,e,n){Hx(t,{id:++zx,t:Date.now(),channel:e,payload:n})},subscribe(t,e,n){let o=St.get(t);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},St.set(t,o));let i=o.channels.get(e);if(i||(i=new Set,o.channels.set(e,i)),i.add(n),s){const r=Bx();r&&ng(t,r.restUrl,r.restNonce)}return()=>{const r=St.get(t);if(!r)return;const a=r.channels.get(e);a&&(a.delete(n),a.size===0&&r.channels.delete(e)),r.channels.size===0&&(r.timer&&clearTimeout(r.timer),St.delete(t))}}}};function sg(t){const e=pt.get(t);e&&e.headers.size===0&&e.observers.size===0&&($x(e),pt.delete(t))}async function ki(t){return await ir(rr()),new Promise(e=>{const n=document.createElement("os-confirm-dialog");n.setAttribute("open",""),t.title&&n.setAttribute("title",t.title),n.setAttribute("message",t.message),t.confirmLabel&&n.setAttribute("confirm-label",t.confirmLabel),t.cancelLabel&&n.setAttribute("cancel-label",t.cancelLabel),t.danger&&n.setAttribute("danger",""),t.hideCancel&&n.setAttribute("hide-cancel",""),t.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),e(i)};n.addEventListener("os-confirm",()=>o(!0)),n.addEventListener("os-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}function Gx(t){const e=[];for(const l of t.getVisibleRects()){if(l.state==="minimized"||l.element.offsetParent===null)continue;const c=l.element.getBoundingClientRect();e.push({id:`window:${l.windowId}`,kind:"window",rect:ig(c),face:"top",element:l.element})}const n=document.getElementById("os-shell");if(n){const l=n.getBoundingClientRect();e.push({id:"shell:floor",kind:"shell",rect:{x:l.left,y:l.bottom-1,width:l.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const l of Array.from(o)){const c=l.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const d=l.getAttribute("data-os-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,d==="bottom"?e.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:c.width,height:1},face:"top",element:l}):d==="right"?e.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:l}):e.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:l})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(l=>{const c=l.getBoundingClientRect();if(c.width===0&&c.height===0)return;const d=l.dataset.widgetId??String(r++);e.push({id:`widget:${d}`,kind:"widget",rect:ig(c),face:"top",element:l})});const a=K(b.WALLPAPER_SURFACES,e);return Array.isArray(a)?a:e}function ig(t){return{x:t.left,y:t.top,width:t.width,height:t.height}}const jx="__openstationKeyedListKey",Vx="__openstationKeyedListData";function qx(t){const e=t.__openstationKeyedList;if(e)return e;const n={byKey:new Map};return t.__openstationKeyedList=n,n}function Kx(t,e,n){const o=qx(t),s=o.byKey,i=new Map,r=[],a=new Set;for(const l of e){const c=String(n.keyOf(l));a.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),a.add(c);const d=s.get(c);if(d){const f=d.data;n.updateItem?.(d.el,l,f),d.data=l,i.set(c,d),r.push(d.el);continue}const u=n.buildItem(l);u[jx]=c,u[Vx]=l,i.set(c,{el:u,data:l}),r.push(u)}for(const[l,c]of s)i.has(l)||c.el.remove();for(let l=0;l<r.length;l++){const c=r[l],d=t.children[l];d!==c&&t.insertBefore(c,d??null)}o.byKey=i}function Yx(t){const e=t.__openstationKeyedList;if(e){for(const n of e.byKey.values())n.el.remove();e.byKey.clear(),delete t.__openstationKeyedList}}function Xx(t){const{root:e,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:l=O=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",O)}}=t;let c=t.sentinel??null;c||(c=document.createElement("div"),c.dataset.osInfiniteListSentinel="",c.style.height="1px",e.appendChild(c));const d=new Set;let u=r,f=!0,p=!1,m=null,g=0,h=!1,w=null;const v=O=>{if(p!==O){p=O;try{a(O)}catch(y){l(y)}}},R=()=>{w&&(w.disconnect(),w=null)},_=()=>{w||!c||h||(w=new IntersectionObserver(O=>{for(const y of O)y.isIntersecting&&E()},{rootMargin:i}),w.observe(c))},E=async()=>{if(h||p||!f)return;v(!0),m=new AbortController;const O=m;try{const y=await n(u,O.signal);if(h||O!==m)return;let M=0;const T=document.createDocumentFragment();for(const x of y.items??[]){const I=String(o(x));if(d.has(I))continue;d.add(I);const W=s(x,g+M);T.appendChild(W),M++}M>0&&(c&&c.parentNode===e?e.insertBefore(T,c):e.appendChild(T),g+=M),u=y.nextCursor??null,u||(f=!1,R())}catch(y){if(y?.name==="AbortError")return;l(y)}finally{O===m&&(v(!1),m=null)}},N=()=>{if(h)return;m?.abort(),m=null,d.clear(),u=r,f=!0,g=0;const O=c&&c.parentNode===e;for(;e.firstChild;)e.removeChild(e.firstChild);O&&c&&e.appendChild(c),v(!1),_(),E()},D=()=>{h||(h=!0,R(),m?.abort(),m=null,!t.sentinel&&c&&c.parentNode===e&&e.removeChild(c),c=null,v(!1))};return _(),E(),{reset:N,loadMore:E,hasMore:()=>f,isLoading:()=>p,destroy:D}}const Zx=520,Jx=720,Qx=500;function eL(t,e={}){if(typeof t!="string"||t==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=nL(),o=oL();return Fe(nt(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:t})},{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=>tL(s,t,e))}function tL(t,e,n){return new Promise((o,s)=>{const i=n.width??Zx,r=n.height??Jx,a=Math.max(0,Math.floor((window.screen.width-i)/2)),l=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${l}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(t.authorize_url,`os-oauth-${e}`,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 m=()=>{p||(p=!0,window.removeEventListener("message",g),f!==null&&(window.clearInterval(f),f=null))},g=h=>{if(h.origin!==u)return;const w=h.data;if(!w||w.type!=="os-oauth-callback")return;const v=w.payload;if(m(),v&&v.ok)o(v);else{const R=v?.reason??"unknown",_=v?.message??"OAuth flow failed",E=new Error(`[openstation] startOAuth(${e}) failed: ${R} — ${_}`);E.cause=v,s(E)}};window.addEventListener("message",g),f=window.setInterval(()=>{d.closed&&(m(),s(new Error(`[openstation] startOAuth(${e}) cancelled — popup closed before completing.`)))},Qx)})}function rg(){return window.openStationConfig??{}}function nL(){const t=rg().restRoot;return typeof t=="string"&&t!==""?t:`${window.location.origin}/wp-json/`}function oL(){const t=rg().restNonce;return typeof t=="string"&&t!==""?t:null}const sL={register:na,unregister:jf,list:qf,get:oi,subscribe:uk,launch:tp,getPlaytime:()=>Lk().then(t=>t.playtime)},iL="",rL="system-default",aL={accent:"pulse",desktopLayout:"classic"};function lL(t,e,n={}){const o=e===iL,s=o?null:Lu(e);if(!o&&!s)return{};const i=o?rL:s.slug,r=t.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=Vv(o?aL:s.recommendedOsSettings),l=Object.keys(a);if(l.length===0)return{};const c=t,d={};for(const u of l){const f=a[u];typeof f!="string"&&typeof f!="number"||!(u in t)||typeof c[u]!=typeof f||(c[u]=f,d[u]=f)}return Object.keys(d).length===0?{}:(r||(t.appliedThemeRecommendations=[...t.appliedThemeRecommendations,i].slice(-64)),d)}const cL=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","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","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 dL(t){const{manager:e,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:l,registerWindow:c,openWindowById:d,openNewWindowById:u,placeSystemTile:f,setDefaultWindow:p,refreshMenu:m,openOsSettings:g,aiAssistant:h,dragBridge:w,dragManager:v,connect:R,getConnection:_,wallpaperSuspend:E,mio:N,config:D}=t,O={windowManager:e,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,icons:i,files:r,confirm:ki,saveSession:a,hooks:Zy(),HOOKS:b,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:y=>{to(y),s.apply()},registerWidget:y=>{Pa(y)},widgetLayer:l,widgets:{redock:y=>{l?.redock(y)}},loadVendorScript:ke,getWallpaperSurfaces:()=>Gx(e),wallpaper:E,mio:N,games:sL,registerWindow:c,openWindow:d,openNewWindow:u,fetch:(y,M,T)=>hl(e,y,M,T),repaintLoadingOverlays:zu,cloneTemplate:Fa,onWindow:lA,createInfiniteList:Xx,startOAuth:eL,registerSystemTile:y=>{f(y),L(b.DOCK_ITEM_APPENDED,{id:y.id})},registerModule:Ff,loadModules:Bf,whenReady:jc,ready:jc,isReady:Qy,setDefaultWindow:p,refreshMenu:m,config:D,ai:h,dragBridge:w,dragManager:v,registerCommand:ai,unregisterCommand:rp,listCommands:ap,registerDestructiveAdminAction:x_,unregisterDestructiveAdminAction:Gu,listDestructiveAdminActions:L_,registerSettingsTab:cp,unregisterSettingsTab:dp,listSettingsTabs:up,registerDockRailRenderer:yu,unregisterDockRailRenderer:Wv,listDockRailRenderers:Fv,openOsSettings:g,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:y=>s.subscribeOsSettings(y),updateOsSettings:(y,M={})=>{if(typeof y.wallpaper=="string"&&(s.state.wallpaper=y.wallpaper),typeof y.accent=="string"&&(s.state.accent=y.accent),typeof y.dockSize=="string"&&(s.state.dockSize=y.dockSize),typeof y.windowRadius=="string"&&(s.state.windowRadius=y.windowRadius),typeof y.adminBarMode=="string"&&(s.state.adminBarMode=y.adminBarMode),typeof y.desktopLayout=="string"&&(s.state.desktopLayout=y.desktopLayout),typeof y.desktopTheme=="string"&&(s.state.desktopTheme=y.desktopTheme),typeof y.unfocusEffect=="string"&&(s.state.unfocusEffect=y.unfocusEffect),typeof y.windowReveal=="string"&&(s.state.windowReveal=y.windowReveal),typeof y.windowRevealDuration=="number"&&(s.state.windowRevealDuration=y.windowRevealDuration),typeof y.dockRailRenderer=="string"&&(s.state.dockRailRenderer=y.dockRailRenderer),typeof y.windowLinkRenderer=="string"&&(s.state.windowLinkRenderer=y.windowLinkRenderer),(y.windowLinkVisibility==="focus"||y.windowLinkVisibility==="always"||y.windowLinkVisibility==="off")&&(s.state.windowLinkVisibility=y.windowLinkVisibility),typeof y.windowLinksEnabled=="boolean"&&(s.state.windowLinksEnabled=y.windowLinksEnabled),typeof y.windowLinkRaiseOnFocus=="boolean"&&(s.state.windowLinkRaiseOnFocus=y.windowLinkRaiseOnFocus),typeof y.windowLinkHighlight=="boolean"&&(s.state.windowLinkHighlight=y.windowLinkHighlight),y.ai&&typeof y.ai=="object"&&(s.state.ai={...s.state.ai,...y.ai}),typeof y.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=y.nativePostsEnabled),typeof y.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=y.nativePagesEnabled),typeof y.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=y.nativeUsersEnabled),typeof y.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=y.nativePluginsEnabled),typeof y.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=y.nativeCommentsEnabled),typeof y.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=y.foldersSharingEnabled),typeof y.developerModeEnabled=="boolean"&&(s.state.developerModeEnabled=y.developerModeEnabled),Array.isArray(y.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=y.nativePostsHiddenColumns.filter(T=>typeof T=="string"&&T!=="").slice(0,32)),y.itemVisibility&&typeof y.itemVisibility=="object"){const T=["both","dock","desktop","hidden"],x={};for(const[I,W]of Object.entries(y.itemVisibility))typeof I!="string"||I===""||typeof W!="string"||!T.includes(W)||(x[I]=W);s.state.itemVisibility=x}if(Array.isArray(y.dockOrder)&&(s.state.dockOrder=y.dockOrder.filter(T=>typeof T=="string"&&T!=="").slice(0,256)),y.dockPromotedPositions&&typeof y.dockPromotedPositions=="object"){const x={};for(const[I,W]of Object.entries(y.dockPromotedPositions)){if(typeof I!="string"||I===""||!W||typeof W!="object")continue;const z=W;if(!(typeof z.x!="number"||typeof z.y!="number"||!Number.isFinite(z.x)||!Number.isFinite(z.y)||Math.abs(z.x)>1e5||Math.abs(z.y)>1e5)&&(x[I]={x:z.x,y:z.y},Object.keys(x).length>=256))break}s.state.dockPromotedPositions=x}s.save(M),(typeof y.wallpaper=="string"||typeof y.accent=="string"||typeof y.dockSize=="string"||typeof y.windowRadius=="string"||typeof y.adminBarMode=="string"||typeof y.desktopLayout=="string"||typeof y.dockRailRenderer=="string"||typeof y.desktopTheme=="string")&&s.apply(),(y.itemVisibility||y.dockOrder)&&o?.refresh()},deriveWindowId:(y,M)=>le(y,M??D.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:y=>o?.getSystemTile(y)??null,getMenuItems:()=>o?.getMenuItems()??[],renderIcon:Zn,applyTileClasses:Lx,applyTileElement:Tx,applyTileTooltip:Nx,dispatchTileRendered:Dx,isDockElement:Ox,registerDockSelector:Mx,registerTitleBarButton:ci,unregisterTitleBarButton:Qk,listTitleBarButtons:t0,registerUnfocusEffect:ui,unregisterUnfocusEffect:N0,listUnfocusEffects:_a,registerWindowReveal:Ue,unregisterWindowReveal:vv,listWindowReveals:su,relations:$_,registerWindowLinkRenderer:gp,unregisterWindowLinkRenderer:o0,listWindowLinkRenderers:wp,registerWindowTheme:zp,unregisterWindowTheme:Gp,listWindowThemes:jp,desktopThemes:{list:Xv,getActive:Nr,setActive:Kr,subscribe:Jv,resolveIcon:$s,resolveIconColor:Dr,applyRecommendedOsSettings:y=>{const M=y??Nr()??"";if(M==="")return{};const T=lL(s.state,M,{force:!0});return Object.keys(T).length>0&&(s.save(),s.apply()),T}},applyWindowTheme:(y,M)=>{const T=e.getById(y);T&&T.setAppearanceTheme(M)},registerWindowControl:po,unregisterWindowControl:Kp,listWindowControls:Yp,applyWindowControls:(y,M)=>{const T=e.getById(y);T&&T.setAppearanceControls(M)},registerWindowSlot:Qp,unregisterWindowSlot:Ca,listWindowSlots:eh,applyWindowSlot:(y,M,T)=>{const x=e.getById(y);x&&x.setAppearanceSlot(M,T)},registerWindowNotice:ih,unregisterWindowNotice:Da,listWindowNotices:rh,dismissWindowNotice:eS,undismissWindowNotice:tS,registerWindowChrome:sS,unregisterWindowChrome:dh,listWindowChromes:uh,applyWindowChrome:(y,M)=>{const T=e.getById(y);T&&T.setAppearanceChrome(M)},connect:R,getConnection:_,broadcast:ya,subscribe:fn,registerPalette:Lm,unregisterPalette:yC,listPalettes:bC,openPalette:Za,devtools:og,createSharedStore:ie,presence:TC,selection:jC,activity:Ee,heartbeat:Ae,showToast:Z,notify:ra,pwa:{promptInstall:bI,undismissInstallHint:vI,getState:oo,subscribe:Zf,requestNotificationPermission:bk,getNotificationPermission:vk},renderKeyedList:Kx,clearKeyedList:Yx,registerNamespace:(y,M)=>{if(typeof y!="string"||y===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!M||typeof M!="object"){console.warn(`[openstation] registerNamespace("${y}"): api must be an object`);return}if(cL.has(y)){console.warn(`[openstation] registerNamespace("${y}"): name is reserved by the shell — pick a plugin-specific key`);return}O[y]=M},getWindowConfig:y=>{const M=window.openStationWindowConfig;if(!M||typeof M!="object")return;const T=M[y];return T===void 0?void 0:T},debug:{window:y=>{const M=(D.nativeWindows??[]).find(A=>A.id===y);if(!M)return null;const T=M.scriptUrl||"";let x="unknown",I=!1;T&&(document.querySelector(`script[data-os-vendor="${T.replace(/"/g,'\\"')}"]`)?(x="lazy",I=!0):Array.from(document.querySelectorAll("script[src]")).find(B=>B.src===T)&&(x="eager",I=!0));const W=window.openStationWindowConfig,z=!!(W&&typeof W=="object"&&Object.prototype.hasOwnProperty.call(W,y));return{id:y,scriptHandle:M.scriptHandle||"",scriptUrl:T,loadPath:x,tagInDom:I,configPresent:z,extras:{hasTranslations:!!M.scriptTranslations,l10nCount:(M.scriptL10n??[]).length,beforeCount:(M.scriptBefore??[]).length,afterCount:(M.scriptAfter??[]).length}}}}};return O}function uL(t){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=t;return}Object.assign(window.wp.os,t)}const wl=ie("desktop-mode/layout",()=>({layout:"classic"}));function ag(t){wl.state.layout!==t&&(wl.state.layout=t,wl.notify())}class lg{constructor(e){this.shape=e}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 fL extends lg{constructor(e,n){super(e),this.typeSlug=n}type(){return this.typeSlug}}const No=new Map,yl=new Set;function Ve(t){if(!t.type)throw new Error("[openstation] registerType: `type` is required.");if(!t.label)throw new Error("[openstation] registerType: `label` is required.");No.set(t.type,{type:t.type,label:t.label,sort:typeof t.sort=="number"?t.sort:100,DesktopFile:t.DesktopFile}),L("os.files.type-registered",t.type,t),dg()}function pL(t){No.delete(t)&&(L("os.files.type-unregistered",t),dg())}function hL(t){const e=No.get(t);return e||null}function cg(){const t=Array.from(No.values()).slice(),e=K("os.files.types",t),n=Array.isArray(e)?e:t;return n.sort((o,s)=>o.sort!==s.sort?o.sort-s.sort:o.label.localeCompare(s.label)),n}function kn(t){const e=No.get(t.type);return e?.DesktopFile?new e.DesktopFile(t):new fL(t,t.type)}function mL(t){return yl.add(t),()=>yl.delete(t)}function dg(){for(const t of yl)try{t()}catch(e){console.error("[openstation] files registry subscriber threw:",e)}}const Si=new Map,bl=new Set;let vl={};function ug(t){vl={...t},Sl()}function _l(){return{...vl}}function Be(t){if(!t.id)throw new Error("[openstation] registerOpener: `id` is required.");if(!t.label)throw new Error("[openstation] registerOpener: `label` is required.");if(!Array.isArray(t.types)||t.types.length===0)throw new Error("[openstation] registerOpener: `types` must be a non-empty array.");if(!t.handler||typeof t.handler!="object")throw new Error("[openstation] registerOpener: `handler` is required.");Si.set(t.id,{id:t.id,label:t.label,types:t.types.slice(),isDefault:!!t.isDefault,sort:typeof t.sort=="number"?t.sort:100,appliesTo:typeof t.appliesTo=="function"?t.appliesTo:void 0,handler:t.handler}),L("os.files.opener-registered",t.id,t),Sl()}function gL(t){Si.delete(t)&&(L("os.files.opener-unregistered",t),Sl())}function wL(t){return Si.get(t)??null}function fg(){const t=Array.from(Si.values()).slice(),e=K("os.files.openers",t),n=Array.isArray(e)?e:t;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 El(t,e){return fg().filter(n=>n.types.includes(t)).filter(n=>n.appliesTo?e!==void 0&&n.appliesTo(e):!0)}function kl(t,e){const n=El(t,e);if(n.length===0)return null;const o=vl[t];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]),K("os.files.resolve-opener",s,t)??null}function yL(t){return bl.add(t),()=>bl.delete(t)}function Sl(){for(const t of bl)try{t()}catch(e){console.error("[openstation] openers subscriber threw:",e)}}let Do=null;function bL(t){Do=t}async function Ai(t,e){if(!Do)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=kl(t.type(),t);if(!n)return L("os.files.open-failed",{reason:"no-opener",type:t.type(),ref:t.ref()}),!1;L("os.files.opening",{file:t,openerId:n.id});try{const o=n.handler;if(o.kind==="url"){const s=await o.url(t);if(!s)return!1;const i=o.windowId?o.windowId(t):Do.deriveWindowId(s),r=o.title?o.title(t):t.title(),a=t.icon(),l=Do.openUrl({id:i,url:s,title:r,icon:a});return L("os.files.opened",{file:t,openerId:n.id,kind:"url"}),l}if(o.kind==="window"){const s=o.config?o.config(t):void 0,i=Do.openNativeWindow(o.windowId,s);return L("os.files.opened",{file:t,openerId:n.id,kind:"window"}),i}return await o.open(t,e),L("os.files.opened",{file:t,openerId:n.id,kind:"js"}),!0}catch(o){return L("os.files.open-failed",{reason:"handler-threw",type:t.type(),ref:t.ref(),openerId:n.id,error:o}),console.error("[openstation] file opener threw:",o),!1}}function vL(){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=ie("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function pg(t){qe.state.activeAgent=t,qe.state.transcripts[t.id]||(qe.state.transcripts[t.id]=[]),qe.state.conversationIds||(qe.state.conversationIds={},qe.state.conversationsRev=0),qe.notify()}const hg="desktop-mode/v1/agents/conversations";async function mg(t,e,n={}){const o=await Fe(nt(t.restRoot,e),{...n,headers:{"Content-Type":"application/json","X-WP-Nonce":t.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 _L(t){return t.filter(e=>!e.pending)}async function EL(t,e){const n=qe.state,o=_L(n.transcripts[t.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[t.id];if(s)await mg(e,`${hg}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await mg(e,hg,{method:"POST",body:JSON.stringify({agentId:t.id,messages:o})});n.conversationIds[t.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,qe.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const gg={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function wg(t){const e=Number.parseInt(String(t??""),10);return Number.isFinite(e)&&e>0?e:0}function yg(t){if(t.type==="shortcut"){const e=t.data;let n=gg[String(e.kind??"")];n==="post"&&e.bridgePayload?.postType==="page"&&(n="page");const o=wg(e.ref);return!n||!o?null:{kind:n,id:o,title:String(e.title??"")||`#${o}`}}if(t.type==="desktop-file"){const n=t.data.placement?.file;if(!n)return null;const o=gg[String(n.type??"")],s=wg(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function kL(t,e,n){return!e||n&&e.kind==="user"&&e.id===n||t==null?!1:t.length===0?!0:t.includes(e.kind)}function SL(t){return ae(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"),t.kind,t.title,String(t.id))}function AL(t){return{kind:t.kind,id:t.id,title:t.title}}function bg(t,e="agents"){pg(t);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:e})}async function IL(t,e,n,o,s){pg(t);const i=qe.state.transcripts[t.id],r=i.filter(l=>!l.pending&&l.role!=="error").map(l=>({role:l.role,text:l.text}));i.push({role:"user",text:e,at:Date.now(),attachment:s});const a={role:"agent",text:k("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(a),qe.notify();try{const l=await Fe(nt(n.restRoot,`desktop-mode/v1/agents/${t.id}/invoke`),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":n.restNonce},body:JSON.stringify({message:e,source:o,history:r})},{source:"desktop-mode/agents"}),c=await l.json().catch(()=>null);if(!l.ok){const u=c&&typeof c=="object"&&typeof c.message=="string"?c.message:`HTTP ${l.status}`;throw new Error(u)}const d=c;a.text=d.text||k("The agent finished without a text answer.","desktop-mode"),a.toolCalls=d.toolCalls,Array.isArray(d.callToActions)&&d.callToActions.length>0&&(a.callToActions=d.callToActions)}catch(l){a.role="error",a.text=l instanceof Error?l.message:String(l)}a.pending=!1,qe.notify(),EL(t,n)}function CL(t,e,n){return bg(t,"agents-drop"),IL(t,SL(e),n,"drag",AL(e))}let Al=null;function vg(t){Al=t}function Ro(){if(!Al)throw new Error("[openstation] files REST client called before installRestDeps().");return Al}function xL(){return Ro()}class Il extends Error{constructor(e){super(`Row was changed by ${e.actor.name||"another session"} (parent="${e.current.parentName}")`),this.name="FilesConflictError",this.status=409,this.detail=e}}async function ue(t,e){const{baseUrl:n,nonce:o}=Ro(),s=nt(n,t),i=new Headers(e.headers??{});i.set("X-WP-Nonce",o),e.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Fe(s,{...e,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),a=await r.text();let l=null,c=null;if(a)try{l=JSON.parse(a)}catch(d){l=null,c=d}if(!r.ok){if(r.status===409){const u=l?.data?.data??l?.data;if(u&&typeof u=="object")throw new Il(u)}const d=l;throw new Error(`[openstation] files REST ${r.status}: ${d?.code??""} ${d?.message??""}`.trim())}if(l===null){if(c&&a){const d=a.slice(0,120).replace(/\s+/g," ");throw new Error(`[openstation] files REST ${r.status} returned non-JSON body — ${c.message}. First 120 chars: ${d}`)}throw new Error(`[openstation] files REST ${r.status}: empty or unparseable body.`)}return l}function Le(t=0){return ue(`/placements?folder=${encodeURIComponent(String(t))}`,{method:"GET"})}function Sn(t){return ue("/placements",{method:"POST",body:JSON.stringify(t)})}function An(t,e,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),ue(`/placements/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:o})}function Cl(t){return ue(`/placements/${t}`,{method:"DELETE"})}async function Ii(t,e){const{baseUrl:n,nonce:o}=Ro(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Fe(i,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o},credentials:"same-origin",body:JSON.stringify({items:[{id:t,type:e}]})},{source:"desktop-mode/files"});if(!r.ok)throw new Error(`[openstation] restore ${r.status}`);return await r.json()}function xl(){return ue("/folders",{method:"GET"})}function Ll(t){return ue("/folders",{method:"POST",body:JSON.stringify(t)})}function _g(t,e,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),ue(`/folders/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:o})}function Tl(t){return ue(`/folders/${t}`,{method:"DELETE"})}function Eg(t){return ue("/associations",{method:"PUT",body:JSON.stringify({associations:t})})}function kg(t){return ue(`/folders/${t}/shares`,{method:"GET"})}function Sg(t,e){return ue(`/folders/${t}/shares`,{method:"POST",body:JSON.stringify(e)})}function Ag(t,e,n){return ue(`/folders/${t}/shares/${e}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function Ig(t,e){return ue(`/folders/${t}/shares/${e}`,{method:"DELETE"})}function Cg(t,e){return ue(`/folders/${t}/shares/${e}/accept`,{method:"POST"})}function xg(t,e){return ue(`/folders/${t}/shares/${e}/deny`,{method:"POST"})}function Lg(t){return ue(`/folders/${t}/leave`,{method:"POST"})}function LL(){return ue("/folder-sharing-tables/purge",{method:"POST"})}function Tg(t){return ue(`/uploads/${t}/shares`,{method:"GET"})}function Ng(t,e){return ue(`/uploads/${t}/shares`,{method:"POST",body:JSON.stringify({userId:e})})}function Dg(t,e){return ue(`/uploads/${t}/shares/${e}`,{method:"DELETE"})}function Rg(t,e){return ue(`/uploads/${t}/shares/${e}/accept`,{method:"POST"})}function Og(t,e){return ue(`/uploads/${t}/shares/${e}/deny`,{method:"POST"})}function Mg(t){return ue(`/uploads/${t}/leave`,{method:"POST"})}function TL(t,e){return ue(`/uploads/${t}`,{method:"PATCH",body:JSON.stringify({name:e})})}function Pg(t,e){return ue("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:t,relativePath:e})})}function Ht(t){const{baseUrl:e,nonce:n}=Ro(),o=nt(e,`/uploads/${t}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function Wg(t){const{baseUrl:e,nonce:n}=Ro(),o=nt(e,`/folders/${t}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const NL=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:Il,acceptFileShare:Rg,acceptShare:Cg,createFolder:Ll,createPlacement:Sn,deleteFolder:Tl,deletePlacement:Cl,denyFileShare:Og,denyShare:xg,ensureUploadPath:Pg,getFilesRestDeps:xL,getFolderZipUrl:Wg,getUploadDownloadUrl:Ht,installRestDeps:vg,inviteFileShare:Ng,inviteShare:Sg,leaveFileShare:Mg,leaveShare:Lg,listFileShares:Tg,listFolders:xl,listPlacements:Le,listShares:kg,purgeFolderSharingTables:LL,renameUpload:TL,restoreTrashedItem:Ii,revokeFileShare:Dg,revokeShare:Ig,saveAssociations:Eg,updateFolder:_g,updatePlacement:An,updateShareCapability:Ag},Symbol.toStringTag,{value:"Module"})),DL="desktop-mode/files";function ht(){return ie(DL,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function In(t){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...t}}))}function mt(t,e){const n=ht(),o=new Map(n.state.placementsByFolder);o.set(t,e.slice());const s=new Set(n.state.hydratedFolders);s.add(t),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),In({kind:"placements-set",folderId:t})}function Ci(t,e="local"){if(!t||typeof t.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",t);return}const n=ht(),o=new Map(n.state.placementsByFolder);for(const[a,l]of o)if(l.findIndex(d=>d&&d.id===t.id)>=0&&a!==t.parentId){const d=l.filter(Boolean),u=d.findIndex(f=>f.id===t.id);u>=0&&d.splice(u,1),o.set(a,d)}const i=(o.get(t.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===t.id);r>=0?i[r]=t:i.push(t),o.set(t.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),In({kind:"placement-upserted",placementId:t.id,folderId:t.parentId,source:e})}function Oo(t,e="local"){const n=ht(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(l=>l&&l.id===t)>=0){const l=r.filter(Boolean).filter(c=>c.id!==t);o.set(i,l),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),In({kind:"placement-removed",placementId:t,folderId:s,source:e}))}function Nl(t){const e=ht(),n=new Map;for(const o of t)n.set(o.id,o);e.state={...e.state,folders:n},e.notify(),In({kind:"folders-set"})}function Dl(t,e="local"){const n=ht(),o=new Map(n.state.folders);o.set(t.id,t),n.state={...n.state,folders:o},n.notify(),In({kind:"folder-upserted",folderRowId:t.id,source:e})}function Rl(t,e="local"){const n=ht(),o=new Map(n.state.folders);o.delete(t);const s=new Map(n.state.placementsByFolder);s.delete(t),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),In({kind:"folder-removed",folderRowId:t,source:e})}function Ol(t){return ht().subscribe(t)}function At(){return ht().getState()}function $g(t){const e=At(),n=e.placementsByFolder.get(t.parentId)?.find(o=>o&&o.id===t.id);if(n)return n;for(const o of e.placementsByFolder.values()){const s=o.find(i=>i&&i.id===t.id);if(s)return s}return t}const te={getState:At,subscribe:Ol,setFolderPlacements:mt,upsertPlacement:Ci,upsertFolder:Dl,removePlacement:Oo,removeFolder:Rl,currentPlacement:$g},RL=re`:host{display:inline-block}`,OL=re`: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 ) )}`,ds=class ds extends be{render(){return q`<span class="banner" part="banner"><slot></slot></span>`}};ds.props=["placement","tone"],ds.styles=[OL],ds.help=void 0;let Ml=ds;Se("os-ribbon",Ml);const oe="os-file-tile",Ug={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function ML(){const t=window.wp?.os?.getOsSettings;if(typeof t!="function")return!0;try{return t()?.showPostStatusRibbons!==!1}catch{return!0}}function PL(){return window.wp?.os?.dragManager??null}const WL=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],$n=class $n extends be{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=e=>{(e.key==="Enter"||e.key===" ")&&(e.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(e,n,o){if(n!==o){if(e==="selected"||e==="selectable"||e==="aria-selected"){this._paintSelection();return}super.attributeChangedCallback(e,n,o)}}_paintSelection(){const e=this.hasAttribute("selected"),n=this.hasAttribute("selectable");if(this.classList.toggle(`${oe}--selected`,e),this.setAttribute("role",n?"option":"listitem"),n){const o=e?"true":"false";this.getAttribute("aria-selected")!==o&&this.setAttribute("aria-selected",o)}else this.removeAttribute("aria-selected")}render(){return q``}_paint(){const e=this.getAttribute("type")??"",n=this.getAttribute("ref")??"",o=this.getAttribute("label")??"",s=this.getAttribute("icon")??"",i=this.getAttribute("thumbnail")??"",r=this.getAttribute("kind")??"entry",a=this.getAttribute("status")??"",l=this.hasAttribute("selected"),c=this.hasAttribute("selectable"),d=this.hasAttribute("missing"),u=this.hasAttribute("access-gated"),f=[oe,`${oe}--folder`,`${oe}--missing`,`${oe}--access-gated`,`${oe}--selected`];for(const w of f)this.classList.remove(w);this.classList.add(oe),r==="folder"&&this.classList.add(`${oe}--folder`),d&&this.classList.add(`${oe}--missing`),u&&this.classList.add(`${oe}--access-gated`),l&&this.classList.add(`${oe}--selected`),this.dataset.fileType=e,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",c?"option":"listitem"),c?this.setAttribute("aria-selected",l?"true":"false"):this.removeAttribute("aria-selected"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const m=[`${oe}__visual`,`${oe}__label`,`${oe}__lock`];for(const w of m)this.querySelectorAll(`:scope > .${w}`).forEach(v=>v.remove());this.querySelectorAll(":scope > os-ribbon").forEach(w=>w.remove());const g=document.createElement("span");if(g.className=`${oe}__visual`,i){const w=document.createElement("img");w.src=i,w.alt="",w.loading="lazy",w.decoding="async",w.className=`${oe}__preview`,w.draggable=!1,g.appendChild(w)}else if(s){const w=Zn(s,{title:o,className:`${oe}__icon`});g.appendChild(w)}this.appendChild(g);const h=document.createElement("span");if(h.className=`${oe}__label`,h.textContent=o,this.appendChild(h),u){const w=document.createElement("span");w.className=`${oe}__lock dashicons dashicons-lock`,w.setAttribute("aria-hidden","true"),this.appendChild(w)}if(a&&a!=="publish"&&Ug[a]&&ML()){const w=document.createElement("os-ribbon");w.setAttribute("placement","top-end"),w.setAttribute("tone",$L(a)),w.textContent=Ug[a],this.appendChild(w)}nb(this),L("os.tile.rendered",{tile:this}),this._wireDragOut()}_wireDragOut(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null);const e=this.getAttribute("drag-kind");if(!e)return;const n=o=>{if(o.button!==0)return;const s=PL();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,a=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,l=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:e,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-l.left,offsetY:o.clientY-l.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};$n.shadow=!1,$n.props=WL,$n.styles=[RL],$n.help=void 0;let Pl=$n;function $L(t){switch(t){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}Se("os-tile",Pl);function UL(t){const e=document.createElement("os-tile");if(e.setAttribute("type",t.type),e.setAttribute("ref",t.ref),e.setAttribute("label",t.label),t.icon&&e.setAttribute("icon",t.icon),t.thumbnail&&e.setAttribute("thumbnail",t.thumbnail),t.role&&e.setAttribute("kind",t.role),t.status&&e.setAttribute("status",t.status),t.missing&&e.setAttribute("missing",""),t.accessGated&&e.setAttribute("access-gated",""),t.dataset)for(const[o,s]of Object.entries(t.dataset))s!=null&&(e.dataset[o]=String(s));if(Array.isArray(t.extraClasses))for(const o of t.extraClasses)o&&e.classList.add(o);const n=K("os.tile.class",e.className,t);return n&&n!==e.className&&(e.className=n),typeof t.x=="number"&&typeof t.y=="number"&&(e.style.position="absolute",e.style.left=`${t.x}px`,e.style.top=`${t.y}px`),e}function FL(t,e){const n=document.createElement("div");n.className="os-drag-stack";const o=t.getBoundingClientRect();n.style.width=`${o.width}px`,n.style.height=`${o.height}px`;const s=t.cloneNode(!0);s.removeAttribute("id"),s.removeAttribute("selected"),s.removeAttribute("aria-selected"),s.classList.remove(`${oe}--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(e),n.appendChild(i),n}function Fg(t){const e=t.meta&&typeof t.meta.name=="string"?t.meta.name.trim():"";return e!==""?e:kn(t.file).title()}function BL(t,e){const n=kn(t.file),o=n.previewUrl(),s=Fg(t),i=t.meta&&typeof t.meta.iconUrl=="string"?t.meta.iconUrl.trim():"";return{type:t.file.type,ref:t.file.ref,label:s,thumbnail:o||void 0,icon:o?void 0:i||$s(s_(t.file.type))||n.icon(),x:t.x,y:t.y,dataset:{placementId:t.id,folderId:e},meta:t.meta,missing:!t.file.exists,accessGated:!!t.accessGated,ariaLabel:s}}function HL(t,e){const n=UL(BL(t,e)),o=K("os.files.tile-class",oe,t);o&&o!==oe&&(n.className=o);const s=K("os.files.tile-element",null,t);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=$g(t),a=kn(r.file);if(r.accessGated){Z({message:`You don’t have permission to open "${r.file.title||a.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}Ai(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),L("os.files.tile-rendered",{tile:n,placement:t}),n}function gt(t,e,n){t.style.left=`${e}px`,t.style.top=`${n}px`}const Mo=new Map;function xi(t,e){const n=Mo.get(t);return n?n.push(e):Mo.set(t,[e]),()=>{const o=Mo.get(t);if(!o)return;const s=o.indexOf(e);s!==-1&&o.splice(s,1),o.length===0&&Mo.delete(t)}}function Wl(t,e){const n=Mo.get(t);if(n)return n.find(o=>o.appliesTo(e))}function zL(t,e){return Wl(t,e)?.acceptLabel}function GL(t,e){const n=Wl(t.type,e);return n?n.accept(t.data,e):!1}function jL(t,e,n){const o=Wl(t.payload.type,n);return o?(o.onDrop(t,e,n),!0):!1}function VL(t,e,n){const o=e.slice().sort((s,i)=>{const r=typeof s.sort=="number"?s.sort:100,a=typeof i.sort=="number"?i.sort:100;return r!==a?r-a:s.label.localeCompare(i.label)});o.length!==0&&HC(t,{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 $l(t){const e=t.value;return typeof e=="string"?e:t.getAttribute("value")??t.shadowRoot?.querySelector("input")?.value??""}function zt(t,e){t.disabled=e,e?t.setAttribute("disabled",""):t.removeAttribute("disabled")}function Li(t){const e=()=>{const n=t.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};e()||queueMicrotask(()=>void e())}const Me="os-create-folder-dialog";let Po=null;function Ul(){Po&&(Po.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),Po.remove(),Po=null,L("os.files.create-folder.closed",{}))}function Fl(t){if(Ul(),K("os.files.create-folder.dialog",null,t)===!1)return;const n=(t.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=t.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${Me}__field`,r.id=`${Me}-input`,r.setAttribute("label",t.label??"Folder name"),r.setAttribute("value",n),r.setAttribute("autocomplete","off"),r.setAttribute("spellcheck","false"),s.appendChild(r);const a=document.createElement("p");a.className=`${Me}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const l=document.createElement("div");l.className=`${Me}__actions`;const c=document.createElement("os-button");c.className=`${Me}__btn ${Me}__btn--secondary`,c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className=`${Me}__btn ${Me}__btn--primary`,d.setAttribute("variant","primary"),d.textContent=t.submitLabel??"Create",l.appendChild(c),l.appendChild(d),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),Po=o,Li(r),L("os.files.create-folder.opened",{});const u=h=>{zt(r,h),zt(c,h),zt(d,h),s.classList.toggle(`${Me}--busy`,h)},f=h=>{a.textContent=h,a.hidden=!1},p=()=>{Ul(),t.onCancel?.()},m=async()=>{const h=$l(r).trim();if(!h){f("Please enter a name."),Li(r);return}a.hidden=!0,u(!0);try{await t.onSubmit(h),Ul()}catch(w){u(!1),f(w instanceof Error?w.message:"Could not create the folder."),Li(r)}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void m()),o.addEventListener("click",h=>{h.target===o&&p()});const g=h=>{h.key==="Escape"?(h.preventDefault(),p()):h.key==="Enter"&&!h.isComposing&&(h.preventDefault(),m())};s.addEventListener("keydown",g),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",g)})}function Ti(t){const e=t.meta;if(!e||typeof e!="object")return null;const n=e.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function qL(t){return t.id<=0||Ti(t)!==null}function Bg(t){if(t.length===0)return;const e=window.wp?.os;if(!e?.getOsSettings||!e?.updateOsSettings)return;const n={...e.getOsSettings().itemVisibility??{}};for(const o of t)n[o]="dock";e.updateOsSettings({itemVisibility:n})}function Cn(t,e,n){window.wp?.os?.broadcast?.(`os.${t}.changed`,{source:"desktop-files",action:e,ids:n})}function Ni(t){const e=window.wp?.os;if(!e?.showToast)return;const o=(t instanceof Error?t.message:String(t)).replace(/^\[openstation\][^:]*:\s*/,"").replace(/^openstation_files_[a-z_]+\s*/,"");e.showToast({message:o||"Could not move this item to the recycle bin.",duration:5e3})}function Bl(t,e){const n=window.wp?.os;n?.showToast&&n.showToast({message:t,duration:6e3,action:{label:"Undo",onClick:e}})}async function Hg(t){const e=t.id,n=t.parentId,o=t.file?.title??"Item",s=t.file?.type==="shortcut"?"shortcut":"placement";te.removePlacement(e);try{await Cl(e),Cn(s,"trashed",[e]),Bl(`"${o}" moved to Trash`,async()=>{try{await Ii(e,"placement");const i=await Le(n);te.setFolderPlacements(n,i.placements),Cn(s,"untrashed",[e])}catch(i){console.error("[openstation] restore failed:",i)}})}catch(i){console.error("[openstation] deletePlacement failed:",i),Ni(i),Le(n).then(r=>{te.setFolderPlacements(n,r.placements)})}}async function zg(t){const e=parseInt(t.file.ref,10);if(!e)return;const n=t.id,o=t.parentId,s=t.file?.title??"Folder";te.removePlacement(n),te.removeFolder(e);try{await Tl(e),Cn("folder","trashed",[e]),Bl(`"${s}" moved to Trash`,async()=>{try{await Ii(e,"folder");const i=await Le(o);te.setFolderPlacements(o,i.placements),Cn("folder","untrashed",[e])}catch(i){console.error("[openstation] restore folder failed:",i)}})}catch(i){console.error("[openstation] deleteFolder failed:",i),Ni(i),Le(o).then(r=>{te.setFolderPlacements(o,r.placements)})}}async function Gg(t){if(t.length===0)return;if(t.length===1)return KL(t[0]);const e=new Set;for(const l of t)if(e.add(l.parentId),te.removePlacement(l.id),l.file?.type==="folder"){const c=parseInt(l.file.ref,10);c&&te.removeFolder(c)}const n=async()=>{for(const l of e)try{const c=await Le(l);te.setFolderPlacements(l,c.placements)}catch(c){console.error("[openstation] files: re-hydrate failed:",c)}},o=await Promise.allSettled(t.map(async l=>{if(l.file?.type==="folder"){const c=parseInt(l.file.ref,10);if(!c)throw new Error("folder placement without a folder id");return await Tl(c),{id:c,kind:"folder",restoreId:c,restoreKind:"folder"}}return await Cl(l.id),{id:l.id,kind:l.file?.type==="shortcut"?"shortcut":"placement",restoreId:l.id,restoreKind:"placement"}})),s=[];let i=0;for(const l of o)l.status==="fulfilled"?s.push(l.value):(i+=1,console.error("[openstation] trash (bulk) failed for one item:",l.reason));if(i>0&&n(),s.length===0){Ni(o.find(l=>l.status==="rejected")?.reason);return}for(const l of["placement","shortcut","folder"]){const c=s.filter(d=>d.kind===l).map(d=>d.id);c.length>0&&Cn(l,"trashed",c)}const r=s.length===1?"item":"items",a=i>0?`${s.length} ${r} moved to Trash · ${i} could not be moved`:`${s.length} ${r} moved to Trash`;Bl(a,async()=>{const l=await Promise.allSettled(s.map(u=>Ii(u.restoreId,u.restoreKind)));await n();const c=s.filter((u,f)=>l[f].status==="fulfilled"),d=s.length-c.length;for(const u of l)u.status==="rejected"&&console.error("[openstation] restore (bulk) failed for one item:",u.reason);for(const u of["placement","shortcut","folder"]){const f=c.filter(p=>p.kind===u).map(p=>p.id);f.length>0&&Cn(u,"untrashed",f)}d>0&&Ni(new Error(`${d} of ${s.length} items could not be restored.`))})}function KL(t){return t.file?.type==="folder"?zg(t):Hg(t)}const YL=5,jg=t=>Gg(t);async function XL(t){if(!(t.length>YL&&!await ki({title:`Open ${t.length} items?`,message:`This opens ${t.length} windows at once.`,confirmLabel:"Open all"})))for(const e of t)await Ai(kn(e.file))}function ZL(t){const e=parseInt(t.file.ref,10);e&&Fl({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:t.file.title,onSubmit:async n=>{const o=n.trim();if(!o||o===t.file.title)return;const s=t.file.title,i={...t,file:{...t.file,title:o}};te.upsertPlacement(i);try{const r=te.getState().folders.get(e)?.updatedAtMs??0,a=await _g(e,{name:o},r);te.upsertFolder(a);const l=await Le(t.parentId);te.setFolderPlacements(t.parentId,l.placements)}catch(r){console.error("[openstation] rename folder failed:",r),te.upsertPlacement({...t,file:{...t.file,title:s}})}}})}function JL(t){const e=parseInt(t.file.ref,10);if(!e)return;const n=window.wp?.os?.myWordpress,s=(typeof t.file.postType=="string"?t.file.postType:"post")==="page"?"pages":"posts";n?.openDetail({entityId:s,postId:e,postTitle:t.file.title||`#${e}`})}function QL(t){const e=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>XL(i),onClick:()=>{Ai(kn(t.file))}}];if(t.file.type==="post"&&e.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>JL(t)}),t.file.type==="folder")e.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>ZL(t)}),t.canTrash!==!1&&e.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:jg,onClick:()=>zg(t)});else{const i=Ti(t),r=t.file.type==="shortcut";if(i||r){const a=i??t.file.ref;e.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,multi:!0,bulkLabel:l=>`Hide ${l} items from desktop`,bulk:l=>{Bg(l.map(c=>Ti(c)??c.file.ref).filter(c=>!!c))},onClick:()=>Bg([a])})}else t.canTrash!==!1&&e.push({id:"remove",multiId:"trash",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:a=>`Move ${a} items to Trash`,bulk:jg,onClick:()=>Hg(t)})}const o=K("os.files.tile-menu",e,t);return Array.isArray(o)?o:e}const He=16,eT=88,tT=104,nT=20,oT=16,It=eT+nT,Wo=tT+oT;function $o(t,e){const n=Math.max(0,Math.round((t-He)/It)),o=Math.max(0,Math.round((e-He)/Wo));return xn(n,o)}function xn(t,e){return{col:t,row:e,x:He+t*It,y:He+e*Wo}}function Ct(t,e,n,o){const s=$o(t,e);if(!n.has(ve(s.col,s.row)))return s;const i=o?Math.max(1,Math.floor((o.clientHeight-He)/Wo)):999;for(let r=0;r<999;r++)for(let a=0;a<i;a++)if(!n.has(ve(r,a)))return xn(r,a);return s}function Vg(t,e){const n=e?Math.max(1,Math.floor((e.clientWidth-He)/It)):4,o=Math.max(1,n);for(let s=0;s<999;s++)for(let i=0;i<o;i++)if(!t.has(ve(i,s)))return xn(i,s);return xn(0,0)}function qg(t,e){const n=new Set;for(const o of t){const s=$o(o.x,o.y);n.add(ve(s.col,s.row))}return n}function ve(t,e){return`${t},${e}`}function Kg(t){return t instanceof Il}function sT(t){const e=t.detail.actor.name||"Someone else",n=t.detail.current.parentName||"another folder";return t.detail.reason==="trashed"?"This item is in the recycle bin.":t.detail.reason==="forbidden"?"You no longer have access.":t.detail.reason==="gone"?"This item was deleted.":`${e} moved this to "${n}".`}function Yg(t){const e=sT(t),n=t.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)}}),Z({message:e,action:o,duration:7e3})}const Uo=new Map;function Xg(t,e){return Uo.set(t,e),()=>{Uo.get(t)===e&&Uo.delete(t)}}function iT(t,e){const n=Uo.get(t.type);return n?n.accept(t.data,e):!1}function rT(t,e,n){const o=Uo.get(t.payload.type);return o?(o.onDrop(t,e,n),!0):!1}function Ln(t){const e=t.placements;return Array.isArray(e)&&e.length>0?e:t.placement?[t.placement]:[]}function Di(t){const e=t.items;return Array.isArray(e)&&e.length>0?e:t.ref?[t]:[]}function aT(t){const e=t.file;if(!e)return;const n=parseInt(String(e.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(e.title??"");if(e.type==="attachment"){const s=String(e.sourceUrl??e.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(e.alt??""),mime:String(e.mime??""),thumbnailUrl:e.previewUrl?String(e.previewUrl):void 0}}if(e.type==="post")return{kind:"post",id:n,postType:String(e.postType??"post"),url:String(e.link??""),title:o};if(e.type==="user")return{kind:"user",id:n,url:String(e.link??""),title:o}}function Fo(){return window.wp?.os?.dragManager??null}const lT="os-files-layer";function cT(t){if(t!==0)return null;const e=window.openStationConfig,n=e?.filesBootPlacements;return!e||!Array.isArray(n)?null:(delete e.filesBootPlacements,n)}function Zg(t,e=0){const n=document.createElement("div");n.className=lT,n.setAttribute("role","list"),n.dataset.folderId=String(e),t.appendChild(n);let o="";const s=A=>{const P=te.getState().placementsByFolder.get(e)??[],B=new Map;for(const C of P)C&&B.set(String(C.id),C);return A.map(C=>B.get(C)).filter(C=>!!C)},i=new Set,r=new Set,a=WC(n,{itemSelector:`.${oe}`,background:t,surface:"files",scope:String(e),keyOf:A=>A.dataset.placementId??null,onChange:A=>{const P=s(A),B=P.length===1?P[0]:null;for(const C of i)try{C(B)}catch($){console.error("[openstation] files: selection listener threw:",$)}for(const C of r)try{C(P)}catch($){console.error("[openstation] files: selection listener threw:",$)}}}),l=()=>s(a.keys()),c=A=>{const P=new Map,B=new Set;let C=0;for(const U of A){if(!Pe(U))continue;const G=xn(0,C);P.set(U.id,{x:G.x,y:G.y}),B.add(ve(G.col,G.row)),C+=1}const $=new Map;for(const U of A){if(P.has(U.id))continue;const G=$o(U.x,U.y),F=ve(G.col,G.row);if(!B.has(F)){B.add(F);continue}const Y=Ct(U.x,U.y,B,t);B.add(ve(Y.col,Y.row)),$.set(U.id,{x:Y.x,y:Y.y})}return{pinnedSlots:P,displaced:$}},d=(A,P,B,C)=>{const $=B.get(P.id),U=C.get(P.id);$?gt(A,$.x,$.y):U?gt(A,U.x,U.y):gt(A,P.x,P.y)},u=(A,P,B)=>{const C=HL(A,e),$=P.get(A.id);if($){if(gt(C,$.x,$.y),C.classList.add(`${oe}--pinned`),nw(C,A,a,l),Jg(A)){const G=Fo();G&&h.set(A.id,tw(G,C,A))}return C}const U=B.get(A.id);if(U&>(C,U.x,U.y),mT(C,A,e,a,l),nw(C,A,a,l),A.file.type==="folder"){const G=parseInt(A.file.ref,10);if(G>0){const F=Fo();if(F){const Y=hT(F,C,G);g.set(A.id,Y)}}}else if(Jg(A)){const G=Fo();G&&h.set(A.id,tw(G,C,A))}return C},f=A=>{const P=new Map;for(const U of n.querySelectorAll("[data-placement-id]")){const G=U.dataset.placementId??"",F=parseInt(G,10);if(G===""||Number.isNaN(F)&&G!=="-0")return!1;P.set(F,U)}const B=new Set;for(const U of A)B.add(U.id);for(const U of A){const G=P.get(U.id);if(!G)continue;if(G.dataset.fileType!==U.file.type||G.dataset.fileRef!==U.file.ref||G.classList.contains(`${oe}--pinned`)!==Pe(U))return!1}for(const[U,G]of P){if(B.has(U))continue;const F=g.get(U);if(F){try{F()}catch{}g.delete(U)}const Y=h.get(U);if(Y){try{Y()}catch{}h.delete(U)}G.remove()}const{pinnedSlots:C,displaced:$}=c(A);for(const U of A){const G=P.get(U.id);if(G){d(G,U,C,$),ew(G,U);continue}n.appendChild(u(U,C,$))}return a.refresh(),L("os.files.grid-rendered",{folderId:e,count:A.length}),!0},p=A=>{const B=(A.placementsByFolder.get(e)??[]).slice().sort((G,F)=>{const Y=Pe(G)?0:1,j=Pe(F)?0:1;return Y-j}),C=dT(B);if(C===o||(o=C,pT(B,n,t))||f(B))return;n.replaceChildren();for(const[,G]of g)try{G()}catch{}g.clear();for(const[,G]of h)try{G()}catch{}h.clear();const{pinnedSlots:$,displaced:U}=c(B);for(const G of B)n.appendChild(u(G,$,U));a.refresh(),L("os.files.grid-rendered",{folderId:e,count:B.length})},m=[],g=new Map,h=new Map;let w=null,v=null;const R=A=>{if(w||A.payload.type!=="desktop-file")return;const P=document.createElement("div");P.className="os-files-drop-preview",P.setAttribute("aria-hidden","true"),n.appendChild(P),w=P;const B=A.payload.ghost,C=B?.offsetX??0,$=B?.offsetY??0,G=A.payload.data?.placement?.id,F=(se,ge)=>{const we=n.getBoundingClientRect(),pe=Math.max(0,se-we.left-C),_e=Math.max(0,ge-we.top-$),Ce=te.getState().placementsByFolder.get(e)??[],$e=Oi(Ce,G),Ie=Ct(pe,_e,$e,t);P.style.transform=`translate3d(${Ie.x}px, ${Ie.y}px, 0)`},Y=A.payload.source.getBoundingClientRect();F(Y.left+C,Y.top+$);const j=se=>{F(se.clientX,se.clientY)};document.addEventListener("pointermove",j),v=j},_=()=>{v&&(document.removeEventListener("pointermove",v),v=null),w&&(w.remove(),w=null)},E={id:`os-files-canvas-${e}`,element:t,accept:A=>{if(A.type!=="desktop-file"&&A.type!=="shortcut")return iT(A,{folderId:e,host:t});if(e>0&&A.type==="desktop-file"){const P=A.data;for(const B of Ln(P)){if(B.file?.type!=="folder")continue;const C=parseInt(B.file.ref,10);if(!Number.isNaN(C)&&Qg(C,e))return!1}}return!0},onEnter:A=>{t.setAttribute("data-files-drop-active",""),(A.payload.type==="desktop-file"||A.payload.type==="shortcut")&&R(A)},onLeave:()=>{t.removeAttribute("data-files-drop-active"),_()},onDrop:(A,P)=>{if(t.removeAttribute("data-files-drop-active"),_(),A.payload.type!=="desktop-file"&&A.payload.type!=="shortcut"){rT(A,P,{folderId:e,host:t});return}const B=n.getBoundingClientRect(),C=A.payload.ghost,$=C?.offsetX??0,U=C?.offsetY??0,G=Math.max(0,P.clientX-B.left-$),F=Math.max(0,P.clientY-B.top-U),Y=te.getState().placementsByFolder.get(e)??[];if(A.payload.type==="desktop-file"){const j=A.payload.data,se=Ln(j),ge=new Set(se.map(_e=>_e.id)),we=Oi(Y,ge),pe=Ct(G,F,we,t);we.add(ve(pe.col,pe.row));for(const _e of se){let Ce=pe;if(_e.id!==j.placement.id){const Ie=_e.x-j.placement.x,Bc=_e.y-j.placement.y;Ce=Ct(Math.max(0,pe.x+Ie),Math.max(0,pe.y+Bc),we,t),we.add(ve(Ce.col,Ce.row))}const $e={..._e,x:Ce.x,y:Ce.y,parentId:e};if(te.upsertPlacement($e),L("os.files.tile-manually-placed",{folderId:e,placementId:_e.id}),Ri(_e)){const Ie=Ti(_e);Ie&&fT(Ie,Ce.x,Ce.y);continue}An(_e.id,{x:Ce.x,y:Ce.y,parentId:e},_e.updatedAtMs).then(Ie=>{te.upsertPlacement(Ie,"remote")}).catch(Ie=>{Kg(Ie)?Yg(Ie):console.error("[openstation] files: drag persist failed",Ie),te.upsertPlacement(_e)})}return}if(A.payload.type==="shortcut"){const j=A.payload.data,se=Oi(Y);for(const ge of Di(j)){const we=Vg(se,t);se.add(ve(we.col,we.row)),Sn({parentId:e,type:ge.kind,ref:ge.ref,x:we.x,y:we.y}).then(pe=>{te.upsertPlacement(pe),L("os.files.shortcut-dropped",{folderId:e,placement:pe})}).catch(pe=>{console.error("[openstation] shortcut drop failed:",pe)})}}}},N=Fo();if(N&&m.push(N.registerDropTarget(E)),!te.getState().hydratedFolders.has(e)){const A=cT(e);A&&te.setFolderPlacements(e,A)}p(te.getState());const D=te.subscribe(p);let O=()=>{};const y=new Promise(A=>{O=A});te.getState().hydratedFolders.has(e)?queueMicrotask(O):Le(e).then(A=>{te.setFolderPlacements(e,A.placements)}).catch(A=>{console.error("[openstation] files: failed to hydrate folder",e,A)}).finally(()=>{O()});const M=()=>{const A=t.clientWidth>0?t.clientWidth:4*It;return Math.max(1,Math.floor((A-He)/It))},T=(A,P)=>{const B=A.slice();switch(P){case"name-asc":B.sort((C,$)=>C.file.title.localeCompare($.file.title));break;case"name-desc":B.sort((C,$)=>$.file.title.localeCompare(C.file.title));break;case"date-asc":B.sort((C,$)=>C.updatedAtMs-$.updatedAtMs);break;case"date-desc":B.sort((C,$)=>$.updatedAtMs-C.updatedAtMs);break}return B},x=A=>{const P=te.getState().placementsByFolder.get(e);if(!P||P.length===0)return;const B=P.filter(j=>Pe(j)),C=P.filter(j=>!Pe(j)),$=T(C,A),U=M(),G=new Set;for(let j=0;j<B.length;j+=1)G.add(ve(0,j));let F=0;const Y=()=>{for(;;){const j=Math.floor(F/U),se=F%U;if(F+=1,!G.has(ve(se,j)))return{col:se,row:j}}};$.forEach((j,se)=>{const ge=Y(),we=He+ge.col*It,pe=He+ge.row*Wo,_e={...j,x:we,y:pe,sortOrder:se};te.upsertPlacement(_e),!Ri(j)&&An(j.id,{x:we,y:pe,sortOrder:se}).catch(Ce=>{console.error("[openstation] files: sort persist failed",Ce)})})},I=()=>{const A=te.getState().placementsByFolder.get(e);if(!A||A.length===0)return;const P=t.clientWidth>0?t.clientWidth:1/0;if(!A.some(j=>j.x+It>P))return;const C=M(),$=A.filter(j=>Pe(j)),U=A.filter(j=>!Pe(j)),G=new Set;for(let j=0;j<$.length;j+=1)G.add(ve(0,j));let F=0;const Y=()=>{for(;;){const j=Math.floor(F/C),se=F%C;if(F+=1,!G.has(ve(se,j)))return{col:se,row:j}}};for(const j of U){const se=Y(),ge=He+se.col*It,we=He+se.row*Wo,pe=n.querySelector(`[data-placement-id="${j.id}"]`);pe&>(pe,ge,we)}};let W=t.clientWidth,z=null;return typeof ResizeObserver<"u"&&(z=new ResizeObserver(()=>{const A=t.clientWidth;A!==W&&(W=A,I())}),z.observe(t)),{host:t,folderId:e,onSelectionChange(A){return i.add(A),()=>{i.delete(A)}},onSelectionChanged(A){return r.add(A),()=>{r.delete(A)}},getSelection:l,selectAll:()=>a.model.selectAll(),clearSelection:()=>a.model.clear(),sort:x,reflow:I,hydrated:y,dispose(){D(),z?.disconnect(),z=null;for(const A of m)try{A()}catch{}m.length=0;for(const A of g.values())try{A()}catch{}g.clear();for(const A of h.values())try{A()}catch{}h.clear(),a.destroy(),i.clear(),r.clear(),n.remove()}}}function dT(t){if(t.length===0)return"0";const e=[];for(const n of t)e.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 e.join("|")}function Pe(t){return!!t.file.pinned}function Ri(t){return qL(t)}const uT="desktop-mode-recycle-bin";function Jg(t){return!(t.file?.type==="folder"||t.file?.ref===uT)}function Oi(t,e){const n=typeof e=="number"?new Set([e]):e??null,o=t.slice().sort((r,a)=>{const l=Pe(r)?0:1,c=Pe(a)?0:1;return l-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(Pe(r))s.add(ve(0,i)),i+=1;else{const a=$o(r.x,r.y);s.add(ve(a.col,a.row))}return s}function Qg(t,e){if(e<=0||t<=0)return!1;if(t===e)return!0;const n=new Map,o=te.getState();for(const a of o.placementsByFolder.values())for(const l of a){if(l.file?.type!=="folder")continue;const c=parseInt(l.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,l.parentId)}const s=new Set;let i=e,r=256;for(;i>0&&r-- >0;){if(i===t||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function fT(t,e,n){const o=window.wp?.os;if(!o?.getOsSettings||!o?.updateOsSettings)return;const s=o.getOsSettings().dockPromotedPositions??{};o.updateOsSettings({dockPromotedPositions:{...s,[t]:{x:e,y:n}}})}function pT(t,e,n){const o=Array.from(e.querySelectorAll("[data-placement-id]"));if(o.length!==t.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 t){const d=s.get(c.id);if(!d||d.dataset.fileType!==c.file.type||d.dataset.fileRef!==c.file.ref||d.classList.contains(`${oe}--pinned`)!==Pe(c))return!1}const i=new Map,r=new Set;let a=0;for(const c of t){if(!Pe(c))continue;const d=xn(0,a);i.set(c.id,{x:d.x,y:d.y}),r.add(ve(d.col,d.row)),a+=1}const l=new Map;for(const c of t){if(i.has(c.id))continue;const d=$o(c.x,c.y),u=ve(d.col,d.row);if(!r.has(u)){r.add(u);continue}const f=Ct(c.x,c.y,r,n);r.add(ve(f.col,f.row)),l.set(c.id,{x:f.x,y:f.y})}for(const c of t){const d=s.get(c.id);if(!d)continue;const u=i.get(c.id),f=l.get(c.id);u?gt(d,u.x,u.y):f?gt(d,f.x,f.y):gt(d,c.x,c.y),ew(d,c)}return!0}function ew(t,e){const n=Fg(e);t.getAttribute("label")!==n&&t.setAttribute("label",n)}function tw(t,e,n){const o={placement:n};let s=null;return t.registerDropTarget({id:`os-files-tile-${n.id}-reject`,element:e,get acceptLabel(){return s?zL(s,o):void 0},accept:i=>(s=i.type,GL(i,o)),onEnter:()=>{e.classList.add(`${oe}--drop-target`)},onLeave:()=>{e.classList.remove(`${oe}--drop-target`)},onDrop:(i,r)=>{e.classList.remove(`${oe}--drop-target`),jL(i,r,o)}})}function hT(t,e,n,o){const s={id:`os-files-folder-${n}-tile-${e.dataset.placementId??"?"}`,element:e,accept:i=>{if(i.type!=="desktop-file"&&i.type!=="shortcut")return!1;if(i.type==="desktop-file"){const r=i.data;for(const a of Ln(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||Ri(a))return!1;if(a.file.type==="folder"){const l=parseInt(a.file.ref,10);if(!Number.isNaN(l)&&Qg(l,n))return!1}}}return!0},onEnter:()=>{e.classList.add(`${oe}--drop-target`)},onLeave:()=>{e.classList.remove(`${oe}--drop-target`)},onDrop:i=>{if(e.classList.remove(`${oe}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data;for(const a of Ln(r))te.upsertPlacement({...a,parentId:n}),An(a.id,{parentId:n},a.updatedAtMs).then(l=>{te.upsertPlacement(l,"remote")}).catch(l=>{Kg(l)?Yg(l):console.error("[openstation] files: move-into-folder persist failed",l),te.upsertPlacement(a)});return}if(i.payload.type==="shortcut"){const r=i.payload.data,a=te.getState().placementsByFolder.get(n)??[],l=Oi(a);for(const c of Di(r)){const d=Vg(l);l.add(ve(d.col,d.row)),Sn({parentId:n,type:c.kind,ref:c.ref,x:d.x,y:d.y}).then(u=>{te.upsertPlacement(u),L("os.files.shortcut-dropped",{folderId:n,placement:u})}).catch(u=>{console.error("[openstation] shortcut drop into folder failed:",u)})}}}};return t.registerDropTarget(s)}function mT(t,e,n,o,s){t.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=Fo();if(!r)return;const l=te.getState().placementsByFolder.get(n)?.find(f=>f.id===e.id)??e;parseFloat(t.style.left)||l.x,parseFloat(t.style.top)||l.y;const c=o.model.has(String(l.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===l.id)?d:[l];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(l.id)])};document.addEventListener("os.drag.start",f);const p=()=>{document.removeEventListener("os.drag.start",f),document.removeEventListener("pointerup",p)};document.addEventListener("pointerup",p)}if(u.length>1){const f=[],p=()=>{for(const g of f)g.classList.remove(`${oe}--dragging`);f.length=0,document.removeEventListener("os.drag.start",m),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},m=()=>{for(const g of u){const h=t.parentElement?.querySelector(`[data-placement-id="${g.id}"]`);h&&h!==t&&(h.classList.add(`${oe}--dragging`),f.push(h))}};document.addEventListener("os.drag.start",m),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:t,data:{placement:l,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:aT(l)},ghost:{offsetX:i.clientX-t.getBoundingClientRect().left,offsetY:i.clientY-t.getBoundingClientRect().top,element:u.length>1?FL(t,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 nw(t,e,n,o){t.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=te.currentPlacement(e);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),a=r.length>0?r:[i],l=Um(a,QL);VL({x:s.clientX,y:s.clientY},l,{placementIds:a.map(c=>c.id)})})}function Gt(t){if(!Number.isFinite(t)||t<=0)return"0 B";const e=["B","KB","MB","GB","TB"];let n=t,o=0;for(;n>=1024&&o<e.length-1;)n/=1024,o++;const s=n>=100||o===0?0:1;return`${n.toFixed(s)} ${e[o]}`}const Tn="os-folder-status-bar";function gT(t,e,n={}){const o=document.createElement("div");o.className=Tn,o.setAttribute("role","status"),o.dataset.folderId=String(e),t.appendChild(o);const s=()=>{const a=At().placementsByFolder.get(e)??[],l=a.filter(p=>p.file.type==="folder").length,c=a.length-l;let d=0;for(const p of a)if(p.file.type==="upload"){const m=Number(p.file.sizeBytes??0);Number.isFinite(m)&&m>0&&(d+=m)}const u={folderId:e,selectedCount:n.selection?.count()??0,totals:{files:c,folders:l,total:a.length,bytes:d}},f=wT(u);yT(o,f)};s();const i=Ol(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function wT(t){const{folders:e,files:n,bytes:o}=t.totals,s=[{id:"count",label:sw(n,"file","files")+(e>0?`, ${sw(e,"folder","folders")}`:"")+(o>0?` (${Gt(o)})`:""),align:"start",sort:10}];t.selectedCount>0&&s.push({id:"selection",label:`${t.selectedCount} selected`,align:"end",sort:10});const i=K("os.files.folder-window.status-bar",s,t);return Array.isArray(i)?i:s}function yT(t,e){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,l=typeof r.sort=="number"?r.sort:100;return a!==l?a-l:i.label.localeCompare(r.label)},o=e.filter(i=>(i.align??"start")==="start").sort(n),s=e.filter(i=>i.align==="end").sort(n);t.replaceChildren(),t.appendChild(ow("start",o)),t.appendChild(ow("end",s))}function ow(t,e){const n=document.createElement("div");n.className=`${Tn}__cluster ${Tn}__cluster--${t}`;for(const o of e)n.appendChild(bT(o));return n}function bT(t){const e=typeof t.onClick=="function",n=document.createElement(e?"button":"span");if(n.className=`${Tn}__segment`,n.dataset.segmentId=t.id,e&&(n.type="button",n.addEventListener("click",s=>t.onClick(s))),t.icon){const s=document.createElement("span");s.className=`${Tn}__icon dashicons ${t.icon.replace(/[^a-zA-Z0-9_-]/g,"")}`,s.setAttribute("aria-hidden","true"),n.appendChild(s)}const o=document.createElement("span");return o.className=`${Tn}__label`,o.textContent=t.label,n.appendChild(o),n}function sw(t,e,n){return`${t} ${t===1?e:n}`}const Mi="os-icon-canvas-menu";let Bo=null,Pi=null,Hl=null,Ho=null,zo=null;function vT(t,e){e.openOnBackgroundClick;const n=i=>{_T(i.target)||iw(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(Hl===t&&Bo){jt();return}const a=ET(e),l=K("os.icon-canvas.menu",a,e.scope),c=Array.isArray(l)?l:a,d=++o;Is(()=>d===o,()=>kT(c,{x:i,y:r},t))};return t.addEventListener("contextmenu",n),{dispose:()=>{t.removeEventListener("contextmenu",n),jt()}}}function _T(t){return t instanceof Element?t.closest(".os-file-tile")!==null:!1}function iw(t){return t instanceof Element?t.closest(`.${Mi}`)!==null:!1}function ET(t){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:()=>t.onSort("name-asc")},{id:"sort-name-desc",label:k("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>t.onSort("name-desc")},{id:"sort-date-desc",label:k("Newest first","desktop-mode"),sort:30,onClick:()=>t.onSort("date-desc")},{id:"sort-date-asc",label:k("Oldest first","desktop-mode"),sort:40,onClick:()=>t.onSort("date-asc")}]}];return Array.isArray(t.extraItems)&&n.push(...t.extraItems),n}function rw(t){return t.slice().sort((e,n)=>{const o=typeof e.sort=="number"?e.sort:100,s=typeof n.sort=="number"?n.sort:100;return o!==s?o-s:e.label.localeCompare(n.label)})}function kT(t,e,n){if(jt(),t.length===0)return;Hl=n;const o=rw(t),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(Mi),s.style.left=`${e.x}px`,s.style.top=`${e.y}px`;const i=new Map;for(const r of o){i.set(r.id,r);const a=aw(s,r);Wi(r)&&a.addEventListener("mouseenter",()=>{lw(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,l=i.get(a.id);if(l){if(Wi(l)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${l.id}"]`);c&&lw(l,c);return}jt(),l.onClick?.()}}),document.body.appendChild(s),Bo=s,nl(s),queueMicrotask(()=>{Ho=r=>{iw(r.target)||jt()},zo=r=>{r.key==="Escape"&&jt()},document.addEventListener("mousedown",Ho),document.addEventListener("keydown",zo)})}function aw(t,e){const n=document.createElement("os-context-menu-option");return n.dataset.menuItemId=e.id,n.setAttribute("value",e.id),e.heading&&n.setAttribute("heading",""),e.disabled&&n.setAttribute("disabled",""),e.icon&&n.setAttribute("icon",ST(e.icon)),Wi(e)&&n.setAttribute("has-children",""),n.textContent=e.label,t.appendChild(n),n}function lw(t,e){if(cw(),!Wi(t))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(Mi,`${Mi}--flyout`);const o=new Map;for(const s of rw(t.children??[]))o.set(s.id,s),aw(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),jt(),r.onClick?.())}),document.body.appendChild(n),Pi=n,Hm(n,e)}function Wi(t){return Array.isArray(t.children)&&t.children.length>0}function cw(){Pi&&(Pi.remove(),Pi=null)}function jt(){cw(),Bo&&(Bo.remove(),Bo=null),Hl=null,Ho&&(document.removeEventListener("mousedown",Ho),Ho=null),zo&&(document.removeEventListener("keydown",zo),zo=null)}function ST(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}const Vt="os-breadcrumbs";function AT(t,e,n={}){if(t.replaceChildren(),t.classList.add(Vt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${Vt}__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()}),t.appendChild(s)}const o=document.createElement("nav");o.className=`${Vt}__crumbs`,o.setAttribute("aria-label",k("Breadcrumb","desktop-mode")),e.forEach((s,i)=>{if(i>0){const l=document.createElement("span");l.className=`${Vt}__sep`,l.setAttribute("aria-hidden","true"),l.textContent="›",o.appendChild(l)}if(!s.onClick){const l=document.createElement("span");l.className=`${Vt}__crumb ${Vt}__crumb--current`,l.setAttribute("aria-current","page"),l.textContent=s.label,o.appendChild(l);return}const r=document.createElement("button");r.type="button",r.className=`${Vt}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),t.appendChild(o)}function $i(t){const e=document.createElement("a");e.href=t,e.setAttribute("download",""),e.style.display="none",document.body.appendChild(e),e.click(),e.remove()}async function Go(t,e={}){const n=await Fe(t,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":IT(),...e.headers??{}},...e});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function IT(){return window.wp?.os?.config?.restNonce??""}function CT(){const t=window.wp?.os?.config;return t?.restUrl?t.restUrl.endsWith("/")?t.restUrl:t.restUrl+"/":`${window.location.origin}/wp-json/`}function jo(t){return nt(CT(),t)}function xT(t,e){const n=K("os.files.preview",null,t);if(n instanceof HTMLElement){e.replaceChildren(n);return}if(t.accessGated){e.replaceChildren(LT(t));return}e.replaceChildren(FT()),TT(t).then(o=>{e.replaceChildren(o)}).catch(o=>{e.replaceChildren(BT(o))})}function LT(t){const e=document.createElement("div");e.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),e.appendChild(n);const s=document.createElement("h2");s.className="os-files__access-gated-title",s.textContent="No permission to view",e.appendChild(s);const i=document.createElement("p");i.className="os-files__access-gated-sub";const r=t.file.title||t.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.`,e.appendChild(i);const a=document.createElement("p");return a.className="os-files__access-gated-hint",a.textContent="Ask the owner to grant access on the underlying item, or to remove it from the shared folder.",e.appendChild(a),e}async function TT(t){const e=t.file;switch(e.type){case"post":return NT(e.ref,e);case"folder":return WT(e);case"shortcut":return $T(e);case"attachment":return MT(e.ref,e);case"upload":return PT(e);case"user":return DT(e.ref,e);case"term":return RT(e);case"comment":return OT(e.ref,e);case"bookmark":return UT(e);default:return Xe(e)}}async function NT(t,e){const n=parseInt(t,10);if(!n)return Xe(e);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await Go(jo(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return Xe(e);const s=it(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Ui(o.title.rendered)||e.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="os-my-wordpress__article-meta";const a=[];if(a.push(dw(o.date)),o.status&&o.status!=="publish"&&a.push(o.status),r.textContent=a.join(" · "),s.appendChild(r),o.content?.rendered){const u=document.createElement("div");u.className="os-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const c=window.wp?.os?.myWordpress;if(c){const u=document.createElement("os-button");u.setAttribute("variant","secondary"),u.textContent=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 e.postType=="string"?e.postType:"post";c.openDetail({entityId:f==="page"?"pages":"posts",postId:n,postTitle:Ui(o.title.rendered)||`#${n}`})}),l.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,g=(typeof e.postType=="string"?e.postType:"post")==="page"?"pages":"posts";p?.open({id:`${g}-edit-${n}`,url:f,title:Ui(o.title.rendered),icon:e.icon})}),l.appendChild(d),s.appendChild(l),s}async function DT(t,e){const n=parseInt(t,10);if(!n)return Xe(e);let o=null;try{o=await Go(jo(`desktop-mode/v1/user-stats/${n}`))}catch{return Xe(e)}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 a=document.createElement("h2");if(a.className="os-my-wordpress__article-title",a.textContent=o.profile.name||e.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const c=document.createElement("div");c.className="os-my-wordpress__user-roles";for(const d of o.profile.roleLabels){const u=document.createElement("span");u.className="os-my-wordpress__user-role",u.textContent=d,c.appendChild(u)}r.appendChild(c)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const c=document.createElement("div");c.className="os-my-wordpress__user-bio",c.textContent=o.profile.description,s.appendChild(c)}const l=document.createElement("div");return l.className="os-my-wordpress__user-stats",l.appendChild(Nn(o.counts.posts.total.toLocaleString(),k("Posts","desktop-mode"))),l.appendChild(Nn(o.counts.pages.total.toLocaleString(),k("Pages","desktop-mode"))),l.appendChild(Nn(o.counts.commentsReceived.toLocaleString(),k("Comments received","desktop-mode"))),s.appendChild(l),s}async function RT(t){const e=parseInt(t.ref,10),n=typeof t.taxonomy=="string"&&t.taxonomy?t.taxonomy:"category";if(!e)return Xe(t);let o=null;try{o=await Go(jo(`desktop-mode/v1/term-stats/${n}/${e}`))}catch{return Xe(t)}const s=it(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=o.profile.name||t.title||`#${e}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const l=document.createElement("div");l.className="os-my-wordpress__article-content",l.innerHTML=o.profile.description,s.appendChild(l)}const a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(Nn(o.counts.posts.total.toLocaleString(),k("Posts","desktop-mode"))),a.appendChild(Nn(o.counts.commentsReceived.toLocaleString(),k("Comments","desktop-mode"))),a.appendChild(Nn(o.counts.distinctAuthors.toLocaleString(),k("Authors","desktop-mode"))),s.appendChild(a),s}async function OT(t,e){const n=parseInt(t,10);if(!n)return Xe(e);let o=null;try{o=await Go(jo(`desktop-mode/v1/comment-stats/${n}`))}catch{return Xe(e)}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 a=document.createElement("h2");a.className="os-my-wordpress__article-title",a.textContent=o.author.name,r.appendChild(a);const l=document.createElement("p");l.className="os-my-wordpress__article-meta",l.textContent=`${dw(o.comment.date)} · ${o.comment.status}`,r.appendChild(l),i.appendChild(r),s.appendChild(i);const c=document.createElement("div");if(c.className="os-my-wordpress__article-content",c.innerHTML=o.comment.rendered,s.appendChild(c),o.post){const d=document.createElement("div");d.className="os-my-wordpress__comment-post";const u=document.createElement("a");u.className="os-my-wordpress__comment-post-title",u.href=o.post.link,u.target="_blank",u.rel="noopener noreferrer",u.textContent=o.post.title,d.appendChild(u),s.appendChild(d)}return s}async function MT(t,e){const n=parseInt(t,10);if(!n)return Xe(e);let o=null;try{o=await Go(jo(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return Xe(e)}const s=it(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Ui(o.title.rendered)||e.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="os-my-wordpress__article-hero";const l=o.media_details?.sizes;a.src=l?.large?.source_url??l?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),l=document.createElement("a");l.href=o.source_url,l.textContent=o.source_url,l.target="_blank",l.rel="noopener noreferrer",a.appendChild(l),s.appendChild(a)}return s}function PT(t){const e=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=t.title||k("Uploaded file","desktop-mode"),e.appendChild(n);const o=typeof t.mime=="string"?t.mime:"",s=typeof t.sizeBytes=="number"?t.sizeBytes:0,i=typeof t.kind=="string"?t.kind:"file",r=document.createElement("p");r.className="os-my-wordpress__article-meta",r.textContent=[o,s>0?Gt(s):""].filter(Boolean).join(" · "),e.appendChild(r);const a=parseInt(t.ref,10),l=()=>{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(a>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=Ht(a),c.alt=t.title||"",c.addEventListener("error",()=>{c.replaceWith(l())}),e.appendChild(c)}else if(a>0&&i==="video"){const c=document.createElement("video");c.className="os-my-wordpress__article-hero",c.controls=!0,c.preload="metadata",c.src=Ht(a),c.addEventListener("error",()=>{c.replaceWith(l())}),e.appendChild(c)}else if(a>0&&i==="audio"){const c=document.createElement("audio");c.controls=!0,c.preload="metadata",c.src=Ht(a),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(l())}),e.appendChild(c)}else e.appendChild(l());if(a>0){const c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=k("Download","desktop-mode"),d.addEventListener("click",()=>{$i(Ht(a))}),c.appendChild(d),e.appendChild(c)}return e}function WT(t){const e=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=t.title||k("(folder)","desktop-mode"),e.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=k("Double-click to open.","desktop-mode"),e.appendChild(o),e}function $T(t){const e=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=t.title||k("Shortcut","desktop-mode"),e.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"),e.appendChild(o),e}function UT(t){const e=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=t.title||k("Bookmark","desktop-mode"),e.appendChild(n);const o=typeof t.url=="string"?t.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",e.appendChild(s)}return e}function Xe(t){const e=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=t.title||t.type,e.appendChild(n);const o=document.createElement("p");if(o.className="os-my-wordpress__article-meta",o.textContent=ae(k("Type: %s","desktop-mode"),t.type),e.appendChild(o),!t.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"),e.appendChild(s)}return e}function it(t=""){const e=document.createElement("article");return e.className="os-my-wordpress__article"+(t?" "+t:""),e}function Nn(t,e){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=t,n.appendChild(o);const s=document.createElement("span");return s.className="os-my-wordpress__user-stat-label",s.textContent=e,n.appendChild(s),n}function FT(){const t=document.createElement("div");t.className="os-my-wordpress__preview-loading";const e=document.createElement("os-spinner");return t.appendChild(e),t}function BT(t){const e=document.createElement("div");return e.className="os-my-wordpress__error",e.textContent=t instanceof Error?t.message:k("Unknown error.","desktop-mode"),e}function Ui(t){const e=document.createElement("div");return e.innerHTML=t,(e.textContent??"").trim()}function dw(t){if(!t)return"";try{return new Date(t).toLocaleString()}catch{return t}}function uw(){const t=document.createElement("div");return t.className="os-my-wordpress__preview-empty",t.textContent=k("Select an item to preview it here.","desktop-mode"),t}function HT(t){const e=document.createElement("div");e.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=ae(k("%d items selected","desktop-mode"),t.length),e.appendChild(n);const o=new Map;for(const i of t){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,e.appendChild(i)}return e}const Fi="desktop-mode-embed-",zT=800,GT=600,zl=360,Gl=240,Bi=16,jl=new Map;function jT(t,e){const n=t.ref();if(!n)return;const o=window.wp?.os?.windowManager;if(!o)return;const s=e?.placement,i=s?.meta??null,r=s?`${Fi}${s.id}`:`${Fi}anon-${YT(n)}`,a=i?.name?.trim()??"",l=a!==""?a:t.title(),c={id:r,baseId:r,url:n,title:l,icon:t.icon(),minWidth:zl,minHeight:Gl},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:m,y:g,width:h,height:w}=KT(d,f,p);c.x=m,c.y=g,c.width=h,c.height=w}else c.width=Math.min(zT,Math.max(zl,f-Bi*2)),c.height=Math.min(GT,Math.max(Gl,p-Bi*2));s&&d&&jl.set(r,{...d}),o.open(c)}let fw=!1;function VT(){if(fw)return;fw=!0;const t=e=>{const o=e?.windowId;if(!o||!o.startsWith(Fi))return;const s=o.slice(Fi.length),i=parseInt(s,10);if(!i)return;const l=window.wp?.os?.windowManager?.getById?.(o)?.element;if(!l)return;const c={x:l.offsetLeft,y:l.offsetTop,width:l.offsetWidth,height:l.offsetHeight},d=jl.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(jl.set(o,c),qT(i,c))};X(b.WINDOW_DRAG_END,"os-embed-persist",t),X(b.WINDOW_RESIZE_END,"os-embed-persist",t)}async function qT(t,e){try{const i={...(await Le(0)).placements.find(r=>r.id===t)?.meta??{},window:e};await An(t,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function KT(t,e,n){const o=Math.max(zl,Math.min(t.width,e-Bi)),s=Math.max(Gl,Math.min(t.height,n-Bi)),i=Math.max(0,Math.min(t.x,Math.max(0,e-o))),r=Math.max(0,Math.min(t.y,Math.max(0,n-s)));return{x:i,y:r,width:o,height:s}}function YT(t){let e=0;for(let n=0;n<t.length;n++)e=(Math.imul(e,31)+t.charCodeAt(n))%2147483647;return Math.abs(e).toString(36)}function Vo(){const e=window.wp?.os?.config?.adminUrl??"/wp-admin/";return e.endsWith("/")?e:`${e}/`}function pw(t){const e=typeof t.shape.url=="string"?t.shape.url:"";if(!e)return"";try{const n=new URL(e,window.location.href);if(n.protocol!=="http:"&&n.protocol!=="https:")return""}catch{return""}return e}function XT(){Be({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Vo()}post.php?post=${encodeURIComponent(t.ref())}&action=edit`}}),Be({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Vo()}post.php?post=${encodeURIComponent(t.ref())}&action=edit`}}),Be({id:"agent-chat",label:k("Agent chat","desktop-mode"),types:["user"],isDefault:!0,sort:5,appliesTo:t=>t.shape.isAgent===!0,handler:{kind:"js",open:t=>{const e=t.shape;bg({id:Number.parseInt(e.ref,10),name:e.title,description:e.agentDescription??"",avatarUrl:e.previewUrl??""},"agents-open")}}}),Be({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Vo()}user-edit.php?user_id=${encodeURIComponent(t.ref())}`}}),Be({id:"wp-term-editor",label:"Term editor",types:["term"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>{const[e,n]=t.ref().split(":");return`${Vo()}term.php?taxonomy=${encodeURIComponent(e??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Be({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Vo()}comment.php?action=editcomment&c=${encodeURIComponent(t.ref())}`}}),Be({id:"desktop-mode-upload-download",label:"Download",types:["upload"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=parseInt(t.ref(),10);e&&$i(Ht(e))}}}),Be({id:"desktop-mode-folder-window",label:"Open folder",types:["folder"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=parseInt(t.ref(),10);if(!e)return;const n=window.wp?.os?.windowManager;if(!n)return;const o=`os-folder-${e}`,s=te.getState().folders.get(e),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=t.title(),l=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${e}`,title:l,icon:t.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window");const d=[{folderId:e,title:t.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 m=()=>{const h=d.map((w,v)=>v===d.length-1?{label:w.title}:{label:w.title,onClick:()=>{d.length=v+1,g()}});AT(f,h,{onBack:()=>{d.length<=1||(d.pop(),g())},backDisabled:d.length<=1})},g=()=>{u?.(),u=null,p.replaceChildren();const h=document.createElement("div");h.className="os-folder-window__split",p.appendChild(h);const w=document.createElement("div");w.className="os-folder-window__layer",h.appendChild(w);const v=document.createElement("div");v.className="os-folder-window__preview",v.appendChild(uw()),h.appendChild(v);const R=d[d.length-1],_=Zg(w,R.folderId),E=_.onSelectionChanged(y=>{if(y.length===0){v.replaceChildren(uw());return}if(y.length>1){v.replaceChildren(HT(y));return}xT(y[0],v)}),N=y=>{if(!(y.target instanceof Element))return;const M=y.target.closest(".os-file-tile");if(!M||M.dataset.fileType!=="folder")return;const T=parseInt(M.dataset.fileRef??"",10);if(!T)return;y.preventDefault(),y.stopPropagation();const x=M.querySelector(".os-file-tile__label")?.textContent??`#${T}`;d.push({folderId:T,title:x}),g()};w.addEventListener("dblclick",N,!0);const D=vT(w,{scope:`os-folder:${R.folderId}`,onSort:y=>_.sort(y),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{Fl({onSubmit:async y=>{const M=await Ll({name:y}),T=te.getState().placementsByFolder.get(R.folderId)??[],x=qg(T),I=Ct(He,He,x,w),W=await Sn({type:"folder",ref:String(M.id),parentId:R.folderId,x:I.x,y:I.y});te.upsertFolder(M),te.upsertPlacement(W)}})}}]}),O=gT(p,R.folderId,{selection:{count:()=>_.getSelection().length,subscribe:y=>_.onSelectionChanged(()=>y())}});u=()=>{E(),D.dispose(),O.dispose(),w.removeEventListener("dblclick",N,!0),_.dispose()},m()};g()},width:720,height:480,minWidth:360,minHeight:240})}}}),Be({id:"desktop-mode-shortcut-opener",label:"Open shortcut",types:["shortcut"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=t.shape,n=window.wp?.os;if(n){if(e.shortcutWindow&&n.openWindow){n.openWindow(e.shortcutWindow);return}if(e.shortcutUrl&&n.windowManager)try{const o=new URL(e.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}const s=n.config?.adminUrl,i=s?le(o.toString(),s):`desktop-icon-${t.ref()}`,r=Nh(o.toString());n.windowManager.open({id:i,baseId:i,url:o.toString(),parentUrl:r?.url??o.toString(),title:t.title(),icon:t.icon(),submenu:r?.submenu,multi:!!r?.multi})}catch{}}}}}),Be({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=pw(t);e&&window.open(e,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=pw(t);e&&window.open(e,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(t,e)=>{jT(t,e)}}})}const ZT="os-file-associations";function JT(){cp({id:ZT,label:"File Associations",order:50,render(t){QT(t)}})}function QT(t){t.replaceChildren();const e=cg();if(e.length===0){const i=document.createElement("p");i.className="os-file-associations__empty",i.textContent="No file types are registered.",t.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.",t.appendChild(n);const o=_l(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of e)s.appendChild(eN(i.type,i.label,o));t.appendChild(s)}function eN(t,e,n){const o=document.createElement("div");o.className="os-file-associations__row",o.setAttribute("role","listitem"),o.dataset.fileType=t;const s=document.createElement("label");s.className="os-file-associations__label",s.textContent=e,o.appendChild(s);const i=El(t);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=kl(t),a=n[t]??r?.id??"",l=document.createElement("os-select");l.setAttribute("value",a),l.setAttribute("aria-label",`Default app for ${e}`),l.className="os-file-associations__select",s.htmlFor=`assoc-${t}`,l.id=`assoc-${t}`;for(const c of i){const d=document.createElement("os-option");d.setAttribute("value",c.id),d.textContent=c.isDefault?`${c.label} (default)`:c.label,l.appendChild(d)}return l.addEventListener("os-pick",c=>{const d=c.detail?.value;if(!d)return;const u={..._l(),[t]:d};ug(u),Eg(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(l),o}let Vl=null;function Ze(){return Vl||(Vl=ie("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),Vl}function tN(t,e){const n=Ze();n.state.byFolder.set(t,e),n.notify()}function nN(t){if(!t||typeof t.folderId!="number")return;const e=Ze(),o=(e.state.byFolder.get(t.folderId)??[]).filter(s=>s.id!==t.id);o.push(t),e.state.byFolder.set(t.folderId,o),e.notify()}function oN(t,e){const n=Ze(),o=n.state.byFolder.get(t)??[];n.state.byFolder.set(t,o.filter(s=>s.id!==e)),n.notify()}function sN(t,e){return t.id===e.id&&t.folderId===e.folderId&&t.capability===e.capability&&t.invitedAtMs===e.invitedAtMs&&t.folderName===e.folderName&&t.fileName===e.fileName&&t.ownerName===e.ownerName}function hw(t){const e=Ze(),n=new Map(e.state.pending.map(s=>[s.id,s]));let o=!1;for(const s of t){const i=s.targetType==="file"&&typeof s.folderId!="number"?{...s,folderId:0}:s;if(i.targetType==="file"){if(typeof i.fileId=="number"&&e.state.deniedFiles.has(i.fileId))continue}else if(e.state.deniedFolders.has(i.folderId))continue;const r=n.get(i.id);if(r){if(sN(r,i))continue;e.state.pending=e.state.pending.map(a=>a.id===i.id?i:a)}else e.state.pending.push(i);i.invitedAtMs>e.state.sharesVersion&&(e.state.sharesVersion=i.invitedAtMs),o=!0}o&&e.notify()}function Hi(t,e={}){const n=Ze();n.state.pending=n.state.pending.filter(o=>o.id!==t),e.denied&&typeof e.folderId=="number"&&n.state.deniedFolders.add(e.folderId),e.denied&&typeof e.fileId=="number"&&n.state.deniedFiles.add(e.fileId),n.notify()}const iN=re`: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}`,us=class us extends be{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=e=>{const n=e.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=e=>{this.emit("os-user-pick",{user:e}),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 e=this.getAttribute("endpoint");return e||window.openStationConfig?.filesUsersSearchUrl||""}_scheduleSearch(e){this._timer&&clearTimeout(this._timer),this._phase="loading",this._open=!0,this._positionDropdown(),this.requestUpdate(),this._timer=setTimeout(()=>this._runSearch(e),200)}async _runSearch(e){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(e)+"&exclude="+encodeURIComponent(s);try{const r={signal:o.signal,credentials:"same-origin"},a=await Fe(i,r,{source:"desktop-mode/files-user-search",silent:!0});if(!a.ok)throw new Error(`HTTP ${a.status}`);const l=await a.json();this._results=l&&Array.isArray(l.users)?l.users:[],this._phase="ready",this._error="",this._open=!0}catch(r){if(r.name==="AbortError")return;this._results=[],this._phase="error",this._error=r.message||"Search failed.",this._open=!0}this._positionDropdown(),this.requestUpdate()}_positionDropdown(){const e=this.shadowRoot?.querySelector(".input");if(!e)return;const n=e.getBoundingClientRect(),o=n.bottom+4,s=n.left,i=n.width,a=window.innerHeight-n.bottom,l=n.top,c=Math.max(120,Math.min(280,Math.max(a,l)-16));a<200&&l>a?this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${n.top-4-c}px`,`width:${i}px`,`max-height:${c}px`].join(";"):this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${o}px`,`width:${i}px`,`max-height:${c}px`].join(";")}_dropdownContent(){if(this._phase==="loading")return q`<div class="empty">Searching…</div>`;if(this._phase==="error")return q`<div class="empty error">${this._error}</div>`;if(this._results.length===0){const e=this._query?"No matches.":"No users available.";return q`<div class="empty">${e}</div>`}return this._results.map(e=>q` |
| 74 |
<button |
| 75 |
type="button" |
| 76 |
class="item" |
| 77 |
role="option" |
| 78 |
@mousedown=${n=>n.preventDefault()} |
| 79 |
@click=${()=>this._pick(e)} |
| 80 |
> |
| 81 |
<img class="avatar" src=${e.avatarUrl} alt="" /> |
| 82 |
<div> |
| 83 |
<div class="name">${e.name}</div> |
| 84 |
<div class="slug">${e.slug}</div> |
| 85 |
</div> |
| 86 |
</button> |
| 87 |
`)}render(){const e=this.getAttribute("placeholder")||"Search users…";return q` |
| 88 |
<input |
| 89 |
class="input" |
| 90 |
type="search" |
| 91 |
placeholder=${e} |
| 92 |
autocomplete="off" |
| 93 |
@input=${this._onInput} |
| 94 |
@focus=${this._onFocus} |
| 95 |
@blur=${this._onBlur} |
| 96 |
.value=${this._query} |
| 97 |
/> |
| 98 |
${this._open?q` |
| 99 |
<div class="dropdown" role="listbox" style=${this._dropdownStyle}> |
| 100 |
${this._dropdownContent()} |
| 101 |
</div> |
| 102 |
`:q``} |
| 103 |
`}};us.props=["placeholder","exclude","endpoint"],us.styles=[iN],us.help=void 0;let ql=us;Se("os-user-search",ql);const rN=re`: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}`,fs=class fs extends be{constructor(){super(...arguments),this._onToggle=e=>{const n=!this._selectedSet().has(e);this.emit("os-role-toggle",{slug:e,selected:n})}}_selectedSet(){const e=this.getAttribute("selected")||"";return new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}_roles(){const e=this.getAttribute("roles");if(e)try{const n=JSON.parse(e);if(Array.isArray(n))return n}catch{}return window.openStationConfig?.shareEligibleRoles||[]}render(){const e=this._roles();if(e.length===0)return q`<span class="empty">No eligible roles.</span>`;const n=this._selectedSet();return q` |
| 104 |
${e.map(o=>{const s=n.has(o.slug);return q` |
| 105 |
<button |
| 106 |
type="button" |
| 107 |
class="chip" |
| 108 |
aria-pressed=${s?"true":"false"} |
| 109 |
@click=${()=>this._onToggle(o.slug)} |
| 110 |
>${o.name}</button> |
| 111 |
`})} |
| 112 |
`}};fs.props=["selected","roles"],fs.styles=[rN],fs.help=void 0;let Kl=fs;Se("os-role-picker",Kl);const aN=re` ${tt}: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:7px;gap:2px}.os-segmented__thumb{position:absolute;top:3px;bottom:3px;left:0;width:var( --_thumb-w,0px );border-radius:5px;background-color:var( --os-ui-segmented-selected-bg,transparent );background-image:var( --os-ui-segmented-selected-image,var( --_holo-fill ) );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;box-shadow:var( --_holo-glow );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}}`,lN=re` ${tt} ${Zr}:host{flex:1 1 auto;min-width:0}button{appearance:none;display:block;width:100%;padding:8px 12px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --os-ui-fg-muted,#646970 );cursor:pointer;border-radius:5px;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( --_holo-ink ) );font-weight:600;transition-duration:var( --_holo-t-fast )}:host( [ aria-checked='true' ] ) button::before{display:none}`,ps=class ps extends be{render(){return this.setAttribute("role","radio"),q` |
| 113 |
<button |
| 114 |
type="button" |
| 115 |
class="os-holo-sheen" |
| 116 |
@click=${()=>this._onPick()} |
| 117 |
> |
| 118 |
<slot></slot> |
| 119 |
</button> |
| 120 |
`}_onPick(){this.emit("os-segment-pick",{value:this.value})}};ps.props=["value"],ps.styles=[lN],ps.help=void 0;let Yl=ps;Se("os-segment",Yl);const hs=class hs extends be{constructor(){super(...arguments),this._resizeObserver=null}connectedCallback(){super.connectedCallback(),this.addEventListener("os-segment-pick",e=>{const n=e.detail;e.stopPropagation(),this.value=n.value,this.emit("os-pick",{value:n.value})}),typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._placeThumb()),this._resizeObserver.observe(this))}disconnectedCallback(){this._resizeObserver?.disconnect(),this._resizeObserver=null}_placeThumb(){if(!this.shadowRoot?.querySelector(".os-segmented__thumb"))return;const n=this.value,o=Array.from(this.querySelectorAll(":scope > os-segment")).find(c=>c.getAttribute("value")===n);if(!o||this.offsetWidth===0){this.removeAttribute("data-thumb");return}const s=this.getBoundingClientRect(),i=s.width/this.offsetWidth,r=Math.abs(i-1)<.02?1:i;if(!(r>0))return;const a=o.getBoundingClientRect(),l=c=>`${Math.round(c*100)/100}px`;this.style.setProperty("--_thumb-x",l((a.left-s.left)/r)),this.style.setProperty("--_thumb-w",l(a.width/r)),this.setAttribute("data-thumb",""),this.hasAttribute("data-thumb-ready")||requestAnimationFrame(()=>this.setAttribute("data-thumb-ready",""))}set items(e){const n=this.querySelectorAll(":scope > os-segment");for(const i of Array.from(n))i.remove();for(const i of e){const r=document.createElement("os-segment");r.setAttribute("value",i.value),r.textContent=i.label,this.appendChild(r)}const o=this.value;!(o!==null&&e.some(i=>i.value===o))&&e.length>0?this.value=e[0].value:this.requestUpdate()}render(){const e=this.label||"";e&&this.setAttribute("aria-label",e),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()}),q`<span class="os-segmented__thumb" aria-hidden="true"></span |
| 121 |
><slot></slot>`}};hs.props=["value","label"],hs.styles=[aN],hs.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <os-segment> children where exactly one is active.",status:"stable",props:[{name:"value",type:"string",description:"Currently selected segment value. Mirrored onto child aria-checked."},{name:"label",type:"string",description:"aria-label for the radiogroup."}],slots:[{name:"(default)",description:'<os-segment value="…"> children.'}],events:[{name:"os-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--os-window-bg",description:"Pill background."},{name:"--os-ui-fg",description:"Active label colour."},{name:"--os-ui-fg-muted",description:"Inactive label colour."}],example:q` |
| 122 |
<os-segmented value="md" label="Dock size"> |
| 123 |
<os-segment value="sm">Small</os-segment> |
| 124 |
<os-segment value="md">Medium</os-segment> |
| 125 |
<os-segment value="lg">Large</os-segment> |
| 126 |
</os-segmented> |
| 127 |
`};let Xl=hs;Se("os-segmented",Xl);const cN=re`: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}`,dN=re` ${tt}: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}}`,er=class er extends be{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return q`<slot></slot>`}};er.styles=[cN],er.help=void 0;let Zl=er;Se("os-toast-container",Zl);const ms=class ms extends be{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status")}render(){const e=this.action||"",n=this.hasAttribute("dismissible");return q` |
| 128 |
<span class="os-toast__label"><slot></slot></span> |
| 129 |
<button |
| 130 |
type="button" |
| 131 |
?hidden=${!e} |
| 132 |
@click=${o=>this._onAction(o)} |
| 133 |
> |
| 134 |
${e} |
| 135 |
</button> |
| 136 |
<button |
| 137 |
type="button" |
| 138 |
class="os-toast__close" |
| 139 |
aria-label=${k("Dismiss")} |
| 140 |
?hidden=${!n} |
| 141 |
@click=${o=>this._onDismiss(o)} |
| 142 |
> |
| 143 |
<svg viewBox="0 0 14 14" width="12" height="12" aria-hidden="true" focusable="false"> |
| 144 |
<path |
| 145 |
d="M3 3 L11 11 M11 3 L3 11" |
| 146 |
stroke="currentColor" |
| 147 |
stroke-width="1.7" |
| 148 |
stroke-linecap="round" |
| 149 |
fill="none" |
| 150 |
></path> |
| 151 |
</svg> |
| 152 |
</button> |
| 153 |
`}_onAction(e){e.preventDefault(),e.stopPropagation(),this.emit("os-toast-action",{})}_onDismiss(e){e.preventDefault(),e.stopPropagation(),this.emit("os-toast-dismiss",{})}};ms.props=["action","state","dismissible"],ms.styles=[dN],ms.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."}],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:"{}"}],example:q` |
| 154 |
<os-toast state="in" action="Undo">Post moved to trash.</os-toast> |
| 155 |
`};let Jl=ms;Se("os-toast",Jl);const uN=re` ${tt}: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}.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 )}`,gs=class gs extends be{constructor(){super(...arguments),this._onKey=e=>{e.key==="Escape"&&(e.preventDefault(),this._cancel()),e.key==="Enter"&&!e.isComposing&&(e.preventDefault(),this._confirm())},this._onBackdrop=e=>{const n=e.composedPath();(n.length>0?n[0]:e.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.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop)}render(){const e=this.title??"",n=this.message??"",o=this["confirm-label"]||"Confirm",s=this["cancel-label"]||"Cancel",i=this.hasAttribute("danger"),r=this.hasAttribute("hide-cancel"),a=this.hasAttribute("dismissable");return q` |
| 156 |
<div class="dialog" tabindex="-1"> |
| 157 |
${a?q`<button |
| 158 |
type="button" |
| 159 |
class="close" |
| 160 |
aria-label="Close" |
| 161 |
@click=${()=>this._cancel()} |
| 162 |
>×</button>`:q``} |
| 163 |
${e?q`<h2 class="title">${e}</h2>`:q``} |
| 164 |
${n?q`<p class="message">${n}</p>`:q``} |
| 165 |
<div class="actions"> |
| 166 |
${r?q``:q`<button |
| 167 |
type="button" |
| 168 |
class="btn btn--secondary" |
| 169 |
@click=${()=>this._cancel()} |
| 170 |
> |
| 171 |
${s} |
| 172 |
</button>`} |
| 173 |
<button |
| 174 |
type="button" |
| 175 |
class="btn ${i?"btn--danger":"btn--primary"}" |
| 176 |
@click=${()=>this._confirm()} |
| 177 |
> |
| 178 |
${o} |
| 179 |
</button> |
| 180 |
</div> |
| 181 |
</div> |
| 182 |
`}};gs.props=["open","title","message","confirm-label","cancel-label","danger","hide-cancel","dismissable"],gs.styles=[uN],gs.help=void 0;let Ql=gs;Se("os-confirm-dialog",Ql);function mw(t){return new Promise(e=>{const n=document.createElement("os-confirm-dialog");n.setAttribute("open",""),t.title&&n.setAttribute("title",t.title),n.setAttribute("message",t.message),t.confirmLabel&&n.setAttribute("confirm-label",t.confirmLabel),t.cancelLabel&&n.setAttribute("cancel-label",t.cancelLabel),t.danger&&n.setAttribute("danger",""),t.hideCancel&&n.setAttribute("hide-cancel",""),t.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),e(i)};n.addEventListener("os-confirm",()=>o(!0)),n.addEventListener("os-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}function gw(t,e){const n=document.createElement("os-segmented");n.setAttribute("value",t),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;e(r.value)}),n}function ec(t,e,n={}){const o=document.createElement("os-button");o.setAttribute("variant","ghost"),o.setAttribute("aria-label",n.danger?"Remove":"Dismiss"),o.textContent=t;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",e),o}async function tc(t){const e=document.createElement("os-modal");e.setAttribute("open",""),e.setAttribute("size","lg"),e.setAttribute("title",`Share "${t.folderName}"`),document.body.appendChild(e);let n=[],o=[];const s=()=>{e.innerHTML="";const l=document.createElement("div");l.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",l.textContent=t.ownerName?`Owner: ${t.ownerName} — cannot be changed`:"Owner cannot be changed",e.appendChild(l);const c=document.createElement("div");c.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const d=document.createElement("div");d.textContent="Add people",d.style.cssText="font-weight:600;",c.appendChild(d);const u=document.createElement("os-user-search"),f=n.filter(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 N=E.detail;o.push({kind:"user",ref:String(N.user.id),label:N.user.name,cap:"read"}),s()}),c.appendChild(u),e.appendChild(c);const p=document.createElement("div");p.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const m=document.createElement("div");m.textContent="Add roles",m.style.cssText="font-weight:600;",p.appendChild(m);const g=document.createElement("os-role-picker"),h=n.filter(E=>E.principalType==="role").map(E=>E.principalRef),w=o.filter(E=>E.kind==="role").map(E=>E.ref);if(g.setAttribute("selected",[...h,...w].join(",")),g.addEventListener("os-role-toggle",E=>{const N=E.detail,D=n.find(O=>O.principalType==="role"&&O.principalRef===N.slug);if(D){N.selected||r(D);return}if(N.selected){const O=(window.openStationConfig?.shareEligibleRoles??[]).find(y=>y.slug===N.slug);o.push({kind:"role",ref:N.slug,label:O?O.name:N.slug,cap:"read"})}else o=o.filter(O=>!(O.kind==="role"&&O.ref===N.slug));s()}),p.appendChild(g),e.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 N=document.createElement("div");N.textContent="New invites (not sent yet)",N.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",E.appendChild(N);for(const O of o){const y=document.createElement("div");y.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const M=document.createElement("span");M.textContent=O.kind==="role"?`Role: ${O.label}`:O.label,M.style.flex="1",y.appendChild(M);const T=gw(O.cap,I=>{O.cap=I});y.appendChild(T);const x=ec("×",()=>{o=o.filter(I=>!(I.kind===O.kind&&I.ref===O.ref)),s()});y.appendChild(x),E.appendChild(y)}const D=document.createElement("os-button");D.setAttribute("variant","primary"),D.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,D.style.marginTop="8px",D.addEventListener("click",async()=>{if(o.length===0)return;D.setAttribute("busy",""),D.setAttribute("disabled","");const O=o.slice();let y=0,M=null;for(const T of O)try{await Sg(t.folderId,{principalType:T.kind,principalRef:T.ref,capability:T.cap}),y++}catch(x){M=x;break}y>0&&(o=o.slice(y));try{await i()}catch{}Z(M?{message:`Could not send invites: ${M.message}`}:{message:y===1?"Invite sent.":`${y} invites sent.`}),D.removeAttribute("busy"),D.removeAttribute("disabled"),s()}),E.appendChild(D),e.appendChild(E)}const v=document.createElement("div");if(v.textContent="Who has access",v.style.cssText="font-weight:600;margin:8px 0 6px;",e.appendChild(v),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;",e.appendChild(E)}else for(const E of n){const N=document.createElement("div");N.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const D=document.createElement("div");if(D.style.flex="1",D.textContent=E.principalType==="role"?`Role: ${E.displayName}`:E.displayName,E.state==="pending"){const T=document.createElement("span");T.textContent=" · pending",T.style.cssText="opacity:0.6;font-size:12px;",D.appendChild(T)}else if(E.state==="denied"){const T=document.createElement("span");T.textContent=" · denied",T.style.cssText="color:#d63638;font-size:12px;",D.appendChild(T)}N.appendChild(D);const O=E.capability==="write"?"write":"read",y=gw(O,T=>{a(E,T)});N.appendChild(y);const M=ec("×",()=>{r(E)},{danger:!0});N.appendChild(M),e.appendChild(N)}const R=document.createElement("div");R.setAttribute("slot","footer"),R.style.display="flex",R.style.justifyContent="flex-end",R.style.gap="10px",R.style.flexWrap="wrap";const _=document.createElement("os-button");_.setAttribute("variant","secondary"),_.textContent="Done",_.addEventListener("click",()=>e.remove()),R.appendChild(_),e.appendChild(R)},i=async()=>{try{n=(await kg(t.folderId)).shares,tN(t.folderId,n)}catch(l){Z({message:`Could not load shares: ${l.message}`})}s()},r=async l=>{try{await Ig(t.folderId,l.id),oN(t.folderId,l.id),await i(),Z({message:"Access revoked."})}catch(c){Z({message:`Could not revoke: ${c.message}`})}},a=async(l,c)=>{try{const d=await Ag(t.folderId,l.id,c);nN(d),await i()}catch(d){Z({message:`Could not update capability: ${d.message}`})}};e.addEventListener("os-modal-cancel",()=>e.remove()),s(),await i()}async function fN(t){const e=document.createElement("os-modal");e.setAttribute("open",""),e.setAttribute("size","md"),e.setAttribute("title",`Share "${t.fileName}"`),document.body.appendChild(e);let n=[];const o=async()=>{try{n=(await Tg(t.fileId)).shares}catch(i){Z({message:`Could not load shares: ${i.message}`})}s()},s=()=>{e.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.",e.appendChild(i);const r=document.createElement("div");r.textContent="Add people",r.style.cssText="font-weight:600;margin-bottom:6px;",e.appendChild(r);const a=document.createElement("os-user-search");a.setAttribute("exclude",n.map(u=>u.principalRef).join(",")),a.setAttribute("placeholder","Search users…"),a.addEventListener("os-user-pick",u=>{const f=u.detail;(async()=>{try{await Ng(t.fileId,f.user.id),Z({message:`Invite sent to ${f.user.name}.`})}catch(p){Z({message:`Could not invite: ${p.message}`})}await o()})()}),e.appendChild(a);const l=document.createElement("div");if(l.textContent="Who has access",l.style.cssText="font-weight:600;margin:14px 0 6px;",e.appendChild(l),n.length===0){const u=document.createElement("div");u.textContent="Only you can see this file.",u.style.cssText="opacity:0.6;font-size:12px;",e.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 m=u.displayName;if(p.textContent=m||`User #${u.principalRef}`,u.state==="pending"){const w=document.createElement("span");w.textContent=" · pending",w.style.cssText="opacity:0.6;font-size:12px;",p.appendChild(w)}else if(u.state==="denied"){const w=document.createElement("span");w.textContent=" · denied",w.style.cssText="color:#d63638;font-size:12px;",p.appendChild(w)}f.appendChild(p);const g=document.createElement("span");g.textContent="Read + download",g.style.cssText="opacity:0.6;font-size:12px;",f.appendChild(g);const h=ec("×",()=>{(async()=>{try{await Dg(t.fileId,u.id),Z({message:"Access revoked."})}catch(w){Z({message:`Could not revoke: ${w.message}`})}await o()})()},{danger:!0});f.appendChild(h),e.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",()=>e.remove()),c.appendChild(d),e.appendChild(c)};e.addEventListener("os-modal-cancel",()=>e.remove()),s(),await o()}function ww(t){return new Promise(e=>{const n=document.createElement("os-modal");n.setAttribute("open",""),n.setAttribute("title",t.fileName?`${t.ownerName??"Someone"} shared "${t.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(),e("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 Og(t.fileId,t.id),Ze().state.deniedFiles.add(t.fileId),Ze().notify(),n.remove(),e("denied")}catch(l){Z({message:`Could not deny: ${l.message}`}),r.removeAttribute("busy"),r.removeAttribute("disabled")}});const a=document.createElement("os-button");a.setAttribute("variant","primary"),a.textContent="Accept",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await Rg(t.fileId,t.id);try{const l=await Le(0);mt(0,l.placements)}catch{}n.remove(),e("accepted")}catch(l){Z({message:`Could not accept: ${l.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}}),s.appendChild(i),s.appendChild(r),s.appendChild(a),n.appendChild(s),n.addEventListener("os-modal-cancel",()=>{n.remove(),e("dismissed")}),document.body.appendChild(n)})}function yw(t){return new Promise(e=>{const n=document.createElement("os-modal");n.setAttribute("open",""),n.setAttribute("title",t.folderName?`${t.ownerName??"Someone"} shared "${t.folderName}" with you`:"Folder shared with you");const o=document.createElement("div"),s=t.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(),e("dismissed")});const a=document.createElement("os-button");a.setAttribute("variant","danger"),a.textContent="Deny",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await xg(t.folderId,t.id),Ze().state.deniedFolders.add(t.folderId),Ze().notify(),n.remove(),e("denied")}catch(c){Z({message:`Could not deny: ${c.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}});const l=document.createElement("os-button");l.setAttribute("variant","primary"),l.textContent="Accept",l.addEventListener("click",async()=>{l.setAttribute("busy",""),l.setAttribute("disabled","");try{await Cg(t.folderId,t.id);try{const c=await Le(0);mt(0,c.placements)}catch{}n.remove(),e("accepted")}catch(c){Z({message:`Could not accept: ${c.message}`}),l.removeAttribute("busy"),l.removeAttribute("disabled")}}),i.appendChild(r),i.appendChild(a),i.appendChild(l),n.appendChild(i),n.addEventListener("os-modal-cancel",()=>{n.remove(),e("dismissed")}),document.body.appendChild(n)})}const pN=Object.freeze(Object.defineProperty({__proto__:null,openFileShareModal:fN,openPendingFileInviteModal:ww,openPendingInviteModal:yw,openShareSettingsModal:tc},Symbol.toStringTag,{value:"Module"}));function bw(){return Number(window.openStationConfig?.currentUserId??0)}function vw(){const t=window.wp?.os?.getOsSettings?.();return t?t.foldersSharingEnabled!==!1:!0}function _w(t){const e=At().folders.get(t);return e?Number(e.ownerId):0}function Ew(t){if(typeof t!="string")return null;const e=/^os-folder-(\d+)$/.exec(t);return e?Number(e[1]):null}function hN(t){if(t.file.type!=="folder")return null;const e=Number(t.file.ref);return!Number.isFinite(e)||e<=0?null:e}function mN(t){return Number(t.file.ownerId??0)}function gN(){Fn("os.files.tile-menu","desktop-mode/folder-share",(t,e)=>{if(!vw())return t;const n=hN(e);if(n===null)return t;const o=_w(n)||mN(e),s=bw();if(o===s){const r=!!e.file.shareSummary?.shared?"Manage sharing…":"Share folder…";t.push({id:"desktop-mode/folder-share",label:r,icon:"dashicons-share",sort:30,onClick:()=>{tc({folderId:n,folderName:e.file.title||`Folder ${n}`})}})}else o>0&&t.push({id:"desktop-mode/folder-leave",label:"Leave shared folder",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await mw({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 Lg(n),Oo(e.id);try{const l=await Le(0);mt(0,l.placements)}catch{}const r=`os-folder-${n}`;window.openStation?.windowManager?.close?.(r),Z({message:"You left the shared folder."})}catch(r){Z({message:`Could not leave: ${r.message}`})}}});return t}),ci({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:t=>{if(!vw())return!1;const e=t.config.baseId??t.id,n=Ew(e);return n===null?!1:_w(n)===bw()},onClick:t=>{const e=t.config.baseId??t.id,n=Ew(e);n!==null&&tc({folderId:n,folderName:t.config.title||`Folder ${n}`})}}),X("os.files.tile-rendered","desktop-mode/folder-share",t=>{const{tile:e,placement:n}=t;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||e.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(";"),e.appendChild(s)})}const kw=new Set;function wN(){const t=window.wp?.os?.getOsSettings?.();return t?t.foldersSharingEnabled!==!1:!0}function yN(){const t=Ze(),e=n=>{if(wN()){for(const o of n.pending)if(!kw.has(o.id)){if(kw.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;ww({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?Hi(o.id):i==="denied"&&Hi(o.id,{denied:!0,fileId:s})});continue}yw({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Hi(o.id):s==="denied"&&Hi(o.id,{denied:!0,folderId:o.folderId})})}}};t.subscribe(e),e(t.state)}function bN(){return Number(window.openStationConfig?.currentUserId??0)}function Sw(){return window.openStationConfig?.desktopStorage??{}}function vN(){const t=window.wp?.os?.getOsSettings?.();return t?t.foldersSharingEnabled!==!1:!0}function _N(t){if(t.file.type!=="upload")return null;const e=Number(t.file.ref);return Number.isFinite(e)&&e>0?e:null}function EN(){Fn("os.files.tile-menu","desktop-mode/uploads",(t,e)=>{if(e.file.type==="folder"&&Sw().zipAvailable){const i=Number(e.file.ref);return Number.isFinite(i)&&i>0&&t.push({id:"desktop-mode/folder-zip-download",label:"Download as .zip",icon:"dashicons-download",sort:45,onClick:()=>{$i(Wg(i))}}),t}const n=_N(e);if(n===null)return t;t.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{$i(Ht(n))}});const o=Number(e.file.ownerId??0),s=bN();return o===s&&vN()?t.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{Promise.resolve().then(()=>pN).then(i=>{i.openFileShareModal({fileId:n,fileName:e.file.title||`File ${n}`})})}}):o>0&&o!==s&&e.parentId===0&&t.push({id:"desktop-mode/upload-leave",label:"Leave shared file",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await mw({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 Mg(n),Oo(e.id);try{const r=await Le(0);mt(0,r.placements)}catch{}Z({message:"You left the shared file."})}catch(r){Z({message:`Could not leave: ${r.message}`})}}}),t}),Fn("os.wallpaper-context-menu","desktop-mode/uploads",t=>(Sw().canUpload&&(t.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>Aw(!1)}),t.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>Aw(!0)})),t))}function Aw(t){const e=document.createElement("input");e.type="file",t?e.setAttribute("webkitdirectory",""):e.multiple=!0,e.style.display="none",document.body.appendChild(e),e.addEventListener("change",()=>{const n=e.files?Array.from(e.files):[];e.remove(),n.length!==0&&kN(n,t)}),e.click()}async function kN(t,e){const n=window.openStationConfig,o=n?.dropConfig??{enabled:!1,allowedMimes:[],maxSize:0},s=await Promise.resolve().then(()=>gO),{accepted:i,rejected:r}=s.partitionByPolicy(t,o);if(r.length>0&&Z({message:r.length===1?r[0].message:`${r.length} files can't be uploaded.`}),i.length===0)return;const a=i.map(({file:c,mime:d})=>({file:c,mime:d,fields:s.defaultFields(c,d),relativePath:e?c.webkitRelativePath??"":""}));await(await Promise.resolve().then(()=>By)).openUploadDialog({entries:a,context:{surface:"folder",folderId:0,x:0,y:0},mediaUrl:n?.mediaUrl??"",restNonce:n?.restNonce??"",filesUrl:n?.filesUrl,storage:n?.desktopStorage,forceDesktop:e,preferDesktop:!0,mediaMaxBytes:o.maxSize})}vL(),XT(),VT(),JT(),gN(),EN();const nc=window.openStationConfig?.serverPendingShares;Array.isArray(nc)&&nc.length>0&&hw(nc),yN();const ze={DesktopFile:lg,registerType:Ve,unregisterType:pL,getType:hL,getTypes:cg,resolve:kn,subscribe:mL,registerOpener:Be,unregisterOpener:gL,getOpener:wL,getOpeners:fg,getOpenersForType:El,resolveOpener:kl,subscribeOpeners:yL,getUserAssociations:_l,open:Ai,registerTilePayloadHandler:xi,rest:NL,store:{get:ht,getState:At,subscribe:Ol,setFolderPlacements:mt,upsertPlacement:Ci,removePlacement:Oo,setFolders:Nl,upsertFolder:Dl,removeFolder:Rl}},Iw="__synthFromDockItem";function SN(t){let e=0;for(let n=0;n<t.length;n++)e=(e*31+t.charCodeAt(n))%2147483647;return-(e+1)}function AN(t,e){const n=e[t.id];return{id:SN(t.id),parentId:0,x:n?n.x:0,y:n?n.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Iw]:t.id},file:{type:"shortcut",ref:`dock-promoted:${t.id}`,title:t.title,icon:t.icon,previewUrl:"",exists:!0,shortcutUrl:t.url}}}function IN(){const t=window.wp?.os;return t?.getMenuItems?t.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 CN(){return window.openStationConfig?.desktopIcons??[]}let oc=!1;const sc=new Map;function xN(t){const e=window.wp?.os;if(!e?.getOsSettings||!e?.updateOsSettings)return;const o={...e.getOsSettings().dockPromotedPositions??{}};let s=!1;for(const i of t)i in o&&(delete o[i],s=!0);s&&e.updateOsSettings({dockPromotedPositions:o})}function zi(t,e={},n){if(!oc){oc=!0;try{const o=IN(),s=CN(),i=new Map(o.map(p=>[p.id,p])),a=ze.store.getState().placementsByFolder.get(0)??[],l=new Map;for(const p of a){const m=(p.meta??null)&&typeof p.meta=="object"?p.meta[Iw]:null;typeof m=="string"&&l.set(m,p)}const c=new Map,d=new Set(s.map(p=>p.id));for(const p of a){const m=p?.file?.ref;typeof m=="string"&&d.has(m)&&c.set(m,p)}const u=new Set;for(const p of o){const m=ko(p.id,"dock",t),g=m==="desktop"||m==="both",h=n==="spatial"&&!!p.isCore&&(m==="dock"||m==="both");(g||h)&&(u.add(p.id),l.has(p.id)||ze.store.upsertPlacement(AN(p,e)))}const f=[];for(const[p,m]of l){if(u.has(p))continue;ze.store.removePlacement(m.id);const h=!!i.get(p)?.isCore&&t[p]===void 0;e[p]&&!h&&f.push(p)}f.length>0&&xN(f);for(const p of s){const m=t[p.id],g=c.get(p.id);if(m==="dock"||m==="hidden"){g&&(sc.set(p.id,g),ze.store.removePlacement(g.id));continue}if(!g){const h=sc.get(p.id);h&&(ze.store.upsertPlacement(h),sc.delete(p.id))}}}finally{oc=!1}}}function LN(t,e=()=>({}),n=()=>{}){return queueMicrotask(()=>zi(t(),e(),n())),ze.store.subscribe(()=>{zi(t(),e(),n())})}const TN=re`: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:12px;height: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-surface,#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-surface,#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}@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:8px;height:8px}.os-save-status__glyph{display:none}.os-save-status__glyph svg{display:block;width:100%;height:100%}`,Cw="os-settings-save-lifecycle",NN=2200,DN=6e3,ws=class ws extends be{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(e,n,o){if(super.attributeChangedCallback(e,n,o),(e==="auto"||e==="event")&&(this._removeAutoListener(),this.auto!==null&&this._installAutoListener()),e==="phase"){this._scheduleAutoClear();const s={phase:this.phase??"idle",error:this.error??void 0};this.emit("os-save-status-change",s)}}render(){const e=this.phase??"idle",n=this.mode??"dot",s=(this.error??"")||this._labelForPhase(e);return s?this.setAttribute("title",s):this.removeAttribute("title"),this.setAttribute("aria-live",e==="failed"?"assertive":"polite"),this.setAttribute("role",e==="failed"?"alert":"status"),q` |
| 189 |
<span class="os-save-status"> |
| 190 |
<span class="os-save-status__indicator" aria-hidden="true"> |
| 191 |
<span class="os-save-status__glyph">${this._renderGlyph(e)}</span> |
| 192 |
</span> |
| 193 |
${n==="pill"?q`<span class="os-save-status__label" |
| 194 |
>${this._labelForPhase(e)}</span |
| 195 |
>`:q``} |
| 196 |
</span> |
| 197 |
`}_renderGlyph(e){return e==="saved"?RN():e==="failed"?ON():""}_labelForPhase(e){switch(e){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 e=this.event||Cw;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(e,this._docListener)}_removeAutoListener(){if(!this._docListener)return;const e=this.event||Cw;document.removeEventListener(e,this._docListener),this._docListener=null}_scheduleAutoClear(){this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null);const e=this.phase??"idle",n=this._autoClearMsFor(e);n<=0||(this._autoTimer=window.setTimeout(()=>{this._autoTimer=null,this.phase="idle"},n))}_autoClearMsFor(e){if(e==="saved"){const n=this["auto-clear-saved-ms"];return parseInt(n||"",10)||NN}if(e==="failed"){const n=this["auto-clear-failed-ms"];return parseInt(n||"",10)||DN}return 0}};ws.props=["phase","mode","animation","auto","event","error","saving-label","saved-label","idle-label","auto-clear-saved-ms","auto-clear-failed-ms"],ws.styles=[TN],ws.help=void 0;let ic=ws;Se("os-save-status",ic);function RN(){return q` |
| 198 |
<svg |
| 199 |
viewBox="0 0 12 12" |
| 200 |
aria-hidden="true" |
| 201 |
focusable="false" |
| 202 |
fill="none" |
| 203 |
stroke="currentColor" |
| 204 |
stroke-width="2" |
| 205 |
stroke-linecap="round" |
| 206 |
stroke-linejoin="round" |
| 207 |
> |
| 208 |
<path d="M2.5 6 L5 8.5 L9.5 4" /> |
| 209 |
</svg> |
| 210 |
`}function ON(){return q` |
| 211 |
<svg |
| 212 |
viewBox="0 0 12 12" |
| 213 |
aria-hidden="true" |
| 214 |
focusable="false" |
| 215 |
fill="currentColor" |
| 216 |
> |
| 217 |
<path |
| 218 |
d="M5 2 H7 V7 H5 z M5 8.5 H7 V10.5 H5 z" |
| 219 |
/> |
| 220 |
</svg> |
| 221 |
`}const MN=re` ${tt} ${Jr}: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}`,ys=class ys extends be{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),Tf(this)}render(){const e=this._attr("label")||"",n=this._attr("value")??"",o=this._attr("placeholder")||"",s=this._boolAttr("disabled"),i=this._boolAttr("readonly"),r=this._attr("aria-label")||e,a=this._attr("name")||"",l=Number(this._attr("rows"))||3,c=this._attr("maxlength"),d=this._attr("minlength"),u=this._boolAttr("invalid"),p=`${this.id||"os-unnamed"}__field`;return q` |
| 222 |
${e?q`<label class="os-textarea__label" for=${p}>${e}</label>`:q``} |
| 223 |
<textarea |
| 224 |
id=${p} |
| 225 |
part="textarea" |
| 226 |
.value=${n} |
| 227 |
placeholder=${o} |
| 228 |
?disabled=${s} |
| 229 |
?readonly=${i} |
| 230 |
rows=${l} |
| 231 |
maxlength=${c??""} |
| 232 |
minlength=${d??""} |
| 233 |
name=${a} |
| 234 |
aria-invalid=${u?"true":"false"} |
| 235 |
aria-label=${r||""} |
| 236 |
@input=${m=>this._onInput(m)} |
| 237 |
@change=${m=>this._onChange(m)} |
| 238 |
@keydown=${m=>this._onKeyDown(m)} |
| 239 |
></textarea> |
| 240 |
`}_attr(e){return this.getAttribute(e)}_boolAttr(e){return this.getAttribute(e)!==null}_onInput(e){const n=e.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(e){const n=e.target;this.emit("os-input-commit",{value:n.value})}_onKeyDown(e){if(this._boolAttr("submit-on-enter")&&e.key==="Enter"&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey){e.preventDefault();const n=e.target;this.emit("os-submit",{value:n.value})}}_autosize(e){const n=Number(this._attr("max-rows"))||8,o=window.getComputedStyle(e),s=parseFloat(o.fontSize)||13,i=o.lineHeight,r=i==="normal"?s*1.45:parseFloat(i)||s*1.45,a=parseFloat(o.paddingTop)||0,l=parseFloat(o.paddingBottom)||0,c=r*n+a+l;e.style.height="auto";const d=Math.min(e.scrollHeight,c);e.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))}};ys.props=["label","value","placeholder","disabled","readonly","ariaLabel","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],ys.styles=[MN],ys.help=void 0;let rc=ys;Se("os-textarea",rc);const PN=re`: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}`,WN={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 $N(t){const e=(t??"").trim();return e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)||/['"()\\<>\s]/.test(e)?"":e}const bs=class bs extends be{constructor(){super(...arguments),this._activateWired=!1}render(){const e=$N(this["icon-src"]||this.getAttribute("icon-src")||""),n=e?"":this.icon||"",o=WN[n]||"";return e?q` |
| 241 |
<button type="button"> |
| 242 |
<span |
| 243 |
class="themed-icon" |
| 244 |
aria-hidden="true" |
| 245 |
style="-webkit-mask: url('${e}') center / contain no-repeat; mask: url('${e}') center / contain no-repeat;" |
| 246 |
></span> |
| 247 |
<slot></slot> |
| 248 |
</button> |
| 249 |
`:q` |
| 250 |
<button type="button"> |
| 251 |
<svg |
| 252 |
width="14" |
| 253 |
height="14" |
| 254 |
viewBox="0 0 12 12" |
| 255 |
aria-hidden="true" |
| 256 |
focusable="false" |
| 257 |
></svg> |
| 258 |
<slot></slot> |
| 259 |
</button> |
| 260 |
<span data-svg-buffer style="display:none">${o}</span> |
| 261 |
`}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paintSvg()),queueMicrotask(()=>this._wireActivateEvent())}attributeChangedCallback(e,n,o){super.attributeChangedCallback(e,n,o),queueMicrotask(()=>this._paintSvg())}_paintSvg(){const e=this.shadowRoot;if(!e)return;const n=e.querySelector("svg"),o=e.querySelector("[data-svg-buffer]");if(n&&o){const s=o.textContent||"";n.innerHTML!==s&&(n.innerHTML=s)}}_wireActivateEvent(){if(this._activateWired)return;const e=this.shadowRoot;if(!e)return;const n=e.querySelector("button");n&&(this._activateWired=!0,n.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("os-button-activate",{bubbles:!0,composed:!0,cancelable:!0}))}))}};bs.props=["icon","icon-src","active","danger"],bs.styles=[PN],bs.help=void 0;let ac=bs;Se("os-window-button",ac);const xt="Sticky Note",UN="<!-- wpworkspace-sticky:",lc="-->",FN=64,BN=48,HN=180;function cc(t){const e=zN(t.title),n=KN(GN(t.content,{stripHtmlForRendered:!0})),o=YN(t);return{localId:`guideline:${t.id}`,guidelineId:t.id,title:e,body:VN(e,n),modified:t.modified,...o>0?{modifiedMs:o}:{},link:t.link,termIds:Array.isArray(t.wp_guideline_type)?t.wp_guideline_type.filter(XN):[]}}function zN(t){const e=[];typeof t=="string"?e.push(t):t&&typeof t=="object"&&(typeof t.raw=="string"&&e.push(t.raw),typeof t.rendered=="string"&&e.push(dc(t.rendered)));for(const n of e){const o=dc(n).trim();if(o)return o}return xt}function GN(t,e={}){return typeof t=="string"?t:!t||typeof t!="object"?"":typeof t.raw=="string"&&t.raw.length>0?t.raw:typeof t.rendered=="string"?e.stripHtmlForRendered?dc(t.rendered):t.rendered:""}function xw(t){const e=t.split(/\r?\n/).find(o=>o.trim().length>0)?.trim(),n=e&&e.length>0?e:xt;return uc(n,FN)}function jN(t){const n=t.replace(/\s+/g," ").trim()||xt;return uc(n,BN)}function VN(t,e){const n=t.trim();return!n||e.split(/\r?\n/)[0]?.trim()===n?e:e?`${n} |
| 262 |
${e}`:n}function qN(t,e=xt){const n=e.trim()||xt,o=xw(t),s=t.search(/\r?\n/);if(s===-1){const r=o===xt?n:o;return{title:r,content:"",excerpt:Lw(r)}}let i=t.slice(s);return i=i.replace(/^\r?\n/,""),i.startsWith(` |
| 263 |
`)&&(i=i.slice(1)),{title:o,content:i,excerpt:Lw(i.trim()?i:o)}}function Lw(t){const e=t.replace(/[\n\t]+/g," ").trim();return uc(e,HN)}function KN(t){if(!t.startsWith(UN)||!t.includes(lc))return t;const e=t.indexOf(lc);let n=t.slice(e+lc.length);return n.startsWith(`\r |
| 264 |
`)?n=n.slice(2):n.startsWith(` |
| 265 |
`)&&(n=n.slice(1)),n}function dc(t){if(typeof document<"u"){const e=document.createElement("template");return e.innerHTML=t,(e.content.textContent??"").trim()}return t.replace(/<[^>]*>/g,"").trim()}function uc(t,e){return t.length>e?`${t.slice(0,e)}...`:t}function YN(t){if(typeof t.openstation_modified_ms=="number"&&Number.isFinite(t.openstation_modified_ms))return t.openstation_modified_ms;if(!t.modified)return 0;const e=Date.parse(t.modified);return Number.isFinite(e)?e:0}function XN(t){return typeof t=="number"&&Number.isFinite(t)}class Tw extends Error{constructor(e,n){super(e),this.name="StickyNotesRestError",this.status=n}}async function ZN(t){const e=await JN(t),n=QN([...e.artifactTerms,...e.artifactsTerms],e.noteTerms,e.stickyTerms);if(n)return n;const o=await fc(t,{slug:"artifact",name:"Artifact",parent:0}),s=await fc(t,{slug:"note",name:"Note",parent:o.id}),i=await fc(t,{slug:"sticky",name:"Sticky",parent:o.id});return{stickyTermId:i.id,termIds:Rw([o.id,s.id,i.id])}}async function JN(t){const[e,n,o,s]=await Promise.all([Dn(t,"artifact"),Dn(t,"artifacts"),Dn(t,"note"),Dn(t,"sticky")]);return{artifactTerms:e,artifactsTerms:n,noteTerms:o,stickyTerms:s}}function QN(t,e,n){if(n.length===0)return null;const o=t.find(r=>["artifact","artifacts"].includes(r.slug))??t[0]??null,s=o?n.find(r=>Number(r.parent)===o.id)??n[0]:n[0];if(!s)return null;const i=o?e.find(r=>Number(r.parent)===o.id)??null:null;return{stickyTermId:s.id,termIds:Rw([o?.id,i?.id,s.id])}}async function Nw(t,e){return(await Gi(t,Dw("wp/v2/guidelines",{context:"edit",status:"private",per_page:"100",orderby:"modified",order:"desc",wp_guideline_type:String(e)}),void 0,!0)).filter(o=>Array.isArray(o.wp_guideline_type)?o.wp_guideline_type.includes(e):!0).map(cc)}async function eD(t,e,n){const o=qN(e.body,e.title),s={status:"private",title:o.title,content:o.content,excerpt:o.excerpt};e.guidelineId===null&&(s.wp_guideline_type=n.termIds);const i=e.guidelineId===null?"wp/v2/guidelines":`wp/v2/guidelines/${e.guidelineId}`,r=await Gi(t,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},!1);return cc(r)}function tD(t,e){const n=new URL("post.php",t);return n.searchParams.set("post",String(e)),n.searchParams.set("action","edit"),n.toString()}async function Dn(t,e){try{return await Gi(t,Dw("wp/v2/wp_guideline_type",{context:"edit",slug:e,per_page:"100"}),void 0,!0)}catch(n){if(n instanceof Tw&&(n.status===404||n.status===400))return[];throw n}}async function fc(t,e){const n=await Dn(t,e.slug),o=n.find(s=>Number(s.parent??0)===e.parent);if(o)return o;if(n[0])return n[0];try{return await Gi(t,"wp/v2/wp_guideline_type",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}catch(s){const i=await Dn(t,e.slug);if(i[0])return i[0];throw s}}async function Gi(t,e,n,o=!0){const s=await Fe(nt(nD(t),e),n,{source:"desktop-mode/sticky-notes",silent:o});if(!s.ok)throw new Tw(s.statusText||`${xt} request failed`,s.status);return await s.json()}function nD(t){return t.restUrl?t.restUrl:`${window.location.origin}/wp-json/`}function Dw(t,e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,s])=>{n.set(o,s)}),`${t}?${n.toString()}`}function Rw(t){const e=[];return t.forEach(n=>{typeof n=="number"&&Number.isFinite(n)&&!e.includes(n)&&e.push(n)}),e}const oD="openstation_sticky_notes_subscribe",sD="openstation_sticky_notes";let Ow=!1,pc=null;function iD(t){pc=t,!Ow&&(Ow=!0,Ae.contribute(oD,()=>pc?.getHeartbeatSubscription()),Ae.subscribe(sD,e=>{pc?.applyHeartbeatPayload(e)}))}const Mw="desktop-mode-sticky-notes-geometry",rD=264,aD=176,hc=180,mc=128,me=16,lD=1e3;class cD{constructor(e){this.root=null,this.terms=null,this.controllers=new Map,this.contextMenuInstalled=!1,this.desktopHooksInstalled=!1,this.highWaterMs=0,this.zIndexCounter=0,this.host=e.host,this.config=e.config,this.available=e.available??!0,this.openArtifact=e.openArtifact,this.getActiveDesktopId=e.getActiveDesktopId??(()=>"desktop-1"),this.onError=e.onError}async boot(){if(this.available)try{if(this.terms=await ZN(this.config),!this.terms)return;this.installContextMenu(),this.installDesktopHooks();const e=await Nw(this.config,this.terms.stickyTermId);if(this.bumpHighWaterFromNotes(e),iD(this),e.length===0)return;this.ensureRoot(),Pw(e).forEach((n,o)=>this.upsert(n,o))}catch(e){e instanceof Error&&console.debug("[openstation] Sticky notes unavailable:",e.message)}}createNote(e=""){if(!this.terms)return;const n={localId:`local:${Date.now()}:${Math.random().toString(36).slice(2)}`,guidelineId:null,title:e.trim()?jN(e):xt,body:e,termIds:this.terms.termIds};this.upsert(n,this.controllers.size,{activate:!0}).focus()}upsert(e,n,o={}){this.ensureRoot();const s=Ge(e),i=this.controllers.get(s);if(i)return i.replace(e),o.activate&&this.bringToFront(i),i;const r=new dD({layer:this,note:e,index:n});return this.controllers.set(s,r),this.root?.appendChild(r.element),this.assignZIndex(r),this.applyDesktopVisibility(r),o.activate&&this.bringToFront(r),r}ensureRoot(){if(this.root)return this.root;const e=document.createElement("section");return e.className="os-sticky-notes",e.setAttribute("aria-label",k("Sticky notes")),this.host.appendChild(e),this.root=e,e}installContextMenu(){this.contextMenuInstalled||(this.contextMenuInstalled=!0,Fn("os.wallpaper-context-menu","desktop-mode/sticky-notes",e=>!Array.isArray(e)||!this.terms||e.some(n=>n.id==="new-sticky-note")?e:[...e,{id:"new-sticky-note",label:k("New sticky note"),icon:"dashicons-edit-page",sort:14,onClick:()=>this.createNote()}]))}installDesktopHooks(){this.desktopHooksInstalled||(this.desktopHooksInstalled=!0,X(b.DESKTOP_SWITCHED,"desktop-mode/sticky-notes",()=>this.refreshDesktopVisibility()),X(b.DESKTOP_CLOSED,"desktop-mode/sticky-notes",e=>{this.migrateDesktopAssignments(e?.desktopId,e?.migratedTo),this.refreshDesktopVisibility()}))}save(e){return this.terms?eD(this.config,e,this.terms):Promise.reject(new Error(k("Sticky term is unavailable.")))}getHeartbeatSubscription(){if(this.terms)return{stickyTermId:this.terms.stickyTermId,knownIds:this.knownGuidelineIds(),version:this.highWaterMs}}applyHeartbeatPayload(e){for(const n of e.notes??[]){const o=cc(n);this.upsertRemote(o)}for(const n of e.removed??[])this.forgetGuidelineId(n);typeof e.serverTimeMs=="number"&&Number.isFinite(e.serverTimeMs)&&e.serverTimeMs>this.highWaterMs&&(this.highWaterMs=e.serverTimeMs),e.truncated&&this.reloadFromServer()}openNoteArtifact(e){e.guidelineId!==null&&this.openArtifact(tD(this.config.adminUrl,e.guidelineId),e.title,e.guidelineId)}notifyError(e){this.onError?.(e)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}defaultGeometry(e){const{width:n,height:o}=this.hostSize(),s=Math.min(rD,Math.max(hc,n-me*2)),i=Math.min(aD,Math.max(mc,o-me*2)),r=e%8*28,a=rt(n-s-32-r,me,Math.max(me,n-s-me)),l=rt(32+r,me,Math.max(me,o-i-me));return{x:a/n,y:l/o,width:s,height:i}}forget(e){this.controllers.delete(Ge(e.note)),e.dispose(),e.element.remove(),this.controllers.size===0&&(this.root?.remove(),this.root=null)}replaceControllerKey(e,n){const o=Ge(n.note);this.controllers.delete(e),this.controllers.set(o,n),fD(e,o),this.applyDesktopVisibility(n)}bumpHighWaterFromNote(e){const n=qo(e);n>this.highWaterMs&&(this.highWaterMs=n)}bringToFront(e){e.setZIndex(this.nextZIndex())}geometryForNote(e,n){const o=Ge(e),s=gc(o),i=this.normalizeDesktopId(s?.desktopId),r=s?{...s,desktopId:i}:{...this.defaultGeometry(n),desktopId:i};return(!s||s.desktopId!==r.desktopId)&&wc(o,r),r}upsertRemote(e){const n=Ge(e),o=this.controllers.get(n);if(o)return o.shouldReplaceFromRemote(e)?(o.replace(e),this.bumpHighWaterFromNote(e),o):(this.bumpHighWaterFromNote(e),o);const s=this.upsert(e,this.controllers.size);return this.bumpHighWaterFromNote(e),s}forgetGuidelineId(e){for(const n of this.controllers.values())if(n.note.guidelineId===e){this.forget(n);return}}knownGuidelineIds(){const e=[];for(const n of this.controllers.values())n.note.guidelineId!==null&&e.push(n.note.guidelineId);return e}bumpHighWaterFromNotes(e){e.forEach(n=>this.bumpHighWaterFromNote(n))}assignZIndex(e){e.setZIndex(this.nextZIndex())}nextZIndex(){return this.zIndexCounter+=1,this.zIndexCounter}applyDesktopVisibility(e){e.setVisible(this.isNoteOnActiveDesktop(e.note))}refreshDesktopVisibility(){for(const e of this.controllers.values())this.applyDesktopVisibility(e)}isNoteOnActiveDesktop(e){const n=Ge(e),o=gc(n),s=this.normalizeDesktopId(o?.desktopId);return o&&o.desktopId!==s&&wc(n,{...o,desktopId:s}),s===this.activeDesktopId()}migrateDesktopAssignments(e,n){if(!e||!n||e===n)return;const o=ji();let s=!1;Object.entries(o).forEach(([i,r])=>{r.desktopId===e&&(o[i]={...r,desktopId:this.normalizeDesktopId(n)},s=!0)}),s&&yc(o)}activeDesktopId(){try{const e=this.getActiveDesktopId();return typeof e=="string"&&e?e:"desktop-1"}catch{return"desktop-1"}}normalizeDesktopId(e){return e||this.activeDesktopId()}async reloadFromServer(){if(this.terms)try{const e=await Nw(this.config,this.terms.stickyTermId),n=new Set;Pw(e).forEach(o=>{o.guidelineId!==null&&n.add(o.guidelineId),this.upsertRemote(o)}),this.knownGuidelineIds().forEach(o=>{n.has(o)||this.forgetGuidelineId(o)})}catch{}}}class dD{constructor(e){this.saveTimer=null,this.geometryTimer=null,this.saving=!1,this.saveAgain=!1,this.resizeObserver=null,this.disposed=!1,this.layer=e.layer,this.note=e.note,this.index=e.index,this.element=document.createElement("article"),this.element.className="os-sticky-note",this.element.dataset.stickyNoteId=Ge(this.note),this.titleEl=document.createElement("span"),this.editor=document.createElement("os-textarea"),this.statusEl=document.createElement("os-save-status"),this.openButton=document.createElement("os-window-button"),this.paint(),this.applyGeometry(this.layer.geometryForNote(this.note,this.index)),this.element.addEventListener("pointerdown",()=>this.layer.bringToFront(this),{capture:!0}),this.element.addEventListener("focusin",()=>this.layer.bringToFront(this)),this.watchResize()}focus(){window.setTimeout(()=>this.editor.focusInput?.(),0)}replace(e){this.note=e,this.element.dataset.stickyNoteId=Ge(this.note),this.titleEl.textContent=this.note.title,this.editor.setAttribute("value",this.note.body),this.refreshOpenButton()}shouldReplaceFromRemote(e){if(this.hasLocalChanges())return!1;const n=qo(this.note),o=qo(e);return!(n>0&&o>0&&o<=n&&this.note.title===e.title&&this.note.body===e.body)}setZIndex(e){this.element.style.zIndex=String(e)}setVisible(e){this.element.style.display=e?"":"none"}dispose(){this.disposed=!0,this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.geometryTimer!==null&&(window.clearTimeout(this.geometryTimer),this.geometryTimer=null),this.resizeObserver?.disconnect(),this.resizeObserver=null}paint(){this.element.innerHTML="",this.element.style.minWidth=`${hc}px`,this.element.style.minHeight=`${mc}px`;const e=document.createElement("div");e.className="os-sticky-note__header";const n=document.createElement("span");n.className="os-sticky-note__grip",n.setAttribute("aria-hidden","true"),this.titleEl.className="os-sticky-note__title",this.titleEl.textContent=this.note.title,this.statusEl.setAttribute("mode","icon"),this.statusEl.setAttribute("phase","idle"),this.statusEl.className="os-sticky-note__status",this.openButton.setAttribute("icon","detach"),this.openButton.setAttribute("title",k("Open artifact")),this.openButton.className="os-sticky-note__open",this.openButton.addEventListener("os-button-activate",()=>{this.layer.openNoteArtifact(this.note)});const o=document.createElement("os-window-button");o.setAttribute("icon","close"),o.setAttribute("danger",""),o.setAttribute("title",k("Hide sticky note")),o.className="os-sticky-note__close",o.addEventListener("os-button-activate",()=>this.close()),e.append(n,this.titleEl,this.statusEl,this.openButton,o),e.addEventListener("pointerdown",s=>this.startDrag(s)),this.editor.className="os-sticky-note__editor",this.editor.setAttribute("aria-label",k("Sticky note text")),this.editor.setAttribute("rows","8"),this.editor.setAttribute("value",this.note.body),this.installEditorKeyboardGuard(),this.editor.addEventListener("os-input-change",s=>{const i=s.detail;this.note.body=i.value,this.note.title=xw(i.value),this.titleEl.textContent=this.note.title,this.setPhase("pending"),this.scheduleSave()}),this.editor.addEventListener("os-input-commit",()=>this.flushSave()),this.element.append(e,this.editor),this.refreshOpenButton()}installEditorKeyboardGuard(){["keydown","keypress","keyup"].forEach(e=>{this.editor.addEventListener(e,n=>{n.stopPropagation()})})}refreshOpenButton(){const e=this.note.guidelineId===null;this.openButton.classList.toggle("is-disabled",e),this.openButton.setAttribute("aria-disabled",e?"true":"false")}close(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.layer.forget(this);return}this.flushSave(),this.layer.forget(this)}scheduleSave(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.setPhase("idle");return}this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},lD)}flushSave(){this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),(this.note.guidelineId!==null||this.note.body.trim().length>0)&&this.save()}async save(){if(this.saving){this.saveAgain=!0,this.setPhase("pending");return}this.saving=!0,this.setPhase("saving");const e=this.note.body;try{const n=await this.layer.save({...this.note,body:e});if(this.disposed)return;const o=Ge(this.note);this.note.guidelineId=n.guidelineId,this.note.modified=n.modified,this.note.link=n.link,this.note.termIds=n.termIds.length>0?n.termIds:this.note.termIds,this.note.body===e&&(this.note.title=n.title,this.titleEl.textContent=n.title),o!==Ge(this.note)&&(this.element.dataset.stickyNoteId=Ge(this.note),this.layer.replaceControllerKey(o,this)),this.layer.bumpHighWaterFromNote(this.note),this.refreshOpenButton(),this.setPhase("saved")}catch(n){if(this.disposed)return;const o=n instanceof Error?n.message:k("Could not save sticky note.");this.setPhase("failed",o),this.layer.notifyError(o)}finally{this.saving=!1,!this.disposed&&this.saveAgain&&(this.saveAgain=!1,this.scheduleSave())}}setPhase(e,n){this.statusEl.setAttribute("phase",e),n?(this.statusEl.setAttribute("error",n),this.statusEl.setAttribute("title",n)):(this.statusEl.removeAttribute("error"),this.statusEl.removeAttribute("title"))}hasLocalChanges(){const e=this.statusEl.getAttribute("phase");return this.saveTimer!==null||this.saving||this.saveAgain||e==="pending"||e==="failed"}startDrag(e){if(e.button!==0||e.target?.closest("os-window-button, os-save-status"))return;e.preventDefault();const o=this.element.getBoundingClientRect(),s=this.layerHostRect(),i=o.left-s.left,r=o.top-s.top,a=e.clientX,l=e.clientY;this.element.classList.add("os-sticky-note--dragging"),this.element.setPointerCapture?.(e.pointerId);const c=u=>{const f=this.element.offsetWidth,p=this.element.offsetHeight,{width:m,height:g}=this.layer.hostSize(),h=rt(i+u.clientX-a,me,Math.max(me,m-f-me)),w=rt(r+u.clientY-l,me,Math.max(me,g-p-me));this.element.style.left=`${h}px`,this.element.style.top=`${w}px`},d=u=>{this.element.classList.remove("os-sticky-note--dragging"),this.element.releasePointerCapture?.(u.pointerId),document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),this.persistGeometry()};document.addEventListener("pointermove",c),document.addEventListener("pointerup",d)}applyGeometry(e){const{width:n,height:o}=this.layer.hostSize(),s=rt(e.width,hc,n-me*2),i=rt(e.height,mc,o-me*2),r=rt(e.x*n,me,Math.max(me,n-s-me)),a=rt(e.y*o,me,Math.max(me,o-i-me));this.element.style.left=`${r}px`,this.element.style.top=`${a}px`,this.element.style.width=`${s}px`,this.element.style.height=`${i}px`}watchResize(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.geometryTimer!==null&&window.clearTimeout(this.geometryTimer),this.geometryTimer=window.setTimeout(()=>{this.geometryTimer=null,this.persistGeometry()},150)}),this.resizeObserver.observe(this.element))}persistGeometry(){const{width:e,height:n}=this.layer.hostSize(),o=parseFloat(this.element.style.left)||0,s=parseFloat(this.element.style.top)||0,i=gc(Ge(this.note));wc(Ge(this.note),{...i??{},x:rt(o/e,0,1),y:rt(s/n,0,1),width:this.element.offsetWidth,height:this.element.offsetHeight})}layerHostRect(){return(this.element.parentElement?.parentElement??document.body).getBoundingClientRect()}}function uD(t){const e=new cD(t);return e.boot(),e}function Ge(t){return t.guidelineId===null?t.localId:`guideline:${t.guidelineId}`}function qo(t){if(typeof t.modifiedMs=="number"&&Number.isFinite(t.modifiedMs))return t.modifiedMs;if(!t.modified)return 0;const e=Date.parse(t.modified);return Number.isFinite(e)?e:0}function Pw(t){return[...t].sort((e,n)=>qo(e)-qo(n))}function gc(t){const n=ji()[t];return!n||!Number.isFinite(n.x)||!Number.isFinite(n.y)||!Number.isFinite(n.width)||!Number.isFinite(n.height)?null:n}function wc(t,e){const n=ji();n[t]=e,yc(n)}function fD(t,e){if(t===e)return;const n=ji();n[t]&&(n[e]=n[t],delete n[t],yc(n))}function ji(){try{const t=window.localStorage.getItem(Mw);return t?JSON.parse(t):{}}catch{return{}}}function yc(t){try{window.localStorage.setItem(Mw,JSON.stringify(t))}catch{}}function rt(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}const pD=re`: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}}`,Ww={xs:20,sm:24,md:40,lg:64,xl:96},$w=new Set(["online","inactive","offline"]),vs=class vs extends be{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(e,n,o){super.attributeChangedCallback(e,n,o),e==="src"&&(this._imgFailed=!1),(e==="user-id"||e==="presence")&&this._maybeAttachPresenceListener()}render(){const e=this._attr("src"),n=this._attr("name")||"",o=this._attr("alt"),s=o!==null?o:n,i=this._attr("size"),r=this._resolveSize(i),a=this._presenceForRender(),l=this._attr("clickable")!==null;this.style.setProperty("--os-ui-avatar-size",`${r}px`);const c=e&&!this._imgFailed?"":this._initialsBg(n),d=e&&!this._imgFailed?q`<img |
| 266 |
src=${e} |
| 267 |
alt=${s} |
| 268 |
@error=${()=>this._onImgError()} |
| 269 |
loading="lazy" |
| 270 |
/>`:this._initials(n),u=a?q`<span |
| 271 |
class=${`os-avatar__dot os-avatar__dot--${a}`} |
| 272 |
aria-label=${this._presenceLabel(a)} |
| 273 |
></span>`:q``;return l?q` |
| 274 |
<button |
| 275 |
type="button" |
| 276 |
class="os-avatar__tile" |
| 277 |
aria-label=${s||"User"} |
| 278 |
style=${c?`background:${c};`:""} |
| 279 |
@click=${f=>this._onClick(f)} |
| 280 |
>${d}</button> |
| 281 |
${u} |
| 282 |
`:q` |
| 283 |
<div |
| 284 |
class="os-avatar__tile" |
| 285 |
role="img" |
| 286 |
aria-label=${s||"User"} |
| 287 |
style=${c?`background:${c};`:""} |
| 288 |
>${d}</div> |
| 289 |
${u} |
| 290 |
`}_attr(e){return this.getAttribute(e)}_resolveSize(e){if(!e)return 32;if(e in Ww)return Ww[e];const n=Number(e);return Number.isFinite(n)&&n>0?n:32}_initials(e){const n=e.trim();return n?Array.from(n)[0]?.toUpperCase()??"?":"?"}_initialsBg(e){const n=Os(e);return`linear-gradient(135deg, hsl(${n} 62% 55%), hsl(${(n+24)%360} 58% 42%))`}_presenceForRender(){const e=this._attr("presence");return e&&$w.has(e)?e:null}_presenceLabel(e){switch(e){case"online":return"Online";case"inactive":return"Inactive";case"offline":return"Offline"}}_onImgError(){this._imgFailed=!0,this.requestUpdate()}_onClick(e){const n=this._attr("user-id"),o={userId:n!==null&&Number(n)||null,originalEvent:e};this.emit("os-avatar-click",o)}_attachHoverEffect(){typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(this._onPointerEnter=()=>{this.style.setProperty("--os-ui-avatar-hover","1")},this._onPointerLeave=()=>{this.style.setProperty("--os-ui-avatar-hover","0"),this._pendingTiltX="0deg",this._pendingTiltY="0deg",this._pendingGlareX="50%",this._pendingGlareY="50%",this._flushTilt()},this._onPointerMove=n=>{const o=this.getBoundingClientRect();if(o.width===0||o.height===0)return;const s=(n.clientX-o.left)/o.width-.5,i=(n.clientY-o.top)/o.height-.5,r=14;this._pendingTiltY=`${(s*r).toFixed(2)}deg`,this._pendingTiltX=`${(-i*r).toFixed(2)}deg`;const a=Math.max(0,Math.min(100,(s+.5)*100)),l=Math.max(0,Math.min(100,(i+.5)*100));this._pendingGlareX=`${a.toFixed(1)}%`,this._pendingGlareY=`${l.toFixed(1)}%`,this._tiltRaf||(this._tiltRaf=requestAnimationFrame(()=>this._flushTilt()))},this.addEventListener("pointerenter",this._onPointerEnter),this.addEventListener("pointerleave",this._onPointerLeave),this.addEventListener("pointermove",this._onPointerMove))}_flushTilt(){this._tiltRaf=0,this.style.setProperty("--os-ui-avatar-tilt-x",this._pendingTiltX),this.style.setProperty("--os-ui-avatar-tilt-y",this._pendingTiltY),this.style.setProperty("--os-ui-avatar-glare-x",this._pendingGlareX),this.style.setProperty("--os-ui-avatar-glare-y",this._pendingGlareY)}_detachHoverEffect(){this._onPointerMove&&(this.removeEventListener("pointermove",this._onPointerMove),this._onPointerMove=null),this._onPointerEnter&&(this.removeEventListener("pointerenter",this._onPointerEnter),this._onPointerEnter=null),this._onPointerLeave&&(this.removeEventListener("pointerleave",this._onPointerLeave),this._onPointerLeave=null),this._tiltRaf&&(cancelAnimationFrame(this._tiltRaf),this._tiltRaf=0)}_maybeAttachPresenceListener(){const e=this._attr("user-id"),n=this._attr("presence"),o=!!e&&!n;o&&!this._presenceHandler?(this._presenceHandler=s=>{const i=s.detail;i&&String(i.userId)===String(e)&&i.newStatus&&$w.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)}};vs.props=["src","alt","name","size","presence","userId","clickable"],vs.styles=[pD],vs.help=void 0;let bc=vs;Se("os-avatar",bc);const Rn=["butter","blush","sky","mint","lilac","peach"];function hD(t){return Rn.includes(t)?t:Rn[0]}function vc(t){return t.toLowerCase().replace(/[^a-z0-9_-]/g,"")||Rn[0]}function Uw(t){const e=Rn.indexOf(hD(t));return Rn[(e+1)%Rn.length]}const Fw="cubic-bezier(0.2, 0.7, 0.2, 1)",Bw="cubic-bezier(0.5, 0, 0.9, 0.4)",mD="cubic-bezier(0.2, 0.7, 0.3, 1.15)";function On(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function at(t,e,n){return typeof t.animate!="function"?Promise.resolve():t.animate(e,n).finished.then(()=>{}).catch(()=>{})}async function gD(t){const e=t.restRotation??0;if(On()){Hw(t.rippleHost,400);return}const n=t.tempo??1,o=t.fallDistance??30;await at(t.pin,[{opacity:0,transform:`translate(8px, ${-o}px) rotate(${e-16}deg) scale(1.9)`},{opacity:1,offset:.35},{opacity:1,transform:`translate(0, 0) rotate(${e}deg) scale(0.92)`}],{duration:170*n,easing:Bw,fill:"forwards"}),Hw(t.rippleHost,420*n);const s=at(t.paper,[{transform:"scale(1) translateY(0) skewX(0)"},{transform:"scale(0.982) translateY(2px) skewX(0)",offset:.08},{transform:"scale(1.01) translateY(0) skewX(0.6deg)",offset:.32},{transform:"scale(0.996) translateY(0) skewX(-0.4deg)",offset:.55},{transform:"scale(1) translateY(0) skewX(0)"}],{duration:370*n,easing:"linear"}),i=at(t.pin,[{transform:`rotate(${e}deg) scale(0.92)`},{transform:`rotate(${e+1.5}deg) scale(1.07)`,offset:.25},{transform:`rotate(${e-1}deg) scale(0.98)`,offset:.5},{transform:`rotate(${e}deg) scale(1)`}],{duration:370*n,easing:Fw,fill:"forwards"});await Promise.all([s,i])}function Hw(t,e){const n=document.createElement("span");n.className="os-pinned-note__ripple",n.setAttribute("aria-hidden","true"),t.appendChild(n),at(n,[{boxShadow:"0 0 0 0 rgba(0, 0, 0, 0.28)",opacity:.35},{boxShadow:"0 0 0 26px rgba(0, 0, 0, 0)",opacity:0}],{duration:e,easing:"ease-out"}).then(()=>n.remove()),window.setTimeout(()=>n.remove(),e+100)}function wD(t){if(On())return{onPointerMove:()=>{},setBias:()=>{},stop:()=>{}};const e=14;let n=0,o=0,s=0,i=0,r=null,a=0,l=0,c=0,d=0,u=!0;const f=p=>{if(!u)return;const m=Math.min(.05,d?(p-d)/1e3:.016);d=p,p-a>80&&(l*=.85),s=Math.max(-14,Math.min(14,-l*.055))+i,o+=(-120*(n-s)-e*o)*m,n+=o*m,t.style.transform=`rotate(${n.toFixed(2)}deg)`,c=window.requestAnimationFrame(f)};return c=window.requestAnimationFrame(f),{onPointerMove(p){const m=performance.now();if(r!==null&&m>a){const g=(p-r)/(m-a)*16.7;l=l*.7+g*.3}r=p,a=m},setBias(p){i=p},stop(){u=!1,window.cancelAnimationFrame(c),t.style.transform=""}}}async function yD(t){if(On()){await at(t.flyback,[{opacity:1},{opacity:0}],{duration:120,easing:"linear",fill:"forwards"});return}const e=t.swing?at(t.swing,[{transform:"rotate(0deg)"},{transform:"rotate(9deg)",offset:.35},{transform:"rotate(-4deg)",offset:.7},{transform:"rotate(0deg)"}],{duration:330,easing:"linear",fill:"forwards"}):Promise.resolve(),n=at(t.flyback,[{left:`${t.flyback.offsetLeft}px`,top:`${t.flyback.offsetTop}px`},{left:`${t.homeX}px`,top:`${t.homeY}px`}],{duration:330,easing:mD,fill:"forwards"});await Promise.all([n,e])}async function bD(t){if(On()){await at(t.clone,[{opacity:1},{opacity:0}],{duration:150,easing:"linear",fill:"forwards"});return}t.pin&&at(t.pin,[{transform:"translate(0, 0) rotate(0deg)",opacity:1},{transform:"translate(2px, -16px) rotate(-30deg)",opacity:0}],{duration:200,easing:Fw,fill:"forwards"});const e=t.clone.getBoundingClientRect(),n=t.binX-(e.left+e.width/2),o=t.binY-(e.top+e.height/2),s="polygon(4% 8%, 38% 2%, 68% 7%, 96% 3%, 98% 42%, 92% 71%, 97% 94%, 60% 98%, 30% 93%, 3% 97%, 6% 62%, 2% 34%)",i="polygon(10% 14%, 42% 6%, 64% 12%, 90% 8%, 94% 38%, 86% 66%, 92% 88%, 58% 94%, 34% 86%, 10% 92%, 14% 58%, 8% 36%)";await at(t.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:Bw,delay:60,fill:"forwards"})}function vD(t){let e=2166136261;for(let o=0;o<t.length;o++)e^=t.charCodeAt(o),e=Math.imul(e,16777619)>>>0;return e>>>1||1}function zw(t){let e=2166136261;const n=`os-note-${t}`;for(let i=0;i<n.length;i++)e^=n.charCodeAt(i),e=Math.imul(e,16777619)>>>0;const o=e>>>3,s=e>>>5;return{rotation:(e%45-22)/10,pinOffsetX:o%21-10,pinRotation:s%17-8}}const _D=.57,ED=.525,kD=56,SD=52;function AD(t){return`${t.replace(/\/$/,"")}/assets/images/pushpin.svg`}function ID(t){const e=document.createElement("img");return e.src=AD(t),e.alt="",e.width=kD,e.height=SD,e.draggable=!1,e.className="os-pinned-note__pin-img",e}let _c=null;function CD(t){_c=t}function xD(){if(!_c)throw new Error("[openstation] notes REST client called before installNotesRestDeps().");return _c}function LD(t){const e=window.openStationConfig;return typeof e?.restNonce=="string"&&e.restNonce?e.restNonce:t}class Gw extends Error{constructor(e){super("Note was changed by another session."),this.status=409,this.name="NotesConflictError",this.current=e}}function TD(t){return t instanceof Gw}async function Mn(t,e){const{baseUrl:n,nonce:o}=xD(),s=t?nt(n,t):n,i=new Headers(e.headers??{});i.set("X-WP-Nonce",LD(o)),e.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Fe(s,{...e,headers:i,credentials:"same-origin"},{source:"desktop-mode/notes"}),a=await r.text();let l=null;if(a)try{l=JSON.parse(a)}catch{l=null}if(!r.ok){if(r.status===409){const d=l?.data?.current;throw new Gw(d??null)}const c=l;throw new Error(`[openstation] notes REST ${r.status}: ${c?.code??""} ${c?.message??""}`.trim())}if(l===null)throw new Error(`[openstation] notes REST ${r.status}: empty or unparseable body.`);return l}function jw(){return Mn("",{method:"GET"})}function ND(t){return Mn("",{method:"POST",body:JSON.stringify(t)})}function DD(t,e){return Mn(`/${t}`,{method:"PATCH",body:JSON.stringify(e)})}function RD(t){return Mn(`/${t}`,{method:"DELETE"})}function Vw(t){return Mn(`/${t}/restore`,{method:"POST"})}function OD(t){return Mn(`/${t}/convert`,{method:"POST"})}const MD="openstation_notes_subscribe",PD="openstation_notes";let qw=!1,Ec=null;function WD(t){Ec=t,!qw&&(qw=!0,Ae.contribute(MD,()=>Ec?.getHeartbeatSubscription()),Ae.subscribe(PD,e=>{Ec?.applyHeartbeatPayload(e)}))}function Kw(){const t=window.wp?.os;return t&&typeof t.showToast=="function"?t:null}async function $D(t,e){e.onEvict(t.id);try{await RD(t.id),Kw()?.showToast?.({message:k("Note moved to Trash","desktop-mode"),duration:6e3,action:{label:k("Undo","desktop-mode"),onClick:()=>{Vw(t.id).then(n=>e.onRestore(n)).catch(n=>{console.error("[openstation] notes: restore failed:",n)})}}})}catch(n){console.error("[openstation] notes: trash failed:",n),e.onRestore(t),Kw()?.showToast?.({message:k("Could not move the note to the Trash.","desktop-mode"),duration:5e3})}}function Vi(){return window.wp?.os??null}function UD(t){const e=Vi();if(!e?.windowManager?.open||!e.deriveWindowId)return window.location.href=t,null;const n=e.deriveWindowId(t);return e.windowManager.open({id:n,baseId:n,url:t,title:k("Edit draft","desktop-mode"),icon:"dashicons-admin-post"}),n}async function FD(t,e){e.onEvict(t.id);try{const n=await OD(t.id),o=UD(n.editUrl);Vi()?.showToast?.({message:k("Note converted to a draft post","desktop-mode"),duration:6e3,action:{label:k("Undo","desktop-mode"),onClick:()=>{o&&Vi()?.windowManager?.getById?.(o)?.close?.(),Vw(t.id).then(s=>e.onRestore(s)).catch(s=>{console.error("[openstation] notes: convert undo failed:",s)})}}})}catch(n){console.error("[openstation] notes: convert failed:",n),e.onRestore(t),Vi()?.showToast?.({message:k("Could not convert the note to a post.","desktop-mode"),duration:5e3})}}const BD="note-draft",Pn="note",HD="os-note-created",zD=208,GD=1e3,jD=800,VD=10,qD=1;function KD(){return window.wp?.os?.dragManager??null}function qi(t){return t.seed||Math.abs(t.id)||1}const YD='<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>';class XD{constructor(e){this.root=null,this.liveRegion=null,this.controllers=new Map,this.zCounter=1,this.highWaterMs=0,this.tempIdCounter=0,this.host=e.host,this.pluginUrl=e.pluginUrl,this.canCreatePosts=e.canCreatePosts??!1,this.onError=e.onError}async boot(){try{const{notes:e}=await jw();e.forEach(n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"none"})}),WD(this)}catch(e){e instanceof Error&&console.debug("[openstation] Pinned notes unavailable:",e.message)}}upsertNote(e,n={animate:"none"}){this.ensureRoot(),this.zCounter=Math.max(this.zCounter,e.z);const o=this.controllers.get(e.id);if(o)return o.replace(e),o;const s=new ZD({layer:this,note:e});return this.controllers.set(e.id,s),this.root?.appendChild(s.element),n.animate!=="none"&&s.playInsertion(n.animate==="thunk"?1:.7),s}removeNote(e){const n=this.controllers.get(e);n&&(this.controllers.delete(e),n.dispose(),n.element.remove())}rekeyNote(e,n){this.controllers.delete(e),this.controllers.set(n.note.id,n)}has(e){return this.controllers.has(e)}get(e){return this.controllers.get(e)}nextTempId(){return this.tempIdCounter-=1,this.tempIdCounter}bringToFront(e){this.zCounter+=1,e.setZ(this.zCounter)}bumpHighWater(e){Number.isFinite(e)&&e>this.highWaterMs&&(this.highWaterMs=e)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}clampPosition(e,n){const{width:o,height:s}=this.hostSize(),i=Math.max(0,1-zD/o),r=Math.max(0,1-120/s);return{x:Math.min(i,Math.max(0,e)),y:Math.min(r,Math.max(0,n))}}announce(e){this.ensureRoot(),this.liveRegion&&(this.liveRegion.textContent=e)}notifyError(e){this.onError?.(e)}trashNote(e){$D(e,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}convertNote(e){!this.canCreatePosts||!e.canEdit||FD(e,{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(e=>e>0),sinceMs:this.highWaterMs}}applyHeartbeatPayload(e){for(const n of e.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 e.removed??[])this.removeNote(n);typeof e.serverTimeMs=="number"&&Number.isFinite(e.serverTimeMs)&&this.bumpHighWater(e.serverTimeMs),e.truncated&&this.reloadFromServer()}async reloadFromServer(){try{const{notes:e}=await jw(),n=new Set;for(const o of e){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 e=document.createElement("section");e.className="os-notes",e.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"),e.appendChild(n),this.host.appendChild(e),this.root=e,this.liveRegion=n,e}}class ZD{constructor(e){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=e.layer,this.note=e.note,this.jitter=zw(qi(e.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 e=this.note;this.element.className="os-pinned-note",this.element.dataset.noteId=String(e.id),this.element.dataset.noteColor=vc(e.color),this.element.dataset.owner=e.canEdit?"me":"other",this.element.setAttribute("role",e.canEdit?"group":"note"),this.element.setAttribute("aria-label",e.canEdit?k("Pinned note","desktop-mode"):ae(k("Note by %s","desktop-mode"),e.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(ID(this.layer.pluginUrl)),e.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",e.canEdit?this.paintOwnerPaper():this.paintViewerPaper(),this.element.append(this.pinEl,this.paperEl)}paintOwnerPaper(){const e=document.createElement("div");e.className="os-pinned-note__meta";const n=document.createElement("button");n.type="button",n.className="os-pinned-note__color-dot",this.colorDot=n,this.refreshColorDot(),n.addEventListener("click",()=>this.cycleColor());const o=document.createElement("os-window-button");if(o.className="os-pinned-note__visibility",this.visibilityBtn=o,this.refreshVisibility(),o.addEventListener("os-button-activate",()=>this.togglePublic()),e.append(n,o),this.layer.canCreatePosts){const a=document.createElement("os-window-button");a.className="os-pinned-note__convert",a.innerHTML=YD;const l=k("Convert to a draft post","desktop-mode");a.setAttribute("title",l),a.setAttribute("aria-label",l),a.addEventListener("os-button-activate",()=>this.layer.convertNote(this.note)),e.append(a)}const s=document.createElement("os-textarea");s.className="os-pinned-note__editor",s.setAttribute("aria-label",k("Note text","desktop-mode")),s.setAttribute("rows","5"),s.setAttribute("auto-grow",""),s.setAttribute("max-rows","10"),s.setAttribute("value",this.note.text),["keydown","keypress","keyup"].forEach(a=>{s.addEventListener(a,l=>l.stopPropagation())}),s.addEventListener("os-input-change",a=>{const l=a.detail;this.pendingText=l.value,this.setPhase("pending"),this.scheduleSave()}),s.addEventListener("os-input-commit",()=>this.flushSave()),this.editor=s;const i=document.createElement("div");i.className="os-pinned-note__footer";const r=document.createElement("os-save-status");r.setAttribute("mode","icon"),r.setAttribute("phase","idle"),r.className="os-pinned-note__status",this.statusEl=r,i.appendChild(r),this.paperEl.append(e,s,i)}paintViewerPaper(){const e=document.createElement("div");e.className="os-pinned-note__body",e.textContent=this.note.text;const n=document.createElement("div");n.className="os-pinned-note__attribution",n.title=ae(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(e,n)}refreshColorDot(){if(!this.colorDot)return;const e=Uw(this.note.color);this.colorDot.style.setProperty("--dm-note-next-paper",`var(--dm-note-${e})`),this.colorDot.setAttribute("aria-label",ae(k("Change paper color (next: %s)","desktop-mode"),e))}refreshVisibility(){if(!this.visibilityBtn)return;const e=this.note.public;this.visibilityBtn.innerHTML="";const n=document.createElement("span");n.className=`dashicons ${e?"dashicons-admin-site-alt3":"dashicons-lock"}`,n.setAttribute("aria-hidden","true"),this.visibilityBtn.appendChild(n),this.visibilityBtn.setAttribute("title",k(e?"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",e)}replace(e){const n=e.id!==this.note.id,o=qi(e)!==qi(this.note),s=e.color!==this.note.color,i=e.x!==this.note.x||e.y!==this.note.y,r=e.z!==this.note.z;if(this.note=e,r&&(this.element.style.zIndex=String(e.z)),n&&(this.element.dataset.noteId=String(e.id)),o&&(this.jitter=zw(qi(e)),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=vc(e.color),this.refreshColorDot()),i&&this.applyPosition(),this.note.canEdit)this.pendingText===null&&this.editor?.setAttribute("value",e.text),this.refreshVisibility();else{const a=this.paperEl.querySelector(".os-pinned-note__body");a&&(a.textContent=e.text)}}shouldReplaceFromRemote(e){return this.pendingText!==null||this.saveTimer!==null?!1:e.updatedAtMs>=this.note.updatedAtMs}setZ(e){this.element.style.zIndex=String(e),!(e===this.note.z||!this.note.canEdit)&&(this.note={...this.note,z:e},!(this.note.id<=0)&&(this.zTimer!==null&&window.clearTimeout(this.zTimer),this.zTimer=window.setTimeout(()=>{this.zTimer=null,this.queuePatch({z:this.note.z})},jD)))}applyPosition(){this.element.style.left=`${(this.note.x*100).toFixed(3)}%`,this.element.style.top=`${(this.note.y*100).toFixed(3)}%`}moveTo(e,n){const o=this.layer.clampPosition(e,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(e=1){return gD({pin:this.pinEl,paper:this.paperEl,rippleHost:this.element,restRotation:this.jitter.pinRotation,fallDistance:e>=1?30:12,tempo:e})}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(e){this.statusEl?.setAttribute("phase",e)}scheduleSave(){this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.flushSave()},GD)}flushPendingEdits(){this.flushSave()}flushSave(){if(this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.pendingText===null||this.note.id<=0)return;const e=this.pendingText;this.pendingText=null,this.note={...this.note,text:e},this.setPhase("saving"),this.queuePatch({text:e})}cycleColor(){const e=Uw(this.note.color);this.note={...this.note,color:e},this.element.dataset.noteColor=e,this.refreshColorDot(),this.note.id>0&&this.queuePatch({color:e})}togglePublic(){const e=!this.note.public;this.note={...this.note,public:e},this.refreshVisibility(),e&&!On()&&this.visibilityBtn&&this.visibilityBtn.animate?.([{transform:"scale(1)"},{transform:"scale(1.25)"},{transform:"scale(1)"}],{duration:300,easing:"ease-out"}),this.layer.announce(k(e?"Note is now public.":"Note is now private.","desktop-mode")),this.note.id>0&&this.queuePatch({public:e})}queuePatch(e){this.patchChain=this.patchChain.then(async()=>{if(!(this.disposed||this.note.id<=0))try{const n=await DD(this.note.id,{...e,updatedAtMs:this.note.updatedAtMs});if(this.disposed)return;this.note={...this.note,updatedAtMs:n.updatedAtMs,public:n.public},this.setPhase("saved")}catch(n){if(this.disposed)return;if(TD(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(e){if(!this.note.canEdit||this.note.id<=0)return;const n=KD();if(!n)return;e.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:Pn,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:e,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 e=this.element.getBoundingClientRect(),o=(this.pinEl.querySelector("img")??this.pinEl).getBoundingClientRect(),s=o.left-e.left+o.width*_D,i=o.top-e.top+o.height*ED,r=document.createElement("div");r.className="os-pinned-note-ghost",r.style.width=`${e.width}px`,r.style.height=`${e.height}px`;const a=document.createElement("div");a.className="os-pinned-note-ghost__swing",a.style.transformOrigin=`${s}px ${i}px`;const l=this.pinEl.cloneNode(!0);l.removeAttribute("aria-pressed"),l.setAttribute("aria-hidden","true");const c=this.paperEl.cloneNode(!0);return c.classList.add("os-pinned-note-ghost__paper"),a.dataset.noteColor=this.element.dataset.noteColor??"",a.append(l,c),r.appendChild(a),{root:r,swing:a,pin:l,paper:c,tipX:s,tipY:i}}installDragListeners(e){this.teardownDragListeners();let n=null;const o=a=>{a.detail?.payload?.data?.noteId===this.note.id&&(n=wD(e.swing))},s=a=>{const l=a.detail;this.lastPointer={x:l.clientX,y:l.clientY},n?.onPointerMove(l.clientX)},i=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(e.root.classList.add("os-pinned-note-ghost--doom"),n?.setBias(6))},r=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(e.root.classList.remove("os-pinned-note-ghost--doom"),n?.setBias(0))};document.addEventListener(he.START,o),document.addEventListener(he.MOVE,s),document.addEventListener(he.ENTER,i),document.addEventListener(he.LEAVE,r),this.dragCleanup=()=>{n?.stop(),n=null,document.removeEventListener(he.START,o),document.removeEventListener(he.MOVE,s),document.removeEventListener(he.ENTER,i),document.removeEventListener(he.LEAVE,r)}}teardownDragListeners(){this.dragCleanup?.(),this.dragCleanup=null}async snapBack(e){if(!this.lastPointer||On()){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 yD({flyback:n.root,swing:n.swing,homeX:e.left,homeY:e.top})}finally{n.root.remove()}this.playInsertion(.63)}async playCrumpleAt(e,n){const o=this.buildGhost();o.root.classList.add("os-pinned-note-ghost--flyback"),o.root.style.position="fixed",o.root.style.left=`${e-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 bD({clone:o.root,pin:o.pin,paper:o.paper,binX:e,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(e){this.moveMode&&(this.moveMode=!1,this.element.classList.remove("os-pinned-note--move-mode"),this.pinEl.setAttribute("aria-pressed","false"),e?(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(e){if(!this.moveMode)return;const{width:n,height:o}=this.layer.hostSize(),s=e.shiftKey?qD:VD,i=s/n,r=s/o;switch(e.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),ki({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(a=>{a&&this.layer.trashNote(this.note)});break;default:return}e.preventDefault(),e.stopPropagation()}nudge(e,n){const o=this.layer.clampPosition(this.note.x+e,this.note.y+n);this.note={...this.note,...o},this.applyPosition()}}const Ko=new Map;function JD(t,e){return Ko.set(t,e),()=>{Ko.get(t)===e&&Ko.delete(t)}}function QD(t){const e=Ko.get(t.type);return e?e.accept(t.data):!1}function eR(t,e){const n=Ko.get(t.payload.type);return n?(n.onDrop(t,e),!0):!1}function Yw(t,e,n){const o=t.host.getBoundingClientRect(),s=e.payload.ghost?.offsetX??0,i=e.payload.ghost?.offsetY??0,{width:r,height:a}=t.hostSize();return t.clampPosition((n.clientX-s-o.left)/r,(n.clientY-i-o.top)/a)}function tR(t,e,n){const o=e.payload.data,s=String(o.text??"");if(!s.trim())return;const{x:i,y:r}=Yw(t,e,n),a=vc(String(o.color??"")),l=o.isPublic===!0,c=vD(s),d=t.nextTempId(),u={id:d,text:s,color:a,x:i,y:r,z:1,public:l,seed:c,ownerId:0,ownerName:"",ownerAvatar:"",canEdit:!0,updatedAtMs:0},f=t.upsertNote(u,{animate:"thunk"});t.bringToFront(f),ND({text:s,color:a,x:i,y:r,public:l,seed:c}).then(p=>{t.bumpHighWater(p.updatedAtMs),f.replace(p),t.rekeyNote(d,f),f.flushPendingEdits()}).catch(p=>{t.removeNote(d),t.notifyError(k("Could not pin the note. Please try again.","desktop-mode")),console.error("[openstation] notes: create failed:",p)})}function nR(t,e,n){const o=e.payload.data,s=t.get(o.noteId);if(!s)return;const{x:i,y:r}=Yw(t,e,n);s.moveTo(i,r)}function oR(t){const e=[],n=o=>o.folderId===0;return e.push(Xg(BD,{accept:(o,s)=>n(s)&&!!String(o.text??"").trim(),onDrop:(o,s)=>tR(t,o,s)})),e.push(Xg(Pn,{accept:(o,s)=>n(s)&&o.canEdit===!0,onDrop:(o,s)=>nR(t,o,s)})),e.push(JD(Pn,{accept:o=>o.canEdit===!0,onDrop:(o,s)=>{const i=o.payload.data,r=t.get(i.noteId);if(!r)return;const a=r.note;r.playCrumpleAt(s.clientX,s.clientY),t.trashNote(a)}})),()=>{e.forEach(o=>o())}}const kc="data-os-posts-drop-active",Xw="desktop-mode-posts",sR='.os-dock__item[data-menu-slug="menu-posts"],.os-dock__item[data-menu-slug="editphp"]',iR="[data-os-posts-root]";function rR(){return window.wp?.os?.dragManager??null}function aR(t){return t.type!==Pn?!1:t.data.canEdit===!0}function lR(t){if(!t)return!1;let e=t,n="";try{const i=new URL(t,window.location.origin);e=i.pathname,n=i.search}catch{}if(!(/(?:^|\/)(?:edit\.php|post-new\.php)$/.test(e)||!e.includes("/")&&(e==="edit.php"||e==="post-new.php")))return!1;const s=new URLSearchParams(n).get("post_type");return!s||s==="post"}function cR(t){const e=t.placement.file;if(!e||e.type!=="shortcut")return!1;const n=typeof e.shortcutUrl=="string"?e.shortcutUrl:"";return lR(n)}function Zw(t,e){if(e.payload.type!==Pn)return;const n=e.payload.data;if(typeof n.noteId!="number")return;const o=t.get(n.noteId);o&&t.convertNote(o.note)}let Jw=!1,Yo=null,Xo=null,Qw=null;function ey(t,e,n,o){return t.registerDropTarget({id:n,element:o,acceptLabel:k("Convert to post","desktop-mode"),accept:s=>aR(s),onEnter:()=>{o.setAttribute(kc,"")},onLeave:()=>{o.removeAttribute(kc)},onDrop:s=>{o.removeAttribute(kc),Zw(e,s)}})}function dR(t,e){const n=t.debug().listTargets().find(o=>o.id===e);return n?n.element:null}function uR(t){if(Jw||!t.canCreatePosts)return;const e=rR();if(!e)return;Jw=!0,xi(Pn,{appliesTo:o=>cR(o),acceptLabel:k("Convert to post","desktop-mode"),accept:o=>o.canEdit===!0,onDrop:o=>Zw(t,o)});const n=()=>{const o=document.querySelector(sR);if(!(o instanceof HTMLElement)){Yo?.(),Yo=null;return}Yo&&dR(e,"notes-convert-dock")===o||(Yo?.(),Yo=ey(e,t,"notes-convert-dock",o))};n(),X(b.DOCK_AFTER_RENDER,"desktop-mode/notes/convert-dock-target",n),typeof MutationObserver<"u"&&(Qw=new MutationObserver(()=>{n()}),Qw.observe(document.body,{childList:!0,subtree:!0})),X(b.WINDOW_OPENED,"desktop-mode/notes/convert-window-target",o=>{if(o.windowId!==Xw)return;Xo?.(),Xo=null;const s=document.querySelector(iR);s instanceof HTMLElement&&(Xo=ey(e,t,"notes-convert-window",s))}),X(b.WINDOW_CLOSED,"desktop-mode/notes/convert-window-cleanup",o=>{o.windowId===Xw&&(Xo?.(),Xo=null)})}function fR(t){const e=t.config.notesUrl;if(typeof e!="string"||!e)return null;CD({baseUrl:e,nonce:t.config.restNonce??""});const n=new XD({host:t.host,pluginUrl:t.config.pluginUrl??"",canCreatePosts:t.config.canCreatePosts??!1,onError:t.onError});return oR(n),uR(n),document.addEventListener(HD,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 pR={id:"clock",get label(){return k("Clock")},get description(){return k("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:t=>{t.classList.add("os-widget-clock");const e=document.createElement("div");e.className="os-widget-clock__time",t.appendChild(e);const n=document.createElement("div");n.className="os-widget-clock__date",t.appendChild(n);const o=()=>{const a=new Date;e.textContent=a.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=a.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})};o();const s=1e3-Date.now()%1e3;let i=null;const r=window.setTimeout(()=>{o(),i=window.setInterval(o,1e3)},s);return()=>{window.clearTimeout(r),i!==null&&window.clearInterval(i)}}};function hR(){Pa(pR)}async function mR(){const t=window;if(t.openStationReleaseCard)return t.openStationReleaseCard;const e=t.openStationConfig?.releaseCardBundleUrl??"";if(!e)return null;try{await ke(e)}catch{return null}return t.openStationReleaseCard??null}function ty(t,e){if(e){const o=k('WordPress %1$s "%2$s" is available.');return ae(o,t,e)}const n=k("WordPress %s is available.");return ae(n,t)}async function gR(t){const{update:e,openUrl:n}=t;if(!e||typeof e.version!="string"||!e.version||typeof e.url!="string"||!e.url)return;const o=e.version,s=typeof e.branch=="string"&&e.branch?e.branch:o,i=e.crossing===!0,a=`desktop-mode/core-update:${typeof e.available=="string"&&e.available?e.available:o}`;if(Ta(a))return;const l=()=>n({url:e.url,title:k("WordPress Updates")}),d=t.resolveArt&&t.loadImage&&t.showCard?null:await mR(),u=t.resolveArt??d?.resolveReleaseArt,f=t.loadImage??d?.preloadImage,p=t.showCard??d?.showReleaseCard,m=u?await u(s):null;if(m&&m.artUrl&&f&&p&&await f(m.artUrl)){p({message:ty(o,i?m.name:""),artUrl:m.artUrl,dismissKey:a,onUpdate:l});return}Z({message:ty(o,""),persistent:!0,dismissible:!0,onDismiss:()=>fi(a),action:{label:k("Update now"),onClick:l}})}function ny(t){const{notices:e,openUrl:n,keyPrefix:o="core-notice"}=t;if(Array.isArray(e))for(const s of e){if(!s||typeof s.id!="string"||!s.id||typeof s.message!="string"||!s.message)continue;const i=`desktop-mode/${o}:${s.id}`;if(Ta(i))continue;const r=s.actionLabel,a=s.actionUrl,l=s.title||r||"";let c;r&&a&&(c={label:r,onClick:()=>n({url:a,title:l})}),Z({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>fi(i),action:c})}}const Sc="desktop-mode/starter",wR="desktop-mode/dev-mode-gate";let oy=!1;function yR({osSettings:t,layer:e}){if(oy)return;oy=!0,Fn(b.WIDGETS,wR,o=>t.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==Sc));let n=t.getOsSettingsSnapshot().developerModeEnabled;t.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?e.mountIfEnabled(Sc):e.unmount(Sc),bo())})}function bR(t){const{layer:e}=t,n=new Set,o=new Set,s=async l=>{if(!(!l.scriptUrl||o.has(l.scriptUrl))){try{await ke(l.scriptUrl,{translations:l.scriptTranslations,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){L(b.SHELL_ERROR,{scope:"widget-script-load",id:l.id,error:c});return}o.add(l.scriptUrl)}},i=l=>{const d=(window.openStationWidgets||{})[l.id];return d?{id:l.id,label:l.label,description:l.description,icon:l.icon,movable:l.movable,resizable:l.resizable,minWidth:l.minWidth||void 0,minHeight:l.minHeight||void 0,maxWidth:l.maxWidth||void 0,maxHeight:l.maxHeight||void 0,defaultWidth:l.defaultWidth||void 0,defaultHeight:l.defaultHeight||void 0,mount:d}:(L(b.SHELL_ERROR,{scope:"widget-missing-mount",id:l.id,error:new Error(`[openstation] No mount callback on window.openStationWidgets["${l.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`)}),null)},r=async l=>{if(n.has(l.id))return;await s(l);const c=i(l);if(c){try{Pa(c)}catch(d){L(b.SHELL_ERROR,{scope:"widget-register",id:l.id,error:d});return}n.add(l.id),bo(),e&&e.mountIfEnabled(l.id)}},a=l=>{n.has(l)&&(e?.unmount(l),SS(l),n.delete(l),bo())};return async l=>{const c=new Set;for(const d of l)c.add(d.id);for(const d of Array.from(n))c.has(d)||a(d);for(const d of l)n.has(d.id)||await r(d)}}const sy=["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"],iy=new Set(sy),vR=2e3,Ac=new Set,ry=new WeakSet;let ay=!1;function _R(t,e){const n=t.length,o=e.length;if(n===0)return o;if(o===0)return n;const s=new Array(o+1);for(let i=0;i<=o;i++)s[i]=i;for(let i=1;i<=n;i++){let r=s[0];s[0]=i;for(let a=1;a<=o;a++){const l=s[a];s[a]=t[i-1]===e[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=l}}return s[o]}function ER(t){let e=null,n=1/0;for(const o of iy){const s=_R(t,o);s<n&&(n=s,e=o)}return n>0&&n<=3?e:null}function kR(t){return t.startsWith("os-")?t.slice(4):t}function SR(t,e){if(Ac.has(t))return;if(Ac.add(t),iy.has(t)){const s=kR(t);console.error(`[wp.os] <${t}> is in the DOM but its module was never imported, so the tag will not upgrade and the component will render as inert HTML. |
| 291 |
|
| 292 |
Fix — side-effect-import the component module from wherever you render it: |
| 293 |
|
| 294 |
import '<rel>/ui/components/${s}/${s}'; |
| 295 |
|
| 296 |
Or pull every os-* component in one go (heavier — only do this from an entry bundle): |
| 297 |
|
| 298 |
import '<rel>/ui/components'; |
| 299 |
|
| 300 |
See docs/components-reference.md for the full list.`,` |
| 301 |
First offending element:`,e);return}const o=ER(t);if(o){console.error(`[wp.os] <${t}> is not a registered os-* component. Did you mean <${o}>? |
| 302 |
|
| 303 |
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'.`,` |
| 304 |
First offending element:`,e);return}console.error(`[wp.os] <${t}> looks like a os-* tag but no component by that name exists. |
| 305 |
|
| 306 |
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.`,` |
| 307 |
First offending element:`,e)}function ly(t){const e=t.tagName.toLowerCase();if(!e.startsWith("os-")||Ac.has(e)||customElements.get(e))return;let n=!1;customElements.whenDefined(e).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(e)||SR(e,t)},vR)}function cy(t){t instanceof Element&&(ly(t),t.shadowRoot&&Ki(t.shadowRoot));const e=t.querySelectorAll("*");for(let n=0;n<e.length;n++){const o=e[n];ly(o),o.shadowRoot&&Ki(o.shadowRoot)}}function Ki(t){if(ry.has(t))return;ry.add(t),cy(t),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(t,{childList:!0,subtree:!0})}function AR(){const t=Element.prototype,e=t.attachShadow;if(e.__wpdPatched)return;const n=function(o){const s=e.call(this,o);return s.mode==="open"&&Ki(s),s};n.__wpdPatched=!0,t.attachShadow=n}function IR(){ay||typeof document>"u"||(ay=!0,AR(),Ki(document))}const dy={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}},J={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 Q(t,e,n){return typeof t!="number"||!Number.isFinite(t)?e:Math.min(n[1],Math.max(n[0],t))}function uy(t,e){if(typeof t=="number"&&Number.isFinite(t))return Math.min(16777215,Math.max(0,Math.floor(t)));if(typeof t=="string"){const n=t.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 e}function fy(t,e){return typeof t=="boolean"?t:e}const CR=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function xR(t,e){return CR.includes(t)?t:e}function Zo(t,e=dy){const n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=n.appearance??{},s=n.physics??{},i={radius:Q(o.radius,e.appearance.radius,J.radius),bodyColor:uy(o.bodyColor,e.appearance.bodyColor),bodyAlpha:Q(o.bodyAlpha,e.appearance.bodyAlpha,J.bodyAlpha),hueStart:Q(o.hueStart,e.appearance.hueStart,J.hueStart),hueSpan:Q(o.hueSpan,e.appearance.hueSpan,J.hueSpan),hueDrift:Q(o.hueDrift,e.appearance.hueDrift,J.hueDrift),hueLoop:fy(o.hueLoop,e.appearance.hueLoop),hueAngle:Q(o.hueAngle,e.appearance.hueAngle,J.hueAngle),hueSpin:Q(o.hueSpin,e.appearance.hueSpin,J.hueSpin),saturation:Q(o.saturation,e.appearance.saturation,J.saturation),lightness:Q(o.lightness,e.appearance.lightness,J.lightness),iridescence:Q(o.iridescence,e.appearance.iridescence,J.iridescence),outlineWidth:Q(o.outlineWidth,e.appearance.outlineWidth,J.outlineWidth),glow:Q(o.glow,e.appearance.glow,J.glow),glowBlur:fy(o.glowBlur,e.appearance.glowBlur),eyeColor:uy(o.eyeColor,e.appearance.eyeColor),eyeScale:Q(o.eyeScale,e.appearance.eyeScale,J.eyeScale)},r={points:Math.round(Q(s.points,e.physics.points,J.points)),shapePreset:xR(s.shapePreset,e.physics.shapePreset),shapeLobes:Math.round(Q(s.shapeLobes,e.physics.shapeLobes,J.shapeLobes)),shapeAmount:Q(s.shapeAmount,e.physics.shapeAmount,J.shapeAmount),shapeAngle:Q(s.shapeAngle,e.physics.shapeAngle,J.shapeAngle),shapeShuffle:Q(s.shapeShuffle,e.physics.shapeShuffle,J.shapeShuffle),radialStiffness:Q(s.radialStiffness,e.physics.radialStiffness,J.radialStiffness),edgeStiffness:Q(s.edgeStiffness,e.physics.edgeStiffness,J.edgeStiffness),bendStiffness:Q(s.bendStiffness,e.physics.bendStiffness,J.bendStiffness),pressure:Q(s.pressure,e.physics.pressure,J.pressure),damping:Q(s.damping,e.physics.damping,J.damping),airDamping:Q(s.airDamping,e.physics.airDamping,J.airDamping),magnetStrength:Q(s.magnetStrength,e.physics.magnetStrength,J.magnetStrength),magnetRange:Q(s.magnetRange,e.physics.magnetRange,J.magnetRange),magnetGrip:Q(s.magnetGrip,e.physics.magnetGrip,J.magnetGrip),magnetDamping:Q(s.magnetDamping,e.physics.magnetDamping,J.magnetDamping),floatAmplitude:Q(s.floatAmplitude,e.physics.floatAmplitude,J.floatAmplitude),floatSpeed:Q(s.floatSpeed,e.physics.floatSpeed,J.floatSpeed),idleWobble:Q(s.idleWobble,e.physics.idleWobble,J.idleWobble),idleWobbleSpeed:Q(s.idleWobbleSpeed,e.physics.idleWobbleSpeed,J.idleWobbleSpeed),speedStretch:Q(s.speedStretch,e.physics.speedStretch,J.speedStretch),friction:Q(s.friction,e.physics.friction,J.friction),restitution:Q(s.restitution,e.physics.restitution,J.restitution),dragStiffness:Q(s.dragStiffness,e.physics.dragStiffness,J.dragStiffness),throwBoost:Q(s.throwBoost,e.physics.throwBoost,J.throwBoost),minStretch:Q(s.minStretch,e.physics.minStretch,J.minStretch),maxStretch:Q(s.maxStretch,e.physics.maxStretch,J.maxStretch),minAngularGap:Q(s.minAngularGap,e.physics.minAngularGap,J.minAngularGap),dragMaxAccel:Q(s.dragMaxAccel,e.physics.dragMaxAccel,J.dragMaxAccel),limitIterations:Math.round(Q(s.limitIterations,e.physics.limitIterations,J.limitIterations)),subStep:Q(s.subStep,e.physics.subStep,J.subStep),maxSubSteps:Math.round(Q(s.maxSubSteps,e.physics.maxSubSteps,J.maxSubSteps))};return{appearance:i,physics:r}}const py="desktop-mode-mio-position",hy="os-mio",LR="os-mio-toggle",TR=`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"> |
| 308 |
<defs><linearGradient id="mio" x1="19" y1="19" x2="5" y2="5" gradientUnits="userSpaceOnUse"> |
| 309 |
<stop offset="0" stop-color="#3f6dff"/><stop offset=".5" stop-color="#a855f7"/><stop offset="1" stop-color="#ff4fd8"/> |
| 310 |
</linearGradient></defs> |
| 311 |
<circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/> |
| 312 |
<rect x="8" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 313 |
<rect x="13.1" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 314 |
</svg>`)}`;class NR{constructor(e){this.layer=null,this.handle=null,this.parked=null,this.generation=0,this.loading=null,this.look=Br(),this.options=e,this.enabled=e.enabled,this.look=af(e.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:(e,n)=>this.handle?.setPosition(e,n),getConfig:()=>this.config,setConfig:e=>{this.config=Zo(e,this.config),this.handle?.applyConfig(this.config)},setStyle:e=>{const n=q_(e);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=Zo({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=Br(),this.config=this.resolveConfig(),this.handle?.applyConfig(this.config),this.commitLook()}}}async setEnabled(e){e!==this.enabled&&(this.enabled=e,this.generation++,this.options.persist(e),L(e?"os.mio.enabled":"os.mio.disabled",{}),L(b.DOCK_REFRESH_ACTIVE,{}),e?await this.mount():this.unmount())}resolveConfig(){const e=Zo(this.options.serverConfig,dy),n=K("os.mio.config",e),o=Zo(n,e);return Zo({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 e=document.getElementById(hy);if(e)return this.layer=e,e;const n=document.createElement("div");return n.id=hy,n.className="os-mio",n.setAttribute("aria-hidden","true"),this.options.shell.appendChild(n),this.layer=n,n}async mount(){const e=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(e!==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:DR(),savePosition:my});if(!s){this.layer?.remove(),this.layer=null;return}if(e!==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 e=this.handle,n=this.layer;if(this.handle=null,this.layer=null,!e||!n){n?.remove();return}const o=e.getPosition();o&&my(o),e.setAnimating(!1),n.style.display="none",this.parked={handle:e,layer:n}}loadBundle(){if(typeof window.openStationMountMio=="function")return Promise.resolve();if(!this.loading){if(!this.options.bundleUrl)return Promise.reject(new Error("No Mio bundle URL in the shell config."));this.loading=ke(this.options.bundleUrl).catch(e=>{throw this.loading=null,e})}return this.loading}}function DR(){try{const t=window.localStorage.getItem(py);if(!t)return null;const e=JSON.parse(t);return typeof e?.x!="number"||typeof e?.y!="number"||!Number.isFinite(e.x)||!Number.isFinite(e.y)?null:{x:e.x,y:e.y}}catch{return null}}function my(t){try{window.localStorage.setItem(py,JSON.stringify(t))}catch{}}const gy=8,RR=t=>`<rect x="28" y="5" width="8" height="12" rx="2" fill="currentColor" transform="rotate(${360/gy*t} 32 32)"/>`,OR='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'+Array.from({length:gy},(t,e)=>RR(e)).join("")+'<circle cx="32" cy="32" r="15.5" fill="none" stroke="currentColor" stroke-width="9"/></svg>',wy=`data:image/svg+xml;base64,${btoa(OR)}`,yy="openstation-rebrand",MR=1200,PR="a[href], button:not([disabled])";async function WR(t){const e=t.seenIntrosUrl;if(e)try{await Fe(`${e.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce??""},body:JSON.stringify({slug:yy})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function $R(){const t=document.createElement("div");t.className="os-announce",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby","os-announce-title"),t.setAttribute("aria-describedby","os-announce-desc");const e=document.createElement("div");e.className="os-announce__card",t.appendChild(e);const n=document.createElement("div");n.className="os-announce__hero",e.appendChild(n);const o=document.createElement("span");o.className="os-announce__eyebrow";const s=document.createElement("span");s.className="os-announce__eyebrow-dot",s.setAttribute("aria-hidden","true"),o.appendChild(s),o.appendChild(document.createTextNode(k("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=k("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=k("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",e.appendChild(a);const l=document.createElement("p");l.id="os-announce-desc",l.textContent=k("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),a.appendChild(l);const c=document.createElement("p");c.textContent=k("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=k("Everything is already set up. You don't need to install any new plugins, so you can keep using the same features as before."),a.appendChild(d);const u=document.createElement("div");u.className="os-announce__actions",e.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),t}async function UR(t){const{config:e}=t;if(!e.rebrandNotice||e.seenIntros?.includes(yy))return;await new Promise(c=>window.setTimeout(c,MR));const n=$R(),o=n.querySelector(".os-announce__card"),i=document.activeElement;let r=!1;const a=()=>{r||(r=!0,document.removeEventListener("keydown",l,!0),n.remove(),i?.focus?.(),WR(e))};function l(c){if(!n.isConnected){document.removeEventListener("keydown",l,!0);return}if(c.key==="Escape"){c.preventDefault(),a();return}if(c.key!=="Tab")return;const d=Array.from(n.querySelectorAll(PR));if(d.length===0)return;const u=d[0],f=d[d.length-1],p=n.ownerDocument.activeElement;c.shiftKey&&(p===u||!n.contains(p))?(c.preventDefault(),f.focus()):!c.shiftKey&&(p===f||!n.contains(p))&&(c.preventDefault(),u.focus())}n.addEventListener("click",c=>{o&&!o.contains(c.target)&&a()});for(const c of n.querySelectorAll("[data-rebrand-dismiss]"))c.addEventListener("click",a);document.addEventListener("keydown",l,!0),document.body.appendChild(n),n.querySelector(".os-announce__btn--primary")?.focus()}const FR=new Set(["post"]);function by(){const t=window.wp?.os?.myWordpress;return t&&typeof t.trashEntity=="function"?t:null}const Ic="data-os-trash-drop-active",qt="desktop-mode-recycle-bin",BR=[`.os-file-tile[data-file-ref="${qt}"]`,`[data-icon-id="${qt}"]`,`[data-system-id="${qt}"]`];function HR(){for(const t of BR){const e=document.querySelector(t);if(e instanceof HTMLElement)return e}return null}let vy=!1,Jo=null,Qo=null,_y=null;function zR(t){return t.payload.type==="desktop-file"}function GR(t){return t.payload.type==="shortcut"}function jR(t){if(!t.kind||!t.ref||!t.entityId||!FR.has(t.kind))return!1;const e=Number.parseInt(t.ref,10);return!Number.isFinite(e)||e<=0?!1:by()!==null}function Ey(t,e,n){return t.registerDropTarget({id:e,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=Ln(s);return r.length>1?r.every(a=>a.file?.ref!==qt&&a.canTrash!==!1):i.file?.ref===qt?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=Di(s);return i.length>0&&i.every(r=>jR(r))}return QD(o)},onEnter:()=>{n.setAttribute(Ic,"")},onLeave:()=>{n.removeAttribute(Ic)},onDrop:(o,s)=>{if(n.removeAttribute(Ic),zR(o)){Gg(Ln(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&eR(o,s))&&GR(o)){const i=by();if(!i?.trashEntity)return;const r=i.trashEntity,l=Di(o.payload.data).map(c=>({entityId:c.entityId,ref:Number.parseInt(c.ref,10)})).filter(c=>!!c.entityId&&Number.isFinite(c.ref)&&c.ref>0);if(l.length===0)return;Promise.allSettled(l.map(c=>r(c.entityId,c.ref))).then(c=>{const d=c.filter(f=>f.status==="rejected");for(const f of d)console.error("[openstation] recycle-bin: shortcut trash failed:",f.reason);const u=l.length-d.length;(u>1||d.length>0)&&Z({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 VR(t){if(vy)return;vy=!0;const e=()=>{const n=HR();if(!n){Jo?.(),Jo=null;return}Jo&&qR(t)===n||(Jo?.(),Jo=Ey(t,"recycle-bin-dock",n))};if(e(),document.addEventListener("os-files-changed",e),X(b.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",e),X(b.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",e),typeof MutationObserver<"u"){_y=new MutationObserver(()=>{e()});const n=document.getElementById("os-area")??document.body;_y.observe(n,{childList:!0,subtree:!0})}X(b.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==qt)return;Qo?.(),Qo=null;const o=document.querySelector("[data-os-recycle-bin-root]");o instanceof HTMLElement&&(Qo=Ey(t,"recycle-bin-window",o))}),X(b.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===qt&&(Qo?.(),Qo=null)})}function qR(t){const e=t.debug().listTargets().find(n=>n.id==="recycle-bin-dock");return e?e.element:null}function Cc(t){const e=t.placement.file;return!e||e.type!=="user"||e.isAgent!==!0?null:e}function KR(){const t=window.openStationConfig;return t?.restUrl&&t?.restNonce?{restRoot:t.restUrl,restNonce:t.restNonce}:null}function ky(t){return{appliesTo(e){return Cc(e)!==null},accept(e,n){const o=Cc(n);if(!o)return!1;const s=yg({type:t,data:e});return kL(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:k("Send to agent","desktop-mode"),onDrop(e,n,o){const s=Cc(o);if(!s)return;const i=yg({type:e.payload.type,data:e.payload.data}),r=KR();!i||!r||CL({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let Sy=!1;function YR(){Sy||(Sy=!0,xi("shortcut",ky("shortcut")),xi("desktop-file",ky("desktop-file")))}let Ay=!1,Kt=0;function XR(){Ay||(Ay=!0,Ae.contribute("openstation_files_subscribe",()=>{const t=At(),e={};for(const[n,o]of t.folders)e[String(n)]=o.updatedAtMs;return{folderVersions:e,placementsVersion:Kt,sharesVersion:Ze().state.sharesVersion}}),Ae.subscribe("openstation_files",t=>{ZR(t)}))}function ZR(t){const e=t.folders??[];for(const i of e)Dl(i,"remote"),i.updatedAtMs>Kt&&(Kt=i.updatedAtMs);const n=t.placements??[];for(const i of n)Ci(i,"remote"),i.updatedAtMs>Kt&&(Kt=i.updatedAtMs);const o=t.removed??{};for(const i of o.folders??[])Rl(i,"remote");for(const i of o.placements??[])Oo(i,"remote");typeof t.serverTimeMs=="number"&&t.serverTimeMs>Kt&&(Kt=t.serverTimeMs);const s=t.shares?.pending;if(Array.isArray(s)&&s.length>0&&hw(s),t.truncated){const i=Array.from(At().hydratedFolders);for(const r of i)Le(r).then(a=>{mt(r,a.placements)}).catch(()=>{})}}let Iy=!1;const JR=[];function QR(){if(Iy)return;Iy=!0;const t=e=>{const n=e;!n||n.action!=="untrashed"||eO()};JR.push(fn("os.placement.changed",t),fn("os.shortcut.changed",t),fn("os.folder.changed",t))}function eO(){xl().then(e=>{Nl(e.folders)}).catch(e=>{console.error("[openstation] files restore-sync: listFolders failed",e)});const t=Array.from(At().hydratedFolders);for(const e of t)Le(e).then(n=>{mt(e,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",e,n)})}const es="os-wallpaper-menu";let Wn=null;function Cy(){return Wn!==null}let xy=0;function tO(t,e,n,o={}){ts();const s=++xy;Is(()=>s===xy,()=>nO(t,e,n,o))}function nO(t,e,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,m=typeof f.sort=="number"?f.sort:100;return p!==m?p-m:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(es),s.style.left=`${e.x}px`,s.style.top=`${e.y}px`;const i=new Map;let r=null,a=null;const l=()=>{r&&(r.remove(),r=null,a=null)};for(const u of n){i.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.heading&&f.setAttribute("heading",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",Ly(u.icon));const p=Array.isArray(u.children)&&u.children.length>0;p&&f.setAttribute("has-children",""),f.textContent=u.label,f.addEventListener("mouseenter",()=>{if(p){c(u,f);return}l()}),s.appendChild(f)}s.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=i.get(f.id)??null;if(p){if(Array.isArray(p.children)&&p.children.length>0){if(u.stopPropagation(),a&&a.id===p.id){l();return}const m=s.querySelector(`[data-menu-item-id="${p.id}"]`);m&&c(p,m);return}ts(),p.onClick(new MouseEvent("click"))}});function c(u,f){l();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(es,`${es}--flyout`),p.dataset.parentId=u.id;const m=(u.children??[]).slice().sort((g,h)=>{const w=typeof g.sort=="number"?g.sort:100,v=typeof h.sort=="number"?h.sort:100;return w!==v?w-v:g.label.localeCompare(h.label)});for(const g of m){const h=document.createElement("os-context-menu-option");h.dataset.menuItemId=g.id,h.setAttribute("value",g.id),g.icon&&h.setAttribute("icon",Ly(g.icon)),g.disabled&&h.setAttribute("disabled",""),g.checked&&h.setAttribute("checked",""),h.textContent=g.label,h.addEventListener("os-context-menu-pick",w=>{w.stopPropagation(),ts(),g.onClick(new MouseEvent("click"))}),p.appendChild(h)}document.body.appendChild(p),r=p,a=u,Hm(p,f)}t.appendChild(s),Wn=s,nl(s);const d=Fm(s,{close:()=>ts(),siblingSelectors:[`.${es}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),L("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function ts(){Wn&&(document.querySelectorAll(`.${es}--flyout`).forEach(t=>t.remove()),Wn.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),Wn.remove(),Wn=null,L("os.wallpaper-menu.closed",{}))}function oO(t){const e=[{id:"create-folder",label:t.labels.createFolder,icon:"dashicons-portfolio",sort:10,onClick:()=>t.createFolder()},{id:"new-url",label:t.labels.newUrl,icon:"dashicons-admin-links",sort:12,onClick:()=>t.createUrl()},{id:"sort-by",label:t.labels.sortHeading,icon:"dashicons-sort",sort:16,onClick:()=>{},children:[{id:"sort-name-asc",label:t.labels.sortNameAsc,sort:10,checked:t.currentSortMode==="name-asc",onClick:()=>t.sortIcons("name-asc")},{id:"sort-name-desc",label:t.labels.sortNameDesc,sort:20,checked:t.currentSortMode==="name-desc",onClick:()=>t.sortIcons("name-desc")},{id:"sort-date-desc",label:t.labels.sortDateDesc,sort:30,checked:t.currentSortMode==="date-desc",onClick:()=>t.sortIcons("date-desc")},{id:"sort-date-asc",label:t.labels.sortDateAsc,sort:40,checked:t.currentSortMode==="date-asc",onClick:()=>t.sortIcons("date-asc")}]},...t.includeShowDesktop===!1?[]:[{id:"show-desktop",label:t.labels.showDesktop,icon:"dashicons-desktop",sort:20,onClick:()=>t.toggleShowDesktop()}],{id:"os-settings",label:t.labels.osSettings,icon:"dashicons-admin-generic",sort:30,onClick:()=>t.openOsSettings()}],n=(t.serverItems??[]).map(i=>sO(i,t)),o=[...e,...n],s=K("os.wallpaper-context-menu",o);return Array.isArray(s)?s:o}function sO(t,e){return{id:t.id,label:t.label,icon:t.icon,sort:t.sort,disabled:t.disabled,onClick:()=>{if(t.callbackId){const n=e.serverCallbacks?.[t.callbackId];if(typeof n=="function")return n()}L("os.wallpaper-context-menu.activated",{id:t.id,callbackId:t.callbackId??""})}}}function Ly(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}const ns="os-url-dialog";let os=null;function xc(){os&&(os.dispatchEvent(new CustomEvent("url-dialog-closed")),os.remove(),os=null,L("os.files.url-dialog.closed",{}))}function iO(t){if(xc(),K("os.files.url-dialog",null,t)===!1)return;const n=document.createElement("div");n.className=`${ns}__overlay os-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${ns} os-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${ns}-title`);const s=document.createElement("h2");if(s.id=`${ns}-title`,s.className="os-create-folder-dialog__title",s.textContent=t.title,o.appendChild(s),t.description){const h=document.createElement("p");h.className=`${ns}__description`,h.textContent=t.description,o.appendChild(h)}const i=document.createElement("os-text-field");i.className="os-create-folder-dialog__field",i.setAttribute("label",t.nameLabel??"Name"),i.setAttribute("value",t.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",t.urlLabel??"URL"),r.setAttribute("value",t.initialUrl??"https://"),r.setAttribute("placeholder","https://example.com"),r.setAttribute("type","url"),r.setAttribute("autocomplete","off"),o.appendChild(r);const a=document.createElement("p");a.className="os-create-folder-dialog__error",a.hidden=!0,a.setAttribute("role","alert"),o.appendChild(a);const l=document.createElement("div");l.className="os-create-folder-dialog__actions";const c=document.createElement("os-button");c.className="os-create-folder-dialog__btn os-create-folder-dialog__btn--secondary",c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className="os-create-folder-dialog__btn os-create-folder-dialog__btn--primary",d.setAttribute("variant","primary"),d.textContent=t.submitLabel??"Create",l.appendChild(c),l.appendChild(d),o.appendChild(l),n.appendChild(o),document.body.appendChild(n),os=n,Li(i),L("os.files.url-dialog.opened",{});const u=h=>{zt(i,h),zt(r,h),zt(c,h),zt(d,h),o.classList.toggle("os-create-folder-dialog--busy",h)},f=h=>{a.textContent=h,a.hidden=!1},p=()=>{xc(),t.onCancel?.()},m=async()=>{const h=$l(r).trim();if(!h){f("Please enter a URL.");return}const w=/^[a-z][a-z0-9+\-.]*:/i.test(h)?h:`https://${h}`;try{new URL(w)}catch{f("That doesn't look like a valid URL.");return}const v=$l(i).trim();a.hidden=!0,u(!0);try{await t.onSubmit({name:v,url:w}),xc()}catch(R){u(!1),f(R instanceof Error?R.message:"Could not save.")}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void m()),n.addEventListener("click",h=>{h.target===n&&p()});const g=h=>{h.key==="Escape"?(h.preventDefault(),p()):h.key==="Enter"&&!h.isComposing&&(h.preventDefault(),m())};o.addEventListener("keydown",g),n.addEventListener("url-dialog-closed",()=>{o.removeEventListener("keydown",g)})}const Ty=[];let Lc=!1;(function(){const e=window;if(e.wp||(e.wp={}),e.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(Lc){Promise.resolve().then(o);return}Ty.push(o)}},ready(o){n.whenReady(o)},isReady(){return Lc}};e.wp.os=n})();const ss="desktop-mode-os-settings";let Tc=[],Yi=Number.POSITIVE_INFINITY,Nc=!1;function Ke(t,e=1500){if(Tc.push(t),e<Yi&&(Yi=e),Nc)return;Nc=!0;const n=()=>{const o=Tc;Tc=[],Yi=Number.POSITIVE_INFINITY,Nc=!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:Yi}):window.setTimeout(n,0)}function Ny(){const t=window.openStationConfig;if(!t)return;const e=document.getElementById("os-area");if(!e)return;const n=new Wb(e),o=document.getElementById("os-wallpaper"),s=t.pluginUrl||"";let i=null;o&&(i=new zf(o,s));const r=document.getElementById("os-widgets");let a=null;hR(),xE(),r&&(a=new JS(r,s)),Ff({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const l=new JE({mediaUrl:t.mediaUrl,restNonce:t.restNonce,canUpload:!!t.canUpload,isAdmin:!!t.currentUserIsAdmin,extendedOptions:t.extendedOptions??null,extendedOptionsUrl:t.extendedOptionsUrl??"",osSettingsPanelBundleUrl:t.osSettingsPanelBundleUrl??"",canManageDesktopThemes:!!t.canManageDesktopThemes,desktopThemesUrl:t.desktopThemesUrl??""},i??new zf(document.createElement("div"),s));l.apply();const c=document.getElementById("os-shell"),d=new NR({shell:c??document.body,bundleUrl:t.mioBundleUrl??"",serverConfig:t.mio,enabled:l.state.mioEnabled,persist:S=>{l.state.mioEnabled=S,l.save()},savedLook:l.state.mioStyle,persistLook:S=>{l.state.mioStyle=S,l.save()}}),u=d.api();d.boot(),a&&yR({osSettings:l,layer:a});const f=new TA({aiSearchUrl:t.aiSearchUrl??"",aiSearchStreamUrl:t.aiSearchStreamUrl??"",restNonce:t.restNonce,adminUrl:t.adminUrl,getTransport:()=>"sse",isAiAvailable:()=>t.aiAssistant?.available===!0&&t.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>l.getOsSettingsSnapshot().ai.enabled!==!1},t.aiAssistantBundleUrl??"");f.attachAsk(MA({config:()=>t,fallbackContext:()=>({close:()=>f.close(),openInWindow:(S,H,V)=>{n.open({url:S,title:H,icon:V??"dashicons-admin-generic"})},confirm:S=>ki({message:S})})}));const p=new II,m=new HI;document.addEventListener(he.START,S=>{const V=S.detail?.payload;if(!V||V.type!=="shortcut"&&V.type!=="desktop-file")return;const ne=V.data?.bridgePayload;ne&&p.start(ne)}),document.addEventListener(he.END,()=>{p.end()}),Ke(()=>eC(m)),Ke(()=>hC(n)),window.addEventListener("message",S=>{if(S.origin!==window.location.origin)return;const H=S.data;!H||H.type!=="os-drop-failed"||Z({message:"Could not insert into the editor."})}),Lm({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>f.open(),close:()=>f.close(),isOpen:()=>f.isOpen}),vC(),Ub(n),Gb(n),Ke(()=>{new mS({manager:n,adminUrl:t.adminUrl}).install(),new kS({manager:n,adminUrl:t.adminUrl}).install()}),document.addEventListener("os-open-ai",()=>{Za("desktop-mode-ai-assistant")}),document.addEventListener("click",S=>{const H=S.target;!(H instanceof Element)||!H.closest("#wp-admin-bar-command-palette")||(S.preventDefault(),S.stopImmediatePropagation(),Za("desktop-mode-ai-assistant"))},!0);const g=document.getElementById("os-dock"),h=document.getElementById("os-shell"),w=h?.querySelector(".os-shell__body");let v=null;const R=cA({manager:n,appendSystemTile:S=>v?.appendSystemTile(S),removeSystemTile:S=>v?.removeSystemTile(S)}),_=R.sync;v_({getSnapshot:()=>l.getOsSettingsSnapshot(),openById:(S,H)=>R.openById(S,H),adminUrl:t.adminUrl});const E=S=>{const H=le(S,t.adminUrl),V=v?v.getMenuItems():t.dockItems??[];for(const ne of V){if(le(ne.url,t.adminUrl)===H)return{title:ne.title,icon:ne.icon,url:ne.url,submenu:ne.submenu,multi:ne.multi};for(const ye of ne.submenu??[])if(le(ye.url,t.adminUrl)===H)return{title:ye.title,icon:ne.icon,url:ne.url,multi:ne.multi}}return null};if(B_({adminUrl:t.adminUrl,deriveSlug:S=>le(S,t.adminUrl),openWindow:S=>{n.open(S)},findDockEntry:E}),sn({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(S,H)=>{if(!H.pathname.endsWith("/edit.php"))return!1;const V=H.searchParams.get("post_type");return!V||V==="post"},enabled:S=>S.nativePostsEnabled===!0}),sn({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(S,H)=>H.pathname.endsWith("/edit.php")?H.searchParams.get("post_type")==="page":!1,enabled:S=>S.nativePagesEnabled===!0}),sn({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(S,H)=>H.pathname.endsWith("/users.php"),enabled:S=>S.nativeUsersEnabled===!0}),sn({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(S,H)=>{if(b_(H))return!1;const V=H.pathname;return V.endsWith("/profile.php")?!0:V.endsWith("/user-edit.php")?H.searchParams.has("user_id"):!1},enabled:S=>S.nativeUsersEnabled===!0,onMatch:(S,H)=>{const V=parseInt(H.searchParams.get("user_id")??"0",10);V>0&&sk(V)}}),sn({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(S,H)=>H.pathname.endsWith("/edit-comments.php"),enabled:S=>S.nativeCommentsEnabled===!0,onMatch:(S,H)=>{const V=parseInt(H.searchParams.get("p")??"0",10);V>0?Uf(V):rk()}}),sn({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(S,H)=>{const V=H.pathname;return V.endsWith("/plugins.php")||V.endsWith("/plugin-install.php")},enabled:S=>S.nativePluginsEnabled===!0,onMatch:(S,H)=>{const V=H.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>OO).then(ne=>{ne.setPluginsWindowTab(V)})}}),g&&h&&w&&t.dockItems){e.classList.add("os-area--with-dock");const S=l.getOsSettingsSnapshot().desktopLayout,H=V=>{Mh(e,V,{openWindow:R.openById,manager:n,deriveWindowId:ne=>le(ne,t.adminUrl)})};v=xA({shellRoot:h,shellBody:w,bottomDockEl:g,desktopArea:e,windowManager:n,adminUrl:t.adminUrl,renderIcons:H,getSettings:()=>{const V=l.getOsSettingsSnapshot();return{itemVisibility:V.itemVisibility,dockOrder:V.dockOrder}}},S,t.dockItems,t.desktopIcons),v.appendSystemTile({id:ss,title:"OpenStation Preferences",icon:wy,isOpen:()=>{const V=n.getById(ss);return V?(V.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:N},"core"),Jh()||v.appendSystemTile(wI(t.pwa?.appName||"WordPress",Z),"core"),window.matchMedia("(display-mode: standalone)").addEventListener("change",V=>{V.matches&&v?.removeSystemTile("os-pwa-install")}),Qh().then(V=>{V&&v?.removeSystemTile("os-pwa-install")})}function N(S={}){S.tabId==="extended"&&(S={...S,tabId:"features"}),S.tabId&&(l.activeTabId=S.tabId),n.open({id:ss,baseId:ss,url:"#os-settings",title:"OpenStation Preferences",icon:wy,native:!0,render:H=>l.renderPanel(H),width:820,height:720,minWidth:560,minHeight:480}),S.tabId&&l.focusTab(S.tabId)}function D(){n.open({id:gn,baseId:gn,url:`#${gn}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:S=>eI(S),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("os-open-bug-report",()=>{D()}),v&&(v.appendSystemTile({id:gn,title:"Report a bug",icon:"dashicons-buddicons-replies",isOpen:()=>{const S=n.getById(gn);return S?(S.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:D},"core"),v.appendSystemTile(ek(),"core"),v.appendSystemTile({id:LR,title:"Mio",icon:TR,placeable:!0,isOpen:()=>u.isEnabled(),onOpen:()=>{u.toggle()}},"plugin"));const O=v?.getPrimary()??null;_(Array.isArray(t.nativeWindows)?t.nativeWindows:[]);const y=yx(t.session);function M(S){return S===ss?(N(),!0):S===gn?(D(),!0):R.openById(S)}const T=y?vx(n,t,e,M).catch(S=>{typeof console<"u"&&console.error("[openstation] session restore failed:",S)}):Promise.resolve(),x=t.defaultWindow?.enabled!==!1,I=t.defaultWindow?.url??"",W=typeof I=="string"&&I.startsWith("native:");Ex({fromPortal:t.fromPortal,fromPortalIntent:t.fromPortalIntent,hasSession:y,defaultEnabled:x,isNativeDefault:W})&&T.then(()=>_x(n,t).catch(S=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",S)}));const z=Ax(n,t);Cx(z);const A=async S=>{try{const H=await hl(n,t.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({url:S})},{source:"desktop-mode/default-window"});if(!H.ok)throw new Error(`HTTP ${H.status}`);const V=await H.json();t.defaultWindow=V,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:V}))}catch(H){L(b.SHELL_ERROR,{scope:"default-window-save",error:H}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",H)}};if(n.onToggleStartupRequested=S=>{const H=t.defaultWindow,V=!!S.config.native,ne=V?`native:${S.id}`:S.getCurrentUrl(),ye=V?H?.url===ne:qc(H?.url??"")===qc(ne),Un=!!H?.enabled&&ye;A(Un?null:ne)},t.defaultWindow?.enabled&&t.fromPortal&&!t.fromPortalIntent&&!y&&W){const S=I.slice(7);queueMicrotask(()=>{M(S)})}const P=S=>{v?.appendSystemTile(S)},B=bR({layer:a});B(Array.isArray(t.serverWidgets)?t.serverWidgets:[]);const C=dk({osSettings:l});C(Array.isArray(t.serverWallpapers)?t.serverWallpapers:[]),X(b.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",S=>{const H=S?.wallpapers;Array.isArray(H)&&C(H)});const $=hk();$(Array.isArray(t.serverGames)?t.serverGames:[]);const U=mk();U(Array.isArray(t.serverDesktopThemes)?t.serverDesktopThemes:[]);const G=Kk();G(Array.isArray(t.serverCommandScripts)?t.serverCommandScripts:[],Array.isArray(t.serverCommands)?t.serverCommands:[]);const F=Zk();F(Array.isArray(t.serverSettingsTabScripts)?t.serverSettingsTabScripts:[],Array.isArray(t.serverSettingsTabs)?t.serverSettingsTabs:[]);const Y=n0();Y(Array.isArray(t.serverTitleBarButtonScripts)?t.serverTitleBarButtonScripts:[]);const j=O0();j(Array.isArray(t.serverUnfocusEffectScripts)?t.serverUnfocusEffectScripts:[]);const se=M0();se(Array.isArray(t.serverWindowLinkRendererScripts)?t.serverWindowLinkRendererScripts:[]),W0({manager:n,osSettings:l}),Sv({osSettings:l}),U_({manager:n}),h0({manager:n,osSettings:l}),y0({manager:n,openUrl:S=>{if(ct(S.url))return;const H=le(S.url,t.adminUrl);n.open({id:H,baseId:H,url:S.url,title:S.label,icon:S.icon||"dashicons-admin-links"})}}),T0({manager:n});const ge=$0();ge(Array.isArray(t.serverDockRailRendererScripts)?t.serverDockRailRendererScripts:[]),B0()(Array.isArray(t.serverWindowThemeScripts)?t.serverWindowThemeScripts:[],Array.isArray(t.serverWindowThemes)?t.serverWindowThemes:[]),G0(),j0()(Array.isArray(t.serverWindowControlScripts)?t.serverWindowControlScripts:[],Array.isArray(t.serverWindowControls)?t.serverWindowControls:[]),K0()(Array.isArray(t.serverWindowSlotScripts)?t.serverWindowSlotScripts:[],Array.isArray(t.serverWindowSlots)?t.serverWindowSlots:[]),ah(Array.isArray(t.serverWindowNotices)?t.serverWindowNotices:[]),rS()(Array.isArray(t.serverWindowChromeScripts)?t.serverWindowChromeScripts:[],Array.isArray(t.serverWindowChromes)?t.serverWindowChromes:[]);const $e=dS(n);b0(n),Ke(()=>v0()),g_(),X("os.shell.toast","desktop-mode/shell-toast",S=>{!S||typeof S.message!="string"||Z({message:S.message,action:S.action,duration:S.duration})});const Ie=t,Bc=Ie.recycleBinCount;UA(Number(Bc)||0,typeof Ie.recycleBinCountUrl=="string"?Ie.recycleBinCountUrl:""),KA({getRecycleBinCount:$A}),window.__openStationConnectionBridge=$e,X(b.WINDOW_CLOSED,"desktop-mode/connection-cleanup",S=>{S?.windowId&&$e.onWindowClosed(S.windowId)}),X(b.IFRAME_READY,"desktop-mode/connection-rearm",S=>{S?.windowId&&$e.onIframeReady(S.windowId)});const qO=rA(n),KO=wx({layoutDispatcher:v,desktopArea:e,config:t,syncNativeWindows:_,syncServerWidgets:B,syncServerWallpapers:C,syncServerCommands:G,syncServerSettingsTabs:F,syncServerTitleBarButtons:Y,syncServerUnfocusEffects:j,syncServerWindowLinkRenderers:se,syncServerDockRailRenderers:ge,syncServerGames:$,syncServerDesktopThemes:U,renderIcons:S=>{if(v){v.applyDesktopIcons(S);return}Mh(e,S,{openWindow:R.openById,manager:n,deriveWindowId:H=>le(H,t.adminUrl)})},syncShortcuts:()=>{const S=l.getOsSettingsSnapshot();zi(S.itemVisibility,S.dockPromotedPositions,S.desktopLayout)}});document.addEventListener(vf,()=>{v&&v.setLayout(v.getLayout());for(const S of n._stack)try{S.repaintWindowControls(),S.repaintThemedChrome()}catch(H){L(b.SHELL_ERROR,{scope:"desktop-theme-repaint",id:S.id,error:H})}}),l.subscribeOsSettings(S=>{if(!v)return;const H=v.getLayout();v.setLayout(S.desktopLayout),tr.dock=v.getPrimary(),tr.sideDock=v.getSide(),tr.desktopLayout=S.desktopLayout,H===S.desktopLayout&&v.refresh(),zi(S.itemVisibility,S.dockPromotedPositions,S.desktopLayout),ag(S.desktopLayout)}),LN(()=>l.getOsSettingsSnapshot().itemVisibility,()=>l.getOsSettingsSnapshot().dockPromotedPositions,()=>l.getOsSettingsSnapshot().desktopLayout),ag(l.getOsSettingsSnapshot().desktopLayout);const tr=dL({manager:n,dock:O,layoutDispatcher:v,osSettings:l,iconsApi:wA,filesApi:ze,saveSession:z,widgetLayer:a,registerWindow:qO,openWindowById:R.openById,openNewWindowById:R.openNewById,placeSystemTile:P,setDefaultWindow:A,refreshMenu:KO,openOsSettings:N,aiAssistant:f,dragBridge:p,dragManager:m,connect:$e.connect,getConnection:$e.getConnection,mio:u,wallpaperSuspend:{suspend:S=>i?.suspend(S),resume:S=>i?.resume(S),isSuspended:()=>i?.isSuspended()??!1},config:t});uL(tr),Ke(()=>VR(m)),Ke(()=>YR()),gk(),t.gamesEnabled!==!1&&Gk({currentUserId:Number(t.currentUserId)||0}),Ke(()=>VC()),Ke(()=>KC()),Ke(()=>ax({currentUserId:Number(t.currentUserId)||0})),uD({host:e,config:t,available:t.stickyNotes?.available,getActiveDesktopId:()=>n.getActiveDesktopId(),openArtifact:(S,H)=>{const V=le(S,t.adminUrl);n.open({id:V,baseId:V,url:S,title:H,icon:"dashicons-edit-page"})},onError:S=>{Z({message:S})}}),fR({host:e,config:t,onError:S=>{Z({message:S})}}),bL({openUrl:({id:S,url:H,title:V,icon:ne})=>(ct(H)||n.open({id:S,baseId:S,url:H,title:V,icon:ne}),!0),openNativeWindow:S=>R.openById(S),deriveWindowId:S=>le(S,t.adminUrl)}),ug(t.userFileAssociations??{}),gR({update:t.coreUpdate,openUrl:({url:S,title:H})=>{ct(S)||n.open({id:"update-core",baseId:"update-core",url:S,title:H,icon:"dashicons-update"})}});const zy=({url:S,title:H})=>{if(ct(S))return;const V=le(S,t.adminUrl);n.open({id:V,baseId:V,url:S,title:H,icon:"dashicons-info"})};if(ny({notices:t.coreNotices,openUrl:zy}),ny({notices:t.pluginNotices,openUrl:zy,keyPrefix:"plugin-notice"}),UR({config:t}),typeof t.filesUrl=="string"&&t.filesUrl){vg({baseUrl:t.filesUrl,nonce:t.restNonce});const S=document.getElementById("os-area");if(S){const H=Zg(S,0),V=()=>{e.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{e.classList.remove("os-area--booting")})},ne=setTimeout(V,2e3);H.hydrated.then(()=>{clearTimeout(ne),V()})}}Ke(()=>XR()),Ke(()=>QR()),Ke(()=>kC()),L(b.COMPONENTS_REGISTERED,{tags:[...sy]}),gC(),_I(t,Z);const Gy=()=>{ab(t.shellOverlaysBundleUrl??""),sb(t.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(Gy,{timeout:1500}):window.setTimeout(Gy,0),L(b.INIT,{config:t}),Lc=!0;const YO=Ty.splice(0);for(const S of YO)try{S()}catch(H){L(b.SHELL_ERROR,{scope:"when-ready-cb",error:H}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",H)}l.apply(),a?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),a?.disposeAll()}),xx(),lx(n,t);const jy=(S,H=!0)=>{const V=ze.store.getState().placementsByFolder.get(0)??[],ne=S(V),ye=Math.max(1,Math.floor((e.clientHeight-16)/110)),Un=new Set;let Xt=0;for(const Ne of ne){const De=Ct(16+Math.floor(Xt/ye)*96,16+Xt%ye*110,Un,e);Un.add(`${De.col},${De.row}`),Xt++,!(Ne.x===De.x&&Ne.y===De.y)&&(ze.store.upsertPlacement({...Ne,x:De.x,y:De.y,sortOrder:Xt}),!(!H||Ri(Ne))&&An(Ne.id,{x:De.x,y:De.y,sortOrder:Xt}).catch(yt=>{console.error("[openstation] relayout persist failed",yt)}))}},Vy=S=>H=>{const V=H.slice();switch(S){case"name-asc":V.sort((ne,ye)=>ne.file.title.localeCompare(ye.file.title));break;case"name-desc":V.sort((ne,ye)=>ye.file.title.localeCompare(ne.file.title));break;case"date-asc":V.sort((ne,ye)=>ne.updatedAtMs-ye.updatedAtMs);break;case"date-desc":V.sort((ne,ye)=>ye.updatedAtMs-ne.updatedAtMs);break}return V},Hc="desktop-mode:root-sort-mode",XO=S=>S==="name-asc"||S==="name-desc"||S==="date-asc"||S==="date-desc";let nr=(()=>{try{const S=window.localStorage.getItem(Hc);return XO(S)?S:null}catch{return null}})();const qy=S=>{nr=S;try{S?window.localStorage.setItem(Hc,S):window.localStorage.removeItem(Hc)}catch{}};if(X("os.files.tile-manually-placed","desktop-mode/root-sort-clear",S=>{S?.folderId===0&&qy(null)}),typeof ResizeObserver<"u"){let S=e.clientWidth,H=e.clientHeight;new ResizeObserver(()=>{if(!nr)return;const ne=e.clientWidth,ye=e.clientHeight;ne===S&&ye===H||(S=ne,H=ye,jy(Vy(nr),!1))}).observe(e)}let Ky=!1;e.addEventListener("pointerdown",S=>{S.isPrimary&&(Ky=S.target===e)}),e.addEventListener("click",S=>{l.state.showDesktopOnWallpaperClick&&S.target===e&&Ky&&(e.classList.contains("os-area--overview")||Cy()||m.recentlyEndedDrag()||$C()||n.toggleShowDesktop())}),e.addEventListener("contextmenu",S=>{if(S.target!==e)return;S.preventDefault();const H=S.clientX,V=S.clientY;(()=>{if(e.classList.contains("os-area--overview"))return;if(Cy()){ts();return}const ne={x:H,y:V},ye=()=>{const Ne=e.getBoundingClientRect(),De=Math.max(0,ne.x-Ne.left),yt=Math.max(0,ne.y-Ne.top),ks=qg(ze.store.getState().placementsByFolder.get(0)??[]);return Ct(De,yt,ks,e)},Un=(Ne,De)=>{iO({title:Ne,description:De,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:yt,url:ks})=>{const Yy=ye(),ZO=await Sn({type:"link",ref:ks,parentId:0,x:Yy.x,y:Yy.y,meta:yt?{name:yt}:void 0});ze.store.upsertPlacement(ZO)}})},Xt=oO({createFolder:()=>{Fl({onSubmit:async Ne=>{const De=await Ll({name:Ne}),yt=ye(),ks=await Sn({type:"folder",ref:String(De.id),parentId:0,x:yt.x,y:yt.y});ze.store.upsertFolder(De),ze.store.upsertPlacement(ks)}})},createUrl:()=>Un("New URL","Opens the URL in a new browser tab."),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>N(),sortIcons:Ne=>{qy(Ne),jy(Vy(Ne))},currentSortMode:nr,includeShowDesktop:!l.state.showDesktopOnWallpaperClick,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:t.serverWallpaperMenuItems??[]});tO(document.body,{x:H,y:V},Xt)})()}),Promise.resolve().then(()=>VO).then(S=>{S.bootOsFileDrop({config:t.dropConfig,mediaUrl:t.mediaUrl,restNonce:t.restNonce,filesUrl:t.filesUrl,storage:t.desktopStorage})}),document.dispatchEvent(new CustomEvent("os-init",{detail:{config:t,restored:y}}))}IR(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ny):Ny();const ce={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"},rO=32;function aO(t){if(!t)return[];const e=[];for(let n=0;n<t.length;n++){const o=t[n];if(o.kind!=="file")continue;const s=typeof o.webkitGetAsEntry=="function"?o.webkitGetAsEntry():null;s&&e.push(s)}return e}function lO(t){const e=t.createReader();return new Promise((n,o)=>{const s=[],i=()=>{e.readEntries(r=>{if(r.length===0){n(s);return}s.push(...r),i()},o)};i()})}function cO(t){return new Promise((e,n)=>{t.file(e,n)})}async function dO(t){const e={files:[],emptyDirs:[],hadDirectory:!1};for(const n of t)await Dy(n,"",e,0);return e}async function Dy(t,e,n,o){if(o>rO)return;if(t.isFile){try{const r=await cO(t);n.files.push({file:r,relativePath:e?`${e}${r.name}`:""})}catch{}return}if(!t.isDirectory)return;n.hadDirectory=!0;const s=`${e}${t.name}`;let i=[];try{i=await lO(t)}catch{i=[]}if(i.length===0){n.emptyDirs.push(s);return}for(const r of i)await Dy(r,`${s}/`,n,o+1)}const Ry=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function is(t){const e=t.dataTransfer?.types;if(!e)return!1;const n=e;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 Xi(t){const e=t?.closest?.(".os-window");if(!e)return;const n=/^wp-window-(.+)$/.exec(e.id||"");return n?n[1]:void 0}function uO(t){if(!t)return;const e=document.querySelectorAll("iframe");for(const n of Array.from(e))if(n.contentWindow===t){const o=Xi(n);return o||n.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0}}function Oy(t){const e=window;if(e.__openStationOsFileDropMounted)return e.__openStationOsFileDropMounted;if(!t.config.enabled)return pO();const n=fO();let o=0,s=null;const i=()=>{o=0,n.classList.remove("is-active"),s!==null&&(clearTimeout(s),s=null)},r=()=>{s!==null&&clearTimeout(s),s=setTimeout(i,250)},a=g=>{is(g)&&(g.preventDefault(),o++,n.classList.add("is-active"),r())},l=g=>{if(is(g)){if(g.defaultPrevented){i();return}g.preventDefault(),g.dataTransfer&&(g.dataTransfer.dropEffect="copy"),r()}},c=()=>{o=Math.max(0,o-1),o===0&&n.classList.remove("is-active")},d=g=>{if(!is(g))return;if(g.defaultPrevented){i();return}g.preventDefault(),i();const h=aO(g.dataTransfer?.items),w=My(g);if(h.some(R=>R.isDirectory)){Py(h,w,t);return}const v=g.dataTransfer?.files?Array.from(g.dataTransfer.files):[];v.length!==0&&Dc(v,w,t)},u=()=>i(),f=()=>{document.visibilityState==="hidden"&&i()},p=g=>{if(g.origin!==window.location.origin)return;const h=g.data;if(!h||h.type!=="os-file-drop"||!Array.isArray(h.files)||h.files.length===0)return;const w=h.files.filter(_=>_ instanceof File);if(w.length===0)return;const v=uO(g.source);if(!v)return;const R={surface:"iframe",windowId:v,x:typeof h.x=="number"?h.x:0,y:typeof h.y=="number"?h.y:0};o=0,n.classList.remove("is-active"),Dc(w,R,t)};window.addEventListener("dragenter",a),window.addEventListener("dragover",l),window.addEventListener("dragleave",c),window.addEventListener("drop",d),window.addEventListener("dragend",u),document.addEventListener("visibilitychange",f),window.addEventListener("blur",u),window.addEventListener("message",p);const m={dispose:()=>{window.removeEventListener("dragenter",a),window.removeEventListener("dragover",l),window.removeEventListener("dragleave",c),window.removeEventListener("drop",d),window.removeEventListener("dragend",u),document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",u),window.removeEventListener("message",p),n.remove(),delete window.__openStationOsFileDropMounted}};return e.__openStationOsFileDropMounted=m,m}function fO(){const t=document.querySelector(".os-drop-overlay");if(t)return t;const e=document.createElement("div");e.className="os-drop-overlay",e.setAttribute("aria-hidden","true"),e.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",e.appendChild(n),document.body.appendChild(e);const o=document.createElement("style");return o.textContent=".os-drop-overlay.is-active{opacity:1!important;}",document.head.appendChild(o),e}function pO(){const t=o=>{if(!is(o))return;const s=o.target;s?.closest&&Ry.some(i=>s.closest(i))||o.preventDefault()};window.addEventListener("dragover",t),window.addEventListener("drop",t);const e=window,n={dispose:()=>{window.removeEventListener("dragover",t),window.removeEventListener("drop",t),delete e.__openStationOsFileDropMounted}};return e.__openStationOsFileDropMounted=n,n}function My(t){const e=t.clientX,n=t.clientY;let o=t.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:e,y:n}}if(o.tagName==="IFRAME")return{surface:"iframe",windowId:Xi(o),x:e,y:n};if(o.classList.contains("os-window")||o.hasAttribute("data-window-id")){const s=Xi(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:e,y:n}:{surface:"window",windowId:s,x:e,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:e,y:n}:{surface:"wallpaper",x:e,y:n}}if(o.id==="os-wallpaper"||o.classList.contains("os-wallpaper")||o.classList.contains("os-desktop"))return{surface:"wallpaper",x:e,y:n};o=o.parentElement}return{surface:"unknown",x:e,y:n}}async function Dc(t,e,n){const o=K(ce.FILES_DETECTED,t,e);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=Rc(o,n.config);if(i.length>0&&(L(ce.FILES_REJECTED,{rejections:i,context:e}),Z({message:i.length===1?i[0].message:`${i.length} files couldn't be uploaded.`})),s.length===0)return;const r=s.map(({file:a,mime:l})=>{const c={file:a,mime:l,fields:Oc(a,l)},d=K(ce.DIALOG_FIELDS,c,e);return!d||typeof d!="object"||!("fields"in d)||typeof d.fields!="object"?c:d});await n.openDialog(r,e)}async function Py(t,e,n){if(!n.storage?.canUpload||!n.filesUrl){Z({message:"Folder uploads need desktop storage, which is not available for your account."});return}const o=await dO(t),s=K(ce.FILES_DETECTED,o.files.map(u=>u.file),e);if(!Array.isArray(s))return;const i=new Set(s),r=o.files.filter(u=>i.has(u.file));if(r.length===0&&o.emptyDirs.length===0)return;const{accepted:a,rejected:l}=Rc(r.map(u=>u.file),n.config);l.length>0&&(L(ce.FILES_REJECTED,{rejections:l,context:e}),Z({message:l.length===1?l[0].message:`${l.length} files couldn't be uploaded.`}));const c=new Map(r.map(u=>[u.file,u.relativePath])),d=a.map(({file:u,mime:f})=>({file:u,mime:f,fields:Oc(u,f),relativePath:c.get(u)??""}));d.length===0&&o.emptyDirs.length===0||await n.openDialog(d,e,{forceDesktop:!0,emptyDirs:o.emptyDirs})}function Rc(t,e){const n=[],o=[];for(const s of t){if(s.size===0){o.push({file:s,reason:"empty",message:`“${s.name}” is empty.`});continue}if(e.maxSize>0&&s.size>e.maxSize){o.push({file:s,reason:"size",message:`“${s.name}” exceeds the ${mO(e.maxSize)} upload limit.`});continue}const i=Wy(s,e.allowedMimes,e.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 Wy(t,e,n){if(e.length===0)return null;const o=t.type.toLowerCase();if(o&&e.includes(o))return o;const s=$y(t.name);if(!s)return null;if(n){for(const[r,a]of Object.entries(n))if(r.split("|").includes(s)&&e.includes(a))return a;return null}const i=hO[s];return i&&e.includes(i)?i:null}const hO={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 $y(t){const e=t.lastIndexOf(".");return e<0?"":t.slice(e+1).toLowerCase()}function Oc(t,e){const n=Uy(t.name),o=$y(n),s=o?n.slice(0,n.length-o.length-1):n,i=Fy(s);return{title:i,altText:e.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function Uy(t){return t.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function Fy(t){const e=t.replace(/[-_]+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):"Upload"}function mO(t){return t>=1048576?`${(t/1048576).toFixed(0)} MB`:t>=1024?`${(t/1024).toFixed(0)} KB`:`${t} B`}const gO=Object.freeze(Object.defineProperty({__proto__:null,IFRAME_PASSTHROUGH_SELECTORS:Ry,classifyDropTarget:My,defaultFields:Oc,dragHasFiles:is,handleFiles:Dc,handleTreeDrop:Py,humanize:Fy,mountOsFileDropManager:Oy,partitionByPolicy:Rc,resolveAllowedMime:Wy,sanitizeFilename:Uy,windowIdFromElement:Xi},Symbol.toStringTag,{value:"Module"})),wO=re` ${tt} ${Jr}: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}`,_s=class _s extends be{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),Tf(this)}render(){const e=this.label||"",n=this.value??"",o=this.placeholder||"",s=this.disabled!==null,i=this.readonly!==null,r=this.autocomplete,a=this.type||"text",l=a==="password";let c=r||"off";l&&(!r||c==="off")&&(c="new-password");const d=this.maxlength,u=this.minlength,f=this.pattern||"",p=this.name||"",m=this.suffix||"",g=this.invalid!==null,h=this.reveal!==null,w=a==="password",v=w&&!(h&&this._revealed);let R;w||h&&this._revealed?R="text":R=a;const _=h?"os-text-field__row os-text-field__row--has-reveal":"os-text-field__row",E=v?"os-text-field__input os-text-field__input--masked":"os-text-field__input",D=`${this.id||"os-unnamed"}__input`;return q` |
| 315 |
${e?q`<label |
| 316 |
class="os-text-field__label" |
| 317 |
for=${D} |
| 318 |
>${e}</label>`:q``} |
| 319 |
<span class=${_}> |
| 320 |
<input |
| 321 |
id=${D} |
| 322 |
class=${E} |
| 323 |
type=${R} |
| 324 |
.value=${n} |
| 325 |
placeholder=${o} |
| 326 |
?disabled=${s} |
| 327 |
?readonly=${i} |
| 328 |
autocomplete=${c} |
| 329 |
maxlength=${d??""} |
| 330 |
minlength=${u??""} |
| 331 |
pattern=${f} |
| 332 |
name=${p} |
| 333 |
aria-invalid=${g?"true":"false"} |
| 334 |
aria-label=${e||""} |
| 335 |
@input=${O=>this._onInput(O)} |
| 336 |
@change=${O=>this._onChange(O)} |
| 337 |
@keydown=${O=>this._onKeyDown(O)} |
| 338 |
/> |
| 339 |
${m?q`<span class="os-text-field__suffix">${m}</span>`:q``} |
| 340 |
${h?this._renderRevealButton(s):q``} |
| 341 |
</span> |
| 342 |
`}_renderRevealButton(e){const n=this._revealed?"Hide":"Show";return q` |
| 343 |
<button |
| 344 |
type="button" |
| 345 |
class="os-text-field__reveal" |
| 346 |
aria-label=${n} |
| 347 |
aria-pressed=${this._revealed?"true":"false"} |
| 348 |
?disabled=${e} |
| 349 |
tabindex="0" |
| 350 |
@click=${()=>this._onToggleReveal()} |
| 351 |
> |
| 352 |
${this._revealed?bO():yO()} |
| 353 |
</button> |
| 354 |
`}_onToggleReveal(){this._revealed=!this._revealed,this.requestUpdate()}_onInput(e){const n=e.target;this.value=n.value,this.emit("os-input-change",{value:n.value})}_onChange(e){const n=e.target;this.emit("os-input-commit",{value:n.value})}_onKeyDown(e){if(e.key==="Enter"&&!e.shiftKey&&!e.altKey&&!e.metaKey){const n=e.target;this.emit("os-submit",{value:n.value})}}};_s.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],_s.styles=[wO],_s.help=void 0;let Mc=_s;Se("os-text-field",Mc);function yO(){return q` |
| 355 |
<svg |
| 356 |
viewBox="0 0 16 16" |
| 357 |
width="14" |
| 358 |
height="14" |
| 359 |
fill="none" |
| 360 |
stroke="currentColor" |
| 361 |
stroke-width="1.5" |
| 362 |
stroke-linecap="round" |
| 363 |
stroke-linejoin="round" |
| 364 |
aria-hidden="true" |
| 365 |
focusable="false" |
| 366 |
> |
| 367 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 368 |
<circle cx="8" cy="8" r="2" /> |
| 369 |
</svg> |
| 370 |
`}function bO(){return q` |
| 371 |
<svg |
| 372 |
viewBox="0 0 16 16" |
| 373 |
width="14" |
| 374 |
height="14" |
| 375 |
fill="none" |
| 376 |
stroke="currentColor" |
| 377 |
stroke-width="1.5" |
| 378 |
stroke-linecap="round" |
| 379 |
stroke-linejoin="round" |
| 380 |
aria-hidden="true" |
| 381 |
focusable="false" |
| 382 |
> |
| 383 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 384 |
<circle cx="8" cy="8" r="2" /> |
| 385 |
<line x1="2" y1="2" x2="14" y2="14" /> |
| 386 |
</svg> |
| 387 |
`}async function vO(t){const e={file:t.file,mime:t.mime,fields:t.fields},n=K(ce.BEFORE_UPLOAD,e,t.context);if(!n)throw new Pc;const o=new FormData,s=n.fields.filename!==n.file.name?new File([n.file],n.fields.filename,{type:n.mime||n.file.type}):n.file;return o.append("file",s),o.append("title",n.fields.title),o.append("alt_text",n.fields.altText),o.append("caption",n.fields.caption),o.append("description",n.fields.description),new Promise((i,r)=>{const a=new XMLHttpRequest;a.open("POST",t.mediaUrl,!0),a.withCredentials=!0,a.setRequestHeader("X-WP-Nonce",t.restNonce),a.responseType="text";let l=!1,c=!1,d=!1;const u=()=>{if(d=!0,!c){l=!0;try{a.abort()}catch{}}};L(ce.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:t.context,abort:u}),a.upload.addEventListener("progress",f=>{L(ce.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:t.context,loaded:f.loaded,total:f.lengthComputable?f.total:0,indeterminate:!f.lengthComputable})}),a.upload.addEventListener("load",()=>{c=!0,L(ce.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:t.context,loaded:n.file.size,total:n.file.size,indeterminate:!1})}),a.addEventListener("error",()=>{if(l)return;const f=new Error("Network error during upload.");L(ce.UPLOAD_FAILED,{file:n.file,error:f,context:t.context}),r(f)}),a.addEventListener("abort",()=>{const f=new Zi;L(ce.UPLOAD_FAILED,{file:n.file,error:f,context:t.context}),r(f)}),a.addEventListener("load",()=>{if(l)return;if(a.status<200||a.status>=300){const m=EO(a),g=new Error(m);L(ce.UPLOAD_FAILED,{file:n.file,error:g,context:t.context}),r(g);return}let f;try{f=JSON.parse(a.responseText)}catch(m){const g=m instanceof Error?m:new Error("Could not parse server response.");L(ce.UPLOAD_FAILED,{file:n.file,error:g,context:t.context}),r(g);return}if(d&&f.id){_O(t.mediaUrl,t.restNonce,f.id);const m=new Zi;L(ce.UPLOAD_FAILED,{file:n.file,error:m,context:t.context}),r(m);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(ce.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:t.context}),i(p)}),a.send(o)})}class Pc extends Error{constructor(){super("Upload cancelled by os.drop.before-upload filter."),this.name="UploadCancelledError"}}class Zi extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function _O(t,e,n){const o=`${t.replace(/\/$/,"")}/${n}?force=true`,s=new XMLHttpRequest;return s.open("DELETE",o,!0),s.withCredentials=!0,s.setRequestHeader("X-WP-Nonce",e),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 EO(t){const e=`Upload failed (HTTP ${t.status}).`,n=t.responseText;if(!n)return e;try{const o=JSON.parse(n);if(o&&typeof o.message=="string")return o.message}catch{}return e}async function kO(t){const e={file:t.file,mime:t.mime,fields:t.fields},n=K(ce.BEFORE_UPLOAD,e,t.context);if(!n)throw new Pc;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(t.parentId)),t.relativePath&&o.append("relativePath",t.relativePath),t.coords&&(o.append("x",String(t.coords.x)),o.append("y",String(t.coords.y)));const i=`${t.filesUrl.replace(/\/$/,"")}/uploads`;return new Promise((r,a)=>{const l=new XMLHttpRequest;l.open("POST",i,!0),l.withCredentials=!0,l.setRequestHeader("X-WP-Nonce",t.restNonce),l.responseType="text";let c=!1;const d=()=>{c=!0;try{l.abort()}catch{}};L(ce.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:t.context,abort:d}),l.upload.addEventListener("progress",f=>{L(ce.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:t.context,loaded:f.loaded,total:f.lengthComputable?f.total:0,indeterminate:!f.lengthComputable})});const u=f=>{L(ce.UPLOAD_FAILED,{file:n.file,error:f,context:t.context}),a(f)};l.addEventListener("error",()=>{c||u(new Error("Network error during upload."))}),l.addEventListener("abort",()=>u(new Zi)),l.addEventListener("load",()=>{if(c)return;if(l.status<200||l.status>=300){u(new Error(SO(l,n.file.name)));return}let f;try{f=JSON.parse(l.responseText)}catch{u(new Error("Could not parse server response."));return}if(!f.placement||typeof f.storedFileId!="number"){u(new Error("Unexpected server response."));return}Ci(f.placement,"local");const p={placement:f.placement,storedFileId:f.storedFileId};L(ce.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:t.context}),r(p)}),l.send(o)})}function SO(t,e){if(t.status===413)return`“${e}” is larger than this server accepts.`;const n=`Upload failed (HTTP ${t.status}).`,o=t.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 AO(t,e){const n=Math.max(0,Math.round((t-16)/96)),o=Math.max(0,Math.round((e-16)/110));return{x:16+n*96,y:16+o*110}}const IO=/^(image|video|audio)\//;function Wc(t){return t.desktopAllowed?t.forceDesktop||t.preferDesktop?"desktop":t.surface==="window"||t.surface==="iframe"?"media":(t.folderId??0)>0?"desktop":t.mimes.length>0&&t.mimes.every(n=>IO.test(n))?"media":"desktop":"media"}let Yt=null;async function CO(t){if(t.entries.length===0&&!t.emptyDirs?.length)return;if(Yt){Yt.replace(t);return}const e=!!(t.storage?.canUpload&&t.filesUrl);let n=Wc({desktopAllowed:e,surface:t.context.surface,folderId:t.context.folderId,forceDesktop:t.forceDesktop,preferDesktop:t.preferDesktop,mimes:t.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=t.entries.length;let u="Media Library";n==="desktop"&&(u=(t.context.folderId??0)>0?"this folder":"Desktop");let f=`Upload ${d} files to ${u}`;d===0?f=(t.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=t.entries.map(d=>({...d.fields})),r=()=>{if(o.innerHTML="",e&&!t.forceDesktop){const g=document.createElement("div");g.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;",g.appendChild(h);const w=document.createElement("os-segmented");w.setAttribute("value",n),w.setAttribute("label","Destination"),w.style.setProperty("--os-ui-segmented-bg","rgba(255,255,255,0.06)");const v=document.createElement("os-segment");v.setAttribute("value","desktop"),v.textContent="Desktop",w.appendChild(v);const R=document.createElement("os-segment");R.setAttribute("value","media"),R.textContent="Media Library",w.appendChild(R),w.addEventListener("os-pick",_=>{n=_.detail.value,s(),r()}),g.appendChild(w),o.appendChild(g)}else if(t.forceDesktop){const g=document.createElement("div");g.style.cssText="opacity:0.7;font-size:12px;margin-bottom:14px;",g.textContent="Folder uploads land in your desktop storage, preserving the folder structure.",o.appendChild(g)}const d=n==="desktop"?t.storage?.maxBytes??0:t.mediaMaxBytes??0;if(d>0){const g=document.createElement("div");g.className="os-upload-dialog__max-size",g.style.cssText="opacity:0.6;font-size:12px;margin-bottom:14px;",g.textContent=`Maximum file size: ${Gt(d)}`,o.appendChild(g)}const u=document.createElement("div");u.style.cssText="display:flex;flex-direction:column;gap:18px;max-height:60vh;overflow:auto;padding-right:6px;",t.entries.forEach((g,h)=>{u.appendChild(a(g,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 m=document.createElement("os-button");m.setAttribute("variant","primary"),t.entries.length===0?m.textContent="Create folders":m.textContent=t.entries.length===1?"Upload":`Upload ${t.entries.length} files`,m.addEventListener("click",()=>{l(m,p)}),f.appendChild(p),f.appendChild(m),o.appendChild(f)},a=(d,u,f)=>{const p=document.createElement("div");p.style.cssText="display:flex;flex-direction:column;gap:8px;border:1px solid rgba(255,255,255,0.08);border-radius:10px;padding:14px;";const m=document.createElement("div");m.style.cssText="display:flex;gap:10px;align-items:center;font-weight:600;";const g=document.createElement("span");g.textContent=t.entries.length===1?"":`#${f} · `,g.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 w=document.createElement("span");if(w.textContent=`${d.mime||"unknown"} · ${Gt(d.file.size)}`,w.style.cssText="opacity:0.6;font-size:12px;",m.appendChild(g),m.appendChild(h),m.appendChild(w),p.appendChild(m),n==="desktop"){if(d.relativePath){const v=document.createElement("div");v.textContent=d.relativePath,v.style.cssText="opacity:0.55;font-size:12px;",p.appendChild(v)}return p.appendChild(rs("Filename",u.filename,v=>u.filename=v)),p}return p.appendChild(rs("Title",u.title,v=>u.title=v)),p.appendChild(rs("Filename",u.filename,v=>u.filename=v)),d.mime.startsWith("image/")&&p.appendChild(rs("Alt text",u.altText,v=>u.altText=v)),p.appendChild(rs("Caption",u.caption,v=>u.caption=v)),p.appendChild(xO("Description",u.description,v=>u.description=v)),p},l=async(d,u)=>{Yt===c&&(Yt=null),d.disabled=!0,u.disabled=!0,d.textContent="Uploading…";const f=t.entries.length;let p=0,m=0,g=0;const h=[],w=t.context.folderId??0;let v=!1;for(let _=0;_<f;_++){const E=t.entries[_];try{if(n==="desktop"&&t.filesUrl){const D=!E.relativePath&&!v&&t.context.surface==="wallpaper"?AO(t.context.x,t.context.y):void 0;D&&(v=!0),await kO({file:E.file,mime:E.mime,fields:i[_],context:t.context,filesUrl:t.filesUrl,restNonce:t.restNonce,parentId:w,relativePath:E.relativePath??"",coords:D})}else await vO({file:E.file,mime:E.mime,fields:i[_],context:t.context,mediaUrl:t.mediaUrl,restNonce:t.restNonce});p++}catch(N){if(N instanceof Pc){g++;continue}if(N instanceof Zi){g++;continue}m++;const D=N instanceof Error?N.message:"Upload failed.";h.push(`“${E.file.name}” — ${D}`)}}if(n==="desktop"&&t.emptyDirs?.length)for(const _ of t.emptyDirs)try{await Pg(w,_)}catch{}const R=t.entries.some(_=>_.relativePath)||!!t.emptyDirs?.length;if(n==="desktop"&&R)try{const[_,E]=await Promise.all([xl(),Le(w)]);Nl(_.folders),mt(w,E.placements)}catch{}o.remove(),LO({total:f,successes:p,failures:m,cancelled:g,failureDetails:h,destination:n})},c={replace:d=>{t.entries=d.entries,t.emptyDirs=d.emptyDirs,t.forceDesktop=d.forceDesktop,t.preferDesktop=d.preferDesktop,t.context=d.context,t.mediaMaxBytes=d.mediaMaxBytes??t.mediaMaxBytes,i.length=0;for(const u of d.entries)i.push({...u.fields});n=Wc({desktopAllowed:e,surface:d.context.surface,folderId:d.context.folderId,forceDesktop:d.forceDesktop,preferDesktop:d.preferDesktop,mimes:d.entries.map(u=>u.mime)}),s(),r()}};Yt=c,r(),await new Promise(d=>{const u=()=>{Yt===c&&(Yt=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 rs(t,e,n){const o=document.createElement("os-text-field");return o.setAttribute("label",t),o.setAttribute("value",e),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function xO(t,e,n){const o=document.createElement("os-textarea");return o.setAttribute("label",t),o.setAttribute("value",e),o.setAttribute("rows","3"),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function LO(t){const{total:e,successes:n,failures:o,cancelled:s,failureDetails:i}=t,r=t.destination==="desktop"?"your desktop":"Media Library";if(e===0){t.destination==="desktop"&&Z({message:"Folder created on your desktop."});return}if(e===1){n===1?Z({message:`Uploaded to ${r}.`}):o===1&&i[0]?Z({message:i[0]}):s===1&&Z({message:"Upload cancelled."});return}if(n===e){Z({message:`Uploaded ${n} files to ${r}.`});return}if(s===e){Z({message:"All uploads cancelled."});return}if(o===e){Z({message:o===1&&i[0]?i[0]:`${o} uploads failed.`});return}const a=[];n>0&&a.push(`Uploaded ${n} file${n===1?"":"s"}.`),s>0&&a.push(`Cancelled ${s}.`),o>0&&a.push(`Failed ${o}.`),Z({message:a.join(" ")})}const By=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:CO,resolveDefaultDestination:Wc},Symbol.toStringTag,{value:"Module"})),TO={tab:null,requestedAt:0};let Ji=null;function $c(){if(Ji)return Ji;const e=window.wp?.os?.createSharedStore;return typeof e!="function"?null:(Ji=e("desktop-mode/plugins-window/tab-target",()=>({...TO})),Ji)}function NO(t){const e=$c();if(e){e.state.tab=t,e.state.requestedAt=Date.now(),e.notify();return}const n=window;n._wpdPluginsWindowTab={tab:t,requestedAt:Date.now()}}function DO(){const t=$c();if(t){const o=t.state.tab;return o!==null&&(t.state.tab=null,t.state.requestedAt=0,t.notify()),o}const e=window,n=e._wpdPluginsWindowTab;return n?(e._wpdPluginsWindowTab={tab:null,requestedAt:0},n.tab):null}function RO(t){const e=$c();return e?e.subscribe(n=>t({...n})):()=>{}}const OO=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:DO,setPluginsWindowTab:NO,subscribePluginsWindowTab:RO},Symbol.toStringTag,{value:"Module"})),MO=re` ${tt} ${Of}: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}}`,Es=class Es extends be{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return q`<div class="root" part="root"> |
| 388 |
<div class="header" part="header" hidden> |
| 389 |
<span class="label" part="label"></span> |
| 390 |
<span class="percent" part="percent"></span> |
| 391 |
</div> |
| 392 |
<div class="track" part="track"> |
| 393 |
<div class="fill" part="fill"></div> |
| 394 |
</div> |
| 395 |
</div>`}requestUpdate(){super.requestUpdate(),queueMicrotask(()=>this._paint())}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paint())}_paint(){const e=this.shadowRoot;if(!e)return;const n=this._readMax(),o=this.hasAttribute("indeterminate")||n<=0,s=o?0:this._readValue(n),i=o?0:s/n,r=Math.round(i*100),a=this.getAttribute("label")??"",l=this.hasAttribute("show-percent"),c=e.querySelector(".fill");c&&!o?c.style.width=`${(i*100).toFixed(2)}%`:c&&o&&c.style.removeProperty("width");const d=e.querySelector(".header"),u=e.querySelector(".label"),f=e.querySelector(".percent");if(d&&u&&f){const m=a||l&&!o;d.hidden=!m,u.textContent=a,f.hidden=!(l&&!o),f.textContent=`${r}%`}this._syncAria(n,s,o,a);const p=e.querySelector(".track");p&&(p.setAttribute("role","progressbar"),p.setAttribute("aria-valuemin","0"),o?(p.removeAttribute("aria-valuenow"),p.removeAttribute("aria-valuemax")):(p.setAttribute("aria-valuemax",String(n)),p.setAttribute("aria-valuenow",String(s))),a?p.setAttribute("aria-label",a):p.removeAttribute("aria-label"))}_syncAria(e,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(e)),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 e=this.getAttribute("max");if(e===null)return 100;const n=parseFloat(e);return Number.isFinite(n)?n:100}_readValue(e){const n=parseFloat(this.getAttribute("value")??"0");return!Number.isFinite(n)||n<0?0:n>e?e:n}};Es.props=["value","max","indeterminate","tone","label","showPercent"],Es.styles=[MO],Es.help=void 0;let Uc=Es;Se("os-progress-bar",Uc);const Je=new Map;let wt=null;function PO(){if(document.body.hasAttribute("data-os-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const t="desktop-mode/os-file-drop-hud";X(ce.UPLOAD_STARTED,t,e=>WO(e.file,e.fields,e.abort)),X(ce.UPLOAD_PROGRESS,t,e=>$O(e.file,e.loaded,e.total,e.indeterminate)),X(ce.AFTER_UPLOAD,t,e=>UO(e.file,e.fields,e.result)),X(ce.UPLOAD_FAILED,t,e=>FO(e.file,e.error))}function WO(t,e,n){const o=BO(),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=e.filename||t.name,r.title=e.filename||t.name;const a=document.createElement("div");a.className="os-upload-hud__status",a.textContent="Uploading…",i.append(r,a);const l=document.createElement("os-progress-bar");l.setAttribute("indeterminate",""),l.setAttribute("show-percent","");const c=document.createElement("div");c.className="os-upload-hud__actions";const d=document.createElement("os-button");d.setAttribute("variant","tertiary"),d.setAttribute("size","small"),d.textContent="Cancel",d.addEventListener("click",()=>{const u=Je.get(t);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):Fc(u))}),c.appendChild(d),s.append(i,l,c),o.querySelector(".os-upload-hud__list").appendChild(s),Je.set(t,{file:t,abort:n,root:s,bar:l,statusEl:a,cancelBtn:d,state:"running",lingerTimer:null}),Qi()}function $O(t,e,n,o){const s=Je.get(t);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${Gt(e)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(e)),s.statusEl.textContent=`${Gt(e)} / ${Gt(n)}`))}function UO(t,e,n){const o=Je.get(t);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(()=>Fc(o),2500),Qi(),Ee.publish("os/upload-hud-complete",{filename:e.filename||n.filename,attachmentId:n.id}))}function FO(t,e){const n=Je.get(t);n&&(n.bar.removeAttribute("indeterminate"),n.bar.setAttribute("tone","danger"),n.cancelBtn.textContent="Dismiss",n.cancelBtn.disabled=!1,e.name==="UploadAbortedError"?(n.state="aborted",n.statusEl.textContent="Cancelled"):(n.state="failed",n.statusEl.textContent=e.message||"Upload failed"),Qi())}function Fc(t){t.lingerTimer&&clearTimeout(t.lingerTimer),Je.delete(t.file),t.root.remove(),Qi(),Je.size===0&&wt&&(wt.hidden=!0)}function BO(){if(wt&&wt.isConnected)return wt.hidden=!1,wt;const t=document.createElement("div");t.className="os-upload-hud",t.setAttribute("role","region"),t.setAttribute("aria-label","Uploads");const e=document.createElement("div");e.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"&&Fc(i);Je.size===0&&(t.hidden=!0)}),e.append(n,o);const s=document.createElement("div");return s.className="os-upload-hud__list",t.append(e,s),document.body.appendChild(t),wt=t,t}function Qi(){if(!wt)return;const t=wt.querySelector(".os-upload-hud__title");if(!t)return;const e=Je.size,n=[...Je.values()].filter(o=>o.state==="running").length;n>0?t.textContent=n===e?`Uploading ${n} file${n===1?"":"s"}…`:`${n} of ${e} uploading…`:e>0?t.textContent=`Uploads (${e})`:t.textContent="Uploads"}function HO(){if(document.body.hasAttribute("data-os-suppress-media-library-refresh"))return;const t=window;t.__wpdMediaLibraryRefresher||(t.__wpdMediaLibraryRefresher=!0,X(ce.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>zO()))}function zO(){const t=document.querySelectorAll("iframe");for(const e of Array.from(t))if(GO(Hy(e)))try{e.contentWindow?.location.reload()}catch{const n=Hy(e);n&&e.setAttribute("src",n)}}function Hy(t){try{return t.contentWindow?.location.href??t.src??""}catch{return t.src??""}}function GO(t){return t?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(t):!1}function jO(t){const e=t.config||{enabled:!1,allowedMimes:[],maxSize:0};PO(),HO(),Oy({config:e,mediaUrl:t.mediaUrl,restNonce:t.restNonce,filesUrl:t.filesUrl,storage:t.storage,openDialog:async(n,o,s)=>{const{openUploadDialog:i}=await Promise.resolve().then(()=>By);await i({entries:n,context:o,mediaUrl:t.mediaUrl,restNonce:t.restNonce,filesUrl:t.filesUrl,storage:t.storage,forceDesktop:s?.forceDesktop,emptyDirs:s?.emptyDirs,mediaMaxBytes:e.maxSize})}})}const VO=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:ce,bootOsFileDrop:jO},Symbol.toStringTag,{value:"Module"}));return or.clampGeometryToViewport=fl,Object.defineProperty(or,Symbol.toStringTag,{value:"Module"}),or}({}); |
| 396 |
|