| 1 |
var openStation=function(xr){"use strict";var Lr=typeof document<"u"?document.currentScript:null;const rv="desktop-mode-my-wordpress";function bd(){return window.wp?.os}async function av(){const e=bd();return typeof e?.loadWindowScript=="function"&&await e.loadWindowScript(rv),bd()?.myWordpress}function Ps(e,t){return async(...n)=>{const o=await av();if(!o||o===t())return;const s=o[e];typeof s=="function"&&await s(...n)}}function lv(){const e=window;e.wp=e.wp??{};const t=e.wp;t.os||(t.os={});const n=t.os;if(n.myWordpress)return;const o=[],s=()=>i,i={openDetail:Ps("openDetail",s),openMedia:Ps("openMedia",s),openUserFootprint:Ps("openUserFootprint",s),trashEntity:Ps("trashEntity",s),registerEntityKind:(r,a)=>{const l={unregister:null},c={kind:r,renderer:a,slot:l};return o.push(c),()=>{if(l.unregister){l.unregister(),l.unregister=null;return}const d=o.indexOf(c);d!==-1&&o.splice(d,1)}},__pendingKinds:o};n.myWordpress=i}lv();function Rt(){const e=window.wp?.hooks;if(!e)throw new Error("[openstation] `window.wp.hooks` is not available. The plugin declares `wp-hooks` as a script dependency; if you are seeing this error, verify the enqueue order.");return e}function Qn(e,t,n,o){Rt().addFilter(e,t,n,o)}function Z(e,t,n,o){Rt().addAction(e,t,n,o)}function Tr(e,t){return Rt().removeAction(e,t)}function Y(e,t,...n){return Rt().applyFilters(e,t,...n)}function L(e,...t){Rt().doAction(e,...t)}function vd(e){return Rt().didAction(e)}function cv(){return Rt()}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_MENU_OPENED:"os.window.menu-opened",WINDOW_CLOSING:"os.window.closing",WINDOW_CLOSED:"os.window.closed",WINDOW_FOCUSED:"os.window.focused",WINDOW_BLURRED:"os.window.blurred",WINDOW_MINIMIZED:"os.window.minimized",WINDOW_RESTORED:"os.window.restored",WINDOW_CHILD_BLOCKED:"os.window.child-blocked",WINDOW_MAXIMIZED:"os.window.maximized",WINDOW_UNMAXIMIZED:"os.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"os.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"os.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"os.window.auto-exit-fullscreen",WINDOW_FOCUS_ON_DRAG_HOVER:"os.window.focus-on-drag-hover",WINDOW_BOUNDS_CHANGED:"os.window.bounds-changed",WINDOW_MOVED:"os.window.moved",WINDOW_RESIZED:"os.window.resized",WINDOW_DRAG_START:"os.window.drag-start",WINDOW_DRAG_END:"os.window.drag-end",WINDOW_RESIZE_START:"os.window.resize-start",WINDOW_RESIZE_END:"os.window.resize-end",WINDOW_DETACHED:"os.window.detached",WINDOW_RELOADED:"os.window.reloaded",WINDOW_TITLE_CHANGED:"os.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"os.window.highlight-changed",WINDOW_BODY_RESIZED:"os.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"os.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"os.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"os.native-window.before-close",WINDOW_CHROME_THEME:"os.window.chrome.theme",WINDOW_CHROME_CONTROLS:"os.window.chrome.controls",WINDOW_CHROME_SLOT:"os.window.chrome.slot",WINDOW_CHROME_RENDER:"os.window.chrome.render",WINDOW_CHROME_APPLIED:"os.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"os.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"os.os-icon.clicked",DESKTOP_ICONS_RENDERED:"os.os-icons.rendered",ICON_BADGE_CHANGED:"os.icon.badge-changed",COMPONENTS_REGISTERED:"os.components.registered",DOCK_ITEM_APPENDED:"os.dock.item-appended",DOCK_ITEM_REMOVED:"os.dock.item-removed",DOCK_BEFORE_RENDER:"os.dock.before-render",DOCK_AFTER_RENDER:"os.dock.after-render",DOCK_REFRESH_ACTIVE:"os.dock.refresh-active",DOCK_TILE_CLASS:"os.dock.tile-class",DOCK_TILE_ELEMENT:"os.dock.tile-element",DOCK_TILE_RENDERED:"os.dock.tile-rendered",DOCK_TILE_TOOLTIP:"os.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"os.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"os.dock.peek-card-element",CONSTELLATION_PANEL:"os.constellation.panel",CONSTELLATION_OPENED:"os.constellation.opened",CONSTELLATION_CLOSED:"os.constellation.closed",OVERVIEW_ENTERING:"os.overview.entering",OVERVIEW_ENTERED:"os.overview.entered",OVERVIEW_EXITING:"os.overview.exiting",OVERVIEW_EXITED:"os.overview.exited",OVERVIEW_WINDOW_HOVER:"os.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"os.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"os.overview.window-click",ARRANGE_CASCADE_STARTING:"os.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"os.arrange.cascade.applied",ARRANGE_TILE_STARTING:"os.arrange.tile.starting",ARRANGE_TILE_APPLIED:"os.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"os.arrange.tile.dimensions",ARRANGE_SNAP_CHANGED:"os.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"os.arrange.snap.cell-size",ARRANGE_CUSTOM_ACTION:"os.arrange.custom-action",SNAP_ZONE_PENDING:"os.snap.zone-pending",SNAP_ZONE_CANCELED:"os.snap.zone-canceled",SNAP_ZONE_COMMITTED:"os.snap.zone-committed",SNAP_SPLIT_FILLED:"os.snap.split-filled",WIDGETS:"os.widgets",WIDGET_MOUNTING:"os.widget.mounting",WIDGET_MOUNTED:"os.widget.mounted",WIDGET_UNMOUNTING:"os.widget.unmounting",WIDGET_MOUNT_FAILED:"os.widget.mount-failed",WIDGET_ADDED:"os.widget.added",WIDGET_REMOVED:"os.widget.removed",DESKTOP_CREATED:"os.os.created",DESKTOP_CLOSED:"os.os.closed",DESKTOP_SWITCHED:"os.os.switched",DESKTOP_RENAMED:"os.os.renamed",PRIMARY_DESKTOP_ID:"os.primary-desktop-id",WINDOWS_BEFORE_CLOSE_ALL:"os.windows.before-close-all",WINDOWS_CLOSE_ALL:"os.windows.close-all",WINDOWS_AFTER_CLOSE_ALL:"os.windows.after-close-all",COMMAND_BEFORE_RUN:"os.command.before-run",COMMAND_AFTER_RUN:"os.command.after-run",COMMAND_ERROR:"os.command.error",SHELL_RESIZED:"os.shell.resized",SHELL_VISIBILITY:"os.shell.visibility",CONNECTION_OPENED:"os.connection.opened",CONNECTION_CLOSED:"os.connection.closed",CONNECTION_MESSAGE:"os.connection.message",IFRAME_CONNECTION_REQUEST:"os.iframe.connection-request",WINDOW_CONTENT_CHANGED:"os.window-links.content-changed",WINDOW_LINK_GROUPS_CHANGED:"os.window-links.groups-changed",WINDOW_LINKS_CONTENT:"os.window-links.content",WINDOW_LINK_GROUPS:"os.window-links.groups",WINDOW_LINK_EDGES:"os.window-links.edges",RELATED_ENTITIES_ITEMS:"os.related-entities.items",WINDOW_LINK_RENDERERS:"os.window-links.renderers",WINDOW_LINK_RENDERER:"os.window-links.renderer",EDITOR_PREVIEW_WINDOW_CONFIG:"os.editor-preview.window-config",EDITOR_PREVIEW_LIVE:"os.editor-preview.live",EDITOR_PREVIEW_OPENED:"os.editor-preview.opened",EDITOR_PREVIEW_CLOSED:"os.editor-preview.closed",FILE_DROP_FILES_DETECTED:"os.drop.files-detected",FILE_DROP_FILES_REJECTED:"os.drop.files-rejected",FILE_DROP_DIALOG_FIELDS:"os.drop.dialog-fields",FILE_DROP_BEFORE_UPLOAD:"os.drop.before-upload",FILE_DROP_UPLOAD_STARTED:"os.drop.upload-started",FILE_DROP_UPLOAD_PROGRESS:"os.drop.upload-progress",FILE_DROP_AFTER_UPLOAD:"os.drop.after-upload",FILE_DROP_UPLOAD_FAILED:"os.drop.upload-failed",AUTH_LOST:"os.auth.lost",AUTH_RESTORED:"os.auth.restored"};let dv=0;function _d(e){if(vd(b.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++dv}`;Z(b.INIT,t,e)}function uv(){return vd(b.INIT)>0}const Ed=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"];Ed.filter(e=>e!=="p");function kd(e){let t=e;try{t=decodeURIComponent(e)}catch{t=e}return t.replace(/\.php/g,"-php").replace(/[?&=/]/g,"-").replace(/[^a-zA-Z0-9_-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")||"index"}function ae(e,t){let n=null;try{n=new URL(e,t)}catch{n=null}if(n){const s=new URL(t).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams;for(const l of Ed){const c=n.searchParams.get(l);c&&r.set(l,c)}const a=r.toString();return kd(a?`${i}?${a}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),kd(o)}function Sd(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function fv(e){e.style.setProperty("--os-file-tile-enter-delay",`${(Math.random()*.25).toFixed(3)}s`),e.style.setProperty("--os-file-tile-enter-duration",`${(.3+Math.random()*.25).toFixed(3)}s`)}function Ad(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("openstation_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function Ws(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("openstation_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.searchParams.delete("_wp_http_referer"),t.searchParams.sort(),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function Cd(e){if(typeof e!="string"||e===""||typeof DOMParser>"u")return"";let t;try{t=new DOMParser().parseFromString(e,"image/svg+xml")}catch{return""}const n=t.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||t.getElementsByTagName("parsererror").length>0)return"";const o=new Set(["script","style","foreignobject","iframe","object","embed"]),s=i=>{const r=Array.from(i.children);for(const a of r){if(o.has(a.nodeName.toLowerCase())){a.remove();continue}for(const l of Array.from(a.attributes)){const c=l.name.toLowerCase(),d=l.value.trim().toLowerCase();if(c.startsWith("on")){a.removeAttribute(l.name);continue}d.startsWith("javascript:")&&a.removeAttribute(l.name)}s(a)}};s(n);for(const i of Array.from(n.attributes)){const r=i.name.toLowerCase(),a=i.value.trim().toLowerCase();(r.startsWith("on")||a.startsWith("javascript:"))&&n.removeAttribute(i.name)}return n.outerHTML}let cn=null;function $s(){return!!window.openStationWindowSystem}function Id(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if($s()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){$s()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osWindowSystem="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))),document.head.appendChild(i)})}function pv(){return window.openStationConfig?.windowSystemBundleUrl??""}function hv(e){!e||$s()||cn||(cn=Id(e).catch(t=>{cn=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function mv(e){if($s())return window.openStationWindowSystem;if(!e){const t=window.openStationWindowSystem;if(t)return t;throw new Error("[openstation] ensureWindowSystemLoaded(): no bundle URL configured and `window.openStationWindowSystem` is not pre-registered.")}return cn||(cn=Id(e)),await cn,window.openStationWindowSystem}let dn=null;function eo(){return!!window.openStationShellOverlays}function xd(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(eo()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){eo()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osShellOverlays="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(i)})}function gv(e){!e||eo()||dn||(dn=xd(e).catch(t=>{dn=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function Nr(e){return eo()||!e?Promise.resolve():(dn||(dn=xd(e)),dn)}function Dr(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function Us(e,t){const n=Dr();if(eo()||!n){t();return}Nr(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Ld="desktop-mode";function Rr(){return window.wp?.i18n}function E(e,t=Ld){return Rr()?.__(e,t)??e}function un(e,t,n,o=Ld){return Rr()?._n(e,t,n,o)??(n===1?e:t)}function le(e,...t){const n=Rr()?.sprintf;if(n)return n(e,...t);let o=0;return e.replace(/%(?:(\d+)\$)?[sd]/g,(s,i)=>{const r=i?Number.parseInt(i,10)-1:o++;return String(t[r]??"")})}const wv=900,yv=260,Or="os-desktop-name-hud";let Ye=null,bt=null;function bv(e,t){t.trim()&&(bt!==null&&window.clearTimeout(bt),Ye||(Ye=document.createElement("div"),Ye.className=Or,Ye.setAttribute("role","status")),Ye.textContent=t,Ye.classList.remove(`${Or}--out`),e.appendChild(Ye),bt=window.setTimeout(()=>{Ye?.classList.add(`${Or}--out`),bt=window.setTimeout(()=>{Ye?.remove(),bt=null},yv)},wv))}function vv(){bt!==null&&(window.clearTimeout(bt),bt=null),Ye?.remove(),Ye=null}function _v(e,t){if(!e||typeof e!="object")return!1;const n=e.cols,o=e.rows;return typeof n!="number"||typeof o!="number"||!Number.isFinite(n)||!Number.isFinite(o)||n<1||o<1?!1:Math.floor(n)*Math.floor(o)>=t}function Ev(e){if(!e||typeof e!="object")return!1;const t=e.cellWidth,n=e.cellHeight;return typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)?!1:t>0&&n>0}function kv(e,t,n){if(e<=1)return{cols:1,rows:1};const o=t/Math.max(1,n),s=6;let i={cols:e,rows:1,score:1/0};for(let r=1;r<=Math.min(s,e);r++){const a=Math.min(s,Math.ceil(e/r));if(r*a<e)continue;const l=t/r/Math.max(1,n/a),c=Math.abs(l-o),d=r*a-e,u=c+d*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function Mr(e,t,n=0){const o=e.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,l=34,c=(t.width-r*2-a*(s-1))/s,d=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-l);return e.map((f,p)=>{const w=p%s,m=Math.floor(p/s),h=t.left+r+w*(c+a),y=t.top+n+r+m*(d+a)+l,v=f.element.offsetWidth,A=f.element.offsetHeight,D=Math.min(c/v,u/A),_=v*D,O=A*D;return{win:f,x:h+(c-_)/2,y:y+(u-O)/2,scale:D}})}const Sv=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],Td=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],Av=[...Sv,...Td],Nd={close:{a:'fill="currentColor"',b:'<path d="m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z" />'},check:{a:'fill="currentColor"',b:'<path d="M16.5 7.5 10 13.9l-2.5-2.4-1 1 3.5 3.6 7.5-7.6z" />'},"chevron-right":{a:'fill="currentColor"',b:'<path d="M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z" />'},"arrow-up-right":{a:'fill="currentColor"',b:'<path d="M10 6H18V14H16.5V8.5L7 18L6 17L15.5 7.5H10V6Z" />'},plus:{a:'fill="currentColor"',b:'<path d="M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z" />'},search:{a:'fill="currentColor"',b:'<path d="M13 5c-3.3 0-6 2.7-6 6 0 1.4.5 2.7 1.3 3.7l-3.8 3.8 1.1 1.1 3.8-3.8c1 .8 2.3 1.3 3.7 1.3 3.3 0 6-2.7 6-6S16.3 5 13 5zm0 10.5c-2.5 0-4.5-2-4.5-4.5s2-4.5 4.5-4.5 4.5 2 4.5 4.5-2 4.5-4.5 4.5z" />'},pin:{a:'fill="currentColor"',b:'<path d="m21.5 9.1-6.6-6.6-4.2 5.6c-1.2-.1-2.4.1-3.6.7-.1 0-.1.1-.2.1-.5.3-.9.6-1.2.9l3.7 3.7-5.7 5.7v1.1h1.1l5.7-5.7 3.7 3.7c.4-.4.7-.8.9-1.2.1-.1.1-.2.2-.3.6-1.1.8-2.4.6-3.6l5.6-4.1zm-7.3 3.5.1.9c.1.9 0 1.8-.4 2.6l-6-6c.8-.4 1.7-.5 2.6-.4l.9.1L15 4.9 19.1 9l-4.9 3.6z" />'},trash:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M12 5.5A2.25 2.25 0 0 0 9.878 7h4.244A2.251 2.251 0 0 0 12 5.5ZM12 4a3.751 3.751 0 0 0-3.675 3H5v1.5h1.27l.818 8.997a2.75 2.75 0 0 0 2.739 2.501h4.347a2.75 2.75 0 0 0 2.738-2.5L17.73 8.5H19V7h-3.325A3.751 3.751 0 0 0 12 4Zm4.224 4.5H7.776l.806 8.861a1.25 1.25 0 0 0 1.245 1.137h4.347a1.25 1.25 0 0 0 1.245-1.137l.805-8.861Z" />'},download:{a:'fill="currentColor"',b:'<path d="M18 11.3l-1-1.1-4 4V3h-1.5v11.3L7 10.2l-1 1.1 6.2 5.8 5.8-5.8zm.5 3.7v3.5h-13V15H4v5h16v-5h-1.5z" />'},settings:{a:'fill="currentColor"',b:'<path d="m19 7.5h-7.628c-.3089-.87389-1.1423-1.5-2.122-1.5-.97966 0-1.81309.62611-2.12197 1.5h-2.12803v1.5h2.12803c.30888.87389 1.14231 1.5 2.12197 1.5.9797 0 1.8131-.62611 2.122-1.5h7.628z" /><path d="m19 15h-2.128c-.3089-.8739-1.1423-1.5-2.122-1.5s-1.8131.6261-2.122 1.5h-7.628v1.5h7.628c.3089.8739 1.1423 1.5 2.122 1.5s1.8131-.6261 2.122-1.5h2.128z" />'},info:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm.75 4v1.5h-1.5V8h1.5Zm0 8v-5h-1.5v5h1.5Z" />'},bell:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M17 11.5c0 1.353.17 2.368.976 3 .266.209.602.376 1.024.5v1H5v-1c.422-.124.757-.291 1.024-.5.806-.632.976-1.647.976-3V9c0-2.8 2.2-5 5-5s5 2.2 5 5v2.5ZM15.5 9v2.5c0 .93.066 1.98.515 2.897l.053.103H7.932a4.018 4.018 0 0 0 .053-.103c.449-.917.515-1.967.515-2.897V9c0-1.972 1.528-3.5 3.5-3.5s3.5 1.528 3.5 3.5Zm-5.492 9.008c0-.176.023-.346.065-.508h3.854A1.996 1.996 0 0 1 12 20c-1.1 0-1.992-.892-1.992-1.992Z" />'},more:{a:'fill="currentColor"',b:'<path d="M11 13h2v-2h-2v2zm-6 0h2v-2H5v2zm12-2v2h2v-2h-2z" />'},maximize:{a:'fill="currentColor"',b:'<path d="M6 4a2 2 0 0 0-2 2v3h1.5V6a.5.5 0 0 1 .5-.5h3V4H6Zm3 14.5H6a.5.5 0 0 1-.5-.5v-3H4v3a2 2 0 0 0 2 2h3v-1.5Zm6 1.5v-1.5h3a.5.5 0 0 0 .5-.5v-3H20v3a2 2 0 0 1-2 2h-3Zm3-16a2 2 0 0 1 2 2v3h-1.5V6a.5.5 0 0 0-.5-.5h-3V4h3Z" />'},edit:{a:'fill="currentColor"',b:'<path d="m19 7-3-3-8.5 8.5-1 4 4-1L19 7Zm-7 11.5H5V20h7v-1.5Z" />'},color:{a:'fill="currentColor"',b:'<path d="M17.2 10.9c-.5-1-1.2-2.1-2.1-3.2-.6-.9-1.3-1.7-2.1-2.6L12 4l-1 1.1c-.6.9-1.3 1.7-2 2.6-.8 1.2-1.5 2.3-2 3.2-.6 1.2-1 2.2-1 3 0 3.4 2.7 6.1 6.1 6.1s6.1-2.7 6.1-6.1c0-.8-.3-1.8-1-3zm-5.1 7.6c-2.5 0-4.6-2.1-4.6-4.6 0-.3.1-1 .8-2.3.5-.9 1.1-1.9 2-3.1.7-.9 1.3-1.7 1.8-2.3.7.8 1.3 1.6 1.8 2.3.8 1.1 1.5 2.2 2 3.1.7 1.3.8 2 .8 2.3 0 2.5-2.1 4.6-4.6 4.6z" />'},wallpaper:{a:'fill="currentColor"',b:'<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.5h14c.3 0 .5.2.5.5v8.4l-3-2.9c-.3-.3-.8-.3-1 0L11.9 14 9 12c-.3-.2-.6-.2-.8 0l-3.6 2.6V5c-.1-.3.1-.5.4-.5zm14 15H5c-.3 0-.5-.2-.5-.5v-2.4l4.1-3 3 1.9c.3.2.7.2.9-.1L16 12l3.5 3.4V19c0 .3-.2.5-.5.5z" />'},warning:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm-.75 12v-1.5h1.5V16h-1.5Zm0-8v5h1.5V8h-1.5Z" />'},minimize:{a:'fill="currentColor"',b:'<path d="M5 11.25h14v1.5H5z" />'},window:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="4.125" y="5.4375" width="15.75" height="13.125" rx="1.75"/><path d="M4.125 9.8125h15.75"/><circle cx="7.275" cy="7.625" r="0.7438" fill="currentColor" stroke="none"/>'},windows:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="8.5" width="11.375" height="10.0625" rx="1.75"/><path d="M3.6875 12h11.375"/><path d="M8.5 8.5V7.1875a1.75 1.75 0 0 1 1.75-1.75h7.875A1.75 1.75 0 0 1 19.875 7.1875v7a1.75 1.75 0 0 1-1.75 1.75h-3.0625"/>'},dock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.25" y="8.5" width="17.5" height="7" rx="3.5"/><circle cx="7.625" cy="12" r="1.0062" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.0062" fill="currentColor" stroke="none"/><circle cx="16.375" cy="12" r="1.0062" fill="currentColor" stroke="none"/>'},spaces:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="5.4375" width="7.4375" height="7.875" rx="1.75"/><rect x="12.875" y="5.4375" width="7.4375" height="7.875" rx="1.75"/><circle cx="9.375" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/><circle cx="12" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/><circle cx="14.625" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/>'},copilot:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<path d="M10 2.5Q10.9 8.5 17.5 10Q10.9 11.5 10 17.5Q9.1 11.5 2.5 10Q9.1 8.5 10 2.5Z" fill="currentColor" stroke="none"/><path d="M17.9 14Q18.35 17.1 21.5 17.6Q18.35 18.1 17.9 21.2Q17.45 18.1 14.3 17.6Q17.45 17.1 17.9 14Z" fill="currentColor" stroke="none"/>'},snap:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="5.4375" width="16.625" height="13.125" rx="1.75"/><path d="M12 5.4375v13.125"/><path d="M12 12h8.3125"/>'},command:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<path d="M14.625 6.75v10.5a2.625 2.625 0 1 0 2.625-2.625H6.75a2.625 2.625 0 1 0 2.625 2.625V6.75a2.625 2.625 0 1 0-2.625 2.625h10.5a2.625 2.625 0 1 0-2.625-2.625"/>'},apps:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="4.125" y="4.125" width="6.5625" height="6.5625" rx="1.75"/><rect x="13.3125" y="4.125" width="6.5625" height="6.5625" rx="1.75"/><rect x="4.125" y="13.3125" width="6.5625" height="6.5625" rx="1.75"/><rect x="13.3125" y="13.3125" width="6.5625" height="6.5625" rx="1.75"/>'},widgets:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="3.6875" width="9.625" height="9.625" rx="1.75"/><rect x="15.0625" y="3.6875" width="5.25" height="5.25" rx="1.75"/><rect x="15.0625" y="10.6875" width="5.25" height="9.625" rx="1.75"/><rect x="3.6875" y="15.0625" width="9.625" height="5.25" rx="1.75"/>'},user:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<circle cx="12" cy="8.9375" r="3.5"/><path d="M5.4375 19.4375a6.5625 6.5625 0 0 1 13.125 0"/>'},lock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="5.4375" y="10.6875" width="13.125" height="8.75" rx="1.75"/><path d="M8.5 10.6875V8.0625a3.5 3.5 0 0 1 7 0v2.625"/>'}};function Dd(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Rd(e){return Object.prototype.hasOwnProperty.call(Nd,e)?Nd[e]:null}function Cv(e){return Rd(e)!==null}function Ot(e,t={}){const n=Rd(e);if(!n)return"";const{size:o=24,className:s,title:i,rotate:r}=t,a=['xmlns="http://www.w3.org/2000/svg"','viewBox="0 0 24 24"'];o!=null&&a.push(`width="${o}"`,`height="${o}"`),a.push(n.a),s&&a.push(`class="${Dd(s)}"`),i?a.push('role="img"',`aria-label="${Dd(i)}"`):a.push('aria-hidden="true"','focusable="false"');const l=r?`<g transform="rotate(${r} 12 12)">${n.b}</g>`:n.b;return`<svg ${a.join(" ")}>${l}</svg>`}function Pr(e,t={}){const n=Ot(e,t),o=document.createElement("div");o.innerHTML=n;const s=o.firstElementChild;return s instanceof SVGSVGElement?s:document.createElementNS("http://www.w3.org/2000/svg","svg")}function Iv(e,t={}){const n=Ot(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const xv=Object.freeze({svg:Ot,node:Pr,dataUri:Iv,names:Object.freeze([...Av]),ours:Object.freeze([...Td]),has:Cv}),Od=120,Md="__openStationSharedStores";function Lv(){const e=window;let t=e[Md];return t||(t=new Map,e[Md]=t),t}function re(e,t){const n=Lv();let o=n.get(e);o||(o={state:t(),listeners:new Set,rebuild:t},n.set(e,o));const s={get state(){return o.state},set state(i){o.state=i},getState(){return o.state},notify(){for(const i of Array.from(o.listeners))try{i(o.state)}catch(r){console.error(`[desktop-mode/shared-store:${e}] subscriber threw:`,r)}},subscribe(i){return o.listeners.add(i),()=>{o.listeners.delete(i)}},setState(i){const r=o.state;if(typeof r!="object"||r===null){console.warn(`[desktop-mode/shared-store:${e}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(r,i),s.notify()},reset(){const i=o.rebuild(),r=o.state;if(typeof r=="object"&&r!==null&&typeof i=="object"&&i!==null){const a=r;for(const l of Object.keys(a))delete a[l];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}const to=re("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),dt=to.state.registry,Wr=to.state.listeners,Tv=/^[a-z0-9_-]+$/;function Pd(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!Tv.test(e.id))throw new TypeError(`[openstation] registerDockRailRenderer: id must match /^[a-z0-9_-]+$/, got: ${String(e.id)}`);if(typeof e.label!="string"||e.label==="")throw new TypeError("[openstation] registerDockRailRenderer: label must be a non-empty string.");if(typeof e.mount!="function")throw new TypeError("[openstation] registerDockRailRenderer: mount must be a function.");if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new TypeError(`[openstation] registerDockRailRenderer: unsupported apiVersion ${e.apiVersion} (this shell speaks v1).`);dt.set(e.id,e),Fs()}function Nv(e){dt.delete(e)&&Fs()}function Dv(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(dt.entries()))o.owner===e&&(dt.delete(n),t++);return t>0&&Fs(),t}function Rv(e){return dt.get(e)}function Ov(){return Array.from(dt.values())}function Mv(e){return Wr.add(e),()=>{Wr.delete(e)}}function Pv(e){to.state.activeId!==e&&(to.state.activeId=e,Fs())}function $r(){return dt.get(to.state.activeId)??dt.get("default")??dt.values().next().value}function Fs(){const e=Array.from(Wr);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function Mt(e,t){if(!e||typeof e!="object")return["def (not an object)"];const n=e,o=[];for(const s of t)s.valid(n)||o.push(`${s.field} (${s.message})`);return o}class Wv extends Error{constructor(t,n,o){super(`[openstation] ${t} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=t,this.errors=n,this.def=o}}function Ne(e,t,n){if(t.length!==0)throw new Wv(e,t,n)}function Wd(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const vt=[[0,0],[100,0],[100,100],[0,100]],$v=48,Uv=80,Ur=6,Fr=8,$d=4,Ud=3,Fd=64,Br=105,_t=2;function Bd(e){return`${Math.round(e*1e3)/1e3}%`}function Et(e){return e.slice().reverse()}function no(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function Fv(e,t,n,o){const s=[];for(let i=0;i<o;i++){const r=i/o*Math.PI*2;s.push([e+Math.cos(r)*n,t+Math.sin(r)*n])}return s}function nt(e,t=[]){const n=[],o=s=>{n.push(`${Bd(s[0])} ${Bd(s[1])}`)};for(const s of e)o(s);if(t.length>0){o(e[0]);for(const s of t){for(const i of s)o(i);o(s[0]),o(e[0])}}return`polygon( ${n.join(", ")} )`}function Hd(e){return nt(vt,[Et(Fv(50,50,e,$v))])}function zd(e){return nt(vt,[Et(no(50-e,-_t,50+e,100+_t))])}function Gd(e){const t=100/Ur,n=[];for(let o=0;o<Ur;o++){const s=o*t;n.push(Et(no(-_t,s,100+_t,s+e)))}return nt(vt,n)}function jd(e){return nt(vt,[Et(no(-_t,50-e,100+_t,50+e))])}function Vd(e){const t=100/Fr,n=[];for(let o=0;o<Fr;o++){const s=o*t;n.push(Et(no(s,-_t,s+e,100+_t)))}return nt(vt,n)}function qd(e){return nt(vt,[Et([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function Kd(e){const t=100/$d,n=100/Ud,o=[];for(let s=0;s<Ud;s++)for(let i=0;i<$d;i++){const r=i*t+t/2,a=s*n+n/2,l=t/2*e,c=n/2*e;o.push(Et(no(r-l,a-c,r+l,a+c)))}return nt(vt,o)}function Yd(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<Fd;s++){const i=t+s/(Fd-1)*n;o.push([50+Math.cos(i)*Br,50+Math.sin(i)*Br])}return nt(vt,[Et(o)])}function Bv(){return{from:Hd(0),to:Hd(Uv)}}function Hv(){return{from:zd(0),to:zd(52)}}function zv(){return{from:Gd(0),to:Gd(100/Ur+.5)}}function Gv(){return{from:jd(0),to:jd(52)}}function jv(){return{from:Vd(0),to:Vd(100/Fr+.5)}}function Vv(){return{from:qd(0),to:qd(Br)}}function qv(){return{from:Kd(0),to:Kd(1.04)}}function Kv(){return{from:Yd(0),to:Yd(360)}}function Yv(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function Xv(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function Zv(){return{from:nt([[-60,0],[100,0],[100,100],[0,100]]),to:nt([[100,0],[260,0],[260,100],[160,100]])}}const Hr=6,zr=100,fn=zr/2,Bs=200,Xd=90,Zd=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],Jv="#101014",Qv=1.25,pn="http://www.w3.org/2000/svg";let e_=0;function Hs(e){return Math.round(e*1e3)/1e3}function Gr(e){return e/Hr*Math.PI*2-Math.PI/2}function t_(e){const n=Gr(e)+Math.PI/Hr+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function n_(e){const t=Gr(e),n=Gr(e+1);return[[fn,fn],[fn+Math.cos(t)*Bs,fn+Math.sin(t)*Bs],[fn+Math.cos(n)*Bs,fn+Math.sin(n)*Bs]]}function Jd(e,t){const n=n_(e),o=document.createElementNS(pn,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${Hs(s)} ${Hs(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",Zd[e%Zd.length]),o.setAttribute("stroke",Jv),o.setAttribute("stroke-width",String(Qv)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function o_(){const e=`os-iris-${++e_}`,t=document.createElementNS(pn,"svg");t.setAttribute("viewBox",`0 0 ${zr} ${zr}`),t.setAttribute("preserveAspectRatio","none"),t.setAttribute("aria-hidden","true"),t.style.width="100%",t.style.height="100%",t.style.display="block";const n=document.createElementNS(pn,"defs"),o=document.createElementNS(pn,"mask");o.setAttribute("id",e);const s=document.createElementNS(pn,"g"),i=document.createElementNS(pn,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let l=0;l<Hr;l++){const c=Jd(l,!0),d=Jd(l,!1);s.appendChild(c),i.appendChild(d),r.push({el:c,index:l},{el:d,index:l})}o.appendChild(s),n.appendChild(o),t.appendChild(n),t.appendChild(i);const a=document.createElement("div");return a.appendChild(t),{element:a,play:l=>r.map(({el:c,index:d})=>{const u=t_(d),f=Hs(u.x*Xd),p=Hs(u.y*Xd);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 oo="none",s_=460,i_="cubic-bezier( 0.33, 0, 0.2, 1 )",Qd=80,eu=4e3,r_=70,a_=600,tu=re("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),zs=tu.state.registry,l_=tu.state.listeners,nu=/^[a-z0-9_/-]+$/;function ou(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function c_(e){return typeof e!="number"||!Number.isFinite(e)?s_:Math.min(eu,Math.max(Qd,e))}const jr=0;function su(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?jr:Math.min(eu,Math.max(Qd,e))}function hn(e){return typeof e!="number"||!Number.isFinite(e)?r_:Math.min(a_,Math.max(0,e))}function iu(e){return typeof e.render=="function"?[]:Array.isArray(e.layers)&&e.layers.length>0?e.layers:typeof e.from=="string"&&typeof e.to=="string"?[{from:e.from,to:e.to}]:[]}function ru(e,t){const n=[],o=typeof e.from=="string"&&e.from.trim()!=="",s=typeof e.to=="string"&&e.to.trim()!=="";if(o||n.push(`${t}.from (missing — the clip-path covering the window)`),s||n.push(`${t}.to (missing — the clip-path uncovering the window)`),o&&s){const i=ou(e.from),r=ou(e.to);i===""||r===""?n.push(`${t}.from|to (must be shape functions, e.g. \`inset( … )\` or \`polygon( … )\` — bare keywords like \`none\` cannot be animated)`):i!==r&&n.push(`${t}.from|to (must use the same shape function to interpolate — got \`${i}()\` and \`${r}()\`)`)}return n}function d_(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function Ue(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):nu.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===oo&&t.push('id ("none" is reserved)'):t.push(`id (must match ${nu} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)");const o=e.render!==void 0,s=Array.isArray(e.layers),i=e.from!==void 0||e.to!==void 0;o&&typeof e.render!="function"?t.push("render (not a function)"):o&&(s||i)?t.push("render|layers|from|to (supply exactly one of: a from/to pair, a layers array, or a render function)"):o||(s&&i?t.push("layers|from|to (supply EITHER a single from/to pair OR a layers array, not both)"):s?(e.layers.length===0&&t.push("layers (empty — supply at least one matched pair)"),e.layers.forEach((r,a)=>{if(!r||typeof r!="object"){t.push(`layers[ ${a} ] (not an object)`);return}t.push(...ru(r,`layers[ ${a} ]`))})):t.push(...ru(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):d_(e.easing)||t.push("easing (not an easing the browser can parse — `Element.animate()` would throw at play time, with the covering surface already over the window)"))}Ne("WindowReveal",t,e);const n=e.id.trim().toLowerCase();zs.set(n,{...e,id:n}),cu()}function u_(e){zs.delete(e.toLowerCase())&&cu()}function au(){const e=Array.from(zs.values()),t=Y(b.WINDOW_REVEALS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-reveals` filter returned a non-array; falling back to registry list."),e)}function lu(e){return au().find(t=>t.id===e)}function f_(e){return zs.has(e)}function cu(){const e=Array.from(l_);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Ue({id:"sweep",label:E("Sweep"),description:E("A straight edge travels across the window, uncovering the page behind it."),...Xv(),duration:420}),Ue({id:"iris",label:E("Iris"),description:E("The page opens out from the centre of the window, like a camera shutter."),...Bv(),duration:520}),Ue({id:"curtain",label:E("Curtain"),description:E("Two panels part from the middle of the window and slide off the sides."),...Hv(),duration:480}),Ue({id:"blinds",label:E("Blinds"),description:E("Six horizontal slats retract at once, letting the page through between them."),...zv(),duration:560}),Ue({id:"diagonal",label:E("Diagonal"),description:E("A slanted edge sweeps off the trailing corner of the window."),...Zv(),duration:460}),Ue({id:"rise",label:E("Rise"),description:E("The page rises into the window from the bottom edge upward."),...Yv(),duration:440}),Ue({id:"shutter",label:E("Shutter"),description:E("Two panels part from the middle of the window and slide off the top and bottom."),...Gv(),duration:480}),Ue({id:"slats",label:E("Slats"),description:E("Eight vertical slats retract at once, letting the page through between them."),...jv(),duration:560}),Ue({id:"diamond",label:E("Diamond"),description:E("The page opens out from the centre of the window through a growing rhombus."),...Vv(),duration:520}),Ue({id:"mosaic",label:E("Mosaic"),description:E("The page arrives as a grid of tiles, each opening out from its own centre."),...qv(),duration:600}),Ue({id:"obturator",label:E("Camera shutter"),description:E("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:o_,duration:720,edgeLag:0}),Ue({id:"radar",label:E("Radar"),description:E("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...Kv(),duration:760});const du="desktop-mode-os-settings",p_="custom-gradient",uu="custom-image",Vr="galaxy",fu="custom",pu=[{id:"pulse",label:"Pulse",value:"#f252fc"},{id:"nebula",label:"Nebula",value:"#ec9bff"},{id:"sirius",label:"Sirius",value:"#9af2ff"},{id:"lagoon",label:"Lagoon",value:"#9f98ff"},{id:"wp-blue",label:"WordPress Blue",value:"#2271b1"},{id:"indigo",label:"Indigo",value:"#3858e9"},{id:"teal",label:"Teal",value:"#04a4cc"},{id:"emerald",label:"Emerald",value:"#059669"},{id:"amber",label:"Amber",value:"#d97706"},{id:"rose",label:"Rose",value:"#e11d48"}];function qr(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return pu;const n=[];for(const o of t)o&&typeof o=="object"&&typeof o.id=="string"&&typeof o.label=="string"&&typeof o.value=="string"&&o.id!==""&&o.label!==""&&/^#[0-9a-f]{3,8}$/i.test(o.value)&&n.push({id:o.id,label:o.label,value:o.value});return n.length>0?n:pu}function hu(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:Vr}const Kr=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],Yr=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],Gs=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],h_=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],m_=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],ee={wallpaper:Vr,accent:"pulse",customAccent:"#f252fc",dockSize:"default",windowRadius:"round",adminBarMode:"hidden",desktopLayout:"unified",dockPlacement:"bottom",dockRailRenderer:"default",desktopTheme:"",appliedThemeRecommendations:[],unfocusEffect:"darken",windowReveal:"none",windowRevealDuration:0,windowLinkRenderer:"svg-splines",windowLinkVisibility:"always",windowLinksEnabled:!0,windowLinkRaiseOnFocus:!0,windowLinkHighlight:!0,customGradient:{from:"#2271b1",to:"#7c3aed",angle:135},customImage:null,wallpaperSettings:{},libraryHdOnly:!0,ai:{enabled:!1},heartbeatRate:60,nativePostsEnabled:!1,nativePostsHiddenColumns:[],nativePagesEnabled:!1,nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,stationHomeEnabled:!1,showDesktopOnWallpaperClick:!1,mioEnabled:!1,mioStyle:{appearance:{},physics:{}},showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,navPlacement:{},navOrder:[],dockPromotedPositions:{}},mu={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},gu=["dockRailRenderer","windowReveal","accent"],wu={windowRevealDuration:{min:80,max:4e3}},g_=/^[a-z0-9_-]+$/;[...Object.keys(mu),...gu,...Object.keys(wu)];function yu(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries(mu)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of gu){const i=t[s];typeof i=="string"&&g_.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(wu)){const r=t[s];typeof r=="number"&&Number.isFinite(r)&&(o[s]=Math.min(i.max,Math.max(i.min,Math.round(r))))}return{...n,...o}}function w_(e){const t=yu(e);return typeof t.dockRailRenderer=="string"&&Rv(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==oo&&!f_(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!qr().some(n=>n.id===t.accent)&&delete t.accent,t}const y_=/^[a-z0-9_-]+$/,bu=128;function b_(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function vu(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!y_.test(n))return null;const o={};if(t.icons&&typeof t.icons=="object"){let l=0;for(const[c,d]of Object.entries(t.icons)){if(l>=bu)break;c===""||!b_(d)||(o[c]=d,l+=1)}}const s={};if(t.tokens&&typeof t.tokens=="object")for(const[l,c]of Object.entries(t.tokens))typeof c=="string"&&(s[l]=c);const i=[];if(Array.isArray(t.fonts))for(const l of t.fonts)typeof l=="string"&&l!==""&&i.push(l);const r={};if(t.iconColors&&typeof t.iconColors=="object"){let l=0;for(const[c,d]of Object.entries(t.iconColors)){if(l>=bu)break;c===""||typeof d!="string"||d===""||(r[c]=d,l+=1)}}const a=l=>typeof t[l]=="string"?t[l]:"";return{id:a("id")||n,slug:n,name:a("name")||n,version:a("version"),author:a("author"),description:a("description"),previewUrl:a("previewUrl"),cssUrl:a("cssUrl"),cssText:a("cssText"),tokens:s,fonts:i,icons:o,iconColors:r,recommendedOsSettings:yu(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload"}}function v_(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=vu(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const mn=re("desktop-mode/desktop-themes",v_);function js(){return mn}function __(){return mn.getState().themes.slice()}function _u(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return mn.getState().themes.find(n=>n.slug===t||n.id===e)??null}function Xr(){return mn.getState().activeId}function E_(e){const t=[];for(const n of e){const o=vu(n);o&&t.push(o)}mn.setState({themes:t})}function k_(e){return mn.subscribe(e)}function Vs(e){const t=js().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=Y(b.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function Zr(e){const t=js().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=Y(b.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?S_(o):null}function S_(e){const t=e.trim();if(t===""||t.length>64||/[;{}<>"'\\]/.test(t))return null;let n=0;for(const o of t)if(o==="(")n+=1;else if(o===")"&&(n-=1,n<0))return null;return n===0?t:null}const Pt={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"},A_={"desktop-mode-os-settings":Pt.OS_SETTINGS,"desktop-mode-recycle-bin":Pt.RECYCLE_BIN,"desktop-mode-bug-report":Pt.BUG_REPORT,"os-exit":Pt.EXIT_OPENSTATION,"os-pwa-install":Pt.PWA_INSTALL};function qs(e){if(typeof e!="string"||e==="")return"";const t=A_[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function C_(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Pt.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Pt?n:""}const Eu=new Map,I_=new Map;function Jr(e,t,n,o){let s=e.get(t);if(!s){if(!o)return;s=new Map,e.set(t,s)}let i=s.get(n);if(!i){if(!o)return;i=new Set,s.set(n,i)}return i}function ku(e,t,n,o){const s={channel:n,windowId:t},i=Jr(e,t,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel subscriber for "${n}" threw:`,l)}const r=Jr(e,t,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel wildcard subscriber for "${t}" threw:`,l)}}function x_(e,t,n){const o=Jr(Eu,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function L_(e,t,n){ku(Eu,e,t,n)}function T_(e,t,n){ku(I_,e,t,n)}const Su=new Set,N_=new Set,Au=new Map;function D_(e){if(!Su.has(e)){Su.add(e);const t=Au.get(e);if(t){Au.delete(e);for(const n of t)try{n.flush()}catch(o){typeof console<"u"&&console.error(`[openstation] flushing queued window-send for "${n.channel}" threw:`,o)}}}N_.delete(e)&&(L(b.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const R_="os.activity.";function Qr(e){return R_+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let O_=0;const ke={publish(e,t){L(Qr(e),t)},subscribe(e,t){const n=`os/activity-sub/${++O_}`,o=Qr(e);Z(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,Tr(o,n))}},filter(e,t,...n){return Y(Qr(e),t,...n)}},M_=4e3,P_=200,W_=1200;function Q(e){const t=ke.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return Us(()=>!n,()=>{o=$_(t)}),()=>{n=!0,o&&o()}}function $_(e){const t=H_(),n=document.createElement("os-toast");n.textContent=e.message,e.action&&(n.setAttribute("action",e.action.label),n.addEventListener("os-toast-action",()=>{e.action?.onClick(),l()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{e.onDismiss?.(),l()})),t.appendChild(n);let o=!1,s=null,i=e.duration??M_,r=0;const a=()=>{s!==null&&(window.clearTimeout(s),s=null)},l=()=>{o||(o=!0,a(),B_(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),F_()},P_))},c=()=>{o||e.persistent||s!==null||(r=Date.now(),s=window.setTimeout(l,i))},d=()=>{s!==null&&(i=Math.max(0,i-(Date.now()-r)),a())};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),n.addEventListener("os-toast-hold",u=>{if(u.detail?.held){d();return}i=Math.max(i,W_),c()}),U_(n),c(),ke.publish("os/toast-shown",{...e}),l}let Ks=null,so=0;function Cu(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(Ks=t))}function U_(e){so===0&&document.addEventListener("focusin",Cu,!0),so+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(Ks=n)}function F_(){so=Math.max(0,so-1),so===0&&document.removeEventListener("focusin",Cu,!0)}function B_(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||Ks?.isConnected===!0&&Ks.focus()}function H_(){const e=document.querySelector("os-toast-container");if(e)return e;const t=document.createElement("os-toast-container");return document.body.appendChild(t),t}const Iu="X-WP-Nonce";function xu(e,t){const n=z_();if(!n)return t;const o=G_(e);if(!o||!j_(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Iu)?t:(i.set(Iu,n),{...t??{},headers:i})}function z_(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function G_(e){try{const t=typeof window<"u"&&window.location?window.location.href:void 0;return typeof e=="string"?new URL(e,t):e instanceof URL?e:typeof Request<"u"&&e instanceof Request?new URL(e.url,t):null}catch{return null}}function j_(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Fe(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=xu(e,t);return fetch(e,s)}const V_="http://localhost/";function ot(e,t){const n=typeof window<"u"&&window.location?window.location.href:V_,o=new URL(e,n),s=t.replace(/^\/+/,""),i=s.indexOf("?"),r=i===-1?s:s.slice(0,i),a=i===-1?"":s.slice(i+1);if(o.searchParams.has("rest_route")){const l=o.searchParams.get("rest_route")??"/",c=l.endsWith("/")?l:l+"/";o.searchParams.set("rest_route",c+r)}else{const l=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=l+r}return a&&new URLSearchParams(a).forEach((c,d)=>{o.searchParams.append(d,c)}),o.toString()}const q_="os-overview",K_="os-system",Ys={mio:10,overview:20,system:30,exit:35},Y_=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="currentColor"><rect x="6" y="6" width="23" height="23" rx="4"/><rect x="35" y="6" width="23" height="23" rx="4"/><rect x="6" y="35" width="23" height="23" rx="4"/><rect x="35" y="35" width="23" height="23" rx="4"/></svg>')}`,X_=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round"><path d="M10 22h44M10 42h44"/><circle cx="24" cy="22" r="7" fill="currentColor" stroke="none"/><circle cx="42" cy="42" r="7" fill="currentColor" stroke="none"/></svg>')}`,Z_="os-exit";function J_(){return{id:Z_,title:E("Exit OpenStation"),navKind:"control",locked:!0,order:Ys.exit,icon:"dashicons-exit",onOpen:()=>{Q_()}}}async function Q_(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){ea(t);return}const n=new URLSearchParams;n.set("action","save-openstation"),n.set("nonce",e.nonce),n.set("enabled","");let o=t;try{const s=await fetch(e.ajaxUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),credentials:"same-origin"});if(s.ok){const i=await s.json();i?.success&&i.data?.redirect&&(o=i.data.redirect)}}catch{}ea(o)}function ea(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const Lu=800;function eE(e,t=Lu){window.setTimeout(()=>{if(e){ea(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const tE="desktop_mode_nonces",nE="desktop-mode/v1",oE=3e4,sE=3,gn=re("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function Tu(){return window.wp?.os?.config??{}}function iE(){const e=Tu().restUrl;return e?ot(e,nE):null}function rE(){gn.state.negativeConfirms=0}async function aE(){const e=gn.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=sE)return;const t=iE();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<oE)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await Fe(t,{credentials:"same-origin"},{silent:!0,source:"desktop-mode/plugin-presence"});if(o.status!==404){e.negativeConfirms+=1;return}if((await o.json())?.code!=="rest_no_route"){e.negativeConfirms+=1;return}lE()}catch{}finally{e.confirmInFlight=!1}}}function lE(){if(!gn.state.exiting){gn.state.exiting=!0,eE(Tu().adminUrl||"");try{Q({message:E("OpenStation is no longer active. Returning to the WordPress dashboard…"),duration:Lu})}catch{}}}function cE(){if(gn.state.booted)return;gn.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[tE]!==void 0){rE();return}aE()}})}const dE=0,ta=40,Nu=250,uE=120,fE=250,io="os-window__loading",Xs="os-window__loading--visible",Zs=re("desktop-mode/window-reveal-active",()=>({id:oo,duration:jr}));function Du(e){Zs.state.id=typeof e=="string"&&e!==""?e:oo}function pE(){const e=Zs.state.id;return!e||e===oo?null:lu(e)??null}function Ru(e){Zs.state.duration=su(e)}function hE(){return Zs.state.duration}function mE({osSettings:e}){const t=e.getOsSettingsSnapshot();Du(t.windowReveal),Ru(t.windowRevealDuration),e.subscribeOsSettings(n=>{Du(n.windowReveal),Ru(n.windowRevealDuration)})}const wn="os-window__reveal",ro="os-window__reveal--edge",gE="os-window__reveal--custom",Wt="os-window__body--revealing",na="data-os-reveal",oa="data-os-reveal-layer",kt=new WeakMap,Ou=re("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function Mu(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const wE="--os-window-reveal-duration",yE="--os-window-reveal-edge-thickness";function Pu(e){const t=e.trim();if(t==="")return 0;const n=/^(-?\d*\.?\d+)\s*(ms|s)?$/i.exec(t);if(!n)return 0;const o=Number(n[1]);return Number.isFinite(o)?n[2]?.toLowerCase()==="s"?o*1e3:o:0}function bE(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return su(Pu(window.getComputedStyle(e).getPropertyValue(wE)))}catch{return 0}}function vE(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function _E(e,t){const n=vE(e,yE);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return hn(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return hn(t*Number(s[1]));const i=Pu(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?hn(i):null}function Wu(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return!1;try{const t=window.getComputedStyle(e),n=t.backgroundImage;if(n&&n!=="none")return!1;const o=/^rgba?\(([^)]+)\)$/.exec(t.backgroundColor.trim());if(!o)return!1;const s=o[1].split(/[,\s/]+/).filter(Boolean);return s.length>=4&&Number(s[3])===0}catch{return!1}}function EE(e,t){const n=c_(t.duration),o=hE(),s=o!==jr?o:bE(e)||n,i=_E(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=hn(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:hn(r*s/n)}}function $u(e){return e.querySelector(":scope .os-window__body")}function kE(e){return e.querySelector(`:scope .${wn}:not( .${ro} )`)}function SE(e){return e.querySelector(`:scope .${ro}`)}function Uu(e){return Array.from(e.querySelectorAll(`:scope .${wn}:not( .${ro} )`))}function Fu(e){return Array.from(e.querySelectorAll(`:scope .${ro}`))}function sa(e){return Array.from(e.querySelectorAll(`:scope .${wn}`))}function Bu(e,t,n,o){const s=document.createElement("div");s.className=o?`${wn} ${ro}`:wn;const i=o?e.edgeColor:t.color??e.surfaceColor;return typeof i=="string"&&i!==""&&(s.style.background=i),s.setAttribute("aria-hidden","true"),s.setAttribute(na,e.id),s.setAttribute(oa,String(n)),s.style.clipPath=t.from,s}function AE(){const e=pE();if(!e)return[];if(typeof e.render=="function"){let o;try{o=e.render()}catch(i){return typeof console<"u"&&console.error(`[openstation] window reveal "${e.id}" render threw:`,i),[]}if(!o?.element||typeof o.play!="function")return[];const s=o.element;return s.classList.add(wn),s.classList.add(gE),s.setAttribute("aria-hidden","true"),s.setAttribute(na,e.id),s.setAttribute(oa,"0"),Ou.set(s,o.play),[s]}const t=iu(e);if(t.length===0)return[];const n=[];return hn(e.edgeLag)>0&&t.forEach((o,s)=>n.push(Bu(e,o,s,!0))),t.forEach((o,s)=>n.push(Bu(e,o,s,!1))),n}function CE(e){const t=$u(e);if(t){t.classList.remove(Wt);for(const n of sa(t))kt.get(n)?.cancel(),kt.delete(n),n.remove();for(const n of AE())t.appendChild(n)}}function Hu(e){const t=$u(e);if(!t)return;const n=kE(t);if(!n)return;let o;try{o=lu(n.getAttribute(na)??"")}catch(_){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",_)}if(!o){sa(t).forEach(_=>_.remove());return}const i=!!t.querySelector(`:scope .${io}`)?.classList.contains(Xs)?Nu:0,{duration:r,edgeLag:a}=EE(t,o),l=o.easing??i_,c=Ou.get(n);if(c){t.classList.add(Wt);const _=()=>{kt.delete(n),n.remove(),t.classList.remove(Wt)};if(Mu()||typeof n.animate!="function"){window.setTimeout(_,i);return}let O=[];try{O=c({duration:r,easing:l,delay:i})}catch(P){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,P)}if(O.length===0){_();return}O[0].addEventListener("finish",_),O[0].addEventListener("cancel",()=>{kt.delete(n),t.classList.remove(Wt)}),kt.set(n,O[0]);return}const d=SE(t);d&&(a<=0||Wu(d))&&Fu(t).forEach(_=>_.remove()),Wu(n)&&Uu(t).forEach(_=>_.remove());const u=sa(t);if(u.length===0)return;t.classList.add(Wt);const f=()=>{for(const _ of u)kt.delete(_),_.remove();t.classList.remove(Wt)};if(Mu()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,w=iu(o),m=(_,O)=>{const P=w[Number(_.getAttribute(oa))];if(!P)return _.remove(),null;_.style.willChange="clip-path";let $;try{$=_.animate([{clipPath:P.from},{clipPath:P.to}],{duration:O,easing:p,delay:i,fill:"both"})}catch(F){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,F),_.remove(),null}return kt.set(_,$),$},h=Uu(t).map(_=>m(_,r)).filter(_=>_!==null),y=Fu(t).map(_=>m(_,r+a)).filter(_=>_!==null),v=h[0]??null,A=y[0]??null;if(!v&&!A){f();return}(A??v)?.addEventListener("finish",f);const D=()=>{for(const _ of u)kt.delete(_);t.classList.remove(Wt)};v?.addEventListener("cancel",D),A?.addEventListener("cancel",D)}const IE="os-window-tab-change";function zu(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function Gu(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function ju(e,t){return`${e.id||"os-window"}-tab-${Gu(t)}`}function Vu(e,t){return`${e.id||"os-window"}-panel-${Gu(t)}`}function xE(e){const t=e.querySelector(".os-window__tab-plate");if(!t)return;const n=e.querySelector(".os-window__tab--active");if(!n){t.dataset.empty="",e.dataset.tabPlateEmpty="";return}delete t.dataset.empty,delete e.dataset.tabPlateEmpty,e.style.setProperty("--_tab-plate-x",`${n.offsetLeft}px`),e.style.setProperty("--_tab-plate-w",`${n.offsetWidth}px`),e.style.setProperty("--_tab-strip-w",`${e.clientWidth}px`),n.offsetWidth>0&&(t.dataset.placed="")}function LE(e){if(e){if(e.querySelector(":scope > .os-window__tab")){e.setAttribute("role","tablist");const t=e.dataset.tablistLabel;t&&e.setAttribute("aria-label",t);return}e.setAttribute("role","presentation"),e.removeAttribute("aria-label")}}function TE(e){const t=zu(e);if(t.length===0)return;const n=t.find(o=>o.classList.contains("os-window__tab--active"))??t[0];for(const o of t){const s=o===n?0:-1;o.tabIndex!==s&&(o.tabIndex=s)}}function qu(e){const t=new Map;for(const n of zu(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function Ku(e){const t=e.querySelector(".os-window__body");return t?Array.from(t.querySelectorAll("os-tabpanel[ for ]")).filter(n=>!n.parentElement?.closest("os-tabpanel, os-tabs")):[]}function NE(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of qu(n)){const r=s===t;o=o||r,i.classList.toggle("os-window__tab--active",r),i.setAttribute("aria-selected",r?"true":"false")}if(o){for(const s of Ku(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}TE(n),xE(n),e.dispatchEvent(new CustomEvent(IE,{bubbles:!0,detail:{value:t}}))}}function DE(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=qu(o),i=Array.from(s.entries()).find(([,d])=>d.classList.contains("os-window__tab--active"))?.[0];let r=o.querySelector(".os-window__tab-plate");for(const d of t){let u=s.get(d.value);if(u)s.delete(d.value);else{const f=document.createElement("button");f.type="button",u=f,u.className="os-window__tab",u.dataset.kind="panel",u.dataset.panel=d.value,u.setAttribute("role","tab"),u.setAttribute("aria-selected","false"),u.tabIndex=-1}u.textContent!==d.label&&(u.textContent=d.label),u.id=ju(e,d.value),u.setAttribute("aria-controls",Vu(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();LE(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of Ku(e)){const u=d.getAttribute("for");u&&(d.id=Vu(e,u),a?d.setAttribute("aria-labelledby",ju(e,u)):d.removeAttribute("aria-labelledby"))}const l=d=>d!==void 0&&t.some(u=>u.value===d),c=[n,i,t[0]?.value].find(l);c!==void 0&&NE(e,c)}const ao="os-window__body--loading",ia="os-window__body--loading-out",ra="data-os-loading-at",Yu="data-os-loading-cycle";function Js(e){return e.getAttribute(Yu)??"0"}function RE(e){e.setAttribute(ra,String(Date.now())),e.setAttribute(Yu,String(Number(Js(e))+1))}function OE(e,t){const n=Number(e.getAttribute(ra)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=uE-o;if(s<=0){t.classList.add(Xs);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(ao)&&t.classList.add(Xs)},s)}const ME=Symbol.for("desktop-mode/window-config");function PE(e){return e[ME]}function aa(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function Xu(){const e=document.createElement("div");e.className=io,e.setAttribute("role","status"),e.setAttribute("aria-live","polite");const t=document.createElement("os-spinner");return t.setAttribute("preset","classic"),t.setAttribute("size","clamp(96px, 14vw, 192px)"),t.setAttribute("label",E("Loading window content")),e.appendChild(t),e}function WE(e){let t=Xu();const n={windowId:e.id,config:e};if(typeof e.loading?.render=="function")try{e.loading.render(t,n)}catch(o){typeof console<"u"&&console.error(`[openstation] loading.render threw for "${e.id}":`,o)}try{const o=Y(b.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[openstation] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains(io)&&t.classList.add(io),t}function Zu(e){e.querySelector(":scope .os-window__loading")?.remove()}function Ju(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=PE(e),s=o?WE(o):Xu();t.appendChild(s),OE(t,s)}const Qu=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],Qs="osHadFullscreenBeforeOverview";function ef(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[Qs]="true",aa()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function tf(e){if(e.element.dataset[Qs]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[Qs],aa();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[Qs],aa()}}function la(e,t=!0){t&&tf(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function nf(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function of(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function $E(e){if(e._overviewActive)return;sf(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,L(b.OVERVIEW_ENTERING,{}),L(b.DOCK_REFRESH_ACTIVE,{});for(const c of Qu){const d=document.getElementById(c);d&&(d.inert=!0)}nf(!0),of(e,!0),e._overviewSnapshot.clear();for(const c of t)e._overviewSnapshot.set(c.id,{transform:c.element.style.transform||"",transition:c.element.style.transition||""});for(const c of t)ef(c);const n=e._desktop.getBoundingClientRect(),o=Array.from(document.querySelectorAll(".os-dock"));let s=0;for(const c of o){const d=c.getBoundingClientRect(),u=d.bottom>n.top&&d.top<n.bottom,f=d.height>d.width;u&&f&&(s+=d.width)}const i=new DOMRect(0,0,n.width+s,n.height);e._desktop.classList.add("os-area--overview"),document.getElementById("os-shell")?.classList.add("os-shell--overview"),e._overviewTopBar=rf(e),e._desktop.appendChild(e._overviewTopBar);const a=Mr(t,i,Od);e._overviewLabels.clear();for(const c of a){const d=c.win.element;d.classList.add("os-window--overview");const u=c.x-d.offsetLeft,f=c.y-d.offsetTop;d.style.transform=`translate(${u}px, ${f}px) scale(${c.scale})`;const p=ca(c);d.insertAdjacentElement("afterend",p),e._overviewLabels.set(c.win.id,p)}const l=c=>{const d=c.target,u=d?.closest(".os-window--overview");return u?{id:u.id.replace(/^wp-window-/,""),element:u}:d===e._desktop?{id:"backdrop",element:e._desktop}:null};e._overviewPointerDownHandler=c=>{if(c.button!==0){e._overviewPressTarget=null;return}e._overviewPressTarget=l(c),e._overviewPressTarget&&(c.preventDefault(),c.stopPropagation())},e._overviewPointerUpHandler=c=>{if(c.button!==0)return;const d=e._overviewPressTarget;if(e._overviewPressTarget=null,!d)return;const u=d.element.getBoundingClientRect();if(!(c.clientX>=u.left&&c.clientX<=u.right&&c.clientY>=u.top&&c.clientY<=u.bottom))return;if(c.preventDefault(),c.stopPropagation(),d.id==="backdrop"){$t(e);return}const p=e.getById(d.id);L(b.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),$t(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){$t(e);return}if(c.key==="Enter"){const u=c.target?.ownerDocument||document;if(u.activeElement&&u.activeElement.tagName==="BUTTON")return;if(c.preventDefault(),e._overviewAddTileFocused){af(e);return}$t(e)}},e._desktop.addEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._desktop.addEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewClickBlocker=c=>{c.target?.closest(".os-overview-top-bar")||(c.stopPropagation(),c.preventDefault())},e._desktop.addEventListener("click",e._overviewClickBlocker,!0),document.addEventListener("keydown",e._overviewKeyHandler),e._lastOverviewHoverId=null,e._overviewMouseHandler=c=>{const u=c.target?.closest(".os-window--overview"),f=u?u.id.replace(/^wp-window-/,""):null;f!==e._lastOverviewHoverId&&(e._lastOverviewHoverId&&L(b.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&L(b.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&L(b.OVERVIEW_ENTERED,{})},300)}function sf(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function UE(e){e._overviewEnterTimeoutId!==null&&(window.clearTimeout(e._overviewEnterTimeoutId),e._overviewEnterTimeoutId=null),e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null),e._overviewExitFinalizer=null}function rf(e){const t=document.createElement("div");t.className="os-overview-top-bar";const n=document.createElement("div");n.className="os-overview-top-bar__list",t.appendChild(n);for(const s of e._desktops)n.appendChild(FE(e,s));const o=document.createElement("button");return o.type="button",o.className="os-overview-top-bar__tile os-overview-top-bar__tile--add",e._overviewAddTileFocused&&o.classList.add("os-overview-top-bar__tile--cursor"),o.setAttribute("aria-label",E("Add new desktop")),o.innerHTML='<span class="os-overview-top-bar__tile-plus" aria-hidden="true">+</span>',o.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),af(e)}),n.appendChild(o),t}function af(e){const t=uf(e);e._overviewAddTileFocused=!1,lf(e,t.id)}function FE(e,t){const n=document.createElement("div");n.className="os-overview-top-bar__tile-wrapper";const o=document.createElement("button");o.type="button",o.className="os-overview-top-bar__tile",o.dataset.desktopId=t.id,t.id===e._activeDesktopId&&!e._overviewAddTileFocused&&o.classList.add("os-overview-top-bar__tile--active"),o.setAttribute("aria-label",le(E("Switch to %s"),t.label));const s=document.createElement("span");s.className="os-overview-top-bar__tile-preview";const i=e._stack.filter(c=>c.config.desktopId===t.id).length;if(i>0){const c=document.createElement("span");c.className="os-overview-top-bar__tile-count",c.textContent=String(i),s.appendChild(c)}o.appendChild(s);const r=document.createElement("span");r.className="os-overview-top-bar__tile-label",r.textContent=t.label,o.appendChild(r),o.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),!r.hasAttribute("contenteditable")&&lf(e,t.id)});const a=document.createElement("button");a.type="button",a.className="os-overview-top-bar__tile-rename",a.setAttribute("aria-label",le(E("Rename %s"),t.label)),a.innerHTML=Ot("edit",{size:14}),a.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),BE(e,r,t)});const l=document.createElement("button");return l.type="button",l.className="os-overview-top-bar__tile-close",l.setAttribute("aria-label",le(E("Close %s"),t.label)),l.innerHTML=Ot("close",{size:16}),l.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),hf(e,t.id),ei(e)}),n.appendChild(o),n.appendChild(a),n.appendChild(l),n}function BE(e,t,n){if(t.hasAttribute("contenteditable"))return;t.setAttribute("contenteditable","true");try{t.contentEditable="plaintext-only"}catch{}t.spellcheck=!1,t.focus();const o=t.ownerDocument.defaultView,s=t.ownerDocument.createRange();s.selectNodeContents(t);const i=o?.getSelection();i?.removeAllRanges(),i?.addRange(s);let r=!1;const a=l=>{r||(r=!0,t.removeAttribute("contenteditable"),l&&ff(e,n.id,t.textContent??""),e._overviewActive&&ei(e))};t.addEventListener("keydown",l=>{l.stopPropagation(),(l.key==="Enter"||l.key==="Escape")&&(l.preventDefault(),a(l.key==="Enter"))}),t.addEventListener("blur",()=>a(!0)),t.addEventListener("click",l=>l.stopPropagation())}function ei(e){if(!e._overviewTopBar)return;const t=rf(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function lf(e,t){pf(e,t),$t(e)}function ca(e){const t=document.createElement("div");t.className="os-overview-label",t.dataset.windowId=e.win.id;const n=e.win.element.offsetWidth*e.scale;t.style.left=`${e.x}px`,t.style.top=`${e.y-34}px`,t.style.width=`${n}px`;const o=e.win.config.icon||"dashicons-admin-generic",s=document.createElement("span");s.className=`os-overview-label__icon dashicons ${o}`,s.setAttribute("aria-hidden","true"),t.appendChild(s);const i=document.createElement("span");i.className="os-overview-label__title",i.textContent=e.win.config.title,t.appendChild(i);const r=e.win.getExternalTabCount();if(r>0){const a=document.createElement("span");a.className="os-overview-label__meta",a.textContent=le(un("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function $t(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,L(b.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),L(b.DOCK_REFRESH_ACTIVE,{}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of Qu){const r=document.getElementById(i);r&&(r.inert=!1)}nf(!1),of(e,!1);for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform)}t&&(t.state==="minimized"&&(tf(t),t.restore()),e.focus(t),n&&t.maximize());for(const i of e._stack)i.state==="minimized"&&i.element.classList.remove("os-window--overview");for(const i of e._overviewLabels.values())i.classList.add("os-overview-label--out");e._overviewTopBar&&e._overviewTopBar.classList.add("os-overview-top-bar--out");const s=280;e._overviewExitFinalizer=()=>{for(const i of e._stack)i.element.classList.remove("os-window--overview"),la(i,i.config.desktopId===e._activeDesktopId);for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),e._overviewTopBar&&(e._overviewTopBar.remove(),e._overviewTopBar=null),e._overviewClickBlocker&&(e._desktop.removeEventListener("click",e._overviewClickBlocker,!0),e._overviewClickBlocker=null),L(b.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>sf(e),s),e._overviewPointerDownHandler&&(e._desktop.removeEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._overviewPointerDownHandler=null),e._overviewPointerUpHandler&&(e._desktop.removeEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewPointerUpHandler=null),e._overviewPressTarget=null,e._overviewKeyHandler&&(document.removeEventListener("keydown",e._overviewKeyHandler),e._overviewKeyHandler=null),e._overviewMouseHandler&&(e._desktop.removeEventListener("mouseover",e._overviewMouseHandler),e._overviewMouseHandler=null),e._lastOverviewHoverId&&(L(b.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function HE(e){return[...e._desktops]}function cf(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function zE(e){return cf(e).id}function df(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&la(t)}function da(e){for(const t of e._stack)df(e,t)}function uf(e){e._desktopSeq++;const t={id:`desktop-${e._desktopSeq}`,label:le(E("Desktop %d"),e._desktopSeq)};return e._desktops.push(t),L(b.DESKTOP_CREATED,{desktopId:t.id}),t}const GE=64;function ff(e,t,n){const o=e._desktops.find(r=>r.id===t);if(!o)return!1;const s=n.trim().slice(0,GE);if(!s||s===o.label)return!1;const i=o.label;return o.label=s,L(b.DESKTOP_RENAMED,{desktopId:t,label:s,previousLabel:i}),!0}function pf(e,t,n){if(t===e._activeDesktopId||!e._desktops.some(s=>s.id===t))return;const o=e._activeDesktopId;if(e._activeDesktopId=t,e._overviewActive)mf(e),ei(e);else{da(e),n?.direction&&jE(e,n.direction);const s=[...e._stack].reverse().find(r=>r.config.desktopId===t&&r.state!=="minimized");s&&e.focus(s);const i=e._desktops.find(r=>r.id===t);i&&bv(e._desktop,i.label)}L(b.DESKTOP_SWITCHED,{from:o,to:t})}function jE(e,t){const n=e._desktop,o=t==="next"?"os-area--sliding-from-right":"os-area--sliding-from-left";n.classList.remove("os-area--sliding-from-right","os-area--sliding-from-left"),n.offsetWidth,n.classList.add(o);const s=i=>{i.animationName.startsWith("os-area-slide-from-")&&(n.classList.remove(o),n.removeEventListener("animationend",s))};n.addEventListener("animationend",s)}function hf(e,t){if(e._desktops.length<=1)return;const n=e._desktops.findIndex(r=>r.id===t);if(n===-1)return;const o=n>0?n-1:1,s=e._desktops[o];for(const r of e._stack)r.config.desktopId===t&&(r.config.desktopId=s.id);e._desktops.splice(n,1),e._activeDesktopId===t&&(e._activeDesktopId=s.id),e._overviewActive?mf(e):da(e),L(b.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function mf(e){for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform,a.element.style.transition=r.transition,a.element.classList.remove("os-window--overview"),la(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),da(e);const t=e._stack.filter(i=>i.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const i of t)e._overviewSnapshot.set(i.id,{transform:i.element.style.transform||"",transition:i.element.style.transition||""}),ef(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=Mr(t,o,Od);for(const i of s){const r=i.win.element;r.classList.add("os-window--overview");const a=i.x-r.offsetLeft,l=i.y-r.offsetTop;r.style.transform=`translate(${a}px, ${l}px) scale(${i.scale})`;const c=ca(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function VE(e,t,n){if(t.length===0)return;e._desktops=t.map(s=>({...s})),e._activeDesktopId=t.some(s=>s.id===n)?n:t[0].id;let o=0;for(const s of t){const i=s.id.match(/^desktop-(\d+)$/);if(i){const r=parseInt(i[1],10);Number.isFinite(r)&&r>o&&(o=r)}}e._desktopSeq=Math.max(e._desktopSeq,o)}function qE(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;L(b.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=e._desktop.getBoundingClientRect(),o=30,s=30,i=Math.min(Math.round(n.width*.7),1100),r=Math.min(Math.round(n.height*.75),750),a=Math.max(1,Math.floor((n.width-i-o)/s)),l=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(a,l);t.forEach((u,f)=>{const p=f%Math.max(1,c);u.element.style.left=`${o+p*s}px`,u.element.style.top=`${o+p*s}px`,u.element.style.width=`${i}px`,u.element.style.height=`${r}px`});const d=e.getFocused();d&&e.focus(d),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"cascade"}})),L(b.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function KE(e){const t=e._stack.filter(f=>f.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const f of t)f.state==="minimized"&&f.restore(),f.state==="fullscreen"&&f.toggleFullscreen(),f.state==="maximized"&&f.toggleMaximize();const n=e._desktop.getBoundingClientRect(),o=kv(t.length,n.width,n.height),s=Y(b.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=_v(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;L(b.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,l=12,c=Math.floor((n.width-a*2-l*(i-1))/i),d=Math.floor((n.height-a*2-l*(r-1))/r);t.forEach((f,p)=>{const w=p%i,m=Math.floor(p/i);f.element.style.left=`${a+w*(c+l)}px`,f.element.style.top=`${a+m*(d+l)}px`,f.element.style.width=`${c}px`,f.element.style.height=`${d}px`});const u=e.getFocused();u&&e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"tile"}})),L(b.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}const gf="desktop-mode-snap-to-grid";function YE(){try{return window.localStorage.getItem(gf)==="1"}catch{return!1}}function XE(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(gf,t?"1":"0")}catch{}L(b.ARRANGE_SNAP_CHANGED,{enabled:t})}}function ZE(e){if(!e._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const t=e._desktop.getBoundingClientRect(),n=t.width>=t.height?12:8,o={cellWidth:Math.max(40,Math.round(t.width/n)),cellHeight:Math.max(40,Math.round(t.height/Math.round(n*.66)))},s=Y(b.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=Ev(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function JE(e,t,n){if(e._splitOverviewActive)return;e._splitOverviewActive=!0,e._splitOverviewAnchor=t,e._splitOverviewZone=n;const o=e._stack.filter(a=>a!==t&&a.state!=="minimized"&&a.config.desktopId===e._activeDesktopId);if(o.length===0){wf(e);return}e._splitOverviewSnapshot.clear();for(const a of o)e._splitOverviewSnapshot.set(a.id,{transform:a.element.style.transform||"",transition:a.element.style.transition||""});e._desktop.classList.add("os-area--split-overview");const s=o0(e,n),i=Mr(o,s,0);e._splitOverviewLabels.clear();for(const a of i){const l=a.win.element;l.classList.add("os-window--overview");const c=a.x-l.offsetLeft,d=a.y-l.offsetTop;l.style.transform=`translate(${c}px, ${d}px) scale(${a.scale})`;const u=ca(a);l.insertAdjacentElement("afterend",u),e._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const l=a.target,c=l?.closest(".os-window--overview");return c?{id:c.id.replace(/^wp-window-/,""),element:c}:l?{id:"dismiss",element:e._desktop}:null};e._splitOverviewPointerDown=a=>{if(a.button!==0){e._splitOverviewPressTarget=null;return}e._splitOverviewPressTarget=r(a),e._splitOverviewPressTarget&&(a.preventDefault(),a.stopPropagation())},e._splitOverviewPointerUp=a=>{if(a.button!==0)return;const l=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!l)return;const c=l.element.getBoundingClientRect();if(!(a.clientX>=c.left&&a.clientX<=c.right&&a.clientY>=c.top&&a.clientY<=c.bottom))return;if(a.preventDefault(),a.stopPropagation(),l.id==="dismiss"){lo(e);return}const u=e.getById(l.id);if(!u){lo(e);return}QE(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&lo(e)},e._splitOverviewClickBlocker=a=>{a.stopPropagation(),a.preventDefault()},e._desktop.addEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._desktop.addEventListener("pointerup",e._splitOverviewPointerUp,!0),e._desktop.addEventListener("click",e._splitOverviewClickBlocker,!0),document.addEventListener("keydown",e._splitOverviewKey)}function QE(e,t){const n=e._splitOverviewZone;if(!n){lo(e);return}const o=n==="left"?"right":"left";t.element.style.transform="",t.element.classList.remove("os-window--overview"),t.applySnap(o),e._splitOverviewSnapshot.delete(t.id),e.focus(t),L(b.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),lo(e)}function lo(e){if(!e._splitOverviewActive)return;e._splitOverviewActive=!1;for(const[n,o]of e._splitOverviewSnapshot){const s=e.getById(n);s&&(s.element.style.transform=o.transform)}for(const n of e._splitOverviewLabels.values())n.classList.add("os-overview-label--out");e._desktop.classList.remove("os-area--split-overview"),window.setTimeout(()=>{for(const n of e._stack)e._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("os-window--overview");for(const n of e._splitOverviewLabels.values())n.remove();wf(e)},260),e._splitOverviewPointerDown&&(e._desktop.removeEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._splitOverviewPointerDown=null),e._splitOverviewPointerUp&&(e._desktop.removeEventListener("pointerup",e._splitOverviewPointerUp,!0),e._splitOverviewPointerUp=null),e._splitOverviewClickBlocker&&(e._desktop.removeEventListener("click",e._splitOverviewClickBlocker,!0),e._splitOverviewClickBlocker=null),e._splitOverviewKey&&(document.removeEventListener("keydown",e._splitOverviewKey),e._splitOverviewKey=null),e._splitOverviewPressTarget=null}function wf(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const yf=30,e0=260;function t0(e,t){return e<=t.left+yf?"left":e>=t.right-yf?"right":null}function n0(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?0:n.width-o,y:0,width:o,height:s}}function o0(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return t==="left"?new DOMRect(o,0,o,s):new DOMRect(0,0,o,s)}function s0(e,t){if(e._snapPendingZone===t&&e._snapPreviewEl)return;if(e._snapPendingZone=t,!e._snapPreviewEl){const o=document.createElement("div");o.className="os-snap-preview",o.setAttribute("aria-hidden","true"),e._desktop.appendChild(o),e._snapPreviewEl=o,Promise.resolve().then(()=>{o.classList.add("os-snap-preview--visible")})}const n=n0(e,t);e._snapPreviewEl.style.left=`${n.x}px`,e._snapPreviewEl.style.top=`${n.y}px`,e._snapPreviewEl.style.width=`${n.width}px`,e._snapPreviewEl.style.height=`${n.height}px`,e._snapPreviewEl.dataset.zone=t}function ua(e){if(!e._snapPreviewEl){e._snapPendingZone=null;return}const t=e._snapPreviewEl;e._snapPreviewEl=null,e._snapPendingZone=null,t.classList.remove("os-snap-preview--visible"),window.setTimeout(()=>{t.remove()},e0)}function i0(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=t0(n,o),i=e._snapPendingZone;s?(s0(e,s),i!==s&&L(b.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(ua(e),L(b.SNAP_ZONE_CANCELED,{windowId:t.id}))}function r0(e,t){const n=e._snapPendingZone;return n?(ua(e),t.state==="normal"&&(t._savedGeometry={x:t.element.offsetLeft,y:t.element.offsetTop,width:t.element.offsetWidth,height:t.element.offsetHeight}),t.applySnap(n),L(b.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{JE(e,t,n)}),!0):!1}function a0(e){e._snapPendingZone&&ua(e)}const bf="desktop-mode-native-window-geometry",vf=64,st=8192;function ti(){try{const e=window.localStorage.getItem(bf);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function _f(e){try{window.localStorage.setItem(bf,JSON.stringify(e))}catch{}}function fa(e){if(!e)return null;const n=ti()[e];if(!n)return null;const o=Number(n.width),s=Number(n.height);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0||s<=0||o>st||s>st)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<=st&&a<=st;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function Ef(e,t){if(!e)return;const n=Math.round(Number(t.width)),o=Math.round(Number(t.height));if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0||n>st||o>st)return;const s=ti(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,l=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===l||(co(s,e,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),uo(s))}function kf(e,t){if(!e)return;const n=Math.round(Number(t.x)),o=Math.round(Number(t.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>st||o>st)return;const s=ti(),i=s[e];i&&(i.x===n&&i.y===o||(co(s,e,{...i,x:n,y:o}),uo(s)))}function Sf(e,t,n){if(!e)return;const o=ti(),s=o[e];if(!s){if(t===null||!n)return;const i=Math.round(Number(n.width)),r=Math.round(Number(n.height));if(!Number.isFinite(i)||!Number.isFinite(r)||i<=0||r<=0||i>st||r>st)return;co(o,e,{width:i,height:r,state:t}),uo(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;co(o,e,r),uo(o);return}s.state!==t&&(co(o,e,{...s,state:t}),uo(o))}function co(e,t,n){delete e[t],e[t]=n}function uo(e){const t=Object.keys(e);if(t.length>vf){const n={};for(const o of t.slice(-vf))n[o]=e[o];_f(n);return}_f(e)}function l0(e,t,n,o,s){const i=ta-n,r=o-ta,a=Math.max(i,Math.min(e,r)),l=dE,c=s-ta,d=Math.max(l,Math.min(t,c));return{x:a,y:d}}const Af=100,ni=30;class c0{constructor(t){this._stack=[],this._cascadeMinimized=new WeakSet,this._cascadeDepth=0,this.cascadeIndex=0,this._pendingRestoreState=new Map,this._desktops=[{id:"desktop-1",label:"Desktop 1"}],this._activeDesktopId="desktop-1",this._desktopSeq=1,this.onToggleStartupRequested=null,this.desktopResizeObserver=null,this._reflowRestoreTimer=null,this._snapEnabled=YE(),this._overviewActive=!1,this._overviewSnapshot=new Map,this._overviewLabels=new Map,this._overviewPointerDownHandler=null,this._overviewPointerUpHandler=null,this._overviewKeyHandler=null,this._overviewPressTarget=null,this._overviewClickBlocker=null,this._overviewTopBar=null,this._overviewMouseHandler=null,this._lastOverviewHoverId=null,this._overviewAddTileFocused=!1,this._overviewEnterTimeoutId=null,this._overviewExitTimeoutId=null,this._overviewExitFinalizer=null,this._snapPendingZone=null,this._snapPreviewEl=null,this._splitOverviewActive=!1,this._splitOverviewAnchor=null,this._splitOverviewZone=null,this._splitOverviewSnapshot=new Map,this._splitOverviewLabels=new Map,this._splitOverviewPointerDown=null,this._splitOverviewPointerUp=null,this._splitOverviewPressTarget=null,this._splitOverviewClickBlocker=null,this._splitOverviewKey=null,this._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const t=this._desktop.ownerDocument?.activeElement??null;if(!t||t.tagName!=="IFRAME")return;const n=t.closest(".os-window");if(!n)return;const o=n.id.replace(/^wp-window-/,""),s=this.getById(o);s&&(this._overviewActive||this.getFocused()!==s&&this.focus(s))},0)})}reflowStatefulWindows(){if(!this._overviewActive){for(const t of this._stack){const n=t.element.parentElement;if(n){if(t.state==="maximized")t.element.classList.add("os-window--reflowing"),t.element.style.width=`${n.clientWidth}px`,t.element.style.height=`${n.clientHeight}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("os-window--reflowing");const o=Math.floor(n.clientWidth/2),s=n.clientHeight,i=t.state==="snapped-left"?0:o;t.element.style.left=`${i}px`,t.element.style.top="0px",t.element.style.width=`${o}px`,t.element.style.height=`${s}px`}else if(t.state==="normal"){const o=parseInt(t.element.style.left,10)||0,s=parseInt(t.element.style.top,10)||0,i=t.element.offsetWidth||0,r=l0(o,s,i,n.clientWidth,n.clientHeight);(o!==r.x||s!==r.y)&&(t.element.classList.add("os-window--reflowing"),t.element.style.left=`${r.x}px`,t.element.style.top=`${r.y}px`)}}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const t of this._stack)t.element.classList.remove("os-window--reflowing")},140)}}async open(t){if(!t||typeof t!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(t===null?"null":typeof t));if(typeof t.id!="string"||t.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof t.url!="string"||t.url==="")throw new TypeError('windowManager.open(): config.url must be a non-empty string. Pass an admin URL (e.g. "/wp-admin/edit.php") or a hash fragment (e.g. "#my-window") for native windows.');if(typeof t.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=t.baseId||t.id,o=this.getByBaseIdOnActiveDesktop(n);if(o){const i=o.state==="minimized";this.focus(o),i&&o.restore();let r=!1;if(!o.config.native){const l=Ws(t.url);l===Ws(o.getCurrentUrl())||l===Ws(o.config.url||"")||l===Ws(o.config.parentUrl??o.config.url??"")||(r=o.navigateTo(t.url))}t.params&&(o.config.params={...t.params});const a={windowId:o.id,baseId:n,wasMinimized:i,navigated:r,params:o.config.params??{}};return document.dispatchEvent(new CustomEvent("os-window-reopened",{detail:a})),L(b.WINDOW_REOPENED,a),o}const s=this.getByBaseId(n)?this.nextInstanceId(n):t.id;return this.createWindow({...t,id:s,baseId:n})}async openNew(t){const n=t.baseId||t.id,o=t.id!==n&&!this.getById(t.id)?t.id:this.nextInstanceId(n),s=40+this.cascadeIndex%8*ni,i=40+this.cascadeIndex%8*ni;return this.createWindow({initialState:"normal",x:s,y:i,...t,id:o,baseId:n})}async createWindow(t){const n=this._pendingRestoreState.get(t.id);n&&(this._pendingRestoreState.delete(t.id),t={...t,...n});const o=this._desktop.getBoundingClientRect(),s=Math.min(Math.round(o.width*.8),1200),i=Math.min(Math.round(o.height*.8),800),r=40+this.cascadeIndex%8*ni,a=40+this.cascadeIndex%8*ni,l=t.baseId||t.id,c=t.minWidth??320,d=t.minHeight??200,u=typeof t.width=="number",f=typeof t.height=="number",p=typeof t.x=="number",w=typeof t.y=="number",m=typeof t.initialState=="string",h=!u||!f||!m||!p||!w?fa(l):null,y=t.width??(h?Math.max(h.width,c):s),v=t.height??(h?Math.max(h.height,d):i),A=t.initialState??(h?.state==="maximized"?"maximized":void 0);let D,_;if(h&&typeof h.x=="number"&&typeof h.y=="number"){const H=Math.max(0,o.width-y-12),T=Math.max(0,o.height-v-12);D=Math.max(12,Math.min(h.x,H)),_=Math.max(12,Math.min(h.y,T))}const O=t.x??D??r,P=t.y??_??a,$=u||f||p||w||m,F=!!h,k={x:O,y:P,width:y,height:v,state:A};let W;try{W=Y(b.WINDOW_GEOMETRY,k,{windowId:t.id,baseId:l,hasSavedGeometry:F,callerPinned:$,desktopRect:{width:o.width,height:o.height}})}catch(R){L(b.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:R}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,R),W=k}const N=(R,H)=>typeof R=="number"&&Number.isFinite(R)?R:H,g=W&&typeof W=="object"?W:k,C=Math.max(N(g.width,y),c),U=Math.max(N(g.height,v),d),V=N(g.x,O),z=N(g.y,P),I=g.state??A,x={icon:t.icon||"dashicons-admin-generic",...t,x:V,y:z,width:C,height:U,minWidth:c,minHeight:d,...I?{initialState:I}:{},baseId:l,desktopId:t.desktopId||this._activeDesktopId};this.cascadeIndex++;const[B]=await Promise.all([mv(pv()),Nr(Dr())]),M=B.createWindow(x);M.onFocusRequest=R=>{this._cascadeDepth>0||this.focus(R)},M.onClose=R=>this.remove(R),M.onMinimize=R=>{this._cascadeDepth++;try{this.cascadeMinimize(R)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const H=this._stack.filter(T=>T.state!=="minimized");H.length>0&&this.focus(H[H.length-1])},M.onRestore=R=>{this._cascadeDepth++;try{this.cascadeRestore(R)}finally{this._cascadeDepth--}},M.onOpenAnother=R=>{const H=R.config.baseId||R.id;R.config.native&&window.wp?.os?.openNewWindow?.(H,{source:"open-another"})||this.openNew({id:H,baseId:H,url:R.config.url||"",title:R.config.title,icon:R.config.icon,submenu:R.config.submenu,multi:!0})},M.onOpenInNewWindow=R=>{const H=R.config.baseId||R.id;if(R.config.native&&window.wp?.os?.openNewWindow?.(H,{source:"open-in-new-window"}))return;const T=R.getCurrentUrl();this.openNew({id:H,baseId:H,url:T||R.config.url||"",title:R.config.title,icon:R.config.icon,submenu:R.config.submenu,multi:!0})},M.onToggleStartup=R=>{this.onToggleStartupRequested?.(R)},M.snapConfigProvider=()=>this.getSnapConfig(),M.onDragMove=(R,H)=>{i0(this,R,H)},M.onDragEnd=R=>this._snapPendingZone?r0(this,R):(a0(this),!1),this._stack.push(M),this._desktop.appendChild(M.element),df(this,M),M.hydrateNative(),this.focus(M);const j={windowId:M.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:j})),L(b.WINDOW_OPENED,j),M}nextInstanceId(t){const n=new Set(this._stack.map(s=>s.id));if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=typeof t=="string"?this.getById(t):t;if(!n||typeof n.setZIndex!="function"){t&&typeof t!="string"&&console.warn("[openstation] windowManager.focus() expects a Window or a window id; received",t);return}const o=this.blockingChildOf(n)??n;o!==n&&(o.shake?.(),L(b.WINDOW_CHILD_BLOCKED,{windowId:n.id,childWindowId:o.id}),document.dispatchEvent(new CustomEvent("os-window-child-blocked",{detail:{windowId:n.id,childWindowId:o.id}})));const s=this._stack.length>0?this._stack[this._stack.length-1]:null,i=this._stack.find(l=>l!==o&&l.isFocused()&&l.isFullscreen());i&&Y(b.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:i.id,focusedTo:o.id})&&i.toggleFullscreen();const r=this._stack.indexOf(o);if(r>-1&&this._stack.splice(r,1),this._stack.push(o),this.enforceOwnershipOrder(),this._stack.forEach((l,c)=>{l.setZIndex(Af+c),l.setFocused(c===this._stack.length-1)}),s&&s!==o&&s.id!==o.id){const l={windowId:s.id,focusedTo:o.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:l})),L(b.WINDOW_BLURRED,l)}const a={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:a})),L(b.WINDOW_FOCUSED,a)}raise(t){const n=this.getById(t);if(!n||this._stack.length<2)return;const o=this._stack.indexOf(n);o===-1||o===this._stack.length-1||(this._stack.splice(o,1),this._stack.splice(this._stack.length-1,0,n),this.enforceOwnershipOrder(),this._stack.forEach((s,i)=>{s.setZIndex(Af+i)}))}async openChild(t,n){const o=this.getById(t);if(!o)throw new Error(`windowManager.openChild(): no open window with id "${t}". Open the owner first, or use open() for a standalone window.`);const s=fa(n.baseId||n.id),i=!!s&&typeof s.x=="number"&&typeof s.y=="number";let r={};if(n.x===void 0&&n.y===void 0&&!i){const a=o.getSnapshot(),l=n.width??Math.round(a.width*.8),c=n.height??Math.round(a.height*.8),d=this._desktop.getBoundingClientRect(),u=Math.max(0,d.width-l),f=Math.max(0,d.height-c);r={width:l,height:c,x:Math.min(u,Math.max(0,Math.round(a.x+(a.width-l)/2))),y:Math.min(f,Math.max(0,Math.round(a.y+(a.height-c)/2)))}}return this.open({...n,...r,desktopId:o.config.desktopId,parentWindowId:t})}ownerOf(t){const n=t.config.parentWindowId;return n?this.getById(n):void 0}childrenOf(t){const n=typeof t=="string"?t:t.id;return this._stack.filter(o=>o.config.parentWindowId===n)}blockingChildOf(t){let n=t,o;const s=new Set([t]);for(;;){const i=this.childrenOf(n).filter(r=>r.state!=="minimized"&&!s.has(r));if(i.length===0)return o;n=i[i.length-1],s.add(n),o=n}}enforceOwnershipOrder(){if(!this._stack.some(s=>s.config.parentWindowId))return;const t=[],n=new Set,o=(s,i)=>{if(!(n.has(s)||i.has(s))){if(i.add(s),s.state!=="minimized"){const r=this.ownerOf(s);r&&r!==s&&o(r,i)}n.has(s)||(n.add(s),t.push(s))}};for(const s of this._stack)o(s,new Set);this._stack.length=0,this._stack.push(...t)}cascadeMinimize(t){for(const n of this.childrenOf(t))n.state!=="minimized"&&(this._cascadeMinimized.add(n),n.minimize())}cascadeRestore(t){for(const n of this.childrenOf(t))this._cascadeMinimized.has(n)&&(this._cascadeMinimized.delete(n),n.restore())}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);const o=this.childrenOf(t).slice();if(o.length>0){this._cascadeDepth++;try{for(const r of o)this._cascadeMinimized.delete(r),r.close()}finally{this._cascadeDepth--}}for(let r=this._stack.length-1;this._cascadeDepth===0&&r>=0;r--){const a=this._stack[r];if(!(a.state==="minimized"||(a.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(a);break}}const s={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("os-window-closing",{detail:s})),L(b.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),L(b.WINDOW_CLOSED,i)}getById(t){return this._stack.find(n=>n.id===t)}getByBaseId(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===t)return o}}getByBaseIdOnActiveDesktop(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==t)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(t){const n=o=>{if(o===t)return 1;const s=`${t}-`;if(o.startsWith(s)){const i=parseInt(o.slice(s.length),10);return Number.isFinite(i)?i:999}return 999};return this._stack.filter(o=>(o.config.baseId||o.id)===t).sort((o,s)=>n(o.id)-n(s.id))}getAllByBaseIdOnActiveDesktop(t){return this.getAllByBaseId(t).filter(n=>(n.config.desktopId||this._activeDesktopId)===this._activeDesktopId)}getAll(){return[...this._stack]}findByIframeSource(t){if(t)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===t)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(t){const n=this.getById(t);if(!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)return!1;const s=this.getFocused();return!!s&&s.id===t}isActiveByBaseId(t){const n=this.getFocused();return!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId?!1:(n.config.baseId||n.id)===t}getDesktops(){return HE(this)}getActiveDesktop(){return cf(this)}getActiveDesktopId(){return zE(this)}createDesktop(){return uf(this)}switchDesktop(t,n){pf(this,t,n)}closeDesktop(t){hf(this,t)}renameDesktop(t,n){return ff(this,t,n)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=Y(b.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(l=>!n.has(l.id));L(b.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=Y(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 t=[];for(const n of this._stack.slice())if((n.config.desktopId||this._activeDesktopId)===this._activeDesktopId&&n.state!=="minimized")try{n.minimize(),t.push(n)}catch(s){typeof console<"u"&&console.error("[openstation] minimizeAll: window.minimize() threw for",n.id,s)}return t}restoreFrom(t){if(!Array.isArray(t))return;const n=new Set(this._stack);for(const o of t)if(!(!n.has(o)||(o.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)&&o.state==="minimized")try{o.restore()}catch(i){typeof console<"u"&&console.error("[openstation] restoreFrom: window.restore() threw for",o.id,i)}}toggleShowDesktop(){const t=this._stack.filter(o=>(o.config.desktopId||this._activeDesktopId)===this._activeDesktopId);if(t.length===0)return!1;if(t.every(o=>o.state==="minimized")){for(const o of t)try{o.restore()}catch{}return!1}return this.minimizeAll(),!0}cascade(){qE(this)}tile(){KE(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){XE(this,t)}getSnapConfig(){return ZE(this)}enterOverview(){$E(this)}exitOverview(t,n=!1){$t(this,t,n)}destroy(){this._overviewActive&&$t(this),UE(this),vv()}getVisibleRects(){return this._stack.map(t=>{const n=t.getSnapshot();return{windowId:t.id,rect:{x:n.x,y:n.y,width:n.width,height:n.height},state:n.state,element:t.element}})}sanitizeParams(t){const n={};for(const[o,s]of Object.entries(t))(typeof s=="string"||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s))&&(n[o]=s);return Object.keys(n).length>0?n:void 0}snapshot(){const t=this.getFocused(),o=this._stack.filter(i=>!i.config.ephemeral&&!i.config.parentWindowId).map(i=>{const r=i.getSnapshot(),a=i.getExternalTabsSnapshot(),l=!!i.config.native,c=i.config.params,d=l&&c?this.sanitizeParams(c):null;return{id:i.id,baseId:i.config.baseId||i.id,desktopId:i.config.desktopId||this._activeDesktopId,...l?{native:!0}:{},...d?{params:d}:{},url:l?i.config.url||`#${i.id}`:i.getCurrentUrl(),title:i.config.title,icon:i.config.icon,state:r.state,x:r.x,y:r.y,width:r.width,height:r.height,...a.length>0?{externalTabs:a}:{}}}),s=t&&!t.config.ephemeral&&!t.config.parentWindowId?t.id:"";return{windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Date.now()}}seedWindowRestoreState(t){this._pendingRestoreState=new Map(Object.entries(t))}seedDesktops(t,n){VE(this,t,n)}}function d0(e){const t=e.getActiveDesktopId(),n=Array.from(e._desktop.children);return e.getAll().filter(o=>(o.config.desktopId||t)===t).sort((o,s)=>n.indexOf(o.element)-n.indexOf(s.element))}function Cf(e,t){if(e._overviewActive)return;const n=d0(e);if(n.length<2)return;const o=e.getFocused(),r=((o?n.indexOf(o):-1)+(t==="next"?1:-1)+n.length)%n.length,a=n[r];a.state==="minimized"?a.restore():e.focus(a)}let If=!1;function xf(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;if(!t)return!1;if(t instanceof HTMLIFrameElement||t instanceof HTMLTextAreaElement)return!0;if(t instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(t.type);if(t instanceof HTMLElement&&t.isContentEditable===!0)return!0;const n=t.getAttribute("contenteditable");return n!==null&&n!=="false"}function u0(e){if(If)return;If=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(xf(document)||(n.preventDefault(),Cf(e,n.shiftKey?"prev":"next")))},!0);const t=window.location.origin;window.addEventListener("message",n=>{if(n.origin!==t)return;const o=n.data;!o||o.type!=="os-window-switch"||Cf(e,o.direction==="prev"?"prev":"next")})}function Lf(e,t){const n=e.getDesktops();if(n.length<2)return!1;const o=e.getActiveDesktopId(),s=n.findIndex(a=>a.id===o);if(s===-1)return!1;const r=(s+(t==="next"?1:-1)+n.length)%n.length;return r===s?!1:(e.switchDesktop(n[r].id,{direction:t}),!0)}function Tf(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(l=>l.id===e.getActiveDesktopId());if(i===-1)return!1;const a=(i+(t==="next"?1:-1)+o)%o;return a===i?!1:a===s?(e._overviewAddTileFocused=!0,ei(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function f0(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function p0(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Nf(e){return e._overviewActive?(e.exitOverview(),!0):!1}function h0(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function m0(e){return h0(e)?(e.toggleShowDesktop(),!0):!1}let Df=!1;function g0(e){Df||(Df=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||xf(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Tf(e,"prev"):Lf(e,"prev");break;case"ArrowRight":n=e._overviewActive?Tf(e,"next"):Lf(e,"next");break;case"ArrowUp":n=Nf(e)||m0(e)||f0(e);break;case"ArrowDown":n=Nf(e)||p0(e);break}n&&t.preventDefault()},!0))}const Rf=Nu;let Of=!1;function Mf(e){return e?document.getElementById(`wp-window-${e}`):null}function w0(){Of||(Of=!0,y0())}function y0(){Z(b.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=Mf(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove(ia),n.classList.add(ao),RE(n),Ju(t),CE(t))}),Z(b.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=Mf(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");if(!n)return;t.removeAttribute("aria-busy");const o=!!n.querySelector(`:scope .${io}`)?.classList.contains(Xs);if(n.classList.remove(ao),n.removeAttribute(ra),!o){Zu(t),Hu(t);return}n.classList.add(ia);const s=Js(n);Hu(t),window.setTimeout(()=>{Js(n)===s&&(n.classList.contains(ao)||Zu(t))},Rf),window.setTimeout(()=>{Js(n)===s&&(n.classList.contains(ao)||n.classList.remove(ia))},Rf+fE)}),Z(b.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Pf())})}function Pf(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),Ju(n))})}const b0="os_person_view";function v0(e){return e.searchParams.has(b0)}const fo=re("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function _0(e){fo.state.deps=e}function St(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.nativeWindowId!="string"||e.nativeWindowId==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=fo.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>E0(e.id)}function E0(e){const t=fo.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function pa(e){const{deps:t,remaps:n}=fo.state;if(!t||!e)return null;let o;try{o=new URL(e,t.adminUrl)}catch{return null}const s=t.getSnapshot();for(const i of n)if(i.matches(e,o)&&!(i.enabled&&!i.enabled(s)))return i.nativeWindowId;return null}function Ge(e){const{deps:t,remaps:n}=fo.state;if(!t||!e)return!1;let o;try{o=new URL(e,t.adminUrl)}catch{return!1}const s=t.getSnapshot();for(const i of n){if(!i.matches(e,o)||i.enabled&&!i.enabled(s))continue;if(i.onMatch)try{i.onMatch(e,o)}catch(l){console.warn(`[openstation] URL remap onMatch hook threw for "${i.id}":`,l)}let r;if(i.params)try{r=i.params(e,o)??void 0}catch(l){console.warn(`[openstation] URL remap params hook threw for "${i.id}":`,l)}if(r?t.openById(i.nativeWindowId,{params:r}):t.openById(i.nativeWindowId))return!0}return!1}const k0="desktop_mode_classic";function S0(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has("page")&&!e.searchParams.has(k0)}const ha=re("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function A0(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=ha.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Wf(e.id)}function Wf(e){const t=ha.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function C0(){return ha.state.entries.slice()}const I0=32,x0=64,L0=/^[a-z0-9_/-]+$/,me=re("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function Ut(e){return`${e.type}:${e.id}`}function $f(e){return e.root?Ut(e.root):Ut(e)}function Uf(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&L0.test(o.trim().toLowerCase());return Mt(e,[{field:"type",valid:o=>n(o.type),message:"must match /^[a-z0-9_/-]+$/ — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-type"},{field:"id",valid:o=>t(o.id),message:"must be a finite number or non-empty string"},{field:"root",valid:o=>o.root===void 0||!!o.root&&typeof o.root=="object"&&n(o.root.type)&&t(o.root.id),message:"when present, must be { type, id } with the same shapes as the ref itself"},{field:"related",valid:o=>o.related===void 0||Array.isArray(o.related)&&o.related.every(s=>!!s&&typeof s=="object"&&typeof s.id=="string"&&s.id.trim()!==""&&typeof s.group=="string"&&s.group.trim()!==""&&typeof s.label=="string"&&s.label.trim()!==""&&typeof s.url=="string"&&s.url.trim()!==""&&(s.groupLabel===void 0||typeof s.groupLabel=="string")&&(s.icon===void 0||typeof s.icon=="string")&&(s.count===void 0||typeof s.count=="number"&&Number.isFinite(s.count))),message:"when present, must be an array of { id, group, label, url, groupLabel?, icon?, count? } entries with non-empty strings"},{field:"links",valid:o=>o.links===void 0||Array.isArray(o.links)&&o.links.every(s=>!!s&&typeof s=="object"&&n(s.type)&&t(s.id)&&(s.rel===void 0||s.rel==="references"||s.rel==="child")),message:"when present, must be an array of { type, id, rel?: 'references'|'child' } entries"}])}function T0(e,t){const n={type:e.type.trim().toLowerCase(),id:e.id,source:t};if(e.root&&(n.root={type:e.root.type.trim().toLowerCase(),id:e.root.id}),Array.isArray(e.links)&&e.links.length>0&&(n.links=e.links.slice(0,I0).map(o=>{const s={type:o.type.trim().toLowerCase(),id:o.id};return o.rel==="child"&&(s.rel="child"),s})),typeof e.label=="string"&&e.label!==""&&(n.label=e.label),typeof e.previewUrl=="string"&&e.previewUrl!=="")try{new URL(e.previewUrl,window.location.origin).origin===window.location.origin&&(n.previewUrl=e.previewUrl)}catch{}return Array.isArray(e.related)&&e.related.length>0&&(n.related=e.related.slice(0,x0).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 Ff(e){return!e||!e.related?"":e.related.map(t=>`${t.id}\0${t.group}\0${t.label}\0${t.url}\0${t.groupLabel??""}\0${t.icon??""}\0${t.count??""}`).join("|")}function ma(e){return e?[Ut(e),$f(e),...(e.links??[]).map(t=>Ut(t)+(t.rel==="child"?"!child":""))].join("|"):""}function oi(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Ne("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=Uf(t);if(a.length>0){o==="api"&&Ne("WindowContentRef",a,t),Wd("WindowContentRef",a,t);return}s=T0(t,o)}if(s=Y(b.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||Uf(s).length>0)){Wd("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=me.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&ma(s)===ma(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&Ff(s)===Ff(i))return;s===null?me.state.contentByWindow.delete(e):me.state.contentByWindow.set(e,s);const r={windowId:e,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("os-window-content-changed",{detail:r})),L(b.WINDOW_CONTENT_CHANGED,r),O0(),D0()}function ut(e){return me.state.contentByWindow.get(e)}function si(){const e=new Map;for(const[s,i]of me.state.contentByWindow){const r=$f(i);let a=e.get(r);a||(a={key:r,root:i.root?{...i.root}:{type:i.type,id:i.id},rootWindowIds:[],children:[]},e.set(r,a)),i.root?a.children.push({windowId:s,content:i}):a.rootWindowIds.push(s)}const t=me.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=Y(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 Bf(e){return si().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function Hf(e){const t=new Set,n=Bf(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of po())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function N0(e){const t=new Set;for(const n of po())n.fromWindowId===e?t.add(n.toWindowId):n.toWindowId===e&&t.add(n.fromWindowId);return t.delete(e),Array.from(t)}function po(){const e=me.state.focusSeq,t=new Map;for(const[a,l]of me.state.contentByWindow){const c=Ut(l),d=t.get(c);(!d||(e.get(a)??0)>(e.get(d)??0))&&t.set(c,a)}const n=new Map,o=(a,l)=>`${a}→${l}`;for(const[a,l]of me.state.contentByWindow){if(l.root){const c=t.get(Ut(l.root));c&&c!==a&&n.set(o(a,c),{fromWindowId:a,toWindowId:c,kind:"child-root",bidirectional:!1})}for(const c of l.links??[]){const d=t.get(Ut(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=Y(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 zf(e){return me.state.listeners.add(e),()=>{me.state.listeners.delete(e)}}function D0(){for(const e of Array.from(me.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function R0(){return Array.from(me.state.contentByWindow).map(([e,t])=>`${e}=${ma(t)}`).sort().join(";")}function O0(){const e=R0();if(e===me.state.lastGroupsSignature)return;me.state.lastGroupsSignature=e;const n={groups:si()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),L(b.WINDOW_LINK_GROUPS_CHANGED,n)}const M0={get:ut,set:(e,t)=>oi(e,t,{source:"api"}),groups:si,edges:po,groupOf:Bf,related:Hf,subscribe:zf};function P0({manager:e}){me.state.manager=e,!me.state.started&&(me.state.started=!0,Z(b.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=me.state.manager?.getById(t.windowId)?.config?.content;o&&oi(t.windowId,o,{source:"config"})}),Z(b.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(me.state.focusSeq.delete(t.windowId),oi(t.windowId,null,{source:"config"}))}),Z(b.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(me.state.seq+=1,me.state.focusSeq.set(t.windowId,me.state.seq))}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t.data;if(!n||n.type!=="os-content-identity")return;const o=me.state.manager?.findByIframeSource?.(t.source);o&&oi(o.id,n.identity??null,{source:"bridge"})}))}const W0=re("desktop-mode/admin-link-deps",()=>({deps:null}));function $0(e){W0.state.deps=e}const Gf=re("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),yn=Gf.state.seed,U0=Gf.state.listeners;function bn(e){Ne("Wallpaper",Mt(e,Kf),e);const t=yn.findIndex(n=>n.id===e.id);t>=0?yn[t]=e:yn.push(e),Vf()}function jf(e){const t=yn.findIndex(n=>n.id===e);t>=0&&(yn.splice(t,1),Vf())}function Vf(){const e=Array.from(U0);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function qf(){const e=yn.slice(),t=Y(b.WALLPAPERS,e);return Array.isArray(t)?t.filter(F0):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function ga(e){return qf().find(t=>t.id===e)}const Kf=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"preview",message:"missing or not a non-empty string",valid:e=>typeof e.preview=="string"&&e.preview!==""},{field:"type",message:'must be "css" or "canvas"',valid:e=>e.type==="css"||e.type==="canvas"},{field:"value/resolveValue/mount",message:"css types need `value` or `resolveValue`; canvas types need `mount`",valid:e=>e.type==="css"?typeof e.value=="string"||typeof e.resolveValue=="function":e.type==="canvas"?typeof e.mount=="function":!0}];function F0(e){return Mt(e,Kf).length===0}const Yf=re("desktop-mode/wallpaper-settings",()=>({values:{}}));function B0(e){return{...Yf.state.values[e]??{}}}function H0(e){const t=Yf.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}function Xf(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const Zf=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","glow","glowBlur","eyeColor","eyeScale"],Jf=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function wa(){return{appearance:{},physics:{}}}function z0(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function ii(e,t){const n={};if(!e||typeof e!="object"||Array.isArray(e))return n;const o=e;for(const s of t){const i=o[s];i!==void 0&&z0(i)&&Object.assign(n,{[s]:i})}return n}function Qf(e){if(!e||typeof e!="object"||Array.isArray(e))return wa();const t=e;return{appearance:ii(t.appearance,Zf),physics:ii(t.physics,Jf)}}function G0(e){return{appearance:ii(e,Zf),physics:ii(e,Jf)}}function j0(){const e=V0();if(e){const t=ep(e);return ba(t),J0(t),t}try{const t=window.localStorage.getItem(du);if(t)return ep(JSON.parse(t))}catch{}return ok()}function V0(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}function ep(e){const t=qr();return{wallpaper:typeof e.wallpaper=="string"&&e.wallpaper!==""?e.wallpaper:hu(),accent:e.accent===fu||t.some(n=>n.id===e.accent)?e.accent:ee.accent,customAccent:typeof e.customAccent=="string"&&/^#[0-9a-fA-F]{6}$/.test(e.customAccent)?e.customAccent:ee.customAccent,dockSize:Kr.some(n=>n.id===e.dockSize)?e.dockSize:ee.dockSize,windowRadius:Yr.some(n=>n.id===e.windowRadius)?e.windowRadius:ee.windowRadius,adminBarMode:Gs.some(n=>n.id===e.adminBarMode)?e.adminBarMode:ee.adminBarMode,desktopLayout:m_.some(n=>n.id===e.desktopLayout)?e.desktopLayout:ee.desktopLayout,dockPlacement:h_.some(n=>n.id===e.dockPlacement)?e.dockPlacement:ee.dockPlacement,dockRailRenderer:typeof e.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(e.dockRailRenderer)?e.dockRailRenderer:ee.dockRailRenderer,desktopTheme:typeof e.desktopTheme=="string"&&/^[a-z0-9_-]*$/.test(e.desktopTheme)?e.desktopTheme:ee.desktopTheme,appliedThemeRecommendations:Array.isArray(e.appliedThemeRecommendations)?Array.from(new Set(e.appliedThemeRecommendations.filter(n=>typeof n=="string"&&/^[a-z0-9_-]+$/.test(n)))).slice(-64):ee.appliedThemeRecommendations.slice(),unfocusEffect:typeof e.unfocusEffect=="string"&&/^[a-z0-9_/-]+$/.test(e.unfocusEffect)?e.unfocusEffect:ee.unfocusEffect,windowReveal:typeof e.windowReveal=="string"&&/^[a-z0-9_/-]+$/.test(e.windowReveal)?e.windowReveal:ee.windowReveal,windowRevealDuration:typeof e.windowRevealDuration=="number"&&Number.isFinite(e.windowRevealDuration)&&e.windowRevealDuration>0?Math.min(4e3,Math.max(80,Math.round(e.windowRevealDuration))):ee.windowRevealDuration,windowLinkRenderer:typeof e.windowLinkRenderer=="string"&&/^[a-z0-9_/-]+$/.test(e.windowLinkRenderer)?e.windowLinkRenderer:ee.windowLinkRenderer,windowLinkVisibility:e.windowLinkVisibility==="focus"||e.windowLinkVisibility==="always"||e.windowLinkVisibility==="off"?e.windowLinkVisibility:ee.windowLinkVisibility,windowLinksEnabled:typeof e.windowLinksEnabled=="boolean"?e.windowLinksEnabled:ee.windowLinksEnabled,windowLinkRaiseOnFocus:typeof e.windowLinkRaiseOnFocus=="boolean"?e.windowLinkRaiseOnFocus:ee.windowLinkRaiseOnFocus,windowLinkHighlight:typeof e.windowLinkHighlight=="boolean"?e.windowLinkHighlight:ee.windowLinkHighlight,customGradient:ik(e.customGradient),customImage:rk(e.customImage),wallpaperSettings:q0(e.wallpaperSettings),libraryHdOnly:typeof e.libraryHdOnly=="boolean"?e.libraryHdOnly:ee.libraryHdOnly,ai:sk(e.ai),heartbeatRate:e.heartbeatRate===15||e.heartbeatRate===30||e.heartbeatRate===45||e.heartbeatRate===60?e.heartbeatRate:ee.heartbeatRate,nativePostsEnabled:typeof e.nativePostsEnabled=="boolean"?e.nativePostsEnabled:ee.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(e.nativePostsHiddenColumns)?e.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):ee.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof e.nativePagesEnabled=="boolean"?e.nativePagesEnabled:ee.nativePagesEnabled,nativeUsersEnabled:typeof e.nativeUsersEnabled=="boolean"?e.nativeUsersEnabled:ee.nativeUsersEnabled,nativePluginsEnabled:typeof e.nativePluginsEnabled=="boolean"?e.nativePluginsEnabled:ee.nativePluginsEnabled,nativeCommentsEnabled:typeof e.nativeCommentsEnabled=="boolean"?e.nativeCommentsEnabled:ee.nativeCommentsEnabled,stationHomeEnabled:typeof e.stationHomeEnabled=="boolean"?e.stationHomeEnabled:ee.stationHomeEnabled,showDesktopOnWallpaperClick:typeof e.showDesktopOnWallpaperClick=="boolean"?e.showDesktopOnWallpaperClick:ee.showDesktopOnWallpaperClick,mioEnabled:typeof e.mioEnabled=="boolean"?e.mioEnabled:ee.mioEnabled,mioStyle:Qf(e.mioStyle),showPostStatusRibbons:typeof e.showPostStatusRibbons=="boolean"?e.showPostStatusRibbons:ee.showPostStatusRibbons,developerModeEnabled:typeof e.developerModeEnabled=="boolean"?e.developerModeEnabled:ee.developerModeEnabled,foldersSharingEnabled:typeof e.foldersSharingEnabled=="boolean"?e.foldersSharingEnabled:ee.foldersSharingEnabled,navPlacement:K0(e.navPlacement),navOrder:Y0(e.navOrder),dockPromotedPositions:X0(e.dockPromotedPositions)}}function q0(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(typeof o!="string"||o===""||!/^[a-z0-9_/-]+$/.test(o)||!s||typeof s!="object"||Array.isArray(s))continue;const i={};let r=0;for(const[a,l]of Object.entries(s)){if(r>=32)break;if(!(typeof a!="string"||a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof l=="boolean")i[a]=l;else if(typeof l=="number"&&Number.isFinite(l))i[a]=l;else if(typeof l=="string")i[a]=l.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function K0(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=["both","rail","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(e)){if(o>=256)break;if(typeof s!="string"||s===""||typeof i!="string")continue;const r=i;t.includes(r)&&(n[s]=r,o++)}return n}function Y0(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const o of e)if(!(typeof o!="string"||o===""||n.has(o))&&(n.add(o),t.push(o),t.length>=256))break;return t}function X0(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(typeof s!="string"||s===""||!i||typeof i!="object"||Array.isArray(i))continue;const r=i;typeof r.x!="number"||typeof r.y!="number"||!Number.isFinite(r.x)||!Number.isFinite(r.y)||Math.abs(r.x)>o||Math.abs(r.y)>o||(t[s]={x:r.x,y:r.y},n++)}return t}let ri=null;const Z0=250;let Ft=null;function J0(e){Ft=ya(e)}function ya(e){return{...e,customGradient:{...e.customGradient},customImage:e.customImage?{...e.customImage}:null,wallpaperSettings:Object.fromEntries(Object.entries(e.wallpaperSettings).map(([t,n])=>[t,{...n}])),ai:{...e.ai},mioStyle:{appearance:{...e.mioStyle.appearance},physics:{...e.mioStyle.physics}},appliedThemeRecommendations:e.appliedThemeRecommendations.slice(),nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),navPlacement:{...e.navPlacement},navOrder:e.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function Q0(e,t={}){ba(e),ek(e,t.windowId)}function ba(e){try{window.localStorage.setItem(du,JSON.stringify(e))}catch{}}function ek(e,t){ri!==null&&clearTimeout(ri),t&&(va=t),Bt("pending"),ri=setTimeout(()=>{ri=null;const n=va;va=null,nk(e,n)},Z0)}let va=null;function tk(e){if(!Ft)return{...e};const t=Ft,n={};let o=!1;for(const s of Object.keys(e))JSON.stringify(e[s])!==JSON.stringify(t[s])&&(Object.assign(n,{[s]:e[s]}),o=!0);return o?n:null}function nk(e,t){const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Bt("saved");return}const i=tk(e);if(!i){Bt("saved");return}Bt("saving");const r=t||"desktop-mode-os-settings";Fe(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:i})},{windowId:r}).then(a=>{if(!a.ok)throw new Error(`${a.status} ${a.statusText}`);Ft=ya(e),Bt("saved")}).catch(a=>{Ft?(ba(Ft),Bt("failed",a instanceof Error?a.message:String(a),ya(Ft))):Bt("failed",a instanceof Error?a.message:String(a))})}function Bt(e,t,n){const o={phase:e};t&&(o.error=t),n&&(o.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:o}))}function ok(){return{...ee,customGradient:{...ee.customGradient},customImage:null,wallpaperSettings:{...ee.wallpaperSettings},ai:{...ee.ai},appliedThemeRecommendations:[...ee.appliedThemeRecommendations],navPlacement:{...ee.navPlacement},navOrder:[...ee.navOrder],dockPromotedPositions:{...ee.dockPromotedPositions}}}function sk(e){if(!e||typeof e!="object")return{...ee.ai};const{enabled:t}=e;return{enabled:typeof t=="boolean"?t:ee.ai.enabled}}function ik(e){if(!e||typeof e!="object")return{...ee.customGradient};const{from:t,to:n,angle:o}=e;return{from:Xf(t)?t:ee.customGradient.from,to:Xf(n)?n:ee.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:ee.customGradient.angle}}function rk(e){if(!e||typeof e!="object")return null;const{id:t,url:n}=e;return typeof t!="number"||!Number.isFinite(t)||t<=0||typeof n!="string"||!/^https?:\/\//i.test(n)?null:{id:t,url:n}}function vn(e){if(!e)return 214;let t=5381;for(let n=0;n<e.length;n++)t=Math.imul(t,33)+e.charCodeAt(n);return(t%360+360)%360}function ak(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function ho(e,t,n){if(!ak(t))return!1;const o=`url("${t}") center / contain no-repeat`;return e.style.backgroundImage="none",e.style.backgroundColor=n,e.style.setProperty("-webkit-mask",o),e.style.setProperty("mask",o),!0}const _a="data-os-constellation";function lk(){return document.body.hasAttribute(_a)}const ai="os-item-menu-opening",ck=180,dk=220,tp=32;function np(e){const{tile:t}=e;let n=null,o=null,s=null,i=!1,r=null;const a=()=>{o!==null&&(window.clearTimeout(o),o=null)},l=()=>{s!==null&&(window.clearTimeout(s),s=null)},c=()=>{a(),l(),t.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),r?.clear(),r=null,e.suppressTooltip(!1)},d=m=>{m.pointerType==="mouse"&&(lk()&&(t.dataset.menuSlug||t.dataset.constellationId)||uk(e)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},ck))))},u=m=>{n&&m.relatedTarget instanceof Node&&n.contains(m.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},dk)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=fk(e,()=>c(),r),document.body.appendChild(n),bk(n),vk(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,l()}),n.addEventListener("pointerleave",m=>{m.relatedTarget instanceof Node&&t.contains(m.relatedTarget)||(i=!1,f())})},w=()=>c();return t.addEventListener("pointerenter",d),t.addEventListener("pointerleave",u),document.addEventListener(ai,w),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(ai,w),c()}}function uk(e){return e.getInstances().length>=1}function fk(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",le(E("%s — open windows"),e.item.title));const s=document.createElement("div");s.className="os-dock-peek__cards",o.appendChild(s);const i=e.getInstances();let r=0;for(const a of i){const l=pk(a,e,r++,t,n);s.appendChild(l)}if(e.enableGhost!==!1){const a=mk(e,r,t);s.appendChild(a)}return o}function op(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function pk(e,t,n,o,s){const i=document.createElement("button");i.type="button",i.setAttribute("role","menuitem"),i.className="os-dock-peek__card os-dock-peek__card--instance",i.style.setProperty("--peek-card-index",String(n)),i.style.setProperty("--peek-card-delay",`${n*tp}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${vn(e.id||r)}`),i.style.setProperty("--peek-card-vt-name",`os-peek-card-${e.id}`);const a=document.createElement("span");a.className="os-dock-peek__card-titlebar";const l=document.createElement("span");l.className="os-dock-peek__card-dots",l.setAttribute("aria-hidden","true");for(let 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=e.config.icon||t.item.icon;d.startsWith("dashicons-")?c.classList.add("dashicons",Sd(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 A=document.createElement("span");A.className="os-dock-peek__card-line",f.appendChild(A)}const p={window:e,item:t.item},w=Y(b.DOCK_PEEK_CARD_CONTENT,f,p);w!==f&&w.classList.add("os-dock-peek__card-body--custom"),i.appendChild(w),e.state==="minimized"&&(i.dataset.state="minimized");const m=()=>{s.delete(e.id),delete i.dataset.preview},h=v=>{if(m(),v.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(v.previouslyFocusedId){const A=t.windowManager.getById(v.previouslyFocusedId);A&&t.windowManager.focus(A)}};return i.addEventListener("click",()=>{m(),hk(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const v=e.state==="minimized",A=t.windowManager.getFocused(),D=A&&A!==e?A.id:null;(v||D!==null)&&(s.set(e.id,{wasMinimized:v,previouslyFocusedId:D}),i.dataset.preview=""),v?op(e,i):A&&A!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const v=s.get(e.id);v&&h(v)}),Y(b.DOCK_PEEK_CARD_ELEMENT,i,p)}function hk(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),op(t,n),e.windowManager.focus(t)};if(typeof s.startViewTransition!="function"){r();return}const a=t.element;n.style.setProperty("view-transition-name",i),a.style.setProperty("view-transition-name",i);const l=s.startViewTransition(r),c=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},d=l;d.finished&&typeof d.finished.then=="function"?d.finished.then(c,c):Promise.resolve().then(c)}function mk(e,t,n){const o=document.createElement("button");o.type="button",o.setAttribute("role","menuitem"),o.className="os-dock-peek__card os-dock-peek__card--ghost",o.style.setProperty("--peek-card-index",String(t)),o.style.setProperty("--peek-card-delay",`${t*tp}ms`);const s=document.createElement("span");s.className="os-dock-peek__card-plus",s.setAttribute("aria-hidden","true"),s.textContent="+",o.appendChild(s);const i=document.createElement("span");return i.className="os-dock-peek__card-label",i.textContent=le(E("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{gk(e,n)}),o}function gk(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const wk=12,yk=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function bk(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of yk){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function vk(e,t,n){const o=t.getBoundingClientRect();e.dataset.orientation=n,n==="bottom"?(e.style.left=`${o.left+o.width/2}px`,e.style.top=`${o.top-12}px`):n==="right"?(e.style.top=`${o.top}px`,e.style.left=`${o.left-12}px`):(e.style.top=`${o.top}px`,e.style.left=`${o.right+12}px`),requestAnimationFrame(()=>_k(e))}function _k(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=wk;let r=0,a=0;n.top<i?r=i-n.top:n.bottom>o-i&&(r=o-i-n.bottom),n.left<i?a=i-n.left:n.right>s-i&&(a=s-i-n.right),!(a===0&&r===0)&&(e.style.setProperty("--peek-clamp-x",`${a}px`),e.style.setProperty("--peek-clamp-y",`${r}px`),e.classList.add("os-dock-peek--clamped"))}function _n(e){try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin?!1:(window.open(t.toString(),"_blank","noopener,noreferrer"),!0)}catch{return!1}}const Ea=new Map;function sp(e){let t,n;try{const s=new URL(e,document.baseURI);t=s.origin,n=s.pathname}catch{return null}if(!n)return null;const o=document.querySelectorAll("script[src]");for(const s of Array.from(o))try{const i=new URL(s.src,document.baseURI);if(i.origin===t&&i.pathname===n)return s}catch{}return null}function _e(e,t){const n=Ea.get(e);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-os-vendor="${Ek(e)}"]`,a=document.querySelector(r);if(a){if(a.dataset.loaded==="1"){s();return}a.addEventListener("load",()=>s(),{once:!0}),a.addEventListener("error",()=>i(new Error(`Failed to load ${e}`)),{once:!0});return}const l=sp(e);if(l){l.dataset.osVendor=e,l.dataset.loaded="1",s();return}t?.translations&&mo(t.translations);for(const d of t?.l10n??[])mo(d);for(const d of t?.before??[])mo(d);const c=document.createElement("script");c.src=e,c.async=!0,c.dataset.osVendor=e,c.addEventListener("load",()=>{c.dataset.loaded="1";for(const d of t?.after??[])mo(d);s()},{once:!0}),c.addEventListener("error",()=>{Ea.delete(e),c.remove(),i(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(c)});return Ea.set(e,o),o}function mo(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function ip(e){mo(e)}function Ek(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let rp=0;function ap(){return window.openStationItemVisibilityMenu??null}function kk(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function lp(e){const t=ap();if(t){t.openItemVisibilityMenu(e);return}const n=kk();if(!n)return;const o=++rp;_e(n).then(()=>{o===rp&&ap()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const Sk={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function Ak(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function Ck(e){return e==="core"?"core":e==="control"?"controls":"apps"}function cp(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??Sk[e.kind]}function dp(e){return e==="rail"||e==="both"}function Ik(e){return e==="desktop"||e==="both"}function xk(e,t,n){return dp(e)?"rail":"hidden"}function ka(e,t){if(t.length===0||e.length<=1)return e.slice();const n=new Map;for(const i of e)n.set(i.id,i);const o=[],s=new Set;for(const i of t){const r=n.get(i);r&&!s.has(i)&&(o.push(r),s.add(i))}for(const i of e)s.has(i.id)||o.push(i);return o}function Lk(e,t){const n=new Set(t),o=t.slice(),s=[];for(const i of e){if(!n.has(i)){s.push(i);continue}const r=o.shift();r!==void 0&&s.push(r)}return s.push(...o),s}function Sa(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>(t.item.order??0)-(n.item.order??0)||t.index-n.index).map(t=>t.item)}function li(){return window.wp?.os??null}function Tk(){const e=li()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function Nk(){return li()?.getNavItems?.()??[]}function Dk(e){const t=Nk();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function Rk(e){const t=li();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n={...t.getOsSettings().navPlacement??{}};let o=!1;for(const{item:s,placement:i}of e)s.locked||(n[s.id]=i,o=!0);o&&t.updateOsSettings({navPlacement:n})}function Ok(e,t,n){const o=Array.isArray(e)?e:[e],s=Tk().placement,i=[];for(const r of o){const a=typeof r=="string"?Dk(r):r;a&&i.push({item:a,placement:xk(cp(a,s))})}Rk(i)}function Mk(e){const t=li();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:Lk(n,e)})}const it=["core","apps","controls"];function up(e){const{items:t,config:n,layout:o,openWindows:s}=e,i={core:[],apps:[],controls:[]},r=[],a=[],l=new Set,c=new Set,d=new Map,u=new Set;for(const f of t){u.add(f.id),f.windowId&&!d.has(f.windowId)&&d.set(f.windowId,f);const p=cp(f,n.placement);if(dp(p)){c.add(f.id);const w=Ck(f.kind);Ak(f.kind,o)==="sidebar"?r.push(f):i[w].push(f)}Ik(p)&&a.push(f)}for(const f of t)for(const p of f.answersFor??[])d.has(p)||d.set(p,f);for(const f of s){const p=d.get(f.id);if(p){if(c.has(p.id)||l.has(p.id))continue;i.apps.push(p),l.add(p.id);continue}f.fromAdminUrl||l.has(f.id)||u.has(f.id)||(i.apps.push({id:f.id,kind:"app",title:f.title,icon:f.icon,windowId:f.id,transient:!0}),l.add(f.id))}for(const f of it)i[f]=ka(Sa(i[f]),n.order);return{dock:i,sidebar:ka(Sa(r),n.order),desktop:ka(Sa(a),n.order),ephemeral:l}}function fp(e){return e.navKind==="control"?"controls":"apps"}const We=class We{constructor(t,n,o,s,i="left"){this.itemElements=new Map,this.systemItems=[],this.systemItemElements=new Map,this.zones={core:[],apps:[],controls:[]},this.badgeOverrides=new Map,this.artOverrides=new Map,this.attentionTimers=new Map,this.peekTeardowns=new Map,this.boundRefresh=()=>{},this.container=t,this.windowManager=n,this.items=o,this.adminUrl=s,this.orientation=i,this.rail=i==="bottom"?"taskbar":"dock",this.hooksNamespace=`desktop-mode/dock/${++We.instanceCounter}`,this.container.classList.add("os-dock--no-transition"),this.container.setAttribute("data-os-dock-placement",i),this.container.offsetWidth,this.container.classList.remove("os-dock--no-transition");const r=document.createElement("div");r.className="os-dock__scroll";const a=document.createElement("div");a.className="os-dock__pinned",t.appendChild(r),t.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="os-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.zones=this.zonesFromMenu(o,[]),this.render(),this.bindWindowEvents()}buildHookContextBase(){return{rail:this.rail,orientation:this.orientation,dockId:this.container.id,container:this.container}}setOrientation(t){this.orientation!==t&&(this.orientation=t,this.container.setAttribute("data-os-dock-placement",t),this.tooltip.classList.remove("os-dock__tooltip--above","os-dock__tooltip--before","os-dock__tooltip--after"),t==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):t==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"))}replaceItems(t){this.zones=this.zonesFromMenu(t,this.systemEntries()),this.render()}setZones(t){this.zones={core:t.core.slice(),apps:t.apps.slice(),controls:t.controls.slice()},this.render()}systemEntries(){const t=[];for(const n of it)for(const o of this.zones[n])o.type==="system"&&t.push(o);return t}zonesFromMenu(t,n){const o={core:[],apps:[],controls:[]};for(const s of t)o[s.isCore?"core":"apps"].push({type:"menu",item:s});for(const s of n)s.type==="system"&&o[fp(s.item)].push(s);return o}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(t){let n=!1;for(const o of it){const s=this.zones[o].filter(i=>i.type!=="system"||i.item.id!==t);s.length!==this.zones[o].length&&(n=!0),this.zones[o]=s}n&&(this.badgeOverrides.delete(t),this.artOverrides.delete(t),this.render(),L(b.DOCK_ITEM_REMOVED,{id:t,placement:this.rail}))}setBadge(t,n){const o=this._resolveTileElement(t);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(t):this.badgeOverrides.set(t,s);const i=o.querySelector(".os-dock__item-primary");pp(i??o,s),ke.publish("os/badge-changed",{itemId:t,count:s,rail:this.rail})}clearBadge(t){this.setBadge(t,0)}setArt(t,n){if(!n){if(!this.artOverrides.delete(t))return;const s=this._resolveTileElement(t),i=this._declaredIcon(t);s&&i&&this._paintArt(s,t,i),ke.publish("os/art-changed",{itemId:t,icon:"",rail:this.rail});return}this.artOverrides.set(t,n);const o=this._resolveTileElement(t);o&&(this._paintArt(o,t,n),ke.publish("os/art-changed",{itemId:t,icon:n,rail:this.rail}))}_declaredIcon(t){const n=this.items.find(s=>s.id===t);if(n)return n.icon;const o=this.systemItems.find(s=>s.id===t);return o?o.icon:""}_paintArt(t,n,o){const s=t.querySelector(".os-dock__item-primary")??t,i=this.resolveIcon(o,this._declaredTitle(n),void 0,qs(n)),r=s.querySelector(".os-dock__item-mask, .os-dock__item-svg, .dashicons, img");r?r.replaceWith(i):s.prepend(i)}_declaredTitle(t){const n=this.items.find(s=>s.id===t);if(n)return n.title;const o=this.systemItems.find(s=>s.id===t);return o?o.title:""}setAttention(t,n,o={}){const s=this._resolveTileElement(t);if(!s)return;const i=this.attentionTimers.get(t);if(i!==void 0&&(window.clearTimeout(i),this.attentionTimers.delete(t)),s.classList.remove("os-dock__item--attention-pulse","os-dock__item--attention-shake","os-dock__item--attention-bounce","os-dock__item--intensity-subtle","os-dock__item--intensity-normal","os-dock__item--intensity-strong"),n===null)return;s.classList.add(`os-dock__item--attention-${n}`);const r=o.intensity??"normal";s.classList.add(`os-dock__item--intensity-${r}`);const a=o.durationMs??4e3;if(a>0){const l=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},a);this.attentionTimers.set(t,l)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}appendSystemItem(t){const n=fp(t),o={type:"system",item:t};for(const a of it)this.zones[a]=this.zones[a].filter(l=>l.type!=="system"||l.item.id!==t.id);const s=this.zones[n],i=t.order??0,r=s.findIndex(a=>a.type==="system"&&(a.item.order??0)>i);r===-1?s.push(o):s.splice(r,0,o),this.render()}render(){if(We.activeDragReset){const o=We.activeDragReset;We.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="",this.systemHost.innerHTML="",this.itemElements.clear(),this.systemItemElements.clear(),this.items=[],this.systemItems=[];for(const o of it)for(const s of this.zones[o])s.type==="menu"?this.items.push(s.item):this.systemItems.push(s.item);const t=this.buildHookContextBase();L(b.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of it){const s=this.zones[o];if(s.length===0)continue;const i=o==="controls"?this.systemHost:this.itemHost;if(n){const r=document.createElement("div");r.className=o==="controls"?"os-dock__separator":"os-dock__separator os-dock__separator--group",r.setAttribute("aria-hidden","true"),i.appendChild(r)}for(const r of s)this.paintEntry(r,o,i,t);n=!0}this.updateActiveStates(),L(b.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}paintEntry(t,n,o,s){const i=t.item.id,r=t.type==="menu"?this.createItemButton(t.item):this.createSystemItemButton(t.item);r.dataset.zone=n,r.dataset.navId=i,t.type==="system"&&t.item.locked===!0?r.dataset.navLocked="true":(this.attachDragReorder(r,i,n),r.addEventListener("contextmenu",d=>{d.preventDefault(),lp({x:d.clientX,y:d.clientY,id:i,title:t.item.title,surface:"dock",pluginFile:t.type==="menu"?t.item.pluginFile??null:null,pluginName:t.type==="menu"?t.item.pluginName??null:null})})),t.type==="menu"?this.itemElements.set(i,r):this.systemItemElements.set(i,r),o.appendChild(r);const l=this.badgeOverrides.get(i);if(l!==void 0){const d=r.querySelector(".os-dock__item-primary");pp(d??r,l)}const c=this.artOverrides.get(i);c&&this._paintArt(r,i,c),L(b.DOCK_TILE_RENDERED,{...s,item:t.item,isSystem:t.type==="system",el:r})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=Y(b.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id,t.submenu&&t.submenu.length>0&&(o.dataset.constellationId=t.id);const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title,void 0,qs(t.id))),r.addEventListener("click",()=>t.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=np({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:""},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(t.id),enableGhost:!!t.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(t.onOpenNew??t.onOpen)()},suppressTooltip:l=>{l&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),Y(b.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];t.multi&&s.push("os-dock__item--multi");const i=Y(b.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const a=this.resolveIcon(t.icon,t.title,t.url,qs(t.id));if(r.appendChild(a),t.badge>0){const d=t.badge>99?"99+":String(t.badge),u=document.createElement("span");u.className="os-dock__badge",u.textContent=d,u.setAttribute("aria-label",le(un("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const l=this.resolveItemBaseId(t),c=np({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(l),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(t),suppressTooltip:d=>{d&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(t.id,c),Y(b.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n,o){let r=!1,a=0,l=0,c=[],d=null,u=-1,f=null,p=!1;const w=()=>{r=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",$),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",k,!0),window.removeEventListener("blur",W),document.removeEventListener("visibilitychange",N),u=-1,f=null},m=o==="controls"?this.systemHost:this.itemHost,h=g=>!!g&&g instanceof HTMLElement&&g.classList.contains("os-dock__item")&&g.dataset.zone===o&&!!g.dataset.navId&&g.dataset.navLocked===void 0,y=g=>{for(const C of Array.from(m.children))C instanceof HTMLElement&&C!==t&&h(C)&&g(C)},v=()=>{const g=[];for(const C of Array.from(m.children))h(C)&&g.push(C.dataset.navId);return g},A=g=>{y(C=>{const U=g.get(C);if(!U)return;const V=C.getBoundingClientRect(),z=U.left-V.left,I=U.top-V.top;if(Math.abs(z)<.5&&Math.abs(I)<.5)return;C.style.transition="none",C.style.transform=`translate(${z}px, ${I}px)`,C.offsetHeight,C.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",C.style.transform="";const x=()=>{C.style.transition="",C.style.transform="",C.removeEventListener("transitionend",x)};C.addEventListener("transitionend",x)})},D=g=>{if(u!==-1&&g.pointerId!==u)return;if(!r){const j=g.clientX-a,R=g.clientY-l;if(j*j+R*R<5*5)return;r=!0,c=v(),d=t.nextSibling,f=t.getBoundingClientRect(),t.classList.add("os-dock__item--dragging"),this.tooltip.classList.remove("os-dock__tooltip--visible")}if(!f)return;const C=g.clientX-a,U=g.clientY-l;t.style.transform=`translate(${C}px, ${U}px)`;const z=document.elementFromPoint(g.clientX,g.clientY)?.closest(".os-dock__item");if(!z||z===t||!h(z))return;const I=z.getBoundingClientRect();let x;this.orientation==="bottom"?x=g.clientX<I.left+I.width/2:x=g.clientY<I.top+I.height/2;const B=new Map;y(j=>{B.set(j,j.getBoundingClientRect())});let M=!1;if(x?z!==t.nextSibling&&(m.insertBefore(t,z),M=!0):z.nextSibling!==t&&(m.insertBefore(t,z.nextSibling),M=!0),M){t.style.transform="";const j=t.getBoundingClientRect();a=j.left+j.width/2,l=j.top+j.height/2,t.style.transform=`translate(${g.clientX-a}px, ${g.clientY-l}px)`,A(B)}},_=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",$),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",k,!0),window.removeEventListener("blur",W),document.removeEventListener("visibilitychange",N),u=-1,f=null,r=!1,We.activeDragReset===w&&(We.activeDragReset=null)},O=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const g=()=>{t.style.transition="",t.removeEventListener("transitionend",g)};t.addEventListener("transitionend",g)},P=g=>{Mk(g)},$=g=>{if(u!==-1&&g.pointerId!==u)return;if(!r){_();return}p=!0;const C=v();O(),_(),C.length===c.length&&C.every((V,z)=>V===c[z])||P(C),setTimeout(()=>{p=!1},200)},F=g=>{if(!(g&&u!==-1&&g.pointerId!==u)){if(r&&d!==void 0){const C=new Map;y(U=>{C.set(U,U.getBoundingClientRect())}),m.insertBefore(t,d),A(C)}O(),_()}},k=g=>{g.key==="Escape"&&F()},W=()=>F(),N=()=>{document.visibilityState!=="visible"&&F()};t.addEventListener("pointerdown",g=>{if(g.button===0){if(We.activeDragReset){const C=We.activeDragReset;We.activeDragReset=null,C()}(r||u!==-1)&&w(),a=g.clientX,l=g.clientY,u=g.pointerId,r=!1,We.activeDragReset=w,document.addEventListener("pointermove",D),document.addEventListener("pointerup",$),document.addEventListener("pointercancel",F),document.addEventListener("keydown",k,!0),window.addEventListener("blur",W),document.addEventListener("visibilitychange",N)}}),t.addEventListener("click",g=>{p&&(g.preventDefault(),g.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=Vs(s);a!==null&&(t=a,i=!0),r=Zr(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if(ho(a,t,r))return a}if(t.startsWith("dashicons-")&&(i||t!=="dashicons-admin-generic")){const a=document.createElement("span");return a.className=`dashicons ${t}`,a.setAttribute("aria-hidden","true"),r!==null&&(a.style.color=r),a}if(t.startsWith("data:image/svg+xml;base64,")){const a=t.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(a))return this._makeSvgIcon(t)}if(t.startsWith("url("))return this._makeSvgIcon(t);if(t.startsWith("http://")||t.startsWith("https://")){const a=document.createElement("img");return a.className="os-dock__item-img",a.src=t,a.alt="",a.setAttribute("aria-hidden","true"),a}if(o&&!i){const a=this._extractNativeMenuIcon(o);if(a)return a}if(t==="dashicons-admin-generic"){const a=document.createElement("span");return a.className="dashicons dashicons-admin-generic",a.setAttribute("aria-hidden","true"),a}return this.createLetterBadge(n)}_makeMaskSpan(){const t=document.createElement("span");return t.className="os-dock__item-mask",t.setAttribute("aria-hidden","true"),t.style.width="var( --os-dock-icon-size, 20px )",t.style.height="var( --os-dock-icon-size, 20px )",t.style.display="block",t.style.flexShrink="0",t}_makeSvgIcon(t){const n=/^url\(\s*(['"]?)(.+?)\1\s*\)$/.exec(t),o=n?n[2]:t,s=this._makeMaskSpan();if(ho(s,o,"currentColor"))return s;const i=document.createElement("span");return i.className="os-dock__item-svg",i.style.backgroundImage=t.startsWith("url(")?t:`url("${t}")`,i.style.backgroundSize="contain",i.style.backgroundRepeat="no-repeat",i.style.backgroundPosition="center",i.setAttribute("aria-hidden","true"),i}_extractNativeMenuIcon(t){const n=document.getElementById("adminmenu");if(!n)return null;let o;try{const f=new URL(t,window.location.href);o=(f.pathname.split("/").pop()||"")+f.search}catch{return null}if(!o)return null;const s=n.querySelectorAll("li.menu-top > a");let i=null;for(const f of Array.from(s))if(f.href.endsWith(o)){i=f.closest("li.menu-top");break}if(!i)return null;const r=i.querySelector(".wp-menu-image");if(!r)return null;const a=r.querySelector("img");if(a&&a.src){const f=document.createElement("img");return f.className="os-dock__item-img",f.src=a.src,f.alt="",f.setAttribute("aria-hidden","true"),f}const l=r.className.match(/\bdashicons-[\w-]+\b/);if(l&&l[0]!=="dashicons-before"){const f=document.createElement("span");return f.className=`dashicons ${l[0]}`,f.setAttribute("aria-hidden","true"),f}const d=window.getComputedStyle(r,"::before").backgroundImage;if(d&&d!=="none"&&!d.includes('url("")'))return this._makeSvgIcon(d);const u=window.getComputedStyle(r).backgroundImage;return u&&u!=="none"&&!u.includes('url("")')?this._makeSvgIcon(u):null}createLetterBadge(t){const n=document.createElement("span");n.className="os-dock__item-letter",n.setAttribute("aria-hidden","true");const o=t.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=vn(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(t,n,o){const s=Y(b.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("os-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("os-dock__tooltip--visible")}))}positionTooltip(t,n){const o=t.getBoundingClientRect();this.tooltip.textContent=n,this.orientation==="bottom"?(this.tooltip.style.left=`${o.left+o.width/2}px`,this.tooltip.style.top=`${o.top-14}px`):this.orientation==="right"?(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.left}px`):(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.right+8}px`)}openPage(t){if(t.windowId&&!t.url){const o=this.windowManager.getById(t.windowId);if(o){this.windowManager.focus(o);return}window.wp?.os?.openWindow?.(t.windowId);return}if(_n(t.url)||Ge(t.url))return;const n=this.deriveWindowId(t.url);this.windowManager.open({id:n,baseId:n,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}openNewInstance(t){if(_n(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=pa(t.url);if(o&&n?.(o,{source:"dock-peek"}))return;const s=this.deriveWindowId(t.url);this.windowManager.openNew({id:s,baseId:s,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,selfLabel:t.selfLabel,multi:!0})}deriveWindowId(t){return ae(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:pa(t.url)??this.deriveWindowId(t.url)}bindWindowEvents(){const t=()=>this.updateActiveStates();this.boundRefresh=t,document.addEventListener("os-window-opened",t),document.addEventListener("os-window-closed",t),document.addEventListener("os-window-focused",t),window.wp?.hooks?.addAction?.("os.os.switched",this.hooksNamespace,t),window.wp?.hooks?.addAction?.("os.os.closed",this.hooksNamespace,t),window.wp?.hooks?.addAction?.(b.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(b.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(b.DOCK_REFRESH_ACTIVE,this.hooksNamespace,t)}destroy(){document.removeEventListener("os-window-opened",this.boundRefresh),document.removeEventListener("os-window-closed",this.boundRefresh),document.removeEventListener("os-window-focused",this.boundRefresh),window.wp?.hooks?.removeAction?.("os.os.switched",this.hooksNamespace),window.wp?.hooks?.removeAction?.("os.os.closed",this.hooksNamespace),window.wp?.hooks?.removeAction?.(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 t of this.attentionTimers.values())window.clearTimeout(t);this.attentionTimers.clear();for(const t of this.peekTeardowns.values())t();for(this.peekTeardowns.clear(),this.tooltip.remove();this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.itemElements.clear(),this.systemItemElements.clear(),this.systemItems=[],this.zones={core:[],apps:[],controls:[]},this.container.removeAttribute("data-os-dock-placement")}updateActiveStates(){const t=this.windowManager.getFocused(),n=this.windowManager.getActiveDesktopId(),o=i=>(i.config.desktopId||n)===n,s=i=>i.state==="minimized";for(const i of this.items){const r=this.itemElements.get(i.id);if(!r)continue;const a=this.resolveItemBaseId(i);let l=this.windowManager.getAllByBaseId(a).filter(o);if(l.length===0&&i.url){const f=this.deriveWindowId(i.url);l=this.windowManager.getAll().filter(p=>{const w=p.config.baseId||p.id;if(w===a||w===f||w===i.id||p.config.parentUrl&&this.deriveWindowId(p.config.parentUrl)===f)return!0;if(p.config.url){const m=this.deriveWindowId(p.config.url);return m===a||m===f}return!1}).filter(o)}const c=l.length>0,d=c&&l.every(s),u=!!t&&o(t)&&!s(t)&&l.some(f=>f.id===t.id||(t.config.baseId||t.id)===a);r.classList.toggle("os-dock__item--active",c),r.classList.toggle("os-dock__item--focused",u),r.classList.toggle("os-dock__item--all-minimized",d),r.classList.toggle("os-dock__item--stacked",c&&l.length>1)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const a=this.windowManager.getById(i.id),l=i.isOpen?i.isOpen():!!a,c=!!a&&s(a),d=!!t&&t.id===i.id&&!s(t);r.classList.toggle("os-dock__item--active",l),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",c)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("os-show-desktop-active",o)}};We.instanceCounter=0,We.activeDragReset=null;let ci=We;function pp(e,t){const n=e.querySelector(":scope > .os-dock__badge");if(t<=0){n?.remove();return}const o=t>99?"99+":String(t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",le(un("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="os-dock__badge",s.textContent=o,s.setAttribute("aria-label",le(un("%d notification","%d notifications",t),t)),e.appendChild(s)}const hp=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),Aa={id:"default",label:"Icon strip",description:"The shipped baseline — icon tiles with badges, tooltips, multi-instance chips, and attention animations.",icon:"dashicons-menu-alt",apiVersion:1,mount(e){const t=new ci(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[hp]:t,replaceItems:o=>t.replaceItems(o),setZones:o=>t.setZones(o),appendSystemItem:o=>t.appendSystemItem(o),removeSystemItem:o=>t.removeSystemItem(o),setBadge:(o,s)=>t.setBadge(o,s),setAttention:(o,s,i)=>t.setAttention(o,s,i),setOrientation:o=>t.setOrientation(o),destroy:()=>t.destroy()}}};function mp(e){if(!e)return null;const n=e[hp];return n instanceof ci?n:null}function Pk(){Pd(Aa)}const gp="os-desktop-theme-css",Wk="os-desktop-theme-inline-css",Ca="data-os-desktop-theme-css",wp="os-desktop-theme-changed";function yp(){return document.getElementById("os-shell")}function bp(){const e=[];for(const t of[gp,Wk]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${Ca}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function vp(){for(const e of bp())e.remove()}function $k(e){const t=yp();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:bp().length>0}function _p(e){const t=document.body;if(!t)return;const n=[];t.classList.forEach(o=>{o.startsWith("os-desktop-theme-")&&n.push(o)});for(const o of n)(e===null||o!==`os-desktop-theme-${e}`)&&t.classList.remove(o);e!==null&&t.classList.add(`os-desktop-theme-${e}`)}function Ia(e){const t=js(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:_u(o),i=s?s.slug:null;if(i===n)return;const r=yp();if(!s)r?.removeAttribute("data-os-desktop-theme"),_p(null),vp(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!$k(s.slug)){if(vp(),s.cssUrl!==""){const l=document.createElement("link");l.id=gp,l.rel="stylesheet",l.href=s.cssUrl,l.setAttribute(Ca,s.slug),document.head.appendChild(l)}else if(s.cssText!==""){const l=document.createElement("style");l.setAttribute(Ca,s.slug),l.textContent=s.cssText,document.head.appendChild(l)}}r?.setAttribute("data-os-desktop-theme",s.slug),_p(s.slug),t.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(wp,{detail:a}))}const Ep=new Set;function xa(e){if(Ep.has(e))return;const n=window.openStationConfig?.deferredStyles?.[e];if(!n?.url)return;Ep.add(e);const o=n.url.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${o}"]`)){const i=document.createElement("link");i.rel="stylesheet",i.href=n.url,i.dataset.osStyleHandle=e,document.head.appendChild(i)}for(const i of n.inline??[]){if(typeof i!="string"||i==="")continue;const r=document.createElement("style");r.dataset.osStyleHandle=e,r.textContent=i,document.head.appendChild(r)}}function J(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function Uk(e){return!!e&&e.__wpdHtml===!0}const Fk="$$wpd$$",De=/\$\$wpd\$\$(\d+)\$\$/g;function Bk(e){let t=e[0];for(let n=1;n<e.length;n++)t+=`${Fk}${n-1}$$`+e[n];return t}const kp=new WeakMap;function Sp(e){const t=kp.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=Bk(e);const o=[],s=(a,l)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const f of Array.from(u.attributes)){const p=f.name,w=f.value,m=p[0];if(De.test(w))if(De.lastIndex=0,m==="@"){const h=De.exec(w);De.lastIndex=0,o.push({path:l,kind:"event",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else if(m==="."){const h=De.exec(w);De.lastIndex=0,o.push({path:l,kind:"prop",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else if(m==="?"){const h=De.exec(w);De.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else{const h=[],y=[];let v=0,A;for(De.lastIndex=0;(A=De.exec(w))!==null;)h.push(w.slice(v,A.index)),y.push(Number(A[1])),v=A.index+A[0].length;h.push(w.slice(v)),o.push({path:l,kind:"attr",name:p,template:h,valueIndices:y}),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 w=f.textContent||"";if(!De.test(w)){De.lastIndex=0;continue}De.lastIndex=0;const m=f.parentNode;let h=0,y;const v=[],A=[];for(De.lastIndex=0;(y=De.exec(w))!==null;){y.index>h&&v.push(document.createTextNode(w.slice(h,y.index)));const D=document.createTextNode("");v.push(D),A.push({path:[...l,p+v.length-1],kind:"node",valueIndex:Number(y[1])}),h=y.index+y[0].length}h<w.length&&v.push(document.createTextNode(w.slice(h)));for(const D of v)m.insertBefore(D,f);m.removeChild(f),d+=v.length-1,o.push(...A)}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 kp.set(e,r),r}const Ap=new WeakMap;function Hk(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function zk(e,t){const n=Ap.get(t);if(n&&n.strings===e.strings&&Hk(n,t)){di(n.parts,e.values);return}const o=Sp(e.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s),di(i,e.values),Ap.set(t,{strings:e.strings,parts:i,nodes:r})}function di(e,t){for(const n of e)if(n.kind==="node")La(n.child,t[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;s<n.valueIndices.length;s++)o+=Cp(t[n.valueIndices[s]]),o+=n.template[s+1];o!==n.last&&(n.last=o,o===""?n.element.removeAttribute(n.name):n.element.setAttribute(n.name,o))}else if(n.kind==="event"){const o=t[n.valueIndex];o!==n.current&&(n.current&&n.element.removeEventListener(n.name,n.current),o&&n.element.addEventListener(n.name,o),n.current=o)}else if(n.kind==="prop"){const o=t[n.valueIndex];o!==n.last&&(n.last=o,n.element[n.name]=o)}else if(n.kind==="bool"){const o=!!t[n.valueIndex];o!==n.last&&(n.last=o,o?n.element.setAttribute(n.name,""):n.element.removeAttribute(n.name))}}function La(e,t){if(t==null||t===!1){e.state&&(Ht(e.state),e.state=null);return}if(Array.isArray(t)){qk(e,t);return}if(Uk(t)){Vk(e,t);return}if(t instanceof Node){Gk(e,t);return}jk(e,Cp(t))}function Gk(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Ht(n),ui(e,[t]),e.state={shape:"node",node:t})}function jk(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Ht(n);const o=document.createTextNode(t);ui(e,[o]),e.state={shape:"text",node:o,text:t}}function Vk(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){di(n.parts,t.values);return}n&&Ht(n);const o=Sp(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);ui(e,[s]),di(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function qk(e,t){const n=e.state;if(n?.shape==="array"&&n.entries.length===t.length){for(let s=0;s<t.length;s++)La(n.entries[s],t[s]);return}n&&Ht(n);const o=[];for(const s of t){const i=document.createTextNode("");ui(e,[i]);const r={anchor:i,state:null};La(r,s),o.push(r)}e.state={shape:"array",entries:o}}function ui(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Ht(e){if(e.shape==="text"){e.node.remove();return}if(e.shape==="template"){for(const t of e.parts)t.kind==="node"&&t.child.state&&(Ht(t.child.state),t.child.state=null);for(const t of e.nodes)t.parentNode&&t.parentNode.removeChild(t);return}if(e.shape==="node"){e.node.parentNode&&e.node.parentNode.removeChild(e.node);return}for(const t of e.entries)t.state&&Ht(t.state),t.anchor.remove()}function Cp(e){return e==null||e===!1?"":String(e)}const Dt=class Dt 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(Ip)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=Kk(t);this._propValues[s]=o,this.requestUpdate()}get classNames(){return Array.from(this.classList)}set classNames(t){if(t==null){this.removeAttribute("class");return}const o=(Array.isArray(t)?t:String(t).split(/\s+/)).map(s=>String(s).trim()).filter(s=>s!=="");this.className=o.join(" ")}requestUpdate(){this._scheduleRender()}emit(t,n){return this.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,composed:!0}))}_installPropAccessors(){const t=this.constructor;for(const n of t.props){if(Object.getOwnPropertyDescriptor(this,n))continue;const o=Ip(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&&zk(this.render(),this._renderRoot)}))}_adoptStyles(){const t=this.constructor;if(t.styles.length!==0)if(t.shadow&&this.shadowRoot){const n=t.styles.map(o=>o.sheet).filter(o=>o!==null);if(this.shadowRoot.adoptedStyleSheets=n,n.length!==t.styles.length){for(const o of t.styles)if(!o.sheet){const s=document.createElement("style");s.textContent=o.cssText,this.shadowRoot.appendChild(s)}}}else this._adoptLightStyles(t)}_adoptLightStyles(t){if(!Dt._lightStylesAdopted.has(t)){Dt._lightStylesAdopted.add(t);for(const n of t.styles){const o=document.createElement("style");o.dataset.osUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};Dt.props=[],Dt.styles=[],Dt.shadow=!0,Dt._lightStylesAdopted=new WeakSet;let Se=Dt;function xe(e,t){customElements.get(e)||customElements.define(e,t)}function Ip(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Kk(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const Yk=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function de(e,...t){let n=e[0];for(let o=1;o<e.length;o++){const s=t[o-1];if(typeof s=="string"||typeof s=="number")n+=String(s);else if(s&&s.__wpdCss)n+=s.cssText;else throw new TypeError("[os-ui] css`` interpolations must be strings, numbers, or other css`` results. Got: "+typeof s);n+=e[o]}if(Yk){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function Xk(e){const t=[],n=[];let o=null,s=e.parentElement;for(;s&&!(s===document.body||s===document.documentElement);){const r=s.id||"";if(r.startsWith("wp-window-")){o=r.slice(10);break}if(s.tagName.toLowerCase()==="os-tabpanel"){const a=s.getAttribute("for");a&&n.unshift(a)}s=s.parentElement}o&&t.push(Ta(o));for(const r of n)t.push("tab-"+Ta(r));const i=e.getAttribute("label");return i&&t.push(Ta(i)),t.length===0?"os-unnamed":"os-"+t.filter(r=>r!=="").join("-")}function Ta(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function xp(e){if(e.id)return e.id;const t=Xk(e);return e.id=t,t}const fi=new Map;function Lp(e){if(!e||typeof e.id!="string"||e.id===""){typeof console<"u"&&console.warn("[openstation] Ignored invalid module registration:",e);return}if(typeof e.url!="string"||e.url===""){typeof console<"u"&&console.warn(`[openstation] Module "${e.id}" has no url; ignored.`);return}fi.set(e.id,e)}function Zk(){return Array.from(fi.keys())}async function Na(e){if(!e||e.length===0)return;const t=e.filter(n=>!fi.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${Zk().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=fi.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():_e(o.url)}))}const En=re("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function Jk(e){En.state.pending.set(e.id,e)}function pi(e){En.state.pending.delete(e)}function Qk(e){return(window.openStationWallpapers||{})[e]??null}function Tp(e){const t=En.state.inflight.get(e);if(t)return t;const n=En.state.pending.get(e);if(!n)return Promise.resolve(null);const o=(async()=>{try{await _e(n.scriptUrl,{translations:n.scriptTranslations,l10n:n.scriptL10n,before:n.scriptBefore,after:n.scriptAfter})}catch(i){return L(b.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=Qk(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return L(b.SHELL_ERROR,{scope:"wallpaper-missing-def",id:n.id,error:new Error(`[openstation] No wallpaper def on window.openStationWallpapers["${n.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)}),null;try{bn(s)}catch(i){return L(b.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return pi(n.id),s})().finally(()=>{En.state.inflight.delete(e)});return En.state.inflight.set(e,o),o}function eS(e){return{id:e.id,label:e.label,type:"canvas",preview:e.preview!==""?e.preview:e.value,description:e.description||void 0,mount:async(t,n)=>{const o=await Tp(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await Na(o.needs),o.mount(t,n))}}}const ft=de`: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 ) )}`,tS=de` .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%}}`,Da=de` .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%}}`,Np=de` .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}}`,Dp=de` .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}}`,Rp=de` .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}}`,Op=de` .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%}}`,nS=de` .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}}`,Ra=de` 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}}`,oS=de` input[ type='checkbox' ],input[ type='radio' ]{appearance:none;-webkit-appearance:none;position:relative;flex:0 0 auto;box-sizing:border-box;width:16px;height:16px;margin:0;padding:0;border:1px solid var( --_holo-track-edge );border-radius:4px;background-color:var( --_holo-track );background-image:none;background-repeat:no-repeat;cursor:inherit;transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input[ type='radio' ]{border-radius:50%}input[ type='checkbox' ]:hover:not(:disabled ),input[ type='radio' ]:hover:not(:disabled ){border-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:focus-visible,input[ type='radio' ]:focus-visible{outline:none;box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked,input[ type='checkbox' ]:indeterminate,input[ type='radio' ]:checked{border-color:transparent;background-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:checked:focus-visible,input[ type='radio' ]:checked:focus-visible{box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:46%;width:3.5px;height:7.5px;border:solid var( --os-ui-fg-on-accent,#fff );border-width:0 2px 2px 0;transform:translate( -50%,-50% ) rotate( 45deg );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:indeterminate::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:8px;height:2px;border:0;border-radius:1px;background:var( --os-ui-fg-on-accent,#fff );transform:translate( -50%,-50% )}input[ type='radio' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:6px;height:6px;border-radius:50%;background:var( --os-ui-fg-on-accent,#fff );transform:translate( -50%,-50% );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:disabled,input[ type='radio' ]:disabled{cursor:not-allowed}@keyframes os-holo-tick{from{opacity:0;transform:translate( -50%,-50% ) rotate( 45deg ) scale( 0.4 )}}@media ( prefers-reduced-motion:reduce ){input[ type='checkbox' ]:checked::after,input[ type='radio' ]:checked::after{animation:none}}`,Mp=de` @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}}`;de` ${ft} ${tS} ${Da} ${Np} ${Dp} ${Rp} ${Op} ${nS} ${Ra} ${oS} ${Mp} `;const sS=de` ${ft}:host{display:none;position:fixed;inset:0;align-items:center;justify-content:center;background:var( --os-ui-scrim,rgba( 0,0,0,0.45 ) );background-image:var( --os-ui-scrim-image,none );background-repeat:var( --os-ui-scrim-image-repeat,repeat );background-size:var( --os-ui-scrim-image-size,auto );background-position:var( --os-ui-scrim-image-position,center );backdrop-filter:blur( 2px );z-index:10000;--os-ui-fg:var( --os-ui-modal-text,#f0f0f1 );--os-ui-fg-muted:var( --os-ui-modal-text-muted,#a7aaad );--os-ui-border:var( --os-ui-modal-border,rgba( 255,255,255,0.25 ) );--os-window-bg:var( --os-ui-modal-field-bg,#2c3338 );--os-ui-button-bg-hover:var( --os-ui-modal-button-bg-hover,rgba( 255,255,255,0.08 ) );--os-ui-surface:var( --os-ui-modal-surface,#2c3338 );--os-ui-surface-elevated:var( --os-ui-modal-surface-elevated,#3c434a );--os-ui-border-strong:var( --os-ui-modal-border-strong,rgba( 255,255,255,0.35 ) );--os-ui-hover:var( --os-ui-modal-hover,rgba( 255,255,255,0.08 ) )}:host( [ open ] ){display:flex;animation:os-modal-scrim var( --_holo-t ) var( --_holo-ease )}:host( [ open ] ) .dialog{animation:os-modal-dialog var( --_holo-t ) var( --_holo-spring )}@keyframes os-modal-scrim{from{opacity:0}}@keyframes os-modal-dialog{from{opacity:0;transform:scale( 0.96 ) translateY( 8px )}}@media ( prefers-reduced-motion:reduce ){:host( [ open ] ),:host( [ open ] ) .dialog{animation:none}}.dialog{max-width:92vw;max-height:90vh;background-color:var( --os-ui-modal-bg,#1d2327 );background-image:var( --os-ui-dialog-bg-image,none );background-repeat:var( --os-ui-dialog-bg-image-repeat,repeat );background-size:var( --os-ui-dialog-bg-image-size,auto );background-position:var( --os-ui-dialog-bg-image-position,center );color:var( --os-ui-modal-fg,var( --os-fg,#fff ) );border:1px solid var( --os-ui-border,rgba( 255,255,255,0.08 ) );border-radius:10px;box-shadow:0 20px 50px rgba( 0,0,0,0.6 );display:flex;flex-direction:column;overflow:hidden}:host( [ size='sm' ] ) .dialog{width:min( 360px,92vw )}:host(:not( [ size ] ) ) .dialog,:host( [ size='md' ] ) .dialog{width:min( 540px,92vw )}:host( [ size='lg' ] ) .dialog{width:min( 760px,94vw )}.header{display:flex;align-items:center;gap:10px;padding:16px 20px 12px;border-bottom:1px solid var( --os-ui-border,rgba( 255,255,255,0.06 ) )}.title{margin:0;flex:1;font-size:15px;font-weight:600}.header-actions{display:flex;gap:6px}.header-actions::slotted( * ){margin-inline-start:6px}.close{background:transparent;border:0;color:inherit;font-size:18px;line-height:1;padding:4px 8px;border-radius:4px;cursor:pointer;opacity:0.7}.close:hover{opacity:1;background:var( --os-ui-hover,rgba( 255,255,255,0.08 ) )}.body{padding:16px 20px;overflow:auto;flex:1 1 auto;font-size:13px;line-height:1.5}.footer{padding:12px 20px 16px;border-top:1px solid var( --os-ui-border,rgba( 255,255,255,0.06 ) )}.footer slot{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap}:host( [ mandatory ] ) .close{display:none}`,Pp='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',bs=class bs extends Se{constructor(){super(...arguments),this._prevFocus=null,this._onKey=t=>{if(t.key==="Escape"&&!this.hasAttribute("mandatory")){t.preventDefault(),this._cancel();return}if(t.key==="Tab"){const n=this._focusables();if(n.length===0)return;const o=n[0],s=n[n.length-1],i=this.ownerDocument,r=i?i.activeElement:null,a=t.composedPath()[0]||r;t.shiftKey&&a===o?(t.preventDefault(),s.focus()):!t.shiftKey&&a===s&&(t.preventDefault(),o.focus())}},this._onBackdrop=t=>{if(this.hasAttribute("mandatory"))return;const n=t.composedPath();(n.length>0?n[0]:t.target)===this&&this._cancel()}}connectedCallback(){super.connectedCallback(),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","true"),this.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback?.(t,n,o),t==="open"){if(o!==null){const s=this.ownerDocument;this._prevFocus=s?s.activeElement:null,queueMicrotask(()=>this._focusFirst())}else if(this._prevFocus){try{this._prevFocus.focus()}catch{}this._prevFocus=null}}}showModal(){this.setAttribute("open","")}hideModal(){this.removeAttribute("open")}_focusables(){const t=this.shadowRoot;if(!t)return[];const n=Array.from(this.querySelectorAll(Pp)),o=Array.from(t.querySelectorAll(Pp));return[...n,...o].filter(s=>s.offsetParent!==null||s.tagName==="BUTTON")}_focusFirst(){const t=this._focusables();t.length>0?t[0].focus():this.shadowRoot?.querySelector(".dialog")?.focus?.()}_cancel(){const t=new CustomEvent("os-modal-cancel",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(t)&&this.hideModal()}render(){const t=this.getAttribute("title")??"",n=this.hasAttribute("mandatory");return J` |
| 2 |
<div part="dialog" class="dialog" tabindex="-1"> |
| 3 |
${t?J` |
| 4 |
<div class="header"> |
| 5 |
<h2 class="title">${t}</h2> |
| 6 |
<div class="header-actions"> |
| 7 |
<slot name="header-actions"></slot> |
| 8 |
${n?J``:J`<button |
| 9 |
type="button" |
| 10 |
class="close" |
| 11 |
aria-label="Close" |
| 12 |
@click=${()=>this._cancel()} |
| 13 |
>×</button>`} |
| 14 |
</div> |
| 15 |
</div> |
| 16 |
`:J``} |
| 17 |
<div class="body"> |
| 18 |
<slot></slot> |
| 19 |
</div> |
| 20 |
<div class="footer"> |
| 21 |
<slot name="footer"></slot> |
| 22 |
</div> |
| 23 |
</div> |
| 24 |
`}};bs.props=["open","title","size","mandatory"],bs.styles=[sS],bs.help=void 0;let Oa=bs;xe("os-modal",Oa);const iS=de` ${ft} ${Da} ${Np} ${Dp} ${Rp} ${Mp}: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 )}}`,vs=class vs extends Se{render(){const t=this.disabled!==null,n=this.busy!==null,o=this.type||"button";return J` |
| 25 |
<button |
| 26 |
part="button" |
| 27 |
class="os-holo-edge os-holo-sheen" |
| 28 |
type=${o} |
| 29 |
?disabled=${t||n} |
| 30 |
aria-busy=${n?"true":"false"} |
| 31 |
> |
| 32 |
${n?J`<span class="os-button__spinner" aria-hidden="true"></span>`:""} |
| 33 |
<slot></slot> |
| 34 |
<!-- |
| 35 |
The two motion layers. Elements rather than |
| 36 |
pseudo-elements because the sheen and the hairline |
| 37 |
have already taken this button's ::before and |
| 38 |
::after — see the pseudo-element budget note in |
| 39 |
src/ui/holo.ts. Both are inert and aria-hidden. |
| 40 |
--> |
| 41 |
<span class="os-holo-glint" aria-hidden="true"></span> |
| 42 |
<span class="os-holo-ring" aria-hidden="true"></span> |
| 43 |
</button> |
| 44 |
`}};vs.props=["variant","disabled","type","busy","fill-cell"],vs.styles=[iS],vs.help=void 0;let Ma=vs;xe("os-button",Ma);function Wp(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}const rS=()=>E("Mix your own two-colour gradient and set the angle — your desk, your palette.");function aS(e){bn({id:p_,label:E("Custom gradient"),type:"css",preview:Wp(e.state),description:rS(),resolveValue:()=>Wp(e.state)})}function lS(e){if(!e.customImage){jf(uu);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`;bn({id:uu,label:E("Custom image"),type:"css",value:n,preview:n,description:E("Any image from your media library or an upload, sized to cover the whole desk.")})}let hi=null;function cS(e){return window.openStationRenderOsSettingsPanel?Promise.resolve(window.openStationRenderOsSettingsPanel):hi||(hi=new Promise((t,n)=>{const o=document.querySelector('script[data-os-settings-panel="1"]'),s=()=>{const r=window.openStationRenderOsSettingsPanel;if(!r){n(new Error("[openstation] os-settings-panel bundle loaded but did not register openStationRenderOsSettingsPanel"));return}t(r)};if(o){window.openStationRenderOsSettingsPanel?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osSettingsPanel="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))),document.head.appendChild(i)}),hi)}class dS{constructor(t,n){this.activeEditorTeardown=null,this.tabRegistryUnsubscribe=null,this.activeTabId=null,this.tabChangeAbort=null,this.osSettingsListeners=new Set,this._lastRenderedBody=null,this.config=t,this.layer=n,this.state=j0(),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))}),aS(this),lS(this.state)}getOsSettingsSnapshot(){return{wallpaper:this.state.wallpaper,accent:this.state.accent,dockSize:this.state.dockSize,windowRadius:this.state.windowRadius,adminBarMode:this.state.adminBarMode,desktopLayout:this.state.desktopLayout,dockPlacement:this.state.dockPlacement,dockRailRenderer:this.state.dockRailRenderer,desktopTheme:this.state.desktopTheme,appliedThemeRecommendations:this.state.appliedThemeRecommendations.slice(),unfocusEffect:this.state.unfocusEffect,windowReveal:this.state.windowReveal,windowRevealDuration:this.state.windowRevealDuration,windowLinkRenderer:this.state.windowLinkRenderer,windowLinkVisibility:this.state.windowLinkVisibility,windowLinksEnabled:this.state.windowLinksEnabled,windowLinkRaiseOnFocus:this.state.windowLinkRaiseOnFocus,windowLinkHighlight:this.state.windowLinkHighlight,ai:{...this.state.ai},nativePostsEnabled:this.state.nativePostsEnabled,nativePostsHiddenColumns:this.state.nativePostsHiddenColumns.slice(),nativePagesEnabled:this.state.nativePagesEnabled,nativeUsersEnabled:this.state.nativeUsersEnabled,nativePluginsEnabled:this.state.nativePluginsEnabled,nativeCommentsEnabled:this.state.nativeCommentsEnabled,stationHomeEnabled:this.state.stationHomeEnabled,developerModeEnabled:this.state.developerModeEnabled,foldersSharingEnabled:this.state.foldersSharingEnabled,showPostStatusRibbons:this.state.showPostStatusRibbons,navPlacement:{...this.state.navPlacement},navOrder:this.state.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(this.state.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}subscribeOsSettings(t){return this.osSettingsListeners.add(t),()=>{this.osSettingsListeners.delete(t)}}apply(){const t=document.getElementById("os-shell");if(!t)return;H0(this.state.wallpaperSettings);const n=ga(this.state.wallpaper)||ga(hu())||ga(Vr)||qf()[0];n&&this.layer.apply(n);const o=qr(),s=o.find(f=>f.id===this.state.accent)??o[0],i=this.state.accent===fu?this.state.customAccent:s.value,r=Kr.find(f=>f.id===this.state.dockSize)??Kr[1],a=Yr.find(f=>f.id===this.state.windowRadius)??Yr[1],l=document.body;l.style.setProperty("--wp-admin-theme-color",i),l.style.setProperty("--os-ui-accent",i);const d=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;d===null?l.style.removeProperty("--os-ui-accent-dim"):l.style.setProperty("--os-ui-accent-dim",d),t.style.setProperty("--os-ui-accent",i),d===null?t.style.removeProperty("--os-ui-accent-dim"):t.style.setProperty("--os-ui-accent-dim",d),l.style.setProperty("--os-dock-width",`${r.width}px`),l.style.setProperty("--os-dock-icon-size",`${r.icon}px`),l.style.setProperty("--os-window-radius",`${a.value}px`),t.style.setProperty("--os-window-radius",`${a.value}px`);const u=Gs.find(f=>f.id===this.state.adminBarMode)??Gs[0];for(const f of Gs)document.body.classList.toggle(`os-admin-bar-${f.id}`,f.id===u.id);t.setAttribute("data-os-layout",this.state.desktopLayout),Pv(this.state.dockRailRenderer),Ia(this.state.desktopTheme)}save(t={}){if(Q0(this.state,t),this.osSettingsListeners.size>0){const n=this.getOsSettingsSnapshot(),o=Array.from(this.osSettingsListeners);for(const s of o)try{s(n)}catch(i){typeof console<"u"&&console.error("[openstation] os-settings listener threw:",i)}}}focusTab(t){this.activeTabId=t;const n=this._lastRenderedBody;if(!n?.isConnected)return;const o=n.querySelector("os-tabs");o&&(o.value=t)}renderPanel(t){xa("os-settings"),this._lastRenderedBody=t;const n=window.openStationRenderOsSettingsPanel;if(n){n(this,t);return}cS(this.config.osSettingsPanelBundleUrl??"").then(o=>{t.isConnected&&o(this,t)}).catch(o=>{typeof console<"u"&&console.error("[openstation] OpenStation Preferences panel failed to load:",o)})}}const uS={userId:null,requestedAt:0,tabRequested:!1};let mi=null;function fS(){if(mi)return mi;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(mi=t("desktop-mode/user-edit/target",()=>({...uS})),mi)}function pS(e){const t=fS();if(t){t.state.userId=e,t.state.requestedAt=Date.now(),t.state.tabRequested=!0,t.notify();return}const n=window;n._wpdUserEditTarget={userId:e,requestedAt:Date.now(),tabRequested:!0}}let gi=null;function hS(){if(gi)return gi;const e=window.wp?.os?.createSharedStore;return typeof e!="function"?null:(gi=e("desktop-mode/comments/post-filter",()=>({postId:0})),gi)}function $p(e){const t=hS();t&&(t.state.postId=e,t.notify())}function mS(){$p(0)}function Up(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:gS(),visible:!document.hidden,settings:B0(e)}}function gS(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class Fp{constructor(t,n){this.generation=0,this.active=null,this.suspendReasons=new Map,this.freezeOverlay=null,this.frozenCanvas=null,this.boundVisibilityChange=()=>{this.emitEffectiveVisibility()},this.element=t,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(t){const n=++this.generation;if(this.teardownActive(),t.type==="css"){this.applyCss(t);return}this.applyCanvas(t,n)}suspend(t){const n=this.isSuspended();this.suspendReasons.set(t,(this.suspendReasons.get(t)??0)+1),!n&&(this.installFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}resume(t){const n=this.suspendReasons.get(t);if(n!==void 0){if(n>1){this.suspendReasons.set(t,n-1);return}this.suspendReasons.delete(t),!this.isSuspended()&&(this.removeFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}}isSuspended(){return this.suspendReasons.size>0}teardownActive(){if(this.removeFreezeOverlay(),!this.active)return;const{id:t,teardown:n}=this.active;this.active=null,L(b.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){L(b.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(t){const n=t.resolveValue?t.resolveValue(Up(t.id,this.pluginUrl)):t.value;typeof n=="string"&&(this.element.style.setProperty("--os-bg",n),document.getElementById("os-shell")?.style.setProperty("--os-bg",n))}applyCanvas(t,n){const o=Up(t.id,this.pluginUrl);L(b.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?Na(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},L(b.WALLPAPER_MOUNTED,{id:t.id,container:this.element,ctx:o}),this.isEffectivelyHidden()&&this.emitEffectiveVisibility()};s.then(()=>{if(n!==this.generation)return;let r;try{r=t.mount(this.element,o)}catch(a){this.handleMountFailure(t.id,a);return}if(wS(r)){r.then(i,a=>{n===this.generation&&this.handleMountFailure(t.id,a)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(t.id,r)})}isEffectivelyHidden(){return document.hidden||this.isSuspended()}emitEffectiveVisibility(){this.active&&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 t=this.element.querySelector("canvas");if(!(!t||t.width===0||t.height===0))try{const n=document.createElement("canvas");n.width=t.width,n.height=t.height;const o=n.getContext("2d");if(!o)return;o.drawImage(t,0,0),n.className="os-wallpaper-freeze",n.style.position="absolute",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.setAttribute("aria-hidden","true"),this.element.appendChild(n),t.style.visibility="hidden",this.freezeOverlay=n,this.frozenCanvas=t}catch{}}removeFreezeOverlay(){this.freezeOverlay?.remove(),this.freezeOverlay=null,this.frozenCanvas&&(this.frozenCanvas.style.visibility="",this.frozenCanvas=null)}handleMountFailure(t,n){this.element.innerHTML="",L(b.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),L(b.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function wS(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const Bp=re("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),kn=Bp.state.seed,Pa=Bp.state.listeners;function Wa(e){Ne("Game",Mt(e,jp),e);const t=kn.findIndex(n=>n.id===e.id);t>=0?kn[t]=e:kn.push(e),zp()}function Hp(e){const t=kn.findIndex(n=>n.id===e);t>=0&&(kn.splice(t,1),zp())}function yS(e){return Pa.add(e),()=>{Pa.delete(e)}}function zp(){const e=Array.from(Pa);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function Gp(){const e=kn.slice(),t=Y(b.GAMES,e);return Array.isArray(t)?t.filter(bS):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function wi(e){return Gp().find(t=>t.id===e)}const jp=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"title",message:"missing or not a non-empty string",valid:e=>typeof e.title=="string"&&e.title!==""},{field:"scoreColumns",message:"must be an array",valid:e=>Array.isArray(e.scoreColumns)},{field:"render/scriptUrl",message:"needs a `render` callback or a `scriptUrl` to lazily load one",valid:e=>typeof e.render=="function"||typeof e.scriptUrl=="string"&&e.scriptUrl!==""}];function bS(e){return Mt(e,jp).length===0}const vS="desktop-mode/games";function _S(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function go(e,t={},n={}){const{restUrl:o,restNonce:s}=_S(),i=new Headers(t.headers??{});i.set("X-WP-Nonce",s),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Fe(ot(o,e),{...t,headers:i,credentials:"same-origin"},{source:vS,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 ES(e,t,n={}){return go(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function kS(){return go("desktop-mode/v1/games/playtime")}function SS(e,t,n={}){return go(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function AS(e){return go(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function CS(e,t,n={}){return go(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const IS=6e4;function xS(e,t={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const l=Date.now();o+=Math.max(0,l-n),n=l},r=()=>{i();const l=Math.floor(o/1e3);l<1||(o-=l*1e3,SS(e,l,{windowId:t.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,IS);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const Sn=re("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function LS(){return Sn.state}function $a(e){const t=Sn.state;let n=!1;for(const o of e){if(!o||typeof o.id!="number")continue;const s=t.rows.get(o.id);(!s||s.updatedAtMs!==o.updatedAtMs)&&(t.rows.set(o.id,o),n=!0),o.updatedAtMs>t.version&&(t.version=o.updatedAtMs)}n&&NS()}function TS(e){return Sn.state.listeners.add(e),()=>{Sn.state.listeners.delete(e)}}function NS(){for(const e of Array.from(Sn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function DS(){return Array.from(Sn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function Vp(){return window.wp?.os??{}}const RS=760,OS=560,MS=480,PS=380;async function WS(e){if(typeof e.render=="function")return e;const t=Vp().loadVendorScript;if(!e.scriptUrl||typeof t!="function")throw new Error(`[openstation] Game "${e.id}" has no render callback and no loadable script.`);await t(e.scriptUrl,{translations:e.scriptTranslations,l10n:e.scriptL10n,before:e.scriptBefore,after:e.scriptAfter});const o=window.openStationGames?.[e.id];if(!o||typeof o.render!="function")throw new Error(`[openstation] No game def on window.openStationGames["${e.id}"]. Script loaded but didn't publish a def — check the plugin's global assignment.`);const s={...e,render:o.render,window:o.window??e.window};return Wa(s),s}async function qp(e,t={}){const n=Vp();let o=wi(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);o=await WS(o);const s=o.render;if(typeof s!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);if(typeof n.registerWindow!="function")throw new Error("[openstation] wp.os.registerWindow is missing — the shell must boot before launching games.");const i=`os-game-${e}`,r=`game:${i}`,a=n.windowManager,l=a?.getByBaseId?.(i)??a?.getById(i);if(l){const m=l.config?.desktopId;m&&a?.switchDesktop&&m!==a?.getActiveDesktopId?.()&&a.switchDesktop(m),n.registerWindow({id:i,title:o.title,icon:o.icon,render:()=>{}});return}n.wallpaper?.suspend(r);let c=!1;const d=()=>{c||(c=!0,n.wallpaper?.resume(r))};let u=null;const f=()=>{u?.stop(),u=null};n.onWindow?.(i,{closed:()=>{f(),d()},minimized:()=>u?.pause(),restored:()=>u?.resume()});const p=(m,h)=>{n.activity?.publish("os/game-score-recorded",{game:e,score:m.score,meta:m.meta??{},windowId:i,challengeId:h})},w=m=>{if(t.challenge){const h=t.challenge.id;return CS(h,m,{windowId:i}).then(({challenge:y})=>{$a([y]),p(m,h)})}return ES(e,m,{windowId:i}).then(()=>p(m))};try{await n.registerWindow({id:i,title:o.title,icon:o.icon,width:o.window?.width??RS,height:o.window?.height??OS,minWidth:o.window?.minWidth??MS,minHeight:o.window?.minHeight??PS,render:m=>{const h={windowId:i,container:m,config:o.config??{},challenge:t.challenge,submitScore:w,close:()=>{n.windowManager?.getById(i)?.close()}};u=xS(e,{windowId:i});const y=s(h);return()=>{try{y?.()}finally{f(),d()}}}})}catch(m){throw f(),d(),m}}const Kp={register:Wa,unregister:Hp,list:Gp,get:wi,subscribe:yS,launch:qp,getPlaytime:()=>kS().then(e=>e.playtime)};function $S(e){const{osSettings:t}=e,n=new Set,o=r=>r.type!=="css"||r.value===""?null:{id:r.id,label:r.label,type:"css",value:r.value,preview:r.preview!==""?r.preview:r.value,description:r.description||void 0},s=async r=>{if(n.has(r.id))return;const a=o(r);if(a){bn(a),n.add(r.id),t.apply();return}if(!r.scriptUrl)return;Jk(r);const l=r.preview!==""||r.value!=="";if(l){try{bn(eS(r))}catch(c){L(b.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:c}),pi(r.id);return}n.add(r.id)}if(!l||t.state.wallpaper===r.id){const c=await Tp(r.id);if(!l){if(!c){pi(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(jf(r),pi(r),n.delete(r),t.apply())};return async r=>{const a=new Set;for(const l of r)a.add(l.id);for(const l of Array.from(n))a.has(l)||i(l);for(const l of r)n.has(l.id)||await s(l)}}function US(e){return{id:e.id,title:e.title,icon:e.icon,description:e.description||void 0,scoreColumns:Array.isArray(e.scoreColumns)?e.scoreColumns:[],config:e.config??{},scriptUrl:e.scriptUrl,scriptTranslations:e.scriptTranslations,scriptL10n:e.scriptL10n,scriptBefore:e.scriptBefore,scriptAfter:e.scriptAfter}}function FS(){const e=new Set,t=o=>{try{const s=wi(o.id),i=US(o);Wa(s&&typeof s.render=="function"?{...i,render:s.render,window:s.window}:i)}catch(s){typeof console<"u"&&console.error(`[openstation] Server game "${o.id}" failed to register:`,s);return}e.add(o.id)},n=o=>{e.has(o)&&(Hp(o),e.delete(o))};return async o=>{const s=new Set;for(const i of o)i&&typeof i.id=="string"&&i.id!==""&&s.add(i.id);for(const i of Array.from(e))s.has(i)||n(i);for(const i of o)s.has(i.id)&&t(i)}}function BS(e={}){const t=e.deactivate??(()=>Ia(""));return function(o){E_(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=js().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const yi=new Map,Ua=new Map;let Yp=!1;const Te={contribute(e,t){return yi.set(e,t),()=>{yi.get(e)===t&&yi.delete(e)}},subscribe(e,t){let n=Ua.get(e);return n||(n=new Set,Ua.set(e,n)),n.add(t),()=>{n.delete(t)}}};function HS(){if(Yp)return;Yp=!0;const e=window.jQuery;if(!e){console.warn("[desktop-mode/heartbeat] jQuery missing — Heartbeat bus disabled.");return}e(document).on("heartbeat-send",(...t)=>{const n=t[1];if(n)for(const[o,s]of yi)try{n[o]=s()}catch(i){console.error(`[desktop-mode/heartbeat] supplier for "${o}" threw:`,i)}}),e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n)for(const[o,s]of Ua){const i=n[o];if(i!==void 0)for(const r of s)try{r(i)}catch(a){console.error(`[desktop-mode/heartbeat] subscriber for "${o}" threw:`,a)}}})}let bi=null,vi={installHintDismissed:!1,notificationsEnabled:!1};const Fa=new Set;function Xp(e){if(!e){bi=null;return}bi=e,vi={...e.state},Jp()}function wo(){return{...vi}}function Ba(e){if(vi={...vi,...e},Jp(),!bi)return wo();const t=JSON.stringify(e),n=zS();return fetch(bi.stateUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",...n?{"X-WP-Nonce":n}:{}},body:t}).catch(o=>{typeof console<"u"&&console.warn("[openstation] pwa-state write failed:",o)}),wo()}function Zp(e){return Fa.add(e),()=>{Fa.delete(e)}}function Jp(){const e=wo();for(const t of Array.from(Fa))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function zS(){return window.openStationConfig?.restNonce??""}const GS=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:wo,initPwaState:Xp,subscribePwaState:Zp,updatePwaState:Ba},Symbol.toStringTag,{value:"Module"}));function Ha(e){const t=ke.filter("os/notification-requested",{...e});if(!t||t.cancel===!0||!t.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=Q({message:t.body?t.title+" — "+t.body:t.title}),ke.publish("os/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=Qp(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){Ba({notificationsEnabled:!0}),o=Qp(t),o||r();return}r()}}),i)}function Qp(e){let t=null;try{t=new Notification(e.title,{body:e.body,icon:e.icon,tag:e.tag,requireInteraction:e.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[openstation] Notification ctor threw:",n),null}if(e.onClick){const n=e.onClick;t.onclick=()=>{try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] notification onClick threw:",o)}}}return ke.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function jS(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&Ba({notificationsEnabled:!0}),e}function VS(){return typeof Notification>"u"?"unsupported":Notification.permission}function qS(e){return wi(e)?.title||e}const eh=new Set,th=new Set;async function KS(e){const{challenge:t}=await AS(e.id);$a([t]),await qp(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function YS(e){const t=le(E("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,qS(e.game),String(e.scoreToBeat));Ha({title:E("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),Q({message:t,persistent:!0,dismissible:!0,action:{label:E("Accept & Play"),onClick:()=>{KS(e).catch(n=>{Q({message:n instanceof Error?n.message:E("Could not accept the challenge.")})})}}})}function XS(e){let t;e.result==="beaten"?t=E("%1$s beat your score: %2$s vs your %3$s."):t=E("%1$s did not beat your score: %2$s vs your %3$s.");const n=le(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));Ha({title:E("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),Q({message:n})}function ZS(e){const{currentUserId:t}=e;if(!t)return;Te.contribute("openstation_games_subscribe",()=>({challengesVersion:LS().version})),Te.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&$a(o.challenges)});const n=()=>{for(const o of DS())o.state==="pending"&&o.recipientId===t&&!eh.has(o.id)&&(eh.add(o.id),YS(o)),o.state==="completed"&&o.challengerId===t&&!th.has(o.id)&&(th.add(o.id),XS(o))};TS(n),n()}const nh=/^[a-z0-9_/-]+$/,oh=re("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),zt=oh.state.registry,JS=oh.state.listeners;function _i(e){const t=[],n=typeof e?.slug=="string"?e.slug.trim().toLowerCase():"";!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.slug!="string"||e.slug.trim()===""?t.push("slug (missing)"):nh.test(n)||t.push(`slug (must match ${nh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.run!="function"&&t.push("run (must be a function)")),Ne("Command",t,e),zt.set(n,{...e,slug:n}),za()}function sh(e){zt.delete(e.toLowerCase())&&za()}function Ei(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(zt.entries()))o.owner===e&&(zt.delete(n),t++);return t>0&&za(),t}function ih(){return Array.from(zt.values())}function QS(){const e=[];for(const t of zt.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function eA(e){return zt.get(e.toLowerCase())??null}function za(){const e=Array.from(JS);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function tA(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await _e(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}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.slug)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.slug)}return a},i=r=>{const a=new Set;for(const c of ih())c.owner===r&&a.add(c.slug);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))sh(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const rh=re("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),yo=rh.state.registry,nA=rh.state.listeners;function ah(e){if(!e||typeof e.id!="string"||e.id.trim()===""||typeof e.label!="string"||e.label.trim()===""||typeof e.render!="function")return;const t=e.id.trim().toLowerCase();if(!/^[a-z0-9_\-]+$/.test(t)){typeof console<"u"&&console.warn("[openstation] registerSettingsTab: id must be [a-z0-9_-]+, got",e.id);return}yo.set(t,{...e,id:t}),Ga()}function lh(e){yo.delete(e.toLowerCase())&&Ga()}function oA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(yo.entries()))o.owner===e&&(yo.delete(n),t++);return t>0&&Ga(),t}function ch(){return Array.from(yo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Ga(){const e=Array.from(nA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function sA(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await _e(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}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{oA(r);const a=n.get(r);if(a){const l=new Set(ch().map(c=>c.id));for(const c of a)l.has(c)&&lh(c)}};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))l.has(c)||(i(c),e.delete(c));for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const dh=re("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),bo=dh.state.registry,iA=dh.state.listeners,uh=/^[a-z0-9_/-]+$/;function ki(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):uh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${uh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (missing)"),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)")),Ne("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();bo.set(n,{...e,id:n}),Si()}function rA(e){bo.delete(e.toLowerCase())&&Si()}function aA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(bo.entries()))o.owner===e&&(bo.delete(n),t++);return t>0&&Si(),t}function lA(){return Array.from(bo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Si(){const e=Array.from(iA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] title-bar-button registry listener threw:",n)}}typeof document<"u"&&document.addEventListener("os-settings-save-lifecycle",e=>{const t=e.detail;t&&t.phase==="saved"&&Si()});function cA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await _e(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}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(aA(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const fh=re("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),vo=fh.state.registry,dA=fh.state.listeners,ph=/^[a-z0-9_/-]+$/;function ja(){for(const e of Array.from(dA))try{e()}catch{}}function uA(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):ph.test(e.id.trim().toLowerCase())||t.push(`id (must match ${ph} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.label!="string"&&typeof e.label!="function"?t.push("label (must be a string or a function)"):typeof e.label=="string"&&e.label.trim()===""&&t.push("label (empty)"),typeof e.onSelect!="function"&&t.push("onSelect (must be a function)"),e.isVisible!==void 0&&typeof e.isVisible!="function"&&t.push("isVisible (must be a function when set)"),e.checked!==void 0&&typeof e.checked!="function"?t.push("checked (must be a function when set)"):e.checkable&&typeof e.checked!="function"&&t.push("checked (required when checkable is set)")),Ne("WindowAction",t,e);const n=e.id.trim().toLowerCase();vo.set(n,{...e,id:n}),ja()}function fA(e){vo.delete(String(e||"").toLowerCase())&&ja()}function pA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(vo.entries()))o.owner===e&&(vo.delete(n),t++);return t>0&&ja(),t}function hA(){return Array.from(vo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function mA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await _e(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(b.SHELL_ERROR,{scope:"window-action-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(pA(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const An="none",Va="svg-splines",hh=re("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),_o=hh.state.registry,qa=hh.state.listeners,mh=/^[a-z0-9_/-]+$/;function gh(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):mh.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===An&&t.push('id ("none" is reserved)'):t.push(`id (must match ${mh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.mount!="function"&&t.push("mount (not a function)")),Ne("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();_o.set(n,{...e,id:n}),Ya()}function gA(e){_o.delete(e.toLowerCase())&&Ya()}function wA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(_o.entries()))o.owner===e&&(_o.delete(n),t++);return t>0&&Ya(),t}function wh(){const e=Array.from(_o.values()),t=Y(b.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function Ka(e){return wh().find(t=>t.id===e)}function yA(e){return qa.add(e),()=>{qa.delete(e)}}function Ya(){const e=Array.from(qa);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}const bA=16;function vA(e,t){const n=t.map(i=>({start:Math.max(e.start,i.start),end:Math.min(e.end,i.end)})).filter(i=>i.end>i.start).sort((i,r)=>i.start-r.start),o=[];let s=e.start;for(const i of n)i.start>s&&o.push({start:s,end:i.start}),s=Math.max(s,i.end);return s<e.end&&o.push({start:s,end:e.end}),o}function _A(e,t){const n=e.x+e.width/2,o=e.y+e.height/2,s=t.x-n,i=t.y-o;if(s===0&&i===0)return{x:n,y:o,side:"right"};const r=s!==0?e.width/2/Math.abs(s):1/0,a=i!==0?e.height/2/Math.abs(i):1/0,l=Math.min(r,a),c=n+s*l,d=o+i*l;let u;return r<=a?u=s>0?"right":"left":u=i>0?"bottom":"top",{x:c,y:d,side:u}}function yh(e,t,n,o){for(const s of n)if(!(s.windowId===o||s.zIndex<=t)&&e.x>=s.rect.x&&e.x<=s.rect.x+s.rect.width&&e.y>=s.rect.y&&e.y<=s.rect.y+s.rect.height)return!1;return!0}function EA(e,t,n,o,s){const i=n.filter(c=>c.windowId!==o&&c.zIndex>t),r=[{side:"top",base:{start:e.x,end:e.x+e.width},at:e.y,horizontal:!0},{side:"bottom",base:{start:e.x,end:e.x+e.width},at:e.y+e.height,horizontal:!0},{side:"left",base:{start:e.y,end:e.y+e.height},at:e.x,horizontal:!1},{side:"right",base:{start:e.y,end:e.y+e.height},at:e.x+e.width,horizontal:!1}];let a=null,l=1/0;for(const{side:c,base:d,at:u,horizontal:f}of r){const p=[];for(const{rect:w}of i)(f?w.y<=u&&u<=w.y+w.height:w.x<=u&&u<=w.x+w.width)&&p.push(f?{start:w.x,end:w.x+w.width}:{start:w.y,end:w.y+w.height});for(const w of vA(d,p)){if(w.end-w.start<bA)continue;const m=(w.start+w.end)/2,h=f?m:u,y=f?u:m,v=Math.hypot(s.x-h,s.y-y);v<l&&(l=v,a={x:h,y,side:c})}}return a}function kA(e,t){const n=Math.max(t.x-(e.x+e.width),e.x-(t.x+t.width)),o=Math.max(t.y-(e.y+e.height),e.y-(t.y+t.height));if(n<0&&o<0)return null;const s=Math.max(e.x,t.x),i=Math.min(e.x+e.width,t.x+t.width),r=Math.max(e.y,t.y),a=Math.min(e.y+e.height,t.y+t.height);let l,c;i>=s?l=c=(s+i)/2:t.x>e.x?(l=e.x+e.width,c=t.x):(l=e.x,c=t.x+t.width);let d,u;a>=r?d=u=(r+a)/2:t.y>e.y?(d=e.y+e.height,u=t.y):(d=e.y,u=t.y+t.height);const f=n>=o,p=(w,m,h)=>f?m<=w.x?"left":"right":h<=w.y?"top":"bottom";return{from:{x:l,y:d,side:p(e,l,d)},to:{x:c,y:u,side:p(t,c,u)}}}function bh(e,t){const n=Math.min(160,Math.max(24,.4*t));switch(e.side){case"left":return{x:e.x-n,y:e.y};case"right":return{x:e.x+n,y:e.y};case"top":return{x:e.x,y:e.y-n};default:return{x:e.x,y:e.y+n}}}function SA(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}const Cn="http://www.w3.org/2000/svg";let AA=0;function vh(e,t,n,o,s){const i=_A(e,s);return t===null||yh(i,t,o,n)?i:EA(e,t,o,n,s)??i}function CA(e,t){const n=document.createElementNS(Cn,"defs"),o=(a,l,c)=>{const d=`${t}-${a}`,u=document.createElementNS(Cn,"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(Cn,"circle");return f.setAttribute("cx","5"),f.setAttribute("cy","5"),f.setAttribute("r","4"),f.classList.add(l),u.appendChild(f),n.appendChild(u),d},s="os-window-link__endpoint",i=`${s}--active`,r={dot:{normal:o("dot",s,"7"),active:o("dot-active",i,"7")},port:{normal:o("port",s,"4.5"),active:o("port-active",i,"4.5")}};return e.appendChild(n),r}gh({id:"svg-splines",label:E("Splines"),description:E("Curved connectors between related windows, ending in circular dots — the larger dot sits on the window the content belongs to; windows that reference each other get large dots on both ends."),mount:e=>{const t=++AA,n=(a,l)=>{const c=document.createElementNS(Cn,"svg");return c.classList.add("os-window-links__svg"),a.appendChild(c),{svg:c,markers:CA(c,`os-window-link-${t}${l}`)}},o={base:n(e.container,""),elevated:n(e.elevatedContainer,"-elevated")},s=new Map,i=a=>{for(const{svg:c}of[o.base,o.elevated])c.setAttribute("width",String(a.container.width)),c.setAttribute("height",String(a.container.height)),c.setAttribute("viewBox",`0 0 ${a.container.width} ${a.container.height}`);const l=new Set;for(const c of a.edges){if(!c.from||!c.to)continue;const d=`${c.fromWindowId}→${c.toWindowId}:${c.kind}`;l.add(d);const u=c.elevated?"elevated":"base";let f=s.get(d);if(f&&f.surface!==u&&(f.group.remove(),s.delete(d),f=void 0),!f){const P=document.createElementNS(Cn,"g");P.classList.add("os-window-link");const $=document.createElementNS(Cn,"path");$.classList.add("os-window-link__path"),P.appendChild($),o[u].svg.appendChild(P),f={group:P,path:$,surface:u},s.set(d,f)}const p=a.obstacles??[],w=kA(c.from,c.to),m=(P,$,F)=>$===null||yh(P,$,p,F);let h=null;w&&m(w.from,c.fromZIndex,c.fromWindowId)&&(h=w.from),h||(h=vh(c.from,c.fromZIndex,c.fromWindowId,p,w?{x:w.to.x,y:w.to.y}:SA(c.to)));let y=null;w&&m(w.to,c.toZIndex,c.toWindowId)&&(y=w.to),y||(y=vh(c.to,c.toZIndex,c.toWindowId,p,{x:h.x,y:h.y}));const v=Math.hypot(y.x-h.x,y.y-h.y),A=bh(h,v),D=bh(y,v);f.path.setAttribute("d",`M ${h.x} ${h.y} C ${A.x} ${A.y}, ${D.x} ${D.y}, ${y.x} ${y.y}`);const _=o[f.surface].markers,O=c.focused?"active":"normal";f.path.setAttribute("marker-end",`url(#${_.dot[O]})`),f.path.setAttribute("marker-start",`url(#${c.bidirectional?_.dot[O]:_.port[O]})`),f.group.classList.toggle("os-window-link--active",c.focused)}for(const[c,d]of Array.from(s))l.has(c)||(d.group.remove(),s.delete(c))},r=e.onFrame(i);return i(e.getFrame()),()=>{r(),s.clear(),o.base.svg.remove(),o.elevated.svg.remove()}}});const _h="os-window-links",Eh="os-window--linked",kh="os-window-links--visible";let Sh=!1;function IA({manager:e,osSettings:t}){if(Sh)return;Sh=!0;let n=t.getOsSettingsSnapshot(),o=null,s=null,i=null,r=null,a=0;const l=new Set;let c=!1;const d=new Set;let u=!1;const f=N=>{const g=N.element;return!g||!g.isConnected||N.state==="minimized"||g.offsetParent===null?null:{x:g.offsetLeft,y:g.offsetTop,width:g.offsetWidth,height:g.offsetHeight}},p=N=>N.state==="snapped-left"||N.state==="snapped-right"?null:f(N),w=()=>{const N=[];for(const z of si()){if(z.rootWindowIds.length===0||z.children.length===0)continue;const I=[],x=(B,M,j)=>{const R=e.getById(B);!R||!j||I.push({windowId:B,role:M,content:j,rect:p(R),focused:R.isFocused(),state:R.state})};for(const B of z.rootWindowIds)x(B,"root",ut(B));for(const B of z.children)x(B.windowId,"child",B.content);I.length>0&&N.push({key:z.key,root:z.root,members:I})}const g=z=>{const I=Number.parseInt(z.element?.style.zIndex||"",10);return Number.isFinite(I)?I:null},C=e.getFocused()?.id??null,U=[];for(const z of po()){const I=e.getById(z.fromWindowId),x=e.getById(z.toWindowId);if(!I||!x)continue;const B=I.isFocused()||x.isFocused();U.push({fromWindowId:z.fromWindowId,toWindowId:z.toWindowId,kind:z.kind,bidirectional:z.bidirectional,focused:B,from:p(I),to:p(x),fromZIndex:g(I),toZIndex:g(x),elevated:C!==null&&(z.fromWindowId===C||z.toWindowId===C)})}const V=[];for(const z of e.getAll()){const I=f(z);I&&V.push({windowId:z.id,rect:I,zIndex:g(z)??0})}return{groups:N,edges:U,obstacles:V,container:{width:o?.offsetWidth??0,height:o?.offsetHeight??0}}},m=()=>{c||l.size===0||(c=!0,requestAnimationFrame(()=>{if(c=!1,!i)return;const N=w();for(const g of Array.from(l))try{g(N)}catch(C){typeof console<"u"&&console.error("[openstation] window-link frame subscriber threw:",C)}}))},h=()=>{if(o&&o.isConnected&&s?.isConnected)return o;const N=document.getElementById("os-area");if(!N)return null;o=document.createElement("div"),o.id=_h,o.className="os-window-links",o.setAttribute("aria-hidden","true"),s=document.createElement("div"),s.id=`${_h}-elevated`,s.className="os-window-links os-window-links--elevated",s.setAttribute("aria-hidden","true");const g=document.getElementById("os-widgets");return g&&g.parentElement===N?(g.insertAdjacentElement("afterend",s),g.insertAdjacentElement("afterend",o)):N.prepend(o,s),o},y=()=>po().length>0,v=()=>{let N=n.windowLinkRenderer||Va;return N=Y(b.WINDOW_LINK_RENDERER,N),N===An?An:Ka(N)?N:Ka(Va)?Va:An},A=()=>{if(a++,l.clear(),c=!1,r){try{r()}catch(N){L(b.SHELL_ERROR,{scope:"window-link-renderer-teardown",error:N})}r=null}i=null,o?.replaceChildren(),s?.replaceChildren()},D=N=>{const g=Ka(N),C=h();if(!g||!C||!s)return;i=N;const U=++a,V={container:C,elevatedContainer:s,getFrame:w,onFrame:z=>(l.add(z),()=>{l.delete(z)})};try{const z=g.mount(V);z instanceof Promise?z.then(I=>{if(U!==a){typeof I=="function"&&I();return}typeof I=="function"&&(r=I)}).catch(I=>{L(b.SHELL_ERROR,{scope:"window-link-renderer-mount",error:I}),U===a&&(i=null)}):typeof z=="function"&&(r=z)}catch(z){L(b.SHELL_ERROR,{scope:"window-link-renderer-mount",error:z}),i=null}m()},_=()=>{const N=e.getFocused();return N?new Set(Hf(N.id)):new Set},O=()=>n.windowLinksEnabled!==!1,P=()=>{if(!o)return;const N=!u&&O()&&(n.windowLinkVisibility==="always"||n.windowLinkVisibility==="focus"&&_().size>0);o.classList.toggle(kh,N),s?.classList.toggle(kh,N)},$=()=>{if(!O()||n.windowLinkRaiseOnFocus===!1||n.windowLinkVisibility==="off")return;const N=e.getFocused();if(N)for(const g of N0(N.id)){const C=e.getById(g);C&&C.state!=="minimized"&&e.raise(g)}},F=()=>{if(!s)return;const N=e.getFocused(),g=_();if(!N||g.size===0||!O()||n.windowLinkVisibility==="off"){s.style.zIndex="";return}let C=-1/0;for(const U of[N.id,...g]){const V=e.getById(U),z=V?.element;if(!z||V.state==="minimized")continue;const I=Number.parseInt(z.style.zIndex||"",10);Number.isFinite(I)&&(C=Math.max(C,I))}s.style.zIndex=Number.isFinite(C)?String(C):""},k=()=>{const N=O()&&n.windowLinkHighlight!==!1&&n.windowLinkVisibility!=="off"?_():new Set;for(const g of d)N.has(g)||e.getById(g)?.element?.classList.remove(Eh);for(const g of N)e.getById(g)?.element?.classList.add(Eh);d.clear();for(const g of N)d.add(g)},W=()=>{const N=O()&&n.windowLinkVisibility!=="off"&&y()?v():An;N===An?i&&A():N!==i&&(A(),D(N)),P(),k(),F(),m()};Z(b.WINDOW_BOUNDS_CHANGED,"desktop-mode/window-links-frame",()=>m());for(const N 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])Z(N,"desktop-mode/window-links-frame",()=>m());Z(b.WINDOW_FOCUSED,"desktop-mode/window-links-focus",()=>{$(),P(),k(),F(),m()}),Z(b.WINDOW_BLURRED,"desktop-mode/window-links-blur",()=>{P(),k(),F(),m()}),Z(b.OVERVIEW_ENTERING,"desktop-mode/window-links-overview",()=>{u=!0,P()}),Z(b.OVERVIEW_EXITED,"desktop-mode/window-links-overview",()=>{u=!1,P(),m()}),zf(W),yA(W),t.subscribeOsSettings(N=>{const g=N.windowLinkRenderer!==n.windowLinkRenderer,C=g||N.windowLinkVisibility!==n.windowLinkVisibility||N.windowLinksEnabled!==n.windowLinksEnabled||N.windowLinkRaiseOnFocus!==n.windowLinkRaiseOnFocus||N.windowLinkHighlight!==n.windowLinkHighlight;n=N,C&&(g&&i&&A(),W())}),W()}function Ah(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function xA({items:e,onPick:t}){const n=document.createElement("os-menu");n.classList.add("os-window__menu-panel"),n.classList.add("os-window__related-panel");const o=new Map;for(const r of e){const a=o.get(r.group);a?a.push(r):o.set(r.group,[r])}const s=Array.from(o.entries()).sort((r,a)=>Ah(r[0])-Ah(a[0])),i=[];for(const[,r]of s){const a=r.find(l=>typeof l.groupLabel=="string"&&l.groupLabel!=="")?.groupLabel;if(a){const l=document.createElement("div");l.className="os-window__related-group",l.setAttribute("role","presentation"),l.textContent=a,n.appendChild(l)}for(const l of r){const c=document.createElement("os-menu-item");c.setAttribute("role","menuitem"),c.setAttribute("value",l.id),c.tabIndex=-1,l.icon&&c.setAttribute("icon",l.icon),c.classList.add("os-window__related-item"),c.textContent=typeof l.count=="number"?`${l.label} (${l.count})`:l.label,c.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),t(l)}),i.push(c),n.appendChild(c)}}return n.addEventListener("keydown",r=>{const a=r,l=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const c=a.key==="ArrowDown";let d=i[c?0:i.length-1];l!==-1&&(d=i[(l+(c?1:-1)+i.length)%i.length]),d?.focus()}else if(a.key==="Home"||a.key==="End")a.preventDefault(),a.stopPropagation(),i[a.key==="Home"?0:i.length-1]?.focus();else if(a.key==="Enter"||a.key===" "){const c=i[l];c&&(a.preventDefault(),a.stopPropagation(),c.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function Ch(e){if(!e||typeof e!="object")return!1;const t=e,n=o=>typeof o=="string"&&o.trim()!=="";return n(t.id)&&n(t.group)&&n(t.label)&&(n(t.url)||n(t.windowId))&&(t.url===void 0||typeof t.url=="string")&&(t.windowId===void 0||typeof t.windowId=="string")&&(t.params===void 0||!!t.params&&typeof t.params=="object")&&(t.groupLabel===void 0||typeof t.groupLabel=="string")&&(t.icon===void 0||typeof t.icon=="string")&&(t.count===void 0||typeof t.count=="number"&&Number.isFinite(t.count))}function Ih(e){const t=ut(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=Y(b.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(Ch):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(Ch))}function Xa(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function LA(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function TA(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=Ih(t.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",a),l.remove(),e.setAttribute("aria-expanded","false")},a=c=>{c.key==="Escape"&&(c.stopPropagation(),r(),e.focus())},l=xA({items:s,onPick:c=>{r(),LA(o),n(c)}});l._wpdRelatedClose=r,o.appendChild(l),o.addEventListener("keydown",a),e.setAttribute("aria-expanded","true"),i=c=>{const d=c.target;!d||l.contains(d)||e.contains(d)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),l.querySelector('[role="menuitem"]')?.focus()}function NA({manager:e,openUrl:t}){ki({id:"desktop-mode/related-entities",label:E("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>Ih(n.id).length>0,render:(n,o)=>{Xa(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")){Xa(o.element);return}TA(n,o,t)})}}),Z(b.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(Xa(o.element),o.renderCustomTitleBarButtons?.())})}const Za="os-broadcast",xh="os-broadcast",Lh=window.location.origin;let Ja=null;function DA(e){Ja=e}function Ai(e,t){const n=String(Y("os.broadcast.topic",e,{payload:t})??e),o=Y("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Za,{detail:s})),L(b.BROADCAST,s),ke.publish(n,o),!Ja)return;const i={type:xh,topic:n,payload:o};for(const r of Ja._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Lh)}catch{}}}function In(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){L(b.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Za,n),()=>document.removeEventListener(Za,n)}function RA(){window.addEventListener("message",e=>{if(e.origin!==Lh)return;const t=e.data;!t||t.type!==xh||t._fromParent||typeof t.topic=="string"&&Ai(t.topic,t.payload)})}function Qa(e,t,n,o=""){const s=(Array.isArray(n)?n:[n]).map(r=>Math.floor(Number(r))).filter(r=>Number.isFinite(r)&&r>0),i=String(e).trim();i===""||s.length===0||Ai(`os.${i}.changed`,{source:o,action:t,ids:s})}const OA=new Set(["saved","no-editor","not-dirty","error"]);let Th=0;function Nh(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function MA(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Th+=1;const o=`os-editor-preview-${Date.now()}-${Th}`;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"&&OA.has(d.status)?d.status:"error",f=Nh(d.previewUrl);a(f?{status:u,previewUrl:f}:{status:u})};window.addEventListener("message",l),i=window.setTimeout(()=>a({status:"timeout"}),t);try{n.postMessage({type:"os-editor-autosave-request",requestId:o},window.location.origin)}catch{a({status:"no-editor"})}})}const Oe=re("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),PA=400,Dh=1500;function Eo(e){return e?`${e.type}:${e.id}`:""}function WA(e){for(const t of Oe.state.pairings.values())if(t.previewWindowId===e)return t}function $A(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function UA(e){const t=e.getCurrentUrl?.()??"";if(!t)return!1;try{return new URL(t,window.location.origin).pathname.endsWith("/post-new.php")}catch{return!1}}function Ci(e,t,n,o){Oe.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(Oh(e,t),o!=="none"){const i=e.getById(t.previewWindowId);i&&(o==="destroy"?i.destroy?.():i.close?.())}const s={editorWindowId:t.editorWindowId,previewWindowId:t.previewWindowId,reason:n};document.dispatchEvent(new CustomEvent("os-editor-preview-closed",{detail:s})),L(b.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function el(e,t,n){t.reloadTimer!==null&&window.clearTimeout(t.reloadTimer),t.reloadTimer=window.setTimeout(()=>{t.reloadTimer=null;const o=e.getById(t.previewWindowId);if(!o)return;const s=n||ut(t.editorWindowId)?.previewUrl,i=s&&s!==t.openUrl?s:void 0;typeof o.swapReload=="function"?(i&&(t.openUrl=i),o.swapReload(i)):i&&o.navigateTo?(t.openUrl=i,o.navigateTo(i)):o.reload?.()},PA)}function FA(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=In(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||el(e,t)})}let Rh=0;function Oh(e,t){if(!t.watchId)return;const n=e.getById(t.editorWindowId);try{n?.iframe?.contentWindow?.postMessage({type:"os-editor-live-unwatch",watchId:t.watchId},window.location.origin)}catch{}t.watchId=""}function Mh(e,t,n){Oh(e,t);const o=Y(b.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:Dh},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;Rh+=1;const i=`${t.previewWindowId}-watch-${Rh}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:Dh},window.location.origin),t.watchId=i}catch{}}let BA=MA;async function HA(e,t){const n=Oe.state.pairings.get(t.id);if(n){Ci(e,n,"toggled","close");return}if(Oe.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=ut(t.id);if(!o?.previewUrl){Q({message:E("No preview is available for this content.")});return}Oe.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=$A();s||t.applySnap?.("left");const i=BA(t);i.then(f=>{f.status==="error"&&Q({message:E("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{Oe.state.busyEditors.delete(t.id),e.getById(t.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=E("Preview");o.label&&(a=le(E("Preview: %s"),o.label));let l={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=Y(b.EDITOR_PREVIEW_WINDOW_CONFIG,l,{editorWindowId:t.id,content:o});if(c&&typeof c=="object"&&typeof c.id=="string"&&c.id!==""&&typeof c.url=="string"&&c.url!==""?l=c:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await e.open(l),!e.getById(t.id)||Eo(ut(t.id))!==Eo(o)){e.getById(l.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:l.id,postKey:Eo(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};FA(e,d,o),Mh(e,d,o),Oe.state.pairings.set(t.id,d);const u={editorWindowId:t.id,previewWindowId:l.id,content:o};document.dispatchEvent(new CustomEvent("os-editor-preview-opened",{detail:u})),L(b.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Oe.state.pairings.get(t.id)===d&&f.status==="saved"&&el(e,d,f.previewUrl)})}function zA({manager:e}){ki({id:"desktop-mode/editor-preview",label:E("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!ut(t.id)?.previewUrl||UA(t)),render:(t,n)=>{if(!ut(n.id)?.previewUrl){const i=E("Save the post to enable its preview");t.setAttribute("aria-disabled","true"),t.setAttribute("aria-label",i),t.setAttribute("title",i),t.classList.add("os-window__btn--disabled"),t.addEventListener("click",r=>{r.stopPropagation(),Q({message:E("The preview opens once the post has been saved.")})});return}const o=Oe.state.pairings.has(n.id),s=Oe.state.busyEditors.has(n.id);t.setAttribute("aria-pressed",String(o)),s&&(t.setAttribute("aria-busy","true"),t.classList.add("os-window__btn--busy")),t.addEventListener("click",i=>{i.stopPropagation(),HA(e,n)})}}),Z(b.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);n&&Eo(t.content)!==n.postKey&&Ci(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),Z(b.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);if(n){Ci(e,n,"editor-closed","destroy");return}const o=WA(t.windowId);o&&Ci(e,o,"preview-closed","none")}),Z(b.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);if(n){const o=ut(t.windowId);o&&Eo(o)===n.postKey&&Mh(e,n,o)}e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t?.data;if(!(!n||typeof n!="object"||n.type!=="os-editor-live-saved"||typeof n.watchId!="string")){for(const o of Oe.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){el(e,o,Nh(n.previewUrl));return}}})}const Ph="none",Wh=re("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),ko=Wh.state.registry,tl=Wh.state.listeners,$h=/^[a-z0-9_/-]+$/;function Ii(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):$h.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Ph&&t.push('id ("none" is reserved)'):t.push(`id (must match ${$h} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.className!="string"&&typeof e.apply!="function"&&t.push("className|apply (at least one must be provided — a CSS class to toggle or an apply callback)")),Ne("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();ko.set(n,{...e,id:n}),ol()}function GA(e){ko.delete(e.toLowerCase())&&ol()}function jA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ko.entries()))o.owner===e&&(ko.delete(n),t++);return t>0&&ol(),t}function nl(){const e=Array.from(ko.values()),t=Y(b.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function Uh(e){return nl().find(t=>t.id===e)}function VA(e){return tl.add(e),()=>{tl.delete(e)}}function ol(){const e=Array.from(tl);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}Ii({id:"darken",label:E("Darken"),description:E("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),Ii({id:"frost",label:E("Frost"),description:E("Throw unfocused windows out of focus — a soft, frosted-glass blur, as if you were looking at them through an iced-over pane."),className:"os-window--fx-frost"}),Ii({id:"grayscale",label:E("Grayscale"),description:E("Drain the colour from unfocused windows so the focused one is the only thing still in colour — your eye snaps right to it."),className:"os-window--fx-grayscale"});function qA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await _e(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}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(jA(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function KA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await _e(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}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(wA(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const sl="data-desktop-unfocus-effect",il="data-desktop-unfocus-effect-class";let Fh=!1;function YA(e){return e.querySelector("canvas")!==null}function XA(e){return e.state==="snapped-left"||e.state==="snapped-right"}function ZA({manager:e,osSettings:t}){if(Fh)return;Fh=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(il);l&&(r.classList.remove(l),r.removeAttribute(il));const c=r.getAttribute(sl);c&&Uh(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(sl)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(il,a.className)),r.setAttribute(sl,a.id),a.apply?.(r)},i=()=>{const r=n===Ph?void 0:Uh(n),a=nl();for(const l of e.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(XA(l)||YA(c)||s(c,r)))}};for(const r of["os-window-opened","os-window-reopened","os-window-closed","os-window-focused","os-window-blurred"])document.addEventListener(r,()=>i());document.addEventListener("os-window-changed",r=>{r.detail?.reason==="state"&&i()}),t.subscribeOsSettings(r=>{n=r.unfocusEffect,i()}),VA(()=>i()),i()}function JA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await _e(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}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(Dv(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function Bh(e){return e.startsWith("dashicons-")?e:"dashicons-admin-generic"}function QA(e,t){if(t.url&&_n(t.url)||t.url&&Ge(t.url))return;const n=ae(t.url,e.adminUrl);e.windowManager.open({id:n,baseId:n,url:t.url,parentUrl:t.url,title:t.title,icon:Bh(t.icon),submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}function eC(e,t,n){_n(n.url)||Ge(n.url)||e.windowManager.open({id:ae(n.url,e.adminUrl),baseId:ae(t.url,e.adminUrl),url:n.url,parentUrl:t.url,title:t.title,icon:Bh(t.icon),submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}const tC=130,nC=240,oC=160,xi=14,Hh=18,At=12,sC=160,iC="os-constellation-open",Li=e=>e.dataset.menuSlug??e.dataset.constellationId??"",rl=e=>{const t=e.closest(".os-dock")?.getAttribute("data-os-dock-placement");return t==="left"?"right":t==="right"?"left":"top"},rC={top:"ArrowUp",right:"ArrowRight",left:"ArrowLeft"};function aC(){return typeof window.matchMedia=="function"&&window.matchMedia("( prefers-reduced-motion: reduce )").matches}function lC(e){let t=null,n=null,o="",s=null,i=null;const r=()=>{s!==null&&(window.clearTimeout(s),s=null)},a=()=>{i!==null&&(window.clearTimeout(i),i=null)},l=A=>{if(!(A instanceof Element))return null;const D=A.closest(".os-dock__item");return!D||!Li(D)||!D.closest(".os-dock")?null:D},c=new Set,d=()=>{document.body.classList.toggle(iC,t!==null||c.size>0)},u=(A,D={})=>{if(!t)return;const _=n,O=t;t=null,n=null,o="",_?.removeAttribute("data-constellation-open"),A==="cut"||aC()?O.remove():(O.classList.remove("os-constellation--open"),O.classList.add("os-constellation--closing"),c.add(O),window.setTimeout(()=>{O.remove(),c.delete(O),d()},oC)),d(),D.restoreFocus&&_&&_.querySelector(".os-dock__item-primary")?.focus(),L(b.CONSTELLATION_CLOSED,{menuSlug:_?Li(_):"",handoff:D.handoff===!0})},f=(A=!1,D=!1)=>{r(),a(),u(D?"cut":"exit",{restoreFocus:A})},p=(A,D=!1)=>{r(),a();const _=Li(A);if(t&&o===_){D&&xn(t,0);return}const O=cC(e,A);if(!O){f();return}const P=t!==null;u("exit",{handoff:P});const $=dC(e,O);t=fC(e,O,$,A,f);for(const F of al(t))F.tabIndex=-1;n=A,o=_,t.dataset.osCnSide=rl(A),document.body.appendChild(t),d(),A.setAttribute("data-constellation-open",""),bC(t),vC(t,A),requestAnimationFrame(()=>{t?.classList.add("os-constellation--open"),D&&t&&xn(t,0)}),L(b.CONSTELLATION_OPENED,{menuSlug:_,item:O,instances:$,handoff:P})},w=A=>{if(A.pointerType&&A.pointerType!=="mouse")return;if(t&&A.target instanceof Node&&t.contains(A.target)){a();return}const D=l(A.target);D&&(a(),!(t&&o===Li(D))&&(r(),s=window.setTimeout(()=>{s=null,p(D)},t?0:tC)))},m=A=>{const D=A.relatedTarget;D instanceof Node&&(t&&t.contains(D)||n&&n.contains(D)||l(D))||(r(),a(),i=window.setTimeout(()=>{i=null,f()},nC))},h=A=>{if(t&&A.target instanceof Node&&t.contains(A.target)){const _=al(t),O=_.indexOf(A.target);A.key==="Escape"?(A.preventDefault(),f(!0)):A.key==="ArrowDown"?(A.preventDefault(),xn(t,O+1)):A.key==="ArrowUp"?(A.preventDefault(),O<=0?f(!0):xn(t,O-1)):A.key==="Home"?(A.preventDefault(),xn(t,0)):A.key==="End"?(A.preventDefault(),xn(t,_.length-1)):A.key==="Tab"&&f(!0);return}const D=l(A.target);D&&(A.key===rC[rl(D)]?(A.preventDefault(),p(D,!0)):A.key==="Escape"&&f())},y=()=>f(!1,!0),v=A=>{!t||!(A.target instanceof Element)||t.contains(A.target)||A.target.closest(".os-dock__item")&&f()};return document.body.setAttribute(_a,""),document.addEventListener("pointerover",w),document.addEventListener("pointerout",m),document.addEventListener("click",v),document.addEventListener("keydown",h),window.addEventListener("resize",y),window.addEventListener("blur",y),document.addEventListener("os-layout-changed",y),document.addEventListener(ai,y),document.addEventListener("scroll",y,!0),()=>{f(!1,!0);for(const A of c)A.remove();c.clear(),d(),document.body.removeAttribute(_a),document.removeEventListener(ai,y),document.removeEventListener("pointerover",w),document.removeEventListener("pointerout",m),document.removeEventListener("click",v),document.removeEventListener("keydown",h),window.removeEventListener("resize",y),window.removeEventListener("blur",y),document.removeEventListener("os-layout-changed",y),document.removeEventListener("scroll",y,!0)}}function cC(e,t){const n=t.dataset.menuSlug;if(n){const i=e.getMenuItems().find(a=>a.id===n);if(!i)return null;const r=i.selfLabel?[{title:i.selfLabel,url:i.url},...i.submenu]:i.submenu;return{id:i.id,title:i.title,icon:i.icon,submenu:r,menuItem:i}}const o=t.dataset.constellationId;if(!o)return null;const s=e.getSystemItem?.(o);return s?.submenu?.length?{id:s.id,title:s.title,icon:s.icon,submenu:s.submenu,menuItem:null}:null}function dC(e,t){const n=new Set;if(t.menuItem){const o=uC(e,t.menuItem);for(const i of e.windowManager.getAllByBaseIdOnActiveDesktop(o))n.add(i);const s=ae(t.menuItem.url,e.adminUrl);if(s){const i=e.windowManager.getActiveDesktopId();for(const r of e.windowManager.getAll())(r.config.desktopId||i)===i&&r.config.parentUrl&&ae(r.config.parentUrl,e.adminUrl)===s&&n.add(r)}return Array.from(n)}for(const o of t.submenu)if(o.windowId)for(const s of e.windowManager.getAllByBaseIdOnActiveDesktop(o.windowId))n.add(s);return Array.from(n)}function uC(e,t){return t.windowId?t.windowId:ae(t.url,e.adminUrl)}function fC(e,t,n,o,s){const i=document.createElement("div");i.className="os-constellation",i.setAttribute("role","menu"),i.setAttribute("aria-label",le(E("%s menu"),t.title)),i.style.setProperty("--os-cn-hue",String(vn(t.title)));const r=document.createElement("div");r.className="os-constellation__surface",i.appendChild(r),r.appendChild(pC(e,t,s));let a=0;const l=()=>a++;n.length>0&&r.appendChild(hC(e,t,n,s,l)),t.submenu.length>0&&r.appendChild(mC(e,t,s,l)),r.addEventListener("pointermove",f=>{const p=r.getBoundingClientRect();!p.width||!p.height||(r.style.setProperty("--os-cn-x",`${(f.clientX-p.left)/p.width*100}%`),r.style.setProperty("--os-cn-y",`${(f.clientY-p.top)/p.height*100}%`))});const c=document.createElement("span");c.className="os-constellation__sheen",c.setAttribute("aria-hidden","true"),i.appendChild(c);const d=document.createElement("span");d.className="os-constellation__beam",d.setAttribute("aria-hidden","true"),i.appendChild(d);const u={item:t,instances:n,tile:o};return Y(b.CONSTELLATION_PANEL,i,u)}function pC(e,t,n){const o=document.createElement("button");o.type="button",o.className="os-constellation__head os-constellation__row",o.setAttribute("role","menuitem");const s=document.createElement("span");s.className="os-constellation__head-icon",s.setAttribute("aria-hidden","true"),s.appendChild(wC(t.icon)),o.appendChild(s);const i=document.createElement("span");i.className="os-constellation__head-text";const r=document.createElement("span");return r.className="os-constellation__head-title",r.textContent=t.title,i.appendChild(r),o.appendChild(i),o.addEventListener("click",()=>{if(n(),t.menuItem){QA(e,t.menuItem);return}zh(e,t,t.submenu[0])}),o}function zh(e,t,n){if(n){if(n.onSelect){n.onSelect();return}if(t.menuItem){eC(e,t.menuItem,n);return}n.url&&window.open(n.url,"_blank","noopener,noreferrer")}}function hC(e,t,n,o,s){const i=document.createElement("div");i.className="os-constellation__group os-constellation__group--live",i.setAttribute("role","group"),i.setAttribute("aria-label",E("Open windows")),i.appendChild(Gh(le(un("%d open window","%d open windows",n.length),n.length)));for(const r of n){const a=document.createElement("button");a.type="button",a.className="os-constellation__row os-constellation__row--live",a.setAttribute("role","menuitem"),a.style.setProperty("--os-cn-row",String(s())),r.state==="minimized"&&(a.dataset.state="minimized");const l=document.createElement("span");l.className="os-constellation__pip",l.setAttribute("aria-hidden","true"),a.appendChild(l);const c=document.createElement("span");c.className="os-constellation__row-label",c.textContent=r.config.title||t.title,a.appendChild(c);const d=document.createElement("span");d.className="os-constellation__row-meta",d.textContent=r.state==="minimized"?E("Minimized"):E("Open"),a.appendChild(d),a.addEventListener("click",()=>{o(),r.state==="minimized"&&r.restore(),e.windowManager.focus(r)}),i.appendChild(a)}return i}function mC(e,t,n,o){const s=document.createElement("div");s.className="os-constellation__group",s.setAttribute("role","group"),s.setAttribute("aria-label",t.title),s.appendChild(Gh(E("Open")));for(const i of t.submenu)s.appendChild(gC(e,t,i,n,o()));return s}function gC(e,t,n,o,s){const i=document.createElement("button");i.type="button",i.className="os-constellation__row os-constellation__row--sub",i.setAttribute("role","menuitem"),i.style.setProperty("--os-cn-row",String(s)),i.style.setProperty("--os-cn-row-hue",String(vn(n.title)));const r=document.createElement("span");r.className="os-constellation__orbit",r.setAttribute("aria-hidden","true"),i.appendChild(r);const a=document.createElement("span");if(a.className="os-constellation__row-label",a.textContent=n.title,i.appendChild(a),n.offSite){const l=document.createElement("span");l.className="dashicons dashicons-external os-constellation__row-offsite",l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-constellation__row-note",c.textContent=E("(opens in a new tab)"),i.appendChild(c)}return i.addEventListener("click",()=>{o(),zh(e,t,n)}),i}function Gh(e){const t=document.createElement("span");return t.className="os-constellation__legend",t.textContent=e,t}function wC(e){if(!e.startsWith("dashicons-")){const n=document.createElement("span");if(n.className="os-constellation__head-art",ho(n,e,"currentColor"))return n}const t=document.createElement("span");return t.className="dashicons",t.classList.add(e.startsWith("dashicons-")?Sd(e):"dashicons-admin-generic"),t}function al(e){return Array.from(e.querySelectorAll(".os-constellation__row"))}function xn(e,t){const n=al(e);if(n.length===0)return;const o=Math.max(0,Math.min(n.length-1,t));n[o].focus()}const yC=["--wp-admin-theme-color","--os-titlebar-bg-focused","--os-titlebar-color-focused"];function bC(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of yC){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function vC(e,t){const n=t.getBoundingClientRect(),o=rl(t),s=o==="top"?n.top-xi-At:window.innerHeight-At*2;if(e.style.setProperty("--os-cn-max-h",`${Math.max(sC,s)}px`),o!=="top"){e.style.left=o==="right"?`${n.right+xi}px`:`${n.left-xi}px`;const i=e.offsetHeight,r=window.innerHeight,a=Math.max(At,Math.min(n.top,r-At-i));e.style.top=`${a}px`;const l=Math.max(Hh,Math.min(n.top+n.height/2-a,i-Hh));e.style.setProperty("--os-cn-beam-y",`${l}px`);return}e.style.left=`${n.left+n.width/2}px`,e.style.top=`${n.top-xi}px`,requestAnimationFrame(()=>{const i=e.getBoundingClientRect(),r=window.innerWidth;let a=0;i.left<At?a=At-i.left:i.right>r-At&&(a=r-At-i.right),a!==0&&(e.style.setProperty("--os-cn-shift",`${a}px`),e.style.setProperty("--os-cn-beam-x",`${-a}px`))})}const jh=re("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),So=jh.state.registry,_C=jh.state.listeners,Vh=/^[a-z0-9_/-]+$/;function qh(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{if(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Vh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Vh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!e.tokens||typeof e.tokens!="object")t.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(e.tokens))if(!o.startsWith("--")){t.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof e.match!="function"&&t.push("match (must be a function)")}Ne("WindowTheme",t,e);const n=e.id.trim().toLowerCase();So.set(n,{...e,id:n}),ll()}function Kh(e){So.delete(e.toLowerCase())&&ll()}function EC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(So.entries()))o.owner===e&&(So.delete(n),t++);return t>0&&ll(),t}function Yh(){return Array.from(So.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function ll(){const e=Array.from(_C);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function kC(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async l=>{if(!l.scriptUrl||t.has(l.scriptUrl)){e.add(l.handle);return}try{await _e(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}t.add(l.scriptUrl),e.add(l.handle)},i=l=>{const c=new Map;if(!l)return c;for(const d of l){if(!d.scriptHandle||!d.id)continue;let u=c.get(d.scriptHandle);u||(u=new Set,c.set(d.scriptHandle,u)),u.add(d.id)}return c},r=l=>{const c=new Set;for(const u of Yh())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{qh({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(e)){if(d.has(u))continue;const f=r(u);for(const p of f)Kh(p),o.delete(p);EC(u),e.delete(u)}a(c);for(const u of l)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const Xh=re("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),Ao=Xh.state.registry,SC=Xh.state.listeners,Zh=/^[a-z0-9_/-]+$/;function Co(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Zh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Zh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)"),typeof e.render!="function"&&(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (required when render is omitted)"),typeof e.match!="function"&&t.push("match (must be a function)"),e.placement!==void 0&&e.placement!=="left"&&e.placement!=="right"&&e.placement!=="controls"&&t.push('placement (must be "left", "right", or "controls")')),Ne("WindowControl",t,e);const n=e.id.trim().toLowerCase();Ao.set(n,{...e,id:n}),cl()}function Jh(e){Ao.delete(e.toLowerCase())&&cl()}function AC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Ao.entries()))o.owner===e&&(Ao.delete(n),t++);return t>0&&cl(),t}function Qh(){return Array.from(Ao.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function cl(){const e=Array.from(SC);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function CC(){Co({id:"core/minimize",label:E("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),Co({id:"core/maximize",label:E("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),Co({id:"core/focus-tab",label:E("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),Co({id:"core/close",label:E("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function IC(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await _e(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}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of Qh())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))Jh(d);AC(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const em=re("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),Io=em.state.registry,xC=em.state.listeners,tm=/^[a-z0-9_/-]+$/,nm=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function om(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):tm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${tm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):nm.has(e.slot)||t.push(`slot (must be one of ${Array.from(nm).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Ne("WindowSlot",t,e);const n=e.id.trim().toLowerCase();Io.set(n,{...e,id:n}),ul()}function dl(e){Io.delete(e.toLowerCase())&&ul()}function LC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Io.entries()))o.owner===e&&(Io.delete(n),t++);return t>0&&ul(),t}function sm(){return Array.from(Io.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function ul(){const e=Array.from(xC);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function TC(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await _e(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}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of sm())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))dl(d);LC(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const NC="desktop-mode-notice-dismissed";function DC(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function im(){return`${NC}:${DC()}`}function fl(){try{const e=window.localStorage.getItem(im());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function rm(e){try{window.localStorage.setItem(im(),JSON.stringify(e))}catch{}}function Ti(e){return e?fl()[e]===!0:!1}function Ni(e){if(!e)return;const t=fl();t[e]=!0,rm(t)}function am(e){if(!e)return;const t=fl();t[e]&&(delete t[e],rm(t))}const RC=de`: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 ) )}`,_s=class _s extends Se{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&Ti(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&Ni(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&am(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return J` |
| 45 |
<span |
| 46 |
class="os-notice__icon dashicons ${t??""}" |
| 47 |
?hidden=${!t} |
| 48 |
aria-hidden="true" |
| 49 |
></span> |
| 50 |
<span class="os-notice__label"><slot></slot></span> |
| 51 |
<button |
| 52 |
type="button" |
| 53 |
class="os-notice__close" |
| 54 |
?hidden=${!n} |
| 55 |
aria-label=${E("Dismiss notice")} |
| 56 |
@click=${o=>this._onDismiss(o)} |
| 57 |
> |
| 58 |
${Pr("close",{size:null})} |
| 59 |
</button> |
| 60 |
`}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};_s.props=["tone","notDismissible","icon","noticeId"],_s.styles=[RC],_s.help=void 0;let pl=_s;xe("os-notice",pl);const xo=re("desktop-mode/window-notices",()=>({entries:new Map})),OC=/^[a-z0-9_/-]+$/;function lm(e){return`os-notice/${e.toLowerCase()}`}function MC(e){const t=document.createElement("os-notice");return t.setAttribute("tone",e.tone??"info"),t.setAttribute("notice-id",e.id),e.dismissible===!1&&t.setAttribute("not-dismissible",""),e.icon&&t.setAttribute("icon",e.icon),t.innerHTML=e.message,t}function cm(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!OC.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};xo.state.entries.set(t,n);const o=lm(t);return om({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=xo.state.entries.get(t);if(!i)return!1;if(typeof i.match!="function")return!0;try{return i.match(s)===!0}catch{return!1}},render:s=>{const i=xo.state.entries.get(t);i&&s.appendChild(MC(i))}}),()=>hl(t)}function hl(e){const t=String(e??"").trim().toLowerCase();t&&xo.state.entries.delete(t)&&dl(lm(t))}function dm(){return Array.from(xo.state.entries.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function PC(e){const t=String(e??"").trim().toLowerCase();t&&Ni(t)}function WC(e){const t=String(e??"").trim().toLowerCase();t&&am(t)}function $C(e){if(!e)return;const t=new Set;if(typeof e.window=="string"&&e.window!==""&&t.add(e.window),Array.isArray(e.windows))for(const o of e.windows)typeof o=="string"&&o!==""&&t.add(o);const n=typeof e.urlContains=="string"&&e.urlContains!==""?e.urlContains.toLowerCase():null;if(!(t.size===0&&n===null))return o=>!(t.size>0&&!t.has(o.id)||n!==null&&!(typeof o.config.url=="string"?o.config.url.toLowerCase():"").includes(n))}function um(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),cm({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:$C(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of dm())n.owner==="__server__"&&(t.has(n.id)||hl(n.id))}const fm=re("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),Lo=fm.state.registry,UC=fm.state.listeners,pm=/^[a-z0-9_/-]+$/;function FC(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):pm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${pm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Ne("WindowChrome",t,e);const n=e.id.trim().toLowerCase();Lo.set(n,{...e,id:n}),ml()}function hm(e){Lo.delete(e.toLowerCase())&&ml()}function BC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Lo.entries()))o.owner===e&&(Lo.delete(n),t++);return t>0&&ml(),t}function mm(){return Array.from(Lo.values()).sort((e,t)=>e.id.localeCompare(t.id))}function ml(){const e=Array.from(UC);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function HC(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await _e(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}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of mm())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))hm(d);BC(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const gl=window.location.origin;let zC=0;const Ln=new Map,Tn=new Map,To=new Map;function GC(e,t){return To.set(e,t),()=>{To.get(e)===t&&To.delete(e)}}function jC(){return`os-conn-${++zC}`}function VC(e){const t=(l,c)=>{try{l.contentWindow?.postMessage(c,gl)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=jC(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let w=!1,m=!1;const h=()=>{const P=To.get(l);return P||(e.getById(l)?.iframe??null)},y=()=>{if(h())return!1;const P=e.getById(l);return!!P&&P.config?.native===!0},v=[],A=()=>{const P=h();if(P)for(;p.length;){const $=p.shift();t(P,{type:"os-bridge-publish",connectionId:d,topic:$.topic,payload:$.payload})}},D={id:d,target:l,isOpen:()=>w,subscribe(P,$){const F=$;if(y()){const W=x_(l,P,(N,g)=>{L(b.CONNECTION_MESSAGE,{connectionId:d,topic:g.channel,direction:"in"});try{F(N,{topic:g.channel})}catch(C){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",C)}});return v.push(W),W}let k=f.get(P);return k||(k=new Set,f.set(P,k)),k.add(F),()=>{k?.delete(F)}},send(P,$){if(m)return;if(L(b.CONNECTION_MESSAGE,{connectionId:d,topic:P,direction:"out"}),y()){T_(l,P,$);return}if(!w){p.push({topic:P,payload:$});return}const F=h();F&&t(F,{type:"os-bridge-publish",connectionId:d,topic:P,payload:$})},disconnect(){D._destroy("disconnect")},_targetWindow:h,_handleIframeMessage(P){if(!P||typeof P!="object")return;const $=P;if($.type==="os-bridge-handshake-ack"){if(w)return;w=!0,L(b.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:D});try{c.onOpen?.()}catch(F){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",F)}A();return}if($.type==="os-bridge-publish"){const F=P,k=typeof F.topic=="string"?F.topic:"";if(!k)return;L(b.CONNECTION_MESSAGE,{connectionId:d,topic:k,direction:"in"});const W=f.get(k);if(W)for(const g of Array.from(W))try{g(F.payload,{topic:k})}catch(C){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",C)}const N=f.get("*");if(N)for(const g of Array.from(N))try{g(F.payload,{topic:k})}catch(C){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",C)}return}$.type==="os-bridge-disconnect"&&D._destroy("disconnect")},_destroy(P){if(m)return;m=!0;const $=w;w=!1,Ln.delete(d);const F=Tn.get(l);F&&(F.delete(d),F.size===0&&Tn.delete(l));for(const k of v.splice(0))try{k()}catch{}if($){const k=h();k&&t(k,{type:"os-bridge-disconnect",connectionId:d})}L(b.CONNECTION_CLOSED,{connectionId:d,reason:P});try{c.onClose?.(P)}catch(k){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",k)}}};Ln.set(d,D);let _=Tn.get(l);if(_||(_=new Set,Tn.set(l,_)),_.add(d),y())return Promise.resolve().then(()=>{if(!(m||w)){w=!0,L(b.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(P){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",P)}}}),D;const O=h();return O&&t(O,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),D},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;Ln.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=To.get(l)??e.getById(l)?.iframe??null;if(!f)return;const p=Y(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"},gl)}catch{}return}const w=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,m=n(l,{topics:w});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:m.id},gl)}catch{}};return{connect:n,getConnection:l=>Ln.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=Tn.get(l);if(c)for(const d of Array.from(c)){const u=Ln.get(d);if(!u||u.isOpen())continue;const f=u._targetWindow();f&&t(f,{type:"os-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:l=>{const c=Tn.get(l);if(c)for(const d of Array.from(c))Ln.get(d)?._destroy("window-closed")}}}const qC={};function KC(...e){(typeof{url:Lr&&Lr.tagName.toUpperCase()==="SCRIPT"&&Lr.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&qC?"production":void 0)!=="production"&&console.log(...e)}const YC="iframe:";function wl(e){return YC+e}function gm(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function XC(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const ZC=250;class JC{constructor(t){this.streamingWindowId=null,this.focusedWindowId=null,this.paletteOpen=!1,this.closeGraceTimer=null,this.manager=t.manager,this.adminUrl=t.adminUrl}install(){document.addEventListener("os-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&this.onFocused(o.windowId)}),document.addEventListener("os-window-closed",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&(Ei(wl(o.windowId)),this.streamingWindowId===o.windowId&&(this.streamingWindowId=null),this.focusedWindowId===o.windowId&&(this.focusedWindowId=null))}),document.addEventListener("os-palette-opened",()=>{this.onPaletteOpened()}),document.addEventListener("os-palette-closed",()=>{this.onPaletteClosed()}),document.addEventListener("os-window-changed",n=>{const o=n.detail;!o||typeof o.windowId!="string"||o.reason==="state"&&o.state==="minimized"&&(this.streamingWindowId===o.windowId&&this.stopStreaming(),this.focusedWindowId===o.windowId&&(this.focusedWindowId=null))}),window.addEventListener("message",n=>{if(n.origin!==window.location.origin)return;const o=n.data;if(!o||typeof o.type!="string")return;if(o.type==="os-bridge-ready"){const i=this.manager.findByIframeSource(n.source);i&&i.id===this.streamingWindowId&&this.sendSubscribe(i.id);return}if(o.type!=="os-commands-list"||!Array.isArray(o.commands))return;const s=this.manager.findByIframeSource(n.source);s&&s.id===this.streamingWindowId&&this.applyList(s.id,o.commands)});const t=this.manager.getFocused();t&&(this.focusedWindowId=t.id)}onFocused(t){const n=!this.paletteOpen||this.streamingWindowId===t;this.focusedWindowId===t&&n||(this.focusedWindowId&&this.focusedWindowId!==t&&Ei(wl(this.focusedWindowId)),this.streamingWindowId&&this.streamingWindowId!==t&&this.stopStreaming(),this.focusedWindowId=t,this.paletteOpen&&this.startStreaming(t))}onPaletteOpened(){this.paletteOpen=!0,this.closeGraceTimer!==null&&(window.clearTimeout(this.closeGraceTimer),this.closeGraceTimer=null),this.focusedWindowId&&this.startStreaming(this.focusedWindowId)}onPaletteClosed(){this.paletteOpen=!1,this.closeGraceTimer!==null&&window.clearTimeout(this.closeGraceTimer),this.closeGraceTimer=window.setTimeout(()=>{this.closeGraceTimer=null,this.stopStreaming()},ZC)}startStreaming(t){this.streamingWindowId!==t&&(this.stopStreaming(),this.streamingWindowId=t,this.sendSubscribe(t))}stopStreaming(){if(!this.streamingWindowId)return;const t=this.manager.getById(this.streamingWindowId);if(this.streamingWindowId=null,t&&t.iframe&&t.iframe.contentWindow)try{t.iframe.contentWindow.postMessage({type:"os-commands-unsubscribe"},window.location.origin)}catch{}}sendSubscribe(t){const n=this.manager.getById(t);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"os-commands-subscribe"},window.location.origin)}catch(o){KC("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=wl(t);Ei(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=XC(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?Cd(s.iconSvg):"",a={slug:i,label:s.label,icon:gm(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,gm(s)):this.runProxy(t,s.name)};try{_i(a)}catch(l){console.error("[openstation] iframe-bridge: dropping bad command",a,l)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Ge(t))return;const r=ae(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runProxy(t,n){return(o,s)=>{s.close();const i=this.manager.getById(t);if(!(!i||!i.iframe||!i.iframe.contentWindow)){try{i.iframe.contentWindow.postMessage({type:"os-commands-invoke",name:n},window.location.origin)}catch{}this.manager.focus(i)}}}}function QC(e){const t=(n,o)=>{const s=e.getById(n);if(!(!s||!s.iframe||!s.iframe.contentWindow))try{s.iframe.contentWindow.postMessage({type:"os-window-active",active:o},window.location.origin)}catch{}};document.addEventListener("os-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&t(o.windowId,!0)}),document.addEventListener("os-window-blurred",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&t(o.windowId,!1)}),window.addEventListener("message",n=>{if(n.origin!==window.location.origin)return;const o=n.data;if(!o||o.type!=="os-bridge-ready")return;const s=e.findByIframeSource(n.source);s&&t(s.id,e.getFocused()?.id===s.id)})}const wm="global",eI=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,tI=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,nI=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,oI=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,sI=/getSiteEditorPage\s*\(|site-editor\.php/,iI=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function rI(e){const t=window.__openStationMenuCommands;if(!Array.isArray(t))return null;for(const n of t)if(n&&typeof n=="object"&&n.name===e&&typeof n.url=="string"&&n.url!=="")return{label:typeof n.label=="string"?n.label:"",url:n.url};return null}class aI{constructor(t){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=t.manager,this.adminUrl=t.adminUrl}install(){this.tryMount(0)}tryMount(t){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){t<40&&window.setTimeout(()=>this.tryMount(t+1),150);return}this.mount()}mount(){const t=window.wp,n=t.element,o=t.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,l=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof l!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const c=document.createElement("div");c.setAttribute("aria-hidden","true"),c.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(c),this.host=c;const d={perLoader:{},statics:[],loadersList:[]},u=m=>{if(!Array.isArray(m)||m.length===0)return"";const h=new Array(m.length);for(let y=0;y<m.length;y++){const v=m[y];h[y]=v&&v.name?v.name:""}return h.join("|")},f=()=>{let m=[];for(const h of d.loadersList){const y=d.perLoader[h];Array.isArray(y)&&(m=m.concat(y))}Array.isArray(d.statics)&&(m=m.concat(d.statics)),this.callbackCache=Object.create(null);for(const h of m)h&&h.name&&typeof h.callback=="function"&&(this.callbackCache[h.name]=h.callback);this.publish(m)},p=m=>{const h=m.loader;let y=null;try{y=h.hook({search:""})}catch{}const v=y&&Array.isArray(y.commands)?y.commands:[],A=a(()=>u(v),[v]);return i(()=>{d.perLoader[h.name]=v,f()},[A]),i(()=>()=>{delete d.perLoader[h.name],f()},[]),null},w=()=>{const m=l(_=>{const O=_("core/commands");return!O||typeof O.getCommandLoaders!="function"?[]:[...O.getCommandLoaders(!1)||[],...O.getCommandLoaders(!0)||[]]},[]),h=l(_=>{const O=_("core/commands");return!O||typeof O.getCommands!="function"?[]:[...O.getCommands(!1)||[],...O.getCommands(!0)||[]]},[]),y=a(()=>Array.isArray(m)?m.map(_=>_&&_.name||""):[],[m]),v=y.join("|");i(()=>{d.loadersList=y,f()},[v]);const A=a(()=>u(Array.isArray(h)?h:[]),[h]);if(i(()=>{d.statics=Array.isArray(h)?h:[],f()},[A]),!Array.isArray(m)||m.length===0)return null;const D=[];for(const _ of m)!_||typeof _.hook!="function"||D.push(s(p,{key:_.name,loader:_}));return s(n.Fragment||"div",null,D)};try{this.root=n.createRoot(c),this.root.render(s(w))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(t){const n=Object.create(null),o=[];for(const i of t)!i||!i.name||!i.label||i.disabled||n[i.name]||(n[i.name]=!0,o.push(this.classify(i)));let s="";for(const i of o)s+=`${i.name}|${i.kind}|${i.url||""} |
| 61 |
`;if(s!==this.lastFingerprint){this.lastFingerprint=s,Ei(wm);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!==""?Cd(i.iconSvg):void 0,owner:wm,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{_i(l)}catch(c){console.error("[openstation] shell-harvester: dropping bad command",l,c)}}}}classify(t){const n={name:String(t.name),label:String(t.label),icon:typeof t.icon=="string"?t.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof t.callback=="function"?t.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=rI(n.name);if(s){try{n.url=new URL(s.url,this.adminUrl).toString(),n.kind="navigate",s.label!==""&&(n.windowTitle=s.label)}catch{n.kind="skip"}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}if(typeof t.callback=="function"){let i="";try{i=Function.prototype.toString.call(t.callback)}catch{i=""}const r=i.match(eI)||i.match(tI)||i.match(nI);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(oI.test(i)){const l=sI.test(i)?n.name.match(iI):null;if(l){const c=l[1],d=l[2],u=`/${c}/${d}`;try{const f=new URL("site-editor.php",this.adminUrl);f.searchParams.set("p",u),f.searchParams.set("canvas","edit"),n.url=f.toString(),n.kind="navigate"}catch{n.kind="skip"}}else n.kind="skip"}}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}renderIcon(t){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(t);if(typeof o=="string"&&o.toLowerCase().startsWith("<svg"))return o}catch{}return""}iconFor(t){return t.icon&&t.icon.startsWith("dashicons-")?t.icon:t.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Ge(t))return;const r=ae(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runInvoke(t,n,o){return(s,i)=>{const r=this.callbackCache[t];if(typeof r!="function"){i.close();return}const a=this.runWithNavCapture(r);if(a){i.close();const l=ae(a,this.adminUrl);this.manager.open({id:l,baseId:l,url:a,title:n,icon:o})}}}runWithNavCapture(t){let n=null;const o=l=>{n===null&&typeof l=="string"&&l!==""&&(n=l)},s=window.location,i=new Proxy(s,{get(l,c){const d=l[c];return c==="assign"||c==="replace"?u=>o(u):typeof d=="function"?d.bind(l):d},set(l,c,d){return c==="href"&&o(d),!0}}),r=[],a=l=>{try{Object.defineProperty(l,"location",{configurable:!0,get:()=>i,set:c=>o(c)}),r.push({obj:l,key:"location"})}catch{}};a(document),a(window);try{t({close:()=>{}})}catch{}finally{for(const l of r)try{delete l.obj[l.key]}catch{}}return n}}const ym="os-command-palette-ready";let No=null;function lI(){const t=window.openStationConfig?.commandPalette;return!t||!Array.isArray(t.scripts)?null:t}function cI(){const e=window.wp;try{return!!e?.data?.select?.("core/commands")}catch{return!1}}function dI(e){if(!e.url)return;const t=e.url.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(document.head.querySelector(`link[rel="stylesheet"][href="${t}"]`))return;const n=document.createElement("link");n.rel="stylesheet",n.href=e.url,n.dataset.osPaletteStyle=e.handle,document.head.appendChild(n);for(const o of e.inline??[]){if(typeof o!="string"||o==="")continue;const s=document.createElement("style");s.dataset.osPaletteStyle=e.handle,s.textContent=o,document.head.appendChild(s)}}function uI(e){const t=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(document.head.querySelector(`link[rel="preload"][href="${t}"]`))return;const n=document.createElement("link");n.rel="preload",n.as="script",n.href=e,document.head.appendChild(n)}async function fI(){const e=lI();if(!e||e.scripts.length===0)return cI();for(const n of e.styles??[])dI(n);const t=e.scripts.filter(n=>!n.url||!sp(n.url));for(const n of t)n.url&&uI(n.url);for(const n of t)if(n.url)await _e(n.url,{translations:n.translations,l10n:n.l10n,before:n.before,after:n.after});else for(const o of[n.translations??"",...n.l10n??[],...n.before??[],...n.after??[]])typeof o=="string"&&o!==""&&ip(o);return document.dispatchEvent(new CustomEvent(ym)),!0}function pI(){return No||(No=fI().catch(e=>{throw No=null,e}),No)}const Nn=[];function yl(e){Ne("Widget",Mt(e,vm),e);const t=Nn.findIndex(n=>n.id===e.id);t>=0?Nn[t]=e:Nn.push(e)}function hI(e){const t=Nn.findIndex(n=>n.id===e);t>=0&&Nn.splice(t,1)}function bm(){const e=Nn.slice(),t=Y(b.WIDGETS,e);return Array.isArray(t)?t.filter(mI):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function Do(e){return bm().find(t=>t.id===e)}const vm=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"description",message:"not a string",valid:e=>typeof e.description=="string"},{field:"icon",message:"missing or not a non-empty string",valid:e=>typeof e.icon=="string"&&e.icon!==""},{field:"mount",message:"not a function",valid:e=>typeof e.mount=="function"}];function mI(e){return Mt(e,vm).length===0}let Xe=null;function gI(e){if(Xe)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",E("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=E("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),_m(o,e),document.body.appendChild(t),wI(t,e.anchor);const s=a=>{const l=a.target;l&&(t.contains(l)||e.anchor.contains(l)||bl())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&bl()};document.addEventListener("keydown",i),Xe={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function Di(){if(!Xe)return;const e=Xe.panel.querySelector(".os-widget-picker__list");e&&_m(e,Xe.options)}function bl(){if(!Xe)return;document.removeEventListener("pointerdown",Xe.onOutsidePointerDown,!0),document.removeEventListener("keydown",Xe.onKeyDown),Xe.panel.remove();const{onClose:e}=Xe.options;Xe=null,e?.()}function _m(e,t){e.innerHTML="";const n=new Set(t.enabledIds()),o=t.registry();if(o.length===0){const s=document.createElement("div");s.className="os-widget-picker__empty",s.textContent=E("No widgets available. Activate a plugin that registers one, or see the docs for the registerWidget API."),e.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="os-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("os-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=le(E("%s (already added)"),s.label):a=le(E("Add %s"),s.label),i.setAttribute("aria-label",a);const l=document.createElement("span");l.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-widget-picker__entry-text";const d=document.createElement("span");if(d.className="os-widget-picker__entry-label",d.textContent=s.label,c.appendChild(d),s.description){const u=document.createElement("span");u.className="os-widget-picker__entry-description",u.textContent=s.description,c.appendChild(u)}if(i.appendChild(c),r){const u=document.createElement("span");u.className="os-widget-picker__entry-status",u.textContent=E("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function wI(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.style.visibility="hidden";const o=e.getBoundingClientRect(),s=o.width||320,i=o.height||200,r=6;let a=n.right-s,l=n.top-i-r;a<8&&(a=8),l<8&&(l=n.bottom+r),e.style.left=`${Math.round(a)}px`,e.style.top=`${Math.round(l)}px`,e.style.visibility=""}const Ri="os-widgets__card--floating",yI="os-widgets__card--movable",bI="os-widgets__card--resizable",Em="os-widgets__card--dragging",km="os-widgets__card--resizing",vI=160,Sm=80,_I=280,EI=180,Dn=20,Gt=20,Am=5,kI=Am*Am,SI='input, textarea, select, button, a, [contenteditable="true"]';function AI(e,t,n){const o=document.createElement("div");o.className="os-widgets__card",o.dataset.widgetId=e.id;const s=e.movable===!0,i=e.resizable===!0;s&&o.classList.add(yI),i&&o.classList.add(bI),s?o.appendChild(CI(e,n.onRemove,n.onRedock)):o.appendChild(xI(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(vl(o,OI(t.geometry,t.floatingParent)),o.classList.add(Ri)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${RI(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(Ri),l=[];if(i)for(const d of NI()){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(TI(o,u,d,e,t,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=LI(o,d,e,t,n))}return{card:o,body:r,dispose:()=>{for(const d of l)try{d()}catch{}if(c)try{c()}catch{}o.remove()}}}function CI(e,t,n){const o=document.createElement("header");o.className="os-widgets__chrome";const s=document.createElement("span");s.className="os-widgets__grip",s.setAttribute("aria-hidden","true"),o.appendChild(s);const i=document.createElement("span");i.className="os-widgets__title",i.textContent=e.label,o.appendChild(i),o.appendChild(II(e,n));const r=Cm(e,t);return o.appendChild(r),o}function II(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",le(E("Dock %s back to widget column"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2 6h6M5.5 3.5L8 6l-2.5 2.5M10 2.5v7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n.dataset.noDrag="true",n}function xI(e,t){const n=Cm(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function Cm(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",le(E("Remove %s"),e.label)),n.innerHTML=Ot("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function LI(e,t,n,o,s){let i=null,r=0,a=0,l=0,c=0,d=!1;const u=m=>{if(m.button!==0)return;const h=m.target;h&&h.closest(SI)||(m.preventDefault(),i=m.pointerId,r=m.clientX,a=m.clientY,d=!1,l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0,t.setPointerCapture(i))},f=()=>{if(!e.classList.contains(Ri)){const m=o.floatingParent.getBoundingClientRect(),h=e.getBoundingClientRect(),y={x:h.left-m.left,y:h.top-m.top,width:h.width||n.defaultWidth||_I,height:h.height||n.defaultHeight||EI};vl(e,y),e.classList.add(Ri),s.onLiberate(y),l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(Em)},p=m=>{if(i===null||m.pointerId!==i)return;const h=m.clientX-r,y=m.clientY-a;if(!d){if(h*h+y*y<kI)return;d=!0,f()}const v=Lm(Rn(l+h),Rn(c+y),e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${xm(v.x)}px`,e.style.top=`${xm(v.y)}px`},w=m=>{if(!(i===null||m.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(Em),s.onGeometryChanged(Im(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",w),t.addEventListener("pointercancel",w),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",w),t.removeEventListener("pointercancel",w)}}function TI(e,t,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const w=y=>{if(y.button!==0||!r()&&!DI(n))return;y.preventDefault(),y.stopPropagation(),a=y.pointerId,l=y.clientX,c=y.clientY;const v=e.getBoundingClientRect(),A=s.floatingParent.getBoundingClientRect();d=v.left-A.left,u=v.top-A.top,f=v.width,p=v.height,t.setPointerCapture(a),e.classList.add(km)},m=y=>{if(a===null||y.pointerId!==a)return;const v=y.clientX-l,A=y.clientY-c,D=MI(n,v,A,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${D.x}px`,e.style.top=`${D.y}px`,e.style.width=`${D.width}px`),e.style.height=`${D.height}px`},h=y=>{if(!(a===null||y.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(km),r()?i.onGeometryChanged(Im(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",w),t.addEventListener("pointermove",m),t.addEventListener("pointerup",h),t.addEventListener("pointercancel",h),()=>{t.removeEventListener("pointerdown",w),t.removeEventListener("pointermove",m),t.removeEventListener("pointerup",h),t.removeEventListener("pointercancel",h)}}function NI(){return["n","e","s","w","ne","nw","se","sw"]}function DI(e){return e==="s"}function vl(e,t){e.style.left=`${t.x}px`,e.style.top=`${t.y}px`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`}function Im(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function RI(e,t){return On(e,t.minHeight??Sm,t.maxHeight??1/0)}function OI(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Lm(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function Rn(e){return Math.round(e/Gt)*Gt}function xm(e){const t=Math.floor(e/Gt)*Gt;return t>=Dn?t:Math.min(e,Dn)}function Lm(e,t,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,a=Math.max(0,i-n-Dn),l=Math.max(0,r-o-Dn);return{x:Math.min(Math.max(Dn,e),a),y:Math.min(Math.max(Dn,t),l)}}function MI(e,t,n,o,s,i,r,a,l,c){const d=a.minWidth??vI,u=a.minHeight??Sm,f=a.maxWidth??1/0,p=a.maxHeight??1/0,w=l.clientWidth||l.getBoundingClientRect().width,m=l.clientHeight||l.getBoundingClientRect().height;let h=o,y=s,v=i,A=r;if((e==="e"||e==="ne"||e==="se")&&(c?v=Oi(Rn(o+i+t),o+d,Math.min(o+f,w))-o:v=On(i+t,d,Math.min(f,w-o))),e==="w"||e==="nw"||e==="sw"){const D=o+i;if(c)h=Oi(Rn(o+t),Math.max(0,D-Math.min(f,D)),D-d),v=D-h;else{const _=On(i-t,d,Math.min(f,D));h=o+(i-_),v=_}}if((e==="s"||e==="se"||e==="sw")&&(c?A=Oi(Rn(s+r+n),s+u,Math.min(s+p,m))-s:A=On(r+n,u,Math.min(p,m-s))),e==="n"||e==="ne"||e==="nw"){const D=s+r;if(c)y=Oi(Rn(s+n),Math.max(0,D-Math.min(p,D)),D-u),A=D-y;else{const _=On(r-n,u,Math.min(p,D));y=s+(r-_),A=_}}return c||(v=i,h=o),{x:h,y,width:v,height:A}}function Oi(e,t,n){const o=On(e,t,n),s=Math.floor(o/Gt)*Gt;if(s>=t)return s;const i=s+Gt;return i<=n?i:o}function On(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const Tm="desktop-mode-widgets",Nm="desktop-mode-widgets-geometry",Dm="desktop-mode-widgets-docked-heights";function Rm(){try{return window.localStorage.getItem(Tm)}catch{return null}}function PI(){const e=Rm();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function _l(e){try{window.localStorage.setItem(Tm,JSON.stringify(e))}catch{}}function WI(){try{const e=window.localStorage.getItem(Nm);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t)){const i=UI(s);i&&(n[o]=i)}return n}catch{return{}}}function El(e){try{window.localStorage.setItem(Nm,JSON.stringify(e))}catch{}}function $I(){try{const e=window.localStorage.getItem(Dm);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t))typeof s=="number"&&Number.isFinite(s)&&s>0&&(n[o]=s);return n}catch{return{}}}function Om(e){try{window.localStorage.setItem(Dm,JSON.stringify(e))}catch{}}function UI(e){if(!e||typeof e!="object")return null;const{x:t,y:n,width:o,height:s}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)||typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||s<=0?null:{x:t,y:n,width:o,height:s}}function FI(e){const t=`os.widget.${e}.`,n=o=>{try{return localStorage.getItem(t+o)}catch{return null}};return{get(o){const s=n(o);if(s===null)return null;try{return JSON.parse(s)}catch{return null}},set(o,s){try{localStorage.setItem(t+o,JSON.stringify(s))}catch{}},remove(o){try{localStorage.removeItem(t+o)}catch{}},clear(){try{for(let o=localStorage.length-1;o>=0;o--){const s=localStorage.key(o);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}}}}const BI=["clock"],Mi=40,HI=12;class zI{constructor(t,n,o){this.mounted=new Map,this.generation=0,this.unwatchPointer=null,this.root=t,this.pluginUrl=n,this.enabledIds=PI(),this.geometry=WI(),this.dockedHeights=$I(),this.floatingHost=o??t.parentElement??t,this.listEl=document.createElement("div"),this.listEl.className="os-widgets__list",this.root.appendChild(this.listEl),this.addTile=this.buildAddTile(),this.root.appendChild(this.addTile),this.paintEmptyState(),this.watchPointerProximity()}hydrate(){Rm()===null&&(this.enabledIds=BI.filter(t=>!!Do(t)),_l(this.enabledIds));for(const t of this.enabledIds)this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){this.enabledIds.includes(t)||Do(t)&&(this.enabledIds.push(t),_l(this.enabledIds),this.mountById(t),this.paintEmptyState(),L(b.WIDGET_ADDED,{id:t}))}remove(t){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(_l(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],El(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],Om(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),L(b.WIDGET_REMOVED,{id:t}),Di())}getEnabledIds(){return[...this.enabledIds]}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),gI({anchor:this.addTile,registry:()=>bm(),enabledIds:()=>[...this.enabledIds],onAdd:t=>{this.add(t),bl(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){Do(t)&&this.enabledIds.includes(t)&&(this.mounted.has(t)||(this.mountById(t),this.paintEmptyState()))}unmount(t){this.mounted.has(t)&&(this.unmountById(t),this.paintEmptyState())}ensureMounted(t){return Do(t)?(this.enabledIds.includes(t)||this.add(t),!0):!1}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t);this.unwatchPointer?.(),this.unwatchPointer=null}mountById(t){const n=Do(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=AI(n,{floatingParent:this.floatingHost,geometry:s,dockedHeight:this.dockedHeights[t]},{onRemove:()=>this.remove(t),onGeometryChanged:u=>this.persistGeometry(t,u),onDockedHeightChanged:u=>this.persistDockedHeight(t,u),onLiberate:u=>this.liberate(t,u),onRedock:()=>this.redock(t)}),r=!!s,a={id:t,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(t,a),this.placeCard(i.card,r);const l={id:t,pluginUrl:this.pluginUrl,storage:FI(t)};L(b.WIDGET_MOUNTING,{id:t,container:i.body,ctx:l});const c=u=>{const f=this.mounted.get(t);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,this.positionAddTile(),L(b.WIDGET_MOUNTED,{id:t,container:i.body,ctx:l})};let d;try{d=n.mount(i.body,l)}catch(u){this.handleMountFailure(t,u);return}if(GI(d)){d.then(c,u=>{this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,u)});return}c(d)}unmountById(t){const n=this.mounted.get(t);if(n){L(b.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){L(b.SHELL_ERROR,{scope:"widget-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" teardown threw:`,o)}this.generation++,n.frame.dispose(),this.mounted.delete(t)}}handleMountFailure(t,n){const o=this.mounted.get(t);o&&(o.frame.dispose(),this.mounted.delete(t)),L(b.WIDGET_MOUNT_FAILED,{id:t,error:n}),L(b.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="os-widgets__add",t.setAttribute("aria-label",E("Add widget"));const n=document.createElement("span");n.className="os-widgets__add-plus",n.setAttribute("aria-hidden","true"),n.textContent="+";const o=document.createElement("span");return o.className="os-widgets__add-label",o.textContent=E("Add widget"),t.appendChild(n),t.appendChild(o),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.openPicker()}),t}watchPointerProximity(){let t=null,n=0;const o=()=>{t=null,this.positionAddTile()},s=()=>{n||(n=requestAnimationFrame(()=>{n=0,this.positionAddTile()}))},i=l=>{t||(t=this.root.getBoundingClientRect());const c=l.clientX>=t.left-Mi&&l.clientX<=t.right+Mi&&l.clientY>=t.top-Mi&&l.clientY<=t.bottom+Mi;this.root.classList.toggle("os-widgets--hovered",c),c&&s()},r=()=>{this.root.classList.remove("os-widgets--hovered")};document.addEventListener("pointermove",i,{passive:!0}),document.documentElement.addEventListener("pointerleave",r),window.addEventListener("resize",o);let a=null;typeof ResizeObserver=="function"&&(a=new ResizeObserver(o),a.observe(this.root),this.root.parentElement&&a.observe(this.root.parentElement)),this.unwatchPointer=()=>{n&&(cancelAnimationFrame(n),n=0),a?.disconnect(),document.removeEventListener("pointermove",i),document.documentElement.removeEventListener("pointerleave",r),window.removeEventListener("resize",o)}}placeCard(t,n){n?this.floatingHost.appendChild(t):this.listEl.appendChild(t)}liberate(t,n){const o=this.mounted.get(t);!o||o.floating||(o.floating=!0,this.floatingHost.appendChild(o.frame.card),vl(o.frame.card,n),this.persistGeometry(t,n),this.paintEmptyState())}redock(t){const n=this.mounted.get(t);if(!n||!n.floating)return;n.floating=!1,this.geometry[t]&&(delete this.geometry[t],El(this.geometry));const o=n.frame.card;o.classList.remove("os-widgets__card--floating"),o.style.left="",o.style.top="",o.style.width="";const s=this.dockedHeights[t];o.style.height=s!==void 0?`${s}px`:"",this.listEl.appendChild(o),this.paintEmptyState()}persistGeometry(t,n){this.geometry[t]=n,El(this.geometry),this.positionAddTile()}positionAddTile(){const t=this.root.getBoundingClientRect();if(!t.height)return;let n=this.listEl.offsetTop+this.listEl.offsetHeight;for(const i of this.mounted.values()){if(!i.floating)continue;const r=i.frame.card.getBoundingClientRect();Math.min(r.right,t.right)-Math.max(r.left,t.left)<t.width/2||(n=Math.max(n,r.bottom-t.top+this.root.scrollTop))}const o=t.height+this.root.scrollTop-this.addTile.offsetHeight,s=Math.max(0,Math.min(n+HI,o));this.addTile.style.top!==`${s}px`&&(this.addTile.style.top=`${s}px`)}persistDockedHeight(t,n){!Number.isFinite(n)||n<=0||(this.dockedHeights[t]=n,Om(this.dockedHeights))}paintEmptyState(){let t=0;for(const n of this.mounted.values())n.floating||t++;this.root.classList.toggle("os-widgets--has-widgets",t>0),this.positionAddTile()}}function GI(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const jI=280,VI=220,qI=520,KI=400;function YI(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function XI(e,t,n){return o=>{const s=YI(o,n),i=document.createElement("iframe");i.style.width="100%",i.style.height="100%",i.style.border="0",i.setAttribute("src",e.url),typeof e.sandbox=="string"&&e.sandbox!==""&&i.setAttribute("sandbox",e.sandbox),o.style.padding="0",o.appendChild(i);const r=GC(s,i);t.push(r);let a;try{a=new URL(e.url,window.location.origin).origin}catch{a=window.location.origin}let l=null;const c=new Promise(f=>{l=f}),d=()=>{if(e.bridge)try{const f=i.contentDocument;if(f&&!f.querySelector("script[data-os-iframe-bridge]")){const p=window.openStationConfig?.iframeBridgeUrl;if(p){const w=f.createElement("script");w.src=p,w.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(w)}}}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!==""&&L_(s,p.channel,p.payload);try{e.onMessage?.(f.data)}catch(w){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",w)}};return window.addEventListener("message",u),t.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),c}}function ZI(e){return async t=>{const n=t.render;let o=n;const s=[];t.iframeContent&&(n&&typeof console<"u"&&console.warn("[openstation] registerWindow: both `render` and `iframeContent` provided — ignoring `render` and using the iframe shorthand. Drop one."),o=XI(t.iframeContent,s,t.id));const i=t.onClose,r=t.iframeContent?()=>{for(const l of s)try{l()}catch{}i?.()}:i;return await e.open({id:t.id,baseId:t.baseId||t.id,native:!0,url:t.url||`#${t.id}`,title:t.title,icon:t.icon,x:t.x??0,y:t.y??0,width:t.width??qI,height:t.height??KI,minWidth:t.minWidth??jI,minHeight:t.minHeight??VI,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let JI=0;function QI(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++JI}`,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)Tr(c,o)}};for(const[c,d]of i){const u=t[c];u&&(r.push(d),Z(d,o,f=>{const p=f;if(p.windowId!==e)return;const{windowId:w,...m}=p;u(m),c==="closed"&&!s&&l()}))}return l}function ex(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function tx(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&DE(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function nx(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,a=new Map,l=new Set,c=new Map,d=g=>{const C=fa(g.id);return C?{width:Math.max(C.width,g.minWidth),height:Math.max(C.height,g.minHeight)}:{width:g.width,height:g.height}},u=g=>{if(i.has(g.templateId))return;if(document.getElementById(g.templateId)){i.add(g.templateId);return}if(!g.templateHtml)return;const C=document.createElement("template");C.id=g.templateId,C.innerHTML=g.templateHtml,document.body.appendChild(C),i.add(g.templateId)},f=g=>{const C=g.styleUrl;if(!C||l.has(C))return;const U=C.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${U}"]`)){const z=document.createElement("link");z.rel="stylesheet",z.href=C,g.styleHandle&&(z.dataset.osStyleHandle=g.styleHandle),document.head.appendChild(z)}if(Array.isArray(g.styleInline))for(const z of g.styleInline){if(typeof z!="string"||z==="")continue;const I=document.createElement("style");g.styleHandle&&(I.dataset.osStyleHandle=g.styleHandle),I.textContent=z,document.head.appendChild(I)}l.add(C)},p=g=>{f(g)},w=g=>{for(const C of g.companionStyles??[])f(C)},m=new Set,h=(g,C)=>{if(m.has(g))return;m.add(g);const U=[C.scriptTranslations??"",...C.scriptL10n??[],...C.scriptBefore??[],...C.scriptAfter??[]];for(const V of U)typeof V=="string"&&V!==""&&ip(V)},y=(g,C)=>{const U=C.scriptUrl,V=`${g}|${U}`;if(r.has(U))return h(V,C),Promise.resolve();const z=a.get(U);if(z)return z.then(()=>h(V,C));m.add(V);const I=_e(U,{translations:C.scriptTranslations,l10n:C.scriptL10n,before:C.scriptBefore,after:C.scriptAfter}).catch(x=>{L(b.SHELL_ERROR,{scope:"native-window-script-load",id:g,error:x})}).then(()=>{r.add(U),a.delete(U)});return a.set(U,I),I},v=async g=>{w(g);for(const C of g.companionScripts??[])C.scriptUrl&&await y(g.id,C);g.scriptUrl&&await y(g.id,g)},A=async g=>{g.preloadScript&&await v(g)},D=g=>async(C,U)=>{C.appendChild(Mm(g.templateId)),tx(C,g),await v(g);const V=ex()[g.id];return V?.(C,U)},_=(g,C)=>{const U=D(g),V=d(g);t.open({id:g.id,baseId:g.id,native:!0,url:`#${g.id}`,title:g.title,icon:g.icon,width:V.width,height:V.height,minWidth:g.minWidth,minHeight:g.minHeight,render:U,autofocus:g.autofocus,ownerHandle:g.ownerHandle||g.scriptHandle,...C?{params:C}:{}})},O=(g,C)=>{const U=D(g),V=d(g);t.openNew({id:g.id,baseId:g.id,native:!0,url:`#${g.id}`,title:g.title,icon:g.icon,width:V.width,height:V.height,minWidth:g.minWidth,minHeight:g.minHeight,initialState:"normal",render:U,autofocus:g.autofocus,ownerHandle:g.ownerHandle||g.scriptHandle,...C?{params:C}:{}})},P=async g=>{if(!s.has(g.id)){if(g.placement==="none"){u(g),p(g),await A(g),s.add(g.id);return}u(g),p(g),await A(g),n({id:g.id,title:g.title,icon:g.icon,windowId:g.id,navKind:g.navKind==="control"?"control":"app",defaultPlacement:"rail",order:g.dockOrder,placeable:g.placeable===!0,isOpen:()=>!!t.getById(g.id),onOpen:()=>_(g)}),L(b.DOCK_ITEM_APPENDED,{id:g.id}),s.add(g.id)}},$=g=>{s.has(g)&&(o(g),s.delete(g),c.delete(g))},F=async g=>{const C=new Set;for(const U of g)C.add(U.id),c.set(U.id,U);for(const U of Array.from(s))C.has(U)||$(U);for(const U of g)s.has(U.id)||await P(U)},k=(g,C={})=>{const U=c.get(g);return U?(ke.publish("os/open-requested",{windowId:g,source:C.source??"api"}),_(U,C.params),!0):!1},W=(g,C={})=>{const U=c.get(g);return U?(ke.publish("os/open-requested",{windowId:g,source:C.source??"api"}),O(U,C.params),!0):!1};return Z(b.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",g=>{const C=g,U=C?.windowId,V=C?.width,z=C?.height;if(!U||typeof V!="number"||typeof z!="number")return;const I=t.getById(U);if(!I||I.state!=="normal")return;const x=I.config.baseId||I.id;Ef(x,{width:V,height:z}),I.element&&kf(x,{x:I.element.offsetLeft,y:I.element.offsetTop})}),Z(b.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",g=>{const C=g?.windowId;if(!C)return;const U=t.getById(C);if(!U||U.state!=="normal"||!U.element)return;const V=U.config.baseId||U.id;Ef(V,{width:U.element.offsetWidth,height:U.element.offsetHeight}),kf(V,{x:U.element.offsetLeft,y:U.element.offsetTop})}),Z(b.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",g=>{const C=g?.windowId;if(!C)return;const U=t.getById(C);if(!U)return;const V=U.config.baseId||U.id,z=c.get(V),I=z?{width:z.width,height:z.height}:{width:U.config.width,height:U.config.height};Sf(V,"maximized",I)}),Z(b.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",g=>{const C=g?.windowId;if(!C)return;const U=t.getById(C);if(!U)return;const V=U.config.baseId||U.id;Sf(V,null)}),{sync:F,openById:k,openNewById:W,loadScriptById:async g=>{const C=c.get(g);return C?(await v(C),!0):!1}}}function Mm(e){let t=null;if(typeof e=="string"){const n=document.getElementById(e);n instanceof HTMLTemplateElement&&(t=n)}else t=e;if(!t)throw new Error(`[openstation] cloneTemplate: no <template> found for ${typeof e=="string"?`#${e}`:"<reference>"}`);return t.content.cloneNode(!0)}function Pm(e){const t=window.wp?.os,n=window.openStationConfig,o=t?.config?.adminUrl??n?.adminUrl;if(!o)return null;const s=t?.getMenuItems?.()??n?.dockItems??[],i=ae(e,o);return s.find(r=>ae(r.url,o)===i||(r.submenu??[]).some(a=>ae(a.url,o)===i))??null}const Wm="data:image/svg+xml;base64,",Pi=new Map;function ox(e){const t=Pi.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(Wm.length)).includes("currentColor")}catch{}return Pi.size>=256&&Pi.clear(),Pi.set(e,n),n}function Ro(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const l=Vs(t.slot);l!==null&&(e=l),s=Zr(t.slot)}if(typeof e=="string"&&e.startsWith("dashicons-")){const l=document.createElement("span");return l.className=`dashicons ${e} ${n}`.trim(),l.setAttribute("aria-hidden","true"),s!==null&&(l.style.color=s),l}if(s!==null&&typeof e=="string"){const l=document.createElement("span");if(l.className=n,l.setAttribute("aria-hidden","true"),l.style.display="inline-block",ho(l,e,s))return l}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const l=e.slice(Wm.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",ox(e)&&ho(c,e,"currentColor")||(c.style.backgroundImage=`url("${e}")`,c.style.backgroundRepeat="no-repeat",c.style.backgroundPosition="center",c.style.backgroundSize="contain"),c}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const l=e.indexOf(","),c=l>=0?e.slice(l+1):"";if(/^[A-Za-z0-9+/=]+$/.test(c))return $m(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return $m(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=sx(o);i.textContent=r;const a=vn(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 $m(e,t){const n=document.createElement("img");return n.className=t,n.src=e,n.alt="",n.setAttribute("aria-hidden","true"),n.draggable=!1,n}function sx(e){const t=(e??"").trim();if(t==="")return"?";const n=t.split(/\s+/);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();const o=n[0];return o.length>=2?o.slice(0,2).toUpperCase():o.toUpperCase()}const Um="os-icon__badge",Oo=new Map,Mo=new Map;function ix(e){return Math.max(0,Math.floor(Number(e)||0))}function Fm(e,t){if(!e)return;const n=Gm(e);if(!n)return;const o=ix(t),s=Oo.get(e)??0;o!==s&&(o===0?Oo.delete(e):Oo.set(e,o),jm(n,o),ke.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),L(b.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function rx(e){Fm(e,0)}function ax(e){return Oo.get(e)??0}function lx(e,t){if(e){if(!t){Mo.delete(e);return}Mo.get(e)!==t&&(Mo.set(e,t),dx(e,t),ke.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function Bm(e){return Mo.get(e)??""}function cx(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function dx(e,t){const o=Gm(e)?.querySelector(".os-icon__image");if(o){const s=Ro(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${cx(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const ux={setBadge:Fm,clearBadge:rx,getBadge:ax,setArt:lx,getArt:Bm};function fx(e){return!e||e.length===0?"":`${Xr()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let Hm="";function zm(e,t,n){const o=fx(t);if(o===Hm&&e.querySelector(":scope > .os-icons"))return;Hm=o;const s=e.querySelector(":scope > .os-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="os-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",E("Desktop icons"));const r=[...t].sort((l,c)=>{const d=l.pinned?0:1,u=c.pinned?0:1;return d-u}),a=new Map;for(const l of r){const c=hx(l,n),d=Oo.get(l.id)??0;d>0&&jm(c,d);const u=Mo.get(l.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(Ro(u,{className:"os-icon__image",title:""}))}i.appendChild(c),a.set(l.id,c)}e.appendChild(i),L(b.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(l=>l.id),container:i,tiles:a})}function Gm(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${px(e)}"]`):null}function jm(e,t){const n=e.querySelector(`:scope > .${Um}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=le(un("%d notification","%d notifications",t),t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",s);return}const i=document.createElement("span");i.className=Um,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function px(e){const t=window.CSS;return t?.escape?t.escape(e):e}function hx(e,t){const n=document.createElement("button");n.type="button",n.className=e.pinned?"os-icon os-icon--pinned":"os-icon",n.dataset.iconId=e.id,e.pinned&&(n.dataset.pinned="1"),n.setAttribute("role","listitem"),n.setAttribute("aria-label",e.title);const o=Ro(e.icon,{title:e.title,className:"os-icon__image",slot:qs(e.id)});n.appendChild(o);const s=document.createElement("span");return s.className="os-icon__label",s.textContent=e.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),L(b.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),mx(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),lp({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function mx(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(_n(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=Pm(n.toString());t.manager.open({id:o,baseId:o,url:n.toString(),parentUrl:s?.url??n.toString(),title:e.title,icon:e.icon,submenu:s?.submenu,selfLabel:s?.selfLabel,multi:!!s?.multi})}catch{}}}function gx(e){const t=[],n=new Map,o=s=>{t.push(s),n.set(s.id,s)};for(const s of e.menuItems)n.has(s.id)||o({id:s.id,kind:s.isCore?"core":"plugin",title:s.title,icon:s.icon,windowId:e.resolveMenuWindowId?.(s)||void 0,menu:s});for(const s of e.systemTiles){const i=n.get(s.item.id);if(i){i.tile=s.item;continue}const a=(s.item.submenu??[]).map(l=>l.windowId).filter(l=>!!l);o({id:s.item.id,kind:s.kind,title:s.item.title,icon:s.item.icon,locked:s.locked,defaultPlacement:s.item.defaultPlacement,windowId:s.item.windowId,answersFor:a.length>0?a:void 0,order:s.item.order,tile:s.item})}for(const s of e.icons){const i=s.window?n.get(s.id)??n.get(s.window):n.get(s.id);if(i){i.entry=s,s.window&&(i.windowId=s.window);continue}o({id:s.id,kind:"app",title:s.title,icon:s.icon,windowId:s.window||void 0,entry:s})}return t}const Vm="os-side-dock";function wx(e,t,n,o,s="bottom"){let i=t,r=s,a=n,l=o??[],c=null,d=null,u=null,f=null,p=null;const w=new Map;let m=[],h=up({items:[],config:{placement:{},order:[]},layout:i,openWindows:[]});const y=()=>e.getSettings?.()??{navPlacement:{},navOrder:[]},v=()=>{const T=e.windowManager.getActiveDesktopId(),K=[],q=new Set;for(const ce of e.windowManager.getAll()){if((ce.config.desktopId||T)!==T)continue;const ve=ce.config.baseId||ce.id;q.has(ve)||(q.add(ve),K.push({id:ve,title:ce.config.title||ve,icon:ce.config.icon||"dashicons-admin-generic",fromAdminUrl:ce.config.native!==!0}))}return K},A=T=>T.windowId?T.windowId:pa(T.url)??ae(T.url,e.adminUrl),D=()=>{const T=[];for(const q of w.values())T.push({item:q,kind:q.navKind==="control"?"control":"app",locked:q.locked});m=gx({menuItems:a,systemTiles:T,icons:l,resolveMenuWindowId:A});const K=y();h=up({items:m,config:{placement:K.navPlacement,order:K.navOrder},layout:i,openWindows:v()})},_=T=>T.tile?{type:"system",item:T.tile}:T.menu?{type:"menu",item:T.windowId?{...T.menu,windowId:T.windowId}:T.menu}:{type:"menu",item:{id:T.id,title:T.title,icon:T.icon,url:T.entry?.url||"",windowId:T.windowId,badge:0,submenu:[],isCore:!1}},O=T=>!!T.entry||!!T.windowId||!!T.menu?.url,P=(T,K)=>T.entry?T.entry:{id:T.id,title:T.title,icon:T.icon,window:T.windowId??"",url:T.menu?.url||"",position:2e3+K},$=T=>({core:(T.core??[]).map(_),apps:(T.apps??[]).map(_),controls:(T.controls??[]).map(_)}),F=(T,K,q)=>{if(!T)return;if(T.setZones){T.setZones(K),q.clear();for(const ye of it)for(const he of K[ye])he.type==="system"&&q.add(he.item.id);return}const ce=[],ve=new Set;for(const ye of it)for(const he of K[ye])he.type==="menu"?ce.push(he.item):ve.add(he.item.id);T.replaceItems(ce);for(const ye of Array.from(q))ve.has(ye)||(T.removeSystemItem(ye),q.delete(ye));for(const ye of it)for(const he of K[ye])he.type==="system"&&!q.has(he.item.id)&&(T.appendSystemItem(he.item),q.add(he.item.id))},k=new Set,W=new Set,N=()=>{D(),F(c,$(h.dock),k),F(d,{core:h.sidebar.map(_),apps:[],controls:[]},W),e.renderIcons(h.desktop.filter(O).map(P))},g=()=>Array.from(h.ephemeral).sort().join(","),C=()=>{const T=document.getElementById(Vm);if(T)return T;const K=document.createElement("nav");return K.id=Vm,K.className="os-dock",K.setAttribute("role","toolbar"),K.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(K,e.shellBody.firstChild),K},U=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},V=()=>{if(c){try{c.destroy()}catch(T){L(b.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:T})}c=null,u=null}if(d){try{d.destroy()}catch(T){L(b.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:T})}d=null,f=null}k.clear(),W.clear()},z=T=>{const K=$r();if(!K)return L(b.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return K.mount(T)}catch(q){if(L(b.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:K.id,error:q}),K===Aa)return null;try{return Aa.mount(T)}catch{return null}}},I=(T,K)=>({container:T,items:[],fullMenu:a.slice(),fullSystemTiles:m.filter(q=>!!q.tile).filter(q=>x(q.id)).map(q=>q.tile),orientation:K,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:q=>{const ce=ae(q.url,e.adminUrl);e.windowManager.open({id:ce,baseId:ce,url:q.url,parentUrl:q.url,title:q.title,icon:q.icon.startsWith("dashicons-")?q.icon:"dashicons-admin-generic",submenu:q.submenu,selfLabel:q.selfLabel,multi:!!q.multi})},openSubmenuPick:(q,ce)=>{_n(ce.url)||e.windowManager.open({id:ae(ce.url,e.adminUrl),baseId:ae(q.url,e.adminUrl),url:ce.url,parentUrl:q.url,title:q.title,icon:q.icon.startsWith("dashicons-")?q.icon:"dashicons-admin-generic",submenu:q.submenu,selfLabel:q.selfLabel,multi:!!q.multi})},openSystemItem:q=>q.onOpen()}),x=T=>{for(const K of it)if(h.dock[K].some(q=>q.id===T))return!0;return h.sidebar.some(K=>K.id===T)},B=()=>i==="classic"?"bottom":r,M=()=>{V(),D(),i==="classic"?(p=C(),d=z(I(p,"left")),f=mp(d)):U(),c=z(I(e.bottomDockEl,B())),u=mp(c),N()},j=()=>{document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:B(),primary:u,side:f}}))},R={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:T=>{T!==i&&(i=T,e.shellRoot.setAttribute("data-os-layout",T),M(),j())},getDockPlacement:()=>r,setDockPlacement:T=>{if(T===r)return;const K=B();r=T,B()!==K&&(M(),j())},applyDockItems:T=>{a=T,N()},applyDesktopIcons:T=>{l=T??[],N()},appendSystemTile:T=>{w.set(T.id,T),N()},removeSystemTile:T=>{w.delete(T)&&N()},listSystemTiles:()=>Array.from(w.values()).map(T=>({id:T.id,title:T.title,icon:T.icon,navKind:T.navKind==="control"?"control":"app",placeable:T.placeable===!0,locked:T.locked===!0})),getSystemTile:T=>w.get(T)??null,getMenuItems:()=>a.slice(),getNavItems:()=>m.slice(),getNav:()=>h,refresh:N,destroy:()=>{V(),U()}};for(const T of["os-window-opened","os-window-closed"])document.addEventListener(T,()=>{const K=g();D(),g()!==K&&N()});e.shellRoot.setAttribute("data-os-layout",i),M();let H=$r()?.id??null;return Mv(()=>{const T=$r()?.id??null;T!==H&&(H=T,M(),j())}),R}function yx(e){return window.openStationCreateAiAssistant?Promise.resolve(window.openStationCreateAiAssistant):new Promise((t,n)=>{const o=document.querySelector('script[data-os-ai="1"]'),s=()=>{const r=window.openStationCreateAiAssistant;if(!r){n(new Error("[openstation] ai-assistant bundle loaded but did not register openStationCreateAiAssistant"));return}t(r)};if(o){window.openStationCreateAiAssistant?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osAi="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))),document.head.appendChild(i)})}class bx{constructor(t,n){this._real=null,this._loadPromise=null,this._pendingAsk=null,this._intendOpen=!1,this.ask=(...o)=>this._ensure().then(s=>s.ask(...o)),this._config=t,this._scriptUrl=n}_ensure(){return this._loadPromise?this._loadPromise:(xa("desktop-mode-ai-assistant"),pI().catch(t=>{console.warn("[openstation] command-palette runtime failed to load",t)}),this._loadPromise=yx(this._scriptUrl).then(t=>{const n=t(this._config);return this._pendingAsk&&n.attachAsk(this._pendingAsk),this._real=n,n}),this._loadPromise)}open(){this._intendOpen=!0,this._ensure().then(t=>t.open())}close(){this._intendOpen=!1,this._real&&this._real.close()}toggle(){this.isOpen?this.close():this.open()}get isOpen(){return this._real?this._real.isOpen:this._intendOpen}attachAsk(t){this._pendingAsk=t,this._real&&this._real.attachAsk(t)}}const qm=e=>!e||typeof e!="object"?!1:e.name==="AbortError",vx=e=>{if(!e)return[];const t=QS();if(e===!0||e==="aiCallable")return t;if(Array.isArray(e)){const n=new Set(e.map(o=>o.toLowerCase()));return t.filter(o=>n.has(o.slug))}return typeof e=="function"?t.filter(n=>{try{return e(n.slug)===!0}catch{return!1}}):[]},_x=e=>e?typeof e=="string"?{text:e,mode:"append"}:typeof e=="object"&&typeof e.text=="string"&&e.text!==""?{text:e.text,mode:e.mode==="replace"?"replace":"append"}:null:null;function Ex(e,t){const n=e??"";return n!==""?n:typeof t=="string"&&t!==""?t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"?t.message:""}function kx(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function Sx(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",l=r.restNonce??"";if(!a||!l)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Fe(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":l},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw qm(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=eA(r);if(!l)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??e.fallbackContext();let d;try{d=await Promise.resolve(l.run(a,c))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:d}},o=async(s,i,r,a,l,c)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:kx(a)}};l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);let u;try{u=await t(d,c)}catch(w){if(qm(w))throw w;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=vx(r.tools),c=_x(r.systemPrompt),d={query:a};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),l.length>0&&(d.command_tools=l),c&&(d.system_prompt_text=c.text,d.system_prompt_mode=c.mode);const u=await t(d,r.signal);if(!u.ok){const 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:w,args:m,result:h}=p;let y=Ex(f.message,h);if(r.followUp===!0){const v=await o(a,w,m,h,c,r.signal);v!==null&&(y=v)}return{answer_type:"tool_call",message:y,entity:null,admin_links:null,toolCall:{slug:w,args:m,result:h},request_id:f.request_id}}}const Km="[os-bin badge]";function rt(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(Km,...e)}catch{}}function Wi(...e){console.warn(Km,...e)}const Po="desktop-mode-recycle-bin",Ax="openstation_recycle_bin_seen_ts";function Cx(){return window.wp?.os}const fe=re("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function Wo(e){const t=Math.max(0,Math.floor(e)),n=fe.state.current;fe.state.current=t,rt("setRecycleBinCount",{prev:n,next:t}),kl(t)}function Ym(e){Wo(fe.state.current+e)}function Ix(){return fe.state.current}function kl(e){const t=e>0?fe.state.fullArt:fe.state.emptyArt;if(rt("paintIconState",{count:e,full:e>0,hasArt:!!t}),!t)return;const n=Cx();n?.dock?.setArt?.(Po,t),n?.taskbar?.setArt?.(Po,t),n?.icons?.setArt?.(Po,t)}function xx(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;fe.state.emptyArt=String(o?.recycleBinIconEmpty??""),fe.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;rt("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:fe.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)||Wi("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),fe.state.started){Wo(n);return}fe.state.started=!0,fe.state.countUrl=t,fe.state.seenTs=Date.now(),Wo(n),Lx(),Tx(),Nx(),Dx(),Rx()}function Lx(){Z(b.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===Po&&kl(fe.state.current)})}function Tx(){Z(b.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(Po)&&kl(fe.state.current)})}function Nx(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":Ym(+r);break;case"untrashed":case"deleted":Ym(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])In(`os.${s}.changed`,e)}function Dx(){const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;if(!n||n.type!=="os-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=fe.state.seenTs){rt("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:fe.state.seenTs});return}rt("postMessage triggers refetch",{ts:o,prevSeenTs:fe.state.seenTs}),fe.state.seenTs=o,Ox()})}function Rx(){const e=window.jQuery;if(!e){Wi("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}rt("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[Ax]=fe.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;rt("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>fe.state.seenTs&&(fe.state.seenTs=o.ts),typeof o.count=="number"&&Wo(o.count))})}async function Ox(){if(!fe.state.countUrl){rt("refetchCount: no countUrl, skip");return}rt("refetchCount: hitting",fe.state.countUrl);try{const e=await fetch(fe.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){Wi("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();rt("refetchCount: response",t),typeof t.count=="number"&&Wo(t.count)}catch(e){Wi("refetchCount: fetch failed",e)}}const Mx="desktop-mode-os-settings",Px="desktop-mode-recycle-bin";function Wx(e){const t=Fx();t&&t.addFilter("os.dock.peek-card-content","desktop-mode/built-in-peek-renderers",(n,o)=>{const s=o,i=s.window.id;return i===Mx?$x():i===Px?Ux(s,e.getRecycleBinCount):n})}function $x(e){const t=document.createElement("span");t.className="os-dock-peek__card-body os-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="os-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="os-dock-peek__os-subtitle",o.textContent=E("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="os-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`os-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function Ux(e,t){const n=document.createElement("span");n.className="os-dock-peek__card-body os-dock-peek__card-body--recycle-bin",n.setAttribute("aria-hidden","true");const o=Math.max(0,Math.floor(t()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="os-dock-peek__bin-stage";const i=document.createElement("span");i.className="os-dock-peek__bin-stack";for(let l=0;l<3;l++){const c=document.createElement("span");c.className="os-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="os-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="os-dock-peek__bin-label",o===0?a.textContent=E("Trash — empty"):o===1?a.textContent=E("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function Fx(){return window.wp?.hooks??null}const $o="desktop-mode-bug-report",Bx="WordPress",Hx="openstation",Xm=6e3;function zx(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="os-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="os-bug-report__intro",n.textContent=E("Found a bug or have a feature idea? Fill this in and we will open a pre-filled GitHub issue for you to review and submit."),t.appendChild(n),t.appendChild(Gx()),t.appendChild(jx("title",E("Title"),{placeholder:E("A short summary"),required:!0})),t.appendChild(Zm("description",E("What happened? What did you expect?"),{placeholder:E("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(Zm("steps",E("Steps to reproduce (bug only)"),{placeholder:E("One step per line"),rows:4}));const o=Vx();t.appendChild(o);const s=document.createElement("div");s.className="os-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="os-bug-report__submit",i.textContent=E("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=E("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const l=Kx(t);if(!l.title.trim()||!l.description.trim()){qx(t,E("Title and description are both required."));return}const c=Yx(l);window.open(c,"_blank","noopener")}),e.appendChild(t)}function Gx(){const e=document.createElement("div");e.className="os-bug-report__field os-bug-report__field--type";const t=document.createElement("span");t.className="os-bug-report__label",t.textContent=E("Type"),e.appendChild(t);const n=document.createElement("div");n.className="os-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:E("Bug"),checked:!0},{value:"feature",label:E("Feature request")},{value:"question",label:E("Question")}];for(const s of o){const i=document.createElement("label");i.className="os-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const a=document.createElement("span");a.textContent=s.label,i.appendChild(a),n.appendChild(i)}return e.appendChild(n),e}function jx(e,t,n={}){const o=document.createElement("div");o.className="os-bug-report__field";const s=document.createElement("label");s.className="os-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("input");return i.type="text",i.name=e,i.className="os-bug-report__input",n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function Zm(e,t,n={}){const o=document.createElement("div");o.className="os-bug-report__field";const s=document.createElement("label");s.className="os-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("textarea");return i.name=e,i.className="os-bug-report__textarea",i.rows=n.rows??4,n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function Vx(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=E("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=Qm(Jm()),e.appendChild(n),e}function qx(e,t){let n=e.querySelector(".os-bug-report__error");n||(n=document.createElement("div"),n.className="os-bug-report__error",n.setAttribute("role","alert"),e.prepend(n)),n.textContent=t}function Kx(e){const t=new FormData(e);return{type:t.get("type")??"bug",title:t.get("title")??"",description:t.get("description")??"",steps:t.get("steps")??""}}function Yx(e){const t=Xx(e.type),n=Zx(e),o=new URLSearchParams;return o.set("title",e.title.trim()),o.set("body",n),t.length&&o.set("labels",t.join(",")),`https://github.com/${Bx}/${Hx}/issues/new?${o.toString()}`}function Xx(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function Zx(e){const t=[];t.push(e.description.trim()),e.type==="bug"&&e.steps.trim()&&(t.push(""),t.push("## Steps to reproduce"),t.push(""),t.push(e.steps.trim())),t.push(""),t.push("<details><summary>Environment</summary>"),t.push(""),t.push("```"),t.push(Qm(Jm())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(` |
| 62 |
`);return n.length>Xm&&(n=n.slice(0,Xm)+` |
| 63 |
|
| 64 |
…(truncated to fit GitHub URL length limit)`),n}function Jm(){const e=window.wp?.os?.config;return{pluginVersion:e?.pluginVersion??"unknown",wordpressVersion:e?.wordpressVersion??"unknown",userAgent:navigator.userAgent,viewport:`${window.innerWidth}x${window.innerHeight}`,platform:navigator.platform||"unknown",currentUrl:window.location.href}}function Qm(e){return[`Plugin version: ${e.pluginVersion}`,`WordPress version: ${e.wordpressVersion}`,`User agent: ${e.userAgent}`,`Viewport: ${e.viewport}`,`Platform: ${e.platform}`,`Current URL: ${e.currentUrl}`].join(` |
| 65 |
`)}let $i=null,eg=!1,tg=!1,ng=!1,jt="pending";function Jx(){if(tg)return;tg=!0;const e=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{e&&(ng||eL()||(tL(),ng=!0,setTimeout(()=>window.location.reload(),0)))})}const og="os-sw-reload-ts",Qx=3e4;function eL(){try{const e=sessionStorage.getItem(og),t=e?Number.parseInt(e,10):0;return!Number.isFinite(t)||t<=0?!1:Date.now()-t<Qx}catch{return!1}}function tL(){try{sessionStorage.setItem(og,String(Date.now()))}catch{}}async function nL(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return jt="unsupported",null;if($i||eg)return $i;if(!t.forceReplace){const o=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(s=>{const i=s.active?.scriptURL??s.installing?.scriptURL??"";return i!==""&&i!==e.swUrl});if(o)return jt="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 $i=await navigator.serviceWorker.register(e.swUrl,{scope:"/",updateViaCache:"none"}),jt="registered",Jx(),$i}catch(n){return eg=!0,jt="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",n),null}}function oL(){return jt}const sL="os-pwa-install";function sg(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function ig(){if(sg())return!0;const e=window.navigator;if(typeof e.getInstalledRelatedApps!="function")return!1;try{const t=await e.getInstalledRelatedApps();return Array.isArray(t)&&t.length>0}catch{return!1}}let Ct=null;function iL(e,t){if(typeof window>"u")return;window.removeEventListener("beforeinstallprompt",n),window.addEventListener("beforeinstallprompt",n),window.removeEventListener("appinstalled",o),window.addEventListener("appinstalled",o);function n(s){s.preventDefault(),Ct=s}function o(){Ct=null,t({message:le(E("Installed %s as an app."),e)})}}function rL(e,t){return{id:sL,title:E("Install web app"),icon:"dashicons-download",onOpen:()=>{aL(e,t)}}}async function aL(e,t){if(Ct){const n=Ct;Ct=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:E("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await ig()){t({message:le(E("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(oL()==="foreign-sw"){t({message:E("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the openstation_pwa_force_replace_sw filter to true.")});return}t({message:E("Install isn't available right now. Keep using the page; if it still doesn't appear, the app may already be installed in this browser.")})}async function lL(){if(!Ct)return"unavailable";const e=Ct;Ct=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function cL(){Promise.resolve().then(()=>GS).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function dL(e,t){e.pwa&&(Xp(e.pwa),iL(e.pwa.appName||"WordPress",t),nL(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw}))}const Mn={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function uL(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function fL(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function pL(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function hL(e){const t=e;return t.kind!==void 0&&t.kind!==null?e:typeof t.id=="number"&&typeof t.url=="string"&&typeof t.mime=="string"?{kind:"attachment",id:t.id,url:t.url,title:typeof t.title=="string"?t.title:"",alt:typeof t.alt=="string"?t.alt:"",mime:t.mime,thumbnailUrl:typeof t.thumbnailUrl=="string"?t.thumbnailUrl:void 0,sizes:t.sizes&&typeof t.sizes=="object"?t.sizes:void 0}:e}class mL{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(uL(n)){this._startDrag(n.payload);return}if(fL(n)){this._endDrag();return}if(pL(n)&&this._payload&&t.source)try{t.source.postMessage({type:"os-drag-payload",payload:this._payload},this._origin)}catch{}},this._origin=window.location.origin,window.addEventListener("message",this._onMessage)}getPayload(){return this._payload}isDragging(){return this._payload!==null}start(t){this._payload!==t&&this._startDrag(t)}end(){this._endDrag()}_startDrag(t){const n=hL(t);this._payload=n,document.dispatchEvent(new CustomEvent(Mn.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(Mn.END,{detail:{payload:t}}))}}class gL{constructor(){this._targets=new Map,this._byElement=new Map}register(t){const n=this._targets.get(t.id);return n&&this._byElement.delete(n.element),this._targets.set(t.id,t),this._byElement.set(t.element,t),()=>{this._targets.get(t.id)===t&&(this._targets.delete(t.id),this._byElement.delete(t.element))}}list(){return Array.from(this._targets.values())}clear(){this._targets.clear(),this._byElement.clear()}hitTest(t){let n=t;for(;n;){if(n instanceof HTMLElement){const o=this._byElement.get(n);if(o)return o;if(n.classList.contains("os-window"))return null}n=n.parentElement}return null}hitTestPoint(t,n){const o=document.elementFromPoint(t,n);return{target:this.hitTest(o),element:o,accepted:!1}}}const wL="os-drag-ghost",rg="os-drag-ghost--accept",ag="os-drag-ghost--reject",yL="os-drag-hint",lg="os-drag-hint--accept",cg="os-drag-hint--reject",dg="os-drag-hint--neutral",bL=16,vL=18;function _L(e,t,n){const o=IL(e),s=e.ghost?.offsetX??xL(e.source),i=e.ghost?.offsetY??LL(e.source);o.classList.add(wL),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=kL(e),a=r?EL():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+bL}px, ${d+vL}px, 0)`)},setMode(c,d){o.classList.remove(rg,ag),c==="accept"?o.classList.add(rg):c==="reject"&&o.classList.add(ag),a&&r&&(a.classList.remove(lg,cg,dg),c==="accept"?(a.classList.add(lg),a.textContent=d?.acceptLabel??r.accept):c==="reject"?(a.classList.add(cg),a.textContent=r.reject):(a.classList.add(dg),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(c){const d=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return c()}finally{o.style.visibility=d,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return l.moveTo(t,n),l.setMode("neutral"),l}function EL(){const e=document.createElement("div");return e.className=yL,e.setAttribute("aria-hidden","true"),e.setAttribute("role","presentation"),e.style.position="fixed",e.style.left="0",e.style.top="0",e.style.margin="0",e.style.pointerEvents="none",e.style.zIndex="2147483647",e.style.willChange="transform",e}function kL(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??SL(e),reject:t?.reject??AL(),neutral:t?.neutral??CL(e)}}function SL(e){return e.type==="shortcut"?E("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?E("Drop here to move","desktop-mode"):E("Drop here","desktop-mode")}function AL(e){return E("Can’t drop here","desktop-mode")}function CL(e){return e.type==="shortcut"?E("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?E("Drop in a folder","desktop-mode"):""}function IL(e){if(e.ghost?.element)return e.ghost.element;const t=e.source.cloneNode(!0);t.removeAttribute("id");const n=e.source.getBoundingClientRect();return t.style.width=`${n.width}px`,t.style.height=`${n.height}px`,t}function xL(e){return e.offsetWidth/2}function LL(e){return e.offsetHeight/2}let ug=!1;function TL(e){ug||(ug=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const fg=4,we={START:"os.drag.start",MOVE:"os.drag.move",ENTER:"os.drag.enter",LEAVE:"os.drag.leave",REJECTED:"os.drag.rejected",COMMIT:"os.drag.commit",CANCEL:"os.drag.cancel",END:"os.drag.end"},Ui="os-file-tile--dragging",pg="os-file-tile--drop-target",hg="data-os-trash-drop-active",mg="data-files-drop-active",gg="data-os-dragging",wg="data-os-drag-type",Sl="data-os-drag-mode";class NL{constructor(){this._registry=new gL,this._active=null,this._docListenersAttached=!1,this._lastLiftedEndAt=0,this._onPointerMove=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;const o=t.clientX-n._origin.clientX,s=t.clientY-n._origin.clientY;if(!n._lifted){if(Math.abs(o)<fg&&Math.abs(s)<fg)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),pt(we.MOVE,{payload:n.payload,clientX:t.clientX,clientY:t.clientY}))},this._onPointerUp=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;if(!n._lifted){n._finished=!0,this._active=null;try{n._callbacks.onClickOnly?.()}catch(s){console.error("[openstation] drag onClickOnly threw:",s)}return}const o=this._hitTestNow(n,t.clientX,t.clientY);if(o&&o.accepted&&o.target){this._commit(n,o.target,t.clientX,t.clientY);return}this._cancel(n,o&&o.target?"rejected":"no-target")},this._onPointerCancel=t=>{const n=this._active;!n||n._pointerId!==t.pointerId||this._cancel(n,"pointercancel")}}start(t){if(this._active||t.origin.button!==0)return null;const n={payload:t.payload,isFinished:()=>n._finished,cancel:o=>this._cancel(n,o??"caller"),_origin:t.origin,_pointerId:t.origin.pointerId,_lifted:!1,_finished:!1,_callbacks:{onClickOnly:t.onClickOnly,onCancel:t.onCancel,onCommit:t.onCommit},_ghost:null,_currentTarget:null,_currentAccepted:!1};return this._active=n,this._ensureDocListeners(),TL(o=>{this._active&&this._cancel(this._active,o)}),n}registerDropTarget(t){return this._registry.register(t)}isDragging(){return this._active!==null&&this._active._lifted}recentlyEndedDrag(t=500){return this._lastLiftedEndAt===0?!1:Date.now()-this._lastLiftedEndAt<t}getActive(){return this._active}debug(){return{findOrphans:()=>yg(),listTargets:()=>this._registry.list()}}_ensureDocListeners(){this._docListenersAttached||(this._docListenersAttached=!0,document.addEventListener("pointermove",this._onPointerMove,!0),document.addEventListener("pointerup",this._onPointerUp,!0),document.addEventListener("pointercancel",this._onPointerCancel,!0))}_lift(t,n){t._lifted=!0,t.payload.source.classList.add(Ui),t._ghost=_L(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(gg,""),document.body.setAttribute(wg,String(t.payload.type)),document.body.setAttribute(Sl,"neutral")),pt(we.START,{payload:t.payload})}_hitTestNow(t,n,o){const s=()=>{const i=document.elementFromPoint(n,o),r=this._registry.hitTest(i);if(!r)return{target:null,accepted:!1};let a=!1;try{a=r.accept(t.payload)}catch(l){console.error("[openstation] drop target accept() threw:",r.id,l)}return{target:r,accepted:a}};return t._ghost?t._ghost.withHidden(s):s()}_updateHover(t,n,o){const s=this._hitTestNow(t,n,o),i=t._currentTarget;if(s.target===i&&s.accepted===t._currentAccepted)return;i&&Al(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(DL(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),pt(we.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Sl,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),Al(n,t),this._cleanupDom(t);const i=this._active;this._active=null;try{n.onDrop(t,{clientX:o,clientY:s})}catch(r){console.error("[openstation] drop target onDrop threw:",n.id,r)}try{t._callbacks.onCommit?.(n)}catch(r){console.error("[openstation] drag onCommit threw:",r)}pt(we.COMMIT,{payload:t.payload,targetId:n.id}),pt(we.END,{payload:t.payload,reason:"commit"}),this._active===i&&(this._active=null)}_cancel(t,n){if(!t._finished){t._finished=!0,t._lifted&&(this._lastLiftedEndAt=Date.now()),t._currentTarget&&Al(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}pt(we.CANCEL,{payload:t.payload,reason:n}),pt(we.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(Ui)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(gg),document.body.removeAttribute(wg),document.body.removeAttribute(Sl)),RL()}}function pt(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function DL(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}pt(we.ENTER,{payload:t.payload,targetId:e.id})}function Al(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}pt(we.LEAVE,{payload:t.payload,targetId:e.id})}function yg(){if(typeof document>"u")return[];const e=[];for(const t of[`.${Ui}`,`.${pg}`,`[${hg}]`,`[${mg}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function RL(){for(const e of yg())e.classList.remove(Ui,pg),e.removeAttribute(hg),e.removeAttribute(mg)}const OL=".os-window",bg="wp-window-";function vg(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(OL);return o instanceof HTMLElement?o:null}function ML(e){if(!e.id.startsWith(bg))return null;const t=e.id.slice(bg.length);return t.length>0?t:null}const PL="desktop-mode-iframe-drop-",Fi="iframe.os-window__iframe",Cl="data-os-iframe-drop-active";let Il=!1,_g=null;const je=new Map,Vt=new Map;let ht=null,qt=null;function WL(){document.querySelectorAll(Fi).forEach(t=>{je.has(t)||(je.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function $L(){je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear()}function Eg(e,t){const n=vg(e,t);if(!n)return null;const o=n.querySelector(Fi);return o instanceof HTMLIFrameElement?o:null}const kg=e=>{if(!ht)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=Eg(e.clientX,e.clientY);t!==qt&&(qt&&Kt(qt,{type:"os-drag-leave"}),qt=t,t&&Kt(t,{type:"os-drag-over",payload:ht}))},Sg=e=>{if(!ht)return;const t=Eg(e.clientX,e.clientY);if(!t){e.preventDefault(),Bi();return}e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const n=ht;Bi();const o=t.getBoundingClientRect();Kt(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},Ag=()=>{Bi()};function UL(e){if(ht){ht=e;return}ht=e,WL(),document.addEventListener("dragover",kg,!0),document.addEventListener("drop",Sg,!0),document.addEventListener("dragend",Ag,!0)}function Bi(){ht&&(ht=null,qt&&(Kt(qt,{type:"os-drag-leave"}),qt=null),document.removeEventListener("dragover",kg,!0),document.removeEventListener("drop",Sg,!0),document.removeEventListener("dragend",Ag,!0),$L())}function Hi(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function Kt(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function FL(e,t,n,o){return e.registerDropTarget({id:`${PL}${o}`,element:n,accept:s=>!!Hi(s),onEnter:s=>{const i=Hi(s.payload);i&&(n.setAttribute(Cl,""),Kt(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(Cl),Kt(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(Cl);const r=Hi(s.payload);if(!r)return;const a=t.getBoundingClientRect();Kt(t,{type:"os-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function Cg(e){let t=e.parentElement;for(;t;){if(t.id.startsWith("wp-window-"))return t.id.slice(10);t=t.parentElement}return`unknown-${Math.random().toString(36).slice(2,10)}`}function BL(e,t,n){try{if(!window.localStorage?.getItem("openStationDragDebug"))return}catch{return}console.info("[openstation] drag-start: suppressing %d iframe(s); bridgeable=%s",e,t,n)}function HL(e){const t=_g;if(!t)return;const n=document.querySelectorAll(Fi),o=!!Hi(e);BL(n.length,o,e),n.forEach(s=>{if(je.has(s)||(je.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||Vt.has(s))return;const i=s.parentElement;if(!i)return;const r=Cg(s),a=FL(t,s,i,r);Vt.set(s,a)})}function zL(){je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear(),Vt.forEach(e=>{try{e()}catch{}}),Vt.clear()}function GL(e){Il||(Il=!0,_g=e,document.addEventListener(we.START,t=>{const n=t.detail;HL(n?.payload)}),document.addEventListener(we.END,()=>{zL()}),document.addEventListener(Mn.START,t=>{const n=t.detail;n?.payload&&UL(n.payload)}),document.addEventListener(Mn.END,()=>{Bi()}),Z(b.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(je))t.isConnected||je.delete(t);for(const[t,n]of Array.from(Vt))if(!t.isConnected){try{n()}catch{}Vt.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:Il,iframesInDom:document.querySelectorAll(Fi).length,suppressedCount:je.size,registeredCount:Vt.size,suppressedIframeIds:Array.from(je.keys()).map(Cg)}))}const jL=250,VL=1e3,qL="os-drag-hover";let Ig=!1,xl=null,Ll=null,Uo=null,Fo=null,Tl=null;function xg(){Uo!==null&&(clearTimeout(Uo),Uo=null)}function Lg(){Fo!==null&&(clearTimeout(Fo),Fo=null)}function Bo(){xg(),Lg(),Ll=null}function Tg(){Lg(),Fo=setTimeout(()=>{Fo=null,Bo()},VL)}function KL(e,t){const n=xl?.getById(e);if(!(!n||n.isFocused()||!Y(b.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{xl?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function Ng(e,t){e!==Ll&&(xg(),Ll=e,e!==null&&(Uo=setTimeout(()=>{Uo=null,KL(e,t)},jL)))}function Dg(e,t,n){const o=vg(e,t);Ng(o?ML(o):null,n)}const YL=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||Dg(t.clientX,t.clientY,t.payload?.type??"")},XL=()=>{Bo()};function ZL(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;return typeof n.includes=="function"?n.includes("Files"):typeof n.contains=="function"&&n.contains("Files")}const JL=e=>{Tg();const t=Tl??(ZL(e)?"os-file":"external");Dg(e.clientX,e.clientY,t)},Rg=()=>{Bo()},QL=e=>{e.relatedTarget===null&&Bo()};function eT(e){if(!e)return null;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e)return n.closest("[data-window-id]")?.getAttribute("data-window-id")||null;return null}const tT=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==qL)return;const n=eT(e.source);n&&(Tg(),Ng(n,typeof t.payloadType=="string"?t.payloadType:"external"))},nT=e=>{const t=e.detail;t?.payload&&(Tl=t.payload.kind??"")},oT=()=>{Tl=null,Bo()};function sT(e){Ig||(Ig=!0,xl=e,document.addEventListener(we.MOVE,YL),document.addEventListener(we.END,XL),document.addEventListener(Mn.START,nT),document.addEventListener(Mn.END,oT),document.addEventListener("dragover",JL,!0),document.addEventListener("drop",Rg,!0),document.addEventListener("dragend",Rg,!0),document.addEventListener("dragleave",QL,!0),window.addEventListener("message",tT))}function Og(){const e=window.wp?.os;if(!e)return[];const t=e.windowManager,n=e.config;if(!t||!n)return[];const o=[],s=(r,a)=>({id:r.id,label:r.title,description:a,icon:r.icon,open:()=>t.open({id:r.id,baseId:r.id,url:r.url,title:r.title,icon:r.icon})});for(const r of n.dockItems??[])o.push(s(r,"Admin menu"));const i=Y("os.open-command.items",o);return Array.isArray(i)?i:o}const iT={slug:"open",label:"Open",description:"Open an admin page or registered window.",hint:"[window]",icon:"dashicons-external",suggest(e){const t=e.trim().toLowerCase(),n=Og();return(t===""?n:n.filter(s=>s.label.toLowerCase().includes(t)||s.id.toLowerCase().includes(t))).slice(0,12).map(s=>({value:s.label,label:s.label,description:s.description,icon:s.icon??"dashicons-external"}))},run(e,t){const n=e.trim();if(!n)return"Type the name of a window to open, for example `/open Posts`.";const o=Og(),s=n.toLowerCase(),i=o.find(r=>r.label.toLowerCase()===s||r.id.toLowerCase()===s)??o.find(r=>r.label.toLowerCase().includes(s)||r.id.toLowerCase().includes(s));if(!i)return`No window matching **${n}** — try \`/open\` alone to see available options.`;i.open(),t.close()}};function rT(){_i(iT)}const Ae=[],aT=new Set;function Mg(e){if(!e||typeof e.id!="string"||e.id==="")return()=>{};if(typeof e.open!="function"||typeof e.close!="function"||typeof e.isOpen!="function")return()=>{};const t=Ae.findIndex(n=>n.id===e.id);return t>=0?Ae[t]=e:Ae.push(e),Nl(),()=>{const n=Ae.findIndex(o=>o.id===e.id);n>=0&&(Ae.splice(n,1),Nl())}}function lT(e){const t=Ae.findIndex(n=>n.id===e);t>=0&&(Ae.splice(t,1),Nl())}function cT(){return Ae.slice()}function Nl(){for(const e of Array.from(aT))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",t)}}function Ho(e,t){try{document.dispatchEvent(new CustomEvent(t?"os-palette-opened":"os-palette-closed",{detail:{id:e}}))}catch{}}function Pg(){if(Ae.length===0)return;const e=Ae.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{Ae[0].open(),Ho(Ae[0].id,!0)}catch{}return}try{Ae[e].close(),Ho(Ae[e].id,!1)}catch{}const t=e+1;if(t<Ae.length)try{Ae[t].open(),Ho(Ae[t].id,!0)}catch{}}function Dl(e){const t=Ae.find(n=>n.id===e);if(t){for(const n of Ae)if(n.id!==e)try{n.isOpen()&&(n.close(),Ho(n.id,!1))}catch{}try{t.open(),Ho(t.id,!0)}catch{}}}let Wg=!1;function dT(){if(Wg)return;Wg=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),Pg())},!0);const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;n&&n.type==="os-palette-cycle"&&Pg()})}const Ze=re("os/presence",()=>({byUser:new Map,serverTimeMs:0})),uT=5*60*1e3;let $g=Date.now(),Ug=!1;function zi(){$g=Date.now()}function fT(e){if(!e||!e.snapshot)return;const t=Ze.state.byUser,n=new Map(t),o=[];for(const[s,i]of Object.entries(e.snapshot)){const r=Number(s);if(!Number.isFinite(r)||r<=0)continue;const l={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=t.get(r);n.set(r,l),(!c||c.status!==l.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:l.status,entry:l})}Ze.state.byUser=n,typeof e.serverTimeMs=="number"&&(Ze.state.serverTimeMs=e.serverTimeMs),Ze.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),ke.publish("os/presence-changed",i)}ke.publish("os/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function pT(){Ug||(Ug=!0,document.addEventListener("pointerdown",zi,{capture:!0,passive:!0}),document.addEventListener("keydown",zi,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||zi()}),Te.contribute("openstation_presence_active",()=>!0),Te.contribute("openstation_user_active",()=>Date.now()-$g<uT),Te.subscribe("openstation_presence",e=>{fT(e)}))}function hT(e){const t=Ze.state.byUser.get(e);return t?t.status:"offline"}function mT(){return new Map(Ze.state.byUser)}function gT(e){return Ze.state.byUser.get(e)??null}function wT(e){return Ze.subscribe(t=>e(t))}function yT(){zi()}function bT(e){if(!Array.isArray(e)||e.length===0)return;const t=Ze.state.byUser,n=new Map(t),o=[];for(const s of e){const i=Number(s.userId);if(!Number.isFinite(i)||i<=0)continue;const r=t.get(i),a={status:s.status,lastSeenMs:typeof s.lastSeenMs=="number"?s.lastSeenMs:r?.lastSeenMs??0,lastActiveMs:typeof s.lastActiveMs=="number"?s.lastActiveMs:r?.lastActiveMs??0};n.set(i,a),(!r||r.status!==a.status)&&o.push({userId:i,oldStatus:r?r.status:null,newStatus:a.status,entry:a})}if(!(o.length===0&&n.size===t.size)){Ze.state.byUser=n,Ze.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),ke.publish("os/presence-changed",i)}ke.publish("os/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const vT=Object.freeze({getStatus:hT,getAll:mT,getEntry:gT,subscribe:wT,markActive:yT,applyBatch:bT});function Fg(e){const t=new Set;let n=null;const o=new Set;e.onChange&&o.add(e.onChange);const s=()=>e.order().filter(a=>t.has(a)),i=()=>{const a=s();for(const l of o)try{l(a)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=a=>{const l=t.size,c=Array.from(t);a(),!(t.size===l&&c.every(d=>t.has(d)))&&i()};return{keys:s,has:a=>t.has(a),size:()=>t.size,anchor:()=>n,set(a){r(()=>{t.clear();for(const l of a)t.add(l)}),n=a.length>0?a[a.length-1]:null},add(a){r(()=>{t.add(a)}),n=a},remove(a){r(()=>{t.delete(a)}),n===a&&(n=null)},toggle(a){r(()=>{t.has(a)?t.delete(a):t.add(a)}),n=a},selectRange(a,l=!1){const c=e.order(),d=c.indexOf(a),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{l||t.clear(),t.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{l||t.clear();for(let w=f;w<=p;w+=1)t.add(c[w])})},selectAll(){const a=e.order();r(()=>{for(const l of a)t.add(l)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const a=new Set(e.order());let l=!1;return r(()=>{for(const c of Array.from(t))a.has(c)||(t.delete(c),l=!0)}),n!==null&&!a.has(n)&&(n=null),l},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const _T=".os-file-tile",ET="os-file-tile--selected",kT="os-selection-marquee",Bg=4,Hg=36,zg=12,Gg="data-os-marquee";function ST(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function AT(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(Gg,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(Gg)}}const CT=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note",IT="os-area--overview";function xT(e,t){const n=t.itemSelector??_T,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??CT,r=()=>Array.from(e.querySelectorAll(n)).filter(x=>t.keyOf(x)!==null),a=()=>{const x=[],B=new Map;r().forEach((j,R)=>{const H=j.parentElement??e;let T=B.get(H);T||(T=[],B.set(H,T),x.push(H)),T.push({key:t.keyOf(j),top:parseFloat(j.style.top)||0,left:parseFloat(j.style.left)||0,index:R})});const M=[];for(const j of x){const R=B.get(j)??[];R.sort((H,T)=>H.top!==T.top?H.top-T.top:H.left!==T.left?H.left-T.left:H.index-T.index);for(const H of R)M.push(H.key)}return M},l=t.order??a,c=Fg({order:l,onChange:x=>{p(),t.onChange?.(x),u(x)}}),d={},u=x=>{typeof document>"u"||(Pn={surface:t.surface??"",scope:t.scope??"",keys:x.slice(),count:x.length},Ol=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:Pn})))},f=x=>r().find(B=>t.keyOf(B)===x)??null,p=()=>{for(const x of r()){const B=t.keyOf(x),M=c.has(B);M!==x.hasAttribute("selected")&&(M?x.setAttribute("selected",""):x.removeAttribute("selected")),x.classList.toggle(ET,M),x.hasAttribute("selectable")||x.setAttribute("selectable","");const j=M?"true":"false";x.getAttribute("aria-selected")!==j&&x.setAttribute("aria-selected",j)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let w=null;const m=x=>{if(!(x.target instanceof Element))return;const B=x.target.closest(n);if(B&&e.contains(B)){const M=t.keyOf(B);if(M===null)return;if(w=M,x.stopPropagation(),x.shiftKey){c.selectRange(M,x.ctrlKey||x.metaKey);return}if(x.ctrlKey||x.metaKey){c.toggle(M);return}c.set([M]);return}if(D){D=!1;return}c.clear()};o.addEventListener("click",m);let h=null,y=null,v=null,A=[],D=!1,_=0,O=null,P=null;const $=x=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(x),P=x}catch{}},F=()=>{if(P===null||typeof o.releasePointerCapture!="function"){P=null;return}try{o.hasPointerCapture?.(P)&&o.releasePointerCapture(P)}catch{}P=null},k=(x,B)=>{const M=o.getBoundingClientRect();return{x:x-M.left+o.scrollLeft,y:B-M.top+o.scrollTop}},W=()=>{h?.remove(),h=null,y=null,v=null,O?.(),O=null,F(),_&&(cancelAnimationFrame(_),_=0),document.removeEventListener("pointermove",C),document.removeEventListener("pointerup",U),document.removeEventListener("pointercancel",V),o.removeEventListener("lostpointercapture",V),o.removeEventListener("scroll",N),window.removeEventListener("blur",V)};function N(){if(!y||!v)return;const x=k(v.x,v.y),B=x.x-y.x,M=x.y-y.y;if(!h&&Math.abs(B)<Bg&&Math.abs(M)<Bg)return;h||(h=document.createElement("div"),h.className=kT,h.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(h),D=!0,O=AT(o),g());const j=Math.min(y.x,x.x),R=Math.min(y.y,x.y),H=Math.abs(B),T=Math.abs(M);h.style.left=`${j}px`,h.style.top=`${R}px`,h.style.width=`${H}px`,h.style.height=`${T}px`;const K=o.getBoundingClientRect(),q=K.left-o.scrollLeft,ce=K.top-o.scrollTop,ve={left:j+q,top:R+ce,right:j+H+q,bottom:R+T+ce},ye=[];for(const he of r()){const Ee=he.getBoundingClientRect();Ee.left<ve.right&&Ee.right>ve.left&&Ee.top<ve.bottom&&Ee.bottom>ve.top&&ye.push(t.keyOf(he))}c.set(Array.from(new Set([...A,...ye])))}function g(){if(_||typeof requestAnimationFrame!="function")return;const x=()=>{if(_=0,!h||!v)return;const B=o.getBoundingClientRect();if(ST(o)){let j=0;if(v.y<B.top+Hg?j=-zg:v.y>B.bottom-Hg&&(j=zg),j!==0){const R=o.scrollTop;o.scrollTop+=j,o.scrollTop!==R&&N()}}_=requestAnimationFrame(x)};_=requestAnimationFrame(x)}const C=x=>{y&&(v={x:x.clientX,y:x.clientY},N())},U=()=>{h&&(Rl=Date.now()),W()},V=()=>{W()},z=x=>{if(!s||x.button!==0||!(x.target instanceof Element)||o.classList.contains(IT)||x.target.closest(n))return;const B=x.target.closest(i);B&&B!==o&&o.contains(B)||(y=k(x.clientX,x.clientY),v={x:x.clientX,y:x.clientY},typeof x.pointerId=="number"&&$(x.pointerId),A=x.ctrlKey||x.metaKey||x.shiftKey?c.keys():[],A.length===0&&c.clear(),document.addEventListener("pointermove",C),document.addEventListener("pointerup",U),document.addEventListener("pointercancel",V),o.addEventListener("lostpointercapture",V),window.addEventListener("blur",V),o.addEventListener("scroll",N,{passive:!0}))};o.addEventListener("pointerdown",z);const I=x=>{if(x.key==="a"&&(x.ctrlKey||x.metaKey)){x.preventDefault(),c.selectAll();return}if(x.key==="Escape"){if(h||y){W();return}c.size()>0&&c.clear();return}const B=x.key==="ArrowRight"||x.key==="ArrowDown",M=x.key==="ArrowLeft"||x.key==="ArrowUp";if(!B&&!M)return;const j=B?1:-1,R=l();if(R.length===0)return;const H=w??c.anchor(),T=H===null?-1:R.indexOf(H),K=Math.min(R.length-1,Math.max(0,T<0?0:T+j));x.preventDefault();const q=R[K];w=q,x.shiftKey?c.selectRange(q):c.set([q]),f(q)?.focus()};return e.addEventListener("keydown",I),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){W(),o.removeEventListener("click",m),o.removeEventListener("pointerdown",z),e.removeEventListener("keydown",I),Ol===d&&(Pn=null,Ol=null)}}}let Rl=0;function LT(){return Rl>0&&Date.now()-Rl<500}let Pn=null,Ol=null;function TT(){return Pn?{...Pn,keys:Pn.keys.slice()}:null}function Ml(e){return typeof e.sort=="number"?e.sort:100}function NT(e,t){return le(E("%1$s (%2$d items)","desktop-mode"),e,t)}function jg(e,t){if(e.length===0)return[];const n=e.map(a=>{const l=t(a);return Array.isArray(l)?l:[]});if(e.length===1)return n[0];const o=e.length,s=[],i=a=>a.multiId??a.id;for(const a of n[0]){const l=i(a),c=[];let d=!1;for(const p of n){const w=p.find(m=>i(m)===l);if(!w||w.multi!==!0){d=!0;break}c.push(w)}if(d||s.some(p=>p.id===l))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):NT(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(Ml)),multi:!0,onClick:async p=>{const w=new Map,m=[];c.forEach((h,y)=>{const v=h.bulk;if(typeof v!="function"){m.push(h);return}const A=w.get(v);A?A.push(e[y]):w.set(v,[e[y]])});for(const[h,y]of w)try{await h(y)}catch(v){console.error(`[openstation] selection action '${l}' failed for a batch:`,v)}for(const h of m)try{await h.onClick(p)}catch(y){console.error(`[openstation] selection action '${l}' failed for one item:`,y)}}})}s.sort((a,l)=>{const c=Ml(a),d=Ml(l);return c!==d?c-d:a.label.localeCompare(l.label)});const r=Y("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function Vg(e,t){const n=s=>{if(!(s.target instanceof Node&&e.contains(s.target))){if(s.target instanceof Node)for(const i of t.siblingSelectors??[]){const r=Array.from(document.querySelectorAll(i));for(const a of r)if(a.contains(s.target))return}t.excludeOutsideTarget&&s.target instanceof Node&&t.excludeOutsideTarget.contains(s.target)||t.close()}},o=s=>{s.key==="Escape"&&t.close()};return document.addEventListener("mousedown",n,{capture:!0}),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",n,{capture:!0}),document.removeEventListener("keydown",o)}}const Pl=8;function qg(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function Wl(e){qg(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-Pl)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-Pl)}px`)})}function Kg(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,qg(e,o=>{o.right>window.innerWidth&&(e.style.left=`${Math.max(0,n.left-o.width)}px`),o.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-o.height-Pl)}px`)})}const DT="os-wallpaper-menu";let Wn=null,$l=null,Yg=0;function Ul(){if(!Wn)return;const e=Wn.dataset.menuScope??"selection",t=$l;Wn.dispatchEvent(new CustomEvent("tile-menu-closed")),Wn.remove(),Wn=null,$l=null,t?.(),L(`os.${e}.menu.closed`,{})}function RT(e,t){Ul();const n=++Yg;Us(()=>n===Yg,()=>OT(e,t))}function OT(e,{actions:t,dataset:n,className:o,scope:s="selection",onOpened:i,onClosed:r}){if(t.length===0)return;const a=document.createElement("os-context-menu");a.setAttribute("open",""),a.classList.add(DT),o&&a.classList.add(o),a.dataset.menuScope=s;for(const[u,f]of Object.entries(n??{}))a.dataset[u]=f;a.style.left=`${e.x}px`,a.style.top=`${e.y}px`;const l=new Map;for(const u of t){l.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.danger&&f.setAttribute("danger",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",MT(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&&(Ul(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(w=>{console.error(`[openstation] menu action '${p.id}' threw:`,w)}))}),document.body.appendChild(a),Wn=a,$l=r??null,Wl(a);const c=Vg(a,{close:()=>Ul()});a.addEventListener("tile-menu-closed",c);const d=t.map(u=>u.id);i?.(d),L(`os.${s}.menu.opened`,{items:d,count:t.length})}function MT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const PT={active:TT,resolveCommonActions:jg,createModel:Fg};let zo=null;function WT(){Te.contribute("openstation_content_changes_seen_ts",()=>zo===null?0:zo),Te.subscribe("openstation_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=zo===null,n=zo??0;let o=Math.max(n,e.ts);if(!t&&Array.isArray(e.entries))for(const s of e.entries)!s||typeof s.ts!="number"||s.ts<=n||typeof s.type!="string"||s.type===""||(Ai(`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));zo=o})}const $T="desktop_mode_nonces",Fl=new Map;let Xg=!1;function Bl(e,t){if(typeof e!="string"||e==="")return()=>{};let n=Fl.get(e);return n||(n=new Set,Fl.set(e,n)),n.add(t),()=>{n.delete(t)}}function UT(){Xg||(Xg=!0,Te.subscribe($T,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=Fl.get(t);if(o)for(const s of o)try{s(n)}catch(i){console.error(`[desktop-mode/nonce-refresh] updater for "${t}" threw:`,i)}}}),FT())}function FT(){Bl("wp_rest",BT),Bl("desktop-mode-plugins",e=>{Zg("desktop-mode-plugins","ajaxNonce",e)}),Bl("updates",e=>{Zg("desktop-mode-plugins","updatesNonce",e)})}function BT(e){const t=HT();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=Jg();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Zg(e,t,n){const s=Jg()?.[e];s&&typeof s=="object"&&(s[t]=n)}function HT(){if(!(typeof window>"u"))return window.openStationConfig}function Jg(){if(!(typeof window>"u"))return window.openStationWindowConfig}const zT="desktop_mode_auth",GT=5e3,Qg=1e3,jT=1e4;let ew=!1,Gi=!1,Hl=!1,ji=0,tw=0,Go=0,$n=null,nw=0,ow=null,sw=null,iw=()=>{try{window.location.reload()}catch{}};function zl(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function Gl(e=Qg){const t=Date.now();if(t<Go){$n===null&&($n=window.setTimeout(()=>{$n=null,Go=Date.now()+Qg,zl()},Go-t));return}Go=t+e,zl()}function VT(){Gi=!0,!Hl&&(Hl=!0,L(b.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function qT(){for(const e of KT())try{e.contentWindow?.location.reload()}catch{}}function KT(){let e;try{e=document.querySelectorAll("iframe")}catch{return[]}return Array.from(e).filter(t=>t.id!=="wp-auth-check-frame"&&!t.closest("#wp-auth-check-wrap"))}function jl(){const e=Date.now();e-nw<jT||(nw=e,Gi=!1,Hl=!1,$n!==null&&(window.clearTimeout($n),$n=null),Go=0,Gl(),qT(),L(b.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function YT(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(ji<=0){ji=t;return}t!==ji&&iw()}}function XT(e,t){if(e!==401&&e!==403)return;let n;try{n=new URL(String(t||""),window.location.href)}catch{return}if(n.origin!==window.location.origin||n.pathname.indexOf("/wp-admin/admin-ajax.php")!==-1&&/(?:^|&|\?)action=heartbeat(?:&|$)/.test(n.search)||n.pathname.indexOf("/wp-login.php")!==-1)return;const o=Date.now();o<tw||(tw=o+GT,zl())}function ZT(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");sw=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&Gl(),t=n}),sw.observe(e,{attributes:!0,attributeFilter:["class"]})}function JT(e={}){ew||(ew=!0,ji=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(iw=e.reloadShell),Te.subscribe("wp-auth-check",t=>{if(t===!1){VT();return}t===!0&&Gi&&jl()}),Te.subscribe("nonces_expired",()=>{if(Gi){jl();return}Gl()}),Te.subscribe(zT,YT),ow=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&jl()},window.addEventListener("message",ow),ZT())}const Un=12;function Vl(e,t){return rw(ae(e,t.adminUrl),t)}function rw(e,t){if(e)return(t.dockItems||[]).find(n=>ae(n.url,t.adminUrl)===e||(n.submenu||[]).some(o=>ae(o.url,t.adminUrl)===e))}function ql(e,t){const n=Math.max(200,t.width-Un*2),o=Math.max(200,t.height-Un*2),s=Math.min(e.width,n),i=Math.min(e.height,o),r=Math.max(0,t.width-s-Un),a=Math.max(0,t.height-i-Un),l=Math.max(Un,Math.min(e.x,r)),c=Math.max(Un,Math.min(e.y,a));return{x:l,y:c,width:s,height:i}}const aw=window.location.origin;function QT(e,t){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let l;try{l=new URL(a,window.location.href)}catch(m){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",a,m);return}if(l.origin!==aw)return;let c;try{c=new URL(t.adminUrl).pathname}catch(m){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,m),c="/wp-admin/"}if(!l.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(l.pathname)||l.searchParams.has("action")&&l.searchParams.get("action")==="logout"||l.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Ge(l.href)))return;const d=ae(l.href,t.adminUrl),u=Vl(l.href,t),f=(i.textContent||"").trim()||u?.title||"",p=!!i.closest("#wp-admin-bar-new-content"),w={id:d,baseId:d,multi:!!u?.multi||p,url:l.href,parentUrl:u?.url??l.href,title:u?.title||f,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu,selfLabel:u?.selfLabel};if(p){e.openNew(w);return}e.open(w)},!0)}function e1(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.total!="number"||!Number.isFinite(t.total)?null:{total:Math.max(0,Math.floor(t.total)),formatted:typeof t.formatted=="string"&&t.formatted!==""?t.formatted:String(t.total),text:typeof t.text=="string"?t.text:"",url:typeof t.url=="string"?t.url:""}}function t1(e){if(!e.url)return null;const t=document.createElement("li");t.id="wp-admin-bar-updates";const n=document.createElement("a");n.className="ab-item",n.href=e.url;const o=document.createElement("span");o.className="ab-icon",o.setAttribute("aria-hidden","true");const s=document.createElement("span");s.className="ab-label",s.setAttribute("aria-hidden","true");const i=document.createElement("span");return i.className="screen-reader-text updates-available-text",n.append(o,s,i),t.appendChild(n),t}function n1(e){const t=e1(e);if(!t)return;let n=document.getElementById("wp-admin-bar-updates");if(t.total<=0){n&&(n.style.display="none");return}if(!n){const i=document.getElementById("wp-admin-bar-root-default");if(!i||(n=t1(t),!n))return;const r=document.getElementById("wp-admin-bar-comments");r&&r.parentNode===i?i.insertBefore(n,r):i.appendChild(n)}n.style.display="";const o=n.querySelector(".ab-label");o&&(o.textContent=t.formatted);const s=n.querySelector(".updates-available-text");s&&(s.textContent=t.text)}const o1="os-registry-changed";function s1(e,t){const n=new Set;if(Array.isArray(e))for(const r of e)r&&typeof r.id=="string"&&n.add(r.id);const o=new Set;for(const r of t)r&&typeof r.id=="string"&&o.add(r.id);const s=[];for(const r of o)n.has(r)||s.push(r);const i=[];for(const r of n)o.has(r)||i.push(r);return{added:s,removed:i}}function Kl(e,t,n){const{added:o,removed:s}=s1(t,n);if(o.length===0&&s.length===0||typeof document>"u")return;const i={registry:e,added:o,removed:s};document.dispatchEvent(new CustomEvent(o1,{detail:i}))}function i1(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:l,syncServerWindowActions:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:w,renderIcons:m,applyDesktopIcons:h,refreshRootPlacements:y,syncShortcuts:v}=e,A=D=>(D??[]).map(_=>String(_?.id??"")).sort().join(` |
| 66 |
`);return function(_){const O=_.dockItems,P=_.nativeWindows,$=_.serverWidgets,F=_.serverWallpapers,k=_.serverCommandScripts,W=_.serverCommands,N=_.serverSettingsTabScripts,g=_.serverSettingsTabs,C=_.serverDockRailRendererScripts,U=_.serverTitleBarButtonScripts,V=_.serverWindowActionScripts,z=_.serverUnfocusEffectScripts,I=_.serverWindowLinkRendererScripts,x=_.serverWindowNotices,B=_.serverGames,M=_.serverDesktopThemes,j=_.desktopIcons;if(!Array.isArray(O)||O.length===0)return;const R=n.dockItems;if(t(O),n.dockItems=O,Kl("dock-items",R,O),v?.(),Array.isArray(P)){const H=n.nativeWindows;o(P),n.nativeWindows=P,Kl("native-windows",H,P)}if(Array.isArray($)&&(s($),n.serverWidgets=$),Array.isArray(F)&&(i(F),n.serverWallpapers=F),Array.isArray(B)&&(p(B),n.serverGames=B),Array.isArray(M)&&(w?.(M),n.serverDesktopThemes=M),Array.isArray(k)&&(r(k,Array.isArray(W)?W:void 0),n.serverCommandScripts=k,Array.isArray(W)&&(n.serverCommands=W)),Array.isArray(N)&&(a(N,Array.isArray(g)?g:void 0),n.serverSettingsTabScripts=N,Array.isArray(g)&&(n.serverSettingsTabs=g)),Array.isArray(U)&&(l(U),n.serverTitleBarButtonScripts=U),Array.isArray(V)&&(c(V),n.serverWindowActionScripts=V),Array.isArray(z)&&(d(z),n.serverUnfocusEffectScripts=z),Array.isArray(I)&&(u(I),n.serverWindowLinkRendererScripts=I),Array.isArray(C)&&(f(C),n.serverDockRailRendererScripts=C),Array.isArray(x)&&(um(x),n.serverWindowNotices=x),Array.isArray(j)){const H=n.desktopIcons;m(j),h?.(j),v?.(),A(H)!==A(j)&&y?.(),n.desktopIcons=j,Kl("desktop-icons",H,j)}n1(_.updateCounts)}}const r1=8e3,a1=600;function l1(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:w,syncServerDesktopThemes:m,renderIcons:h,refreshRootPlacements:y,syncShortcuts:v}=e,A=i1({applyDockItems:N=>t?.applyDockItems(N),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:w,syncServerDesktopThemes:m,renderIcons:h,applyDesktopIcons:N=>t?.applyDesktopIcons(N),refreshRootPlacements:y,syncShortcuts:v});let D=typeof o.menuSig=="string"?o.menuSig:"",_=!1,O=null,P=!1,$=!1;const F=()=>{if(!o.adminUrl)return Promise.resolve();const N=(()=>{try{const g=new URL("admin.php",o.adminUrl);return g.searchParams.set("openstation_chromeless","1"),g.searchParams.set("openstation_menu_refresh","1"),g.toString()}catch{return null}})();return N?new Promise(g=>{const C=document.createElement("iframe");C.setAttribute("aria-hidden","true"),C.tabIndex=-1,C.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",C.src=N;let U=!1;const V=()=>{U||(U=!0,window.clearTimeout(I),window.removeEventListener("message",z),C.parentNode&&C.parentNode.removeChild(C),g())},z=x=>{if(x.source!==C.contentWindow)return;const B=x.data;!B||B.type!=="os-plugins-changed"||V()},I=window.setTimeout(()=>{L(b.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),V()},r1);window.addEventListener("message",z),document.body.appendChild(C)}):Promise.resolve()},k=()=>{if(P){$=!0;return}P=!0,F().finally(()=>{P=!1,$&&($=!1,k())})},W=()=>{O!==null&&window.clearTimeout(O),O=window.setTimeout(()=>{O=null,k()},a1)};return window.addEventListener("message",N=>{if(N.origin!==aw)return;const g=N.data;if(g){if(g.type==="os-plugins-changed"){g.payload&&(A(g.payload),typeof g.payload.menuSig=="string"&&(D=g.payload.menuSig));return}if(g.type==="os-updates-changed"){W();return}if(g.type==="os-menu-signature"){const C=g.sig;typeof C=="string"&&C!==""&&C!==D&&!_&&(_=!0,F().finally(()=>{_=!1}))}}}),F}function c1(e){if(!e)return!1;if(Array.isArray(e.windows)&&e.windows.length>0)return!0;if(typeof e.updated!="number"||e.updated<=0||!Array.isArray(e.desktops)||e.desktops.length===0)return!1;if(e.desktops.length>1)return!0;const t=e.desktops[0];return t?.id&&t.id!=="desktop-1"?!0:!!e.activeDesktop&&e.activeDesktop!=="desktop-1"}function d1(e,t,n=5e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=l=>{window.clearTimeout(a),document.removeEventListener("os-window-opened",r),s(l)},r=l=>{l.detail?.windowId===t&&i(e.getById(t)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function u1(e,t,n,o){const s=n.getBoundingClientRect();Array.isArray(t.session.desktops)&&t.session.desktops.length>0&&e.seedDesktops(t.session.desktops,t.session.activeDesktop||t.session.desktops[0].id);const i={};for(const r of t.session.windows){if(!r.native)continue;const a=ql(r,s);i[r.id]={desktopId:r.desktopId,initialState:r.state,x:a.x,y:a.y,width:a.width,height:a.height,...r.params?{params:r.params}:{}}}Object.keys(i).length>0&&e.seedWindowRestoreState(i);for(const r of t.session.windows){if(r.native){if(!o?.(r.id))continue;await d1(e,r.id);continue}const a=ql(r,s),l=Vl(r.url,t)??rw(r.baseId||r.id,t),c=await e.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!l?.multi,url:r.url,parentUrl:l?.url??r.url,title:r.title,icon:r.icon||"dashicons-admin-generic",x:a.x,y:a.y,width:a.width,height:a.height,initialState:r.state,submenu:l?.submenu,selfLabel:l?.selfLabel});if(Array.isArray(r.externalTabs))for(const d of r.externalTabs)d&&typeof d.url=="string"&&d.url!==""&&c.addExternalTab(d.url,typeof d.label=="string"&&d.label!==""?d.label:d.url)}if(t.session.focused){const r=e.getById(t.session.focused);r&&e.focus(r)}}async function f1(e,t){if(Ge(t.currentPage))return;const n=ae(t.currentPage,t.adminUrl),o=Vl(t.currentPage,t);await e.open({id:n,baseId:n,multi:!!o?.multi,url:t.currentPage,parentUrl:o?.url??t.currentPage,title:t.currentTitle,icon:t.currentIcon,submenu:o?.submenu,selfLabel:o?.selfLabel})}function p1(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function Yl(e,t,n,o){const s=xu(t,n),i=window.fetch(t,s);if(i.then(a=>{if(a.status===401||a.status===403){let l;typeof t=="string"?l=t:t instanceof URL?l=t.href:l=t.url,XT(a.status,l)}},()=>{}),o?.silent)return i;let r=o?.window;return!r&&o?.windowId&&(r=e.getById(o.windowId)??null),r||(r=e.getFocused()),r&&typeof r.trackActivity=="function"&&r.trackActivity(i.then(a=>{if(!a.ok)throw new Error(h1(a));return a})).catch(()=>{}),i}function h1(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return le(E("Request failed (HTTP %s)."),t)}const m1=500,g1=1500;function w1(e,t){let n=null,o=!1,s=!1,i=0;const r=async()=>{if(o){s=!0;return}o=!0,i=Date.now();const c=e.snapshot();try{await Yl(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:c}),keepalive:!0},{silent:!0})}catch(d){L(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=e.snapshot(),d=new Blob([JSON.stringify({session:c})],{type:"application/json"}),u=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);navigator.sendBeacon&&navigator.sendBeacon(u,d)||r()},l=()=>{n!==null&&clearTimeout(n);let c=m1;if(i!==0){const d=Date.now()-i;c=Math.max(c,g1-d)}n=window.setTimeout(()=>{n=null,r()},c)};return window.addEventListener("pagehide",a),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&a()}),l}const y1=120;function b1(e){document.addEventListener("os-window-opened",e),document.addEventListener("os-window-closed",e),document.addEventListener("os-window-focused",e),document.addEventListener("os-window-changed",e),Z(b.DESKTOP_CREATED,"desktop-mode/session-save",e),Z(b.DESKTOP_CLOSED,"desktop-mode/session-save",e),Z(b.DESKTOP_SWITCHED,"desktop-mode/session-save",e),Z(b.DESKTOP_RENAMED,"desktop-mode/session-save",e)}function v1(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.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",()=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(n,y1)}),document.addEventListener("visibilitychange",()=>{L(b.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function _1(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return Y(b.DOCK_TILE_CLASS,e,o)}function E1(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return Y(b.DOCK_TILE_ELEMENT,e,o)}function k1(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return Y(b.DOCK_TILE_TOOLTIP,e,o)}function S1(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};L(b.DOCK_TILE_RENDERED,{...o,el:e})}const A1=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),Xl=new Set;function C1(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(A1))return!0;for(const n of Xl)if(t.closest(n))return!0;return!1}function I1(e){return typeof e!="string"||e.trim()===""?()=>{}:(Xl.add(e),()=>{Xl.delete(e)})}const mt=new Map,x1=window.location.origin;function lw(e){let t=mt.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},mt.set(e,t)),L1(e,t),t}function L1(e,t){const n=Zl(e);if(!n||t.loadHandlerTarget===n&&t.loadHandler||(t.loadHandlerTarget&&t.loadHandler&&typeof t.loadHandlerTarget.removeEventListener=="function"&&t.loadHandlerTarget.removeEventListener("load",t.loadHandler),typeof n.addEventListener!="function"))return;const o=()=>{queueMicrotask(()=>Fn(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function T1(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function Zl(e){const t=window.wp?.os?.windowManager;if(t&&typeof t.getById=="function"){const o=t.getById(e);if(o?.iframe)return o.iframe;if(o?.element){const s=o.element.querySelector("iframe");if(s)return s}}return document.getElementById(`wp-window-${e}`)?.querySelector("iframe")??null}function N1(e){const t={};for(const[n,o]of e.headers){const s=[];for(const i of o){let r;try{r=typeof i.value=="function"?i.value():i.value}catch{continue}typeof r=="string"&&r!==""&&s.push(r)}s.length>0&&(t[n]=s.join(", "))}return t}function Fn(e){const t=Zl(e);if(!t||!t.contentWindow)return;const n=mt.get(e),o=n?N1(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},x1)}catch{}}Z(b.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&mt.has(t.windowId)&&Fn(t.windowId)}),Z(b.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=mt.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const It=new Map,D1=1e3;function cw(e,t,n){const o=It.get(e);if(!o||o.inflight)return;o.inflight=!0;const s=new URL(t+"desktop-mode/v1/debug",window.location.origin);s.searchParams.set("sessionId",e),s.searchParams.set("since",String(o.cursor));for(const r of o.channels.keys())s.searchParams.append("channels[]",r);const i=s.toString();fetch(i,{credentials:"same-origin",headers:{"X-WP-Nonce":n}}).then(r=>r.ok?r.json():{events:[],cursor:o.cursor}).then(r=>{if(o.inflight=!1,!!It.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const l=o.channels.get(a.channel);if(l)for(const c of l)try{c(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=It.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>cw(e,t,n),D1))})}function R1(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function O1(e,t){const n=It.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let M1=0;const dw={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=lw(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),Fn(e),()=>{const r=mt.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const l=a.indexOf(s);l>=0&&a.splice(l,1),a.length===0&&r.headers.delete(t),Fn(e),uw(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=lw(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,Fn(e)),()=>{const i=mt.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),Fn(e)),uw(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=Zl(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=dw.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",l=new URL(a,window.location.origin);l.searchParams.set(i,t),o.src=l.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const e=window.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(e,t,n){O1(e,{id:++M1,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=It.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},It.set(e,o));let i=o.channels.get(t);if(i||(i=new Set,o.channels.set(t,i)),i.add(n),s){const r=R1();r&&cw(e,r.restUrl,r.restNonce)}return()=>{const r=It.get(e);if(!r)return;const a=r.channels.get(t);a&&(a.delete(n),a.size===0&&r.channels.delete(t)),r.channels.size===0&&(r.timer&&clearTimeout(r.timer),It.delete(e))}}}};function uw(e){const t=mt.get(e);t&&t.headers.size===0&&t.observers.size===0&&(T1(t),mt.delete(e))}async function Bn(e){return await Nr(Dr()),new Promise(t=>{const n=document.createElement("os-confirm-dialog");n.setAttribute("open",""),e.title&&n.setAttribute("title",e.title),n.setAttribute("message",e.message),e.confirmLabel&&n.setAttribute("confirm-label",e.confirmLabel),e.cancelLabel&&n.setAttribute("cancel-label",e.cancelLabel),e.danger&&n.setAttribute("danger",""),e.hideCancel&&n.setAttribute("hide-cancel",""),e.dismissable&&n.setAttribute("dismissable","");const o=s=>{n.remove(),t(s)};n.addEventListener("os-confirm",()=>o(!0)),n.addEventListener("os-cancel",()=>o(!1)),document.body.appendChild(n)})}function P1(e){const t=[];for(const l of e.getVisibleRects()){if(l.state==="minimized"||l.element.offsetParent===null)continue;const c=l.element.getBoundingClientRect();t.push({id:`window:${l.windowId}`,kind:"window",rect:fw(c),face:"top",element:l.element})}const n=document.getElementById("os-shell");if(n){const l=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:l.left,y:l.bottom-1,width:l.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const l of Array.from(o)){const c=l.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const d=l.getAttribute("data-os-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,d==="bottom"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:c.width,height:1},face:"top",element:l}):d==="right"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:l}):t.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:l})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(l=>{const c=l.getBoundingClientRect();if(c.width===0&&c.height===0)return;const d=l.dataset.widgetId??String(r++);t.push({id:`widget:${d}`,kind:"widget",rect:fw(c),face:"top",element:l})});const a=Y(b.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function fw(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const W1="__openstationKeyedListKey",$1="__openstationKeyedListData";function U1(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function F1(e,t,n){const o=U1(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const l of t){const c=String(n.keyOf(l));a.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),a.add(c);const d=s.get(c);if(d){const f=d.data;n.updateItem?.(d.el,l,f),d.data=l,i.set(c,d),r.push(d.el);continue}const u=n.buildItem(l);u[W1]=c,u[$1]=l,i.set(c,{el:u,data:l}),r.push(u)}for(const[l,c]of s)i.has(l)||c.el.remove();for(let l=0;l<r.length;l++){const c=r[l],d=e.children[l];d!==c&&e.insertBefore(c,d??null)}o.byKey=i}function B1(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function H1(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:l=$=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",$)}}=e;let c=e.sentinel??null;c||(c=document.createElement("div"),c.dataset.osInfiniteListSentinel="",c.style.height="1px",t.appendChild(c));const d=new Set;let u=r,f=!0,p=!1,w=null,m=0,h=!1,y=null;const v=$=>{if(p!==$){p=$;try{a($)}catch(F){l(F)}}},A=()=>{y&&(y.disconnect(),y=null)},D=()=>{y||!c||h||(y=new IntersectionObserver($=>{for(const F of $)F.isIntersecting&&_()},{rootMargin:i}),y.observe(c))},_=async()=>{if(h||p||!f)return;v(!0),w=new AbortController;const $=w;try{const F=await n(u,$.signal);if(h||$!==w)return;let k=0;const W=document.createDocumentFragment();for(const N of F.items??[]){const g=String(o(N));if(d.has(g))continue;d.add(g);const C=s(N,m+k);W.appendChild(C),k++}k>0&&(c&&c.parentNode===t?t.insertBefore(W,c):t.appendChild(W),m+=k),u=F.nextCursor??null,u||(f=!1,A())}catch(F){if(F?.name==="AbortError")return;l(F)}finally{$===w&&(v(!1),w=null)}},O=()=>{if(h)return;w?.abort(),w=null,d.clear(),u=r,f=!0,m=0;const $=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);$&&c&&t.appendChild(c),v(!1),D(),_()},P=()=>{h||(h=!0,A(),w?.abort(),w=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,v(!1))};return D(),_(),{reset:O,loadMore:_,hasMore:()=>f,isLoading:()=>p,destroy:P}}const z1=520,G1=720,j1=500;function V1(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=K1(),o=Y1();return Fe(ot(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:e})},{source:"desktop-mode/oauth-start"}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`[openstation] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>q1(s,e,t))}function q1(e,t,n){return new Promise((o,s)=>{const i=n.width??z1,r=n.height??G1,a=Math.max(0,Math.floor((window.screen.width-i)/2)),l=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${l}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(e.authorize_url,`os-oauth-${t}`,c);if(!d){s(new Error("[openstation] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let f=null,p=!1;const w=()=>{p||(p=!0,window.removeEventListener("message",m),f!==null&&(window.clearInterval(f),f=null))},m=h=>{if(h.origin!==u)return;const y=h.data;if(!y||y.type!=="os-oauth-callback")return;const v=y.payload;if(w(),v&&v.ok)o(v);else{const A=v?.reason??"unknown",D=v?.message??"OAuth flow failed",_=new Error(`[openstation] startOAuth(${t}) failed: ${A} — ${D}`);_.cause=v,s(_)}};window.addEventListener("message",m),f=window.setInterval(()=>{d.closed&&(w(),s(new Error(`[openstation] startOAuth(${t}) cancelled — popup closed before completing.`)))},j1)})}function pw(){return window.openStationConfig??{}}function K1(){const e=pw().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function Y1(){const e=pw().restNonce;return typeof e=="string"&&e!==""?e:null}const X1="",Z1="system-default",J1={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function Q1(e,t,n={}){const o=t===X1,s=o?null:_u(t);if(!o&&!s)return{};const i=o?Z1:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=w_(o?J1:s.recommendedOsSettings),l=Object.keys(a);if(l.length===0)return{};const c=e,d={};for(const u of l){const f=a[u];typeof f!="string"&&typeof f!="number"||!(u in e)||typeof c[u]!=typeof f||(c[u]=f,d[u]=f)}return Object.keys(d).length===0?{}:(r||(e.appliedThemeRecommendations=[...e.appliedThemeRecommendations,i].slice(-64)),d)}const Vi=["os-section","os-button","os-swatch","os-swatch-grid","os-segmented","os-segment","os-select","os-option","os-multiselect","os-color-field","os-range-field","os-text-field","os-number-field","os-checkbox","os-checkbox-label","os-switch","os-toast","os-toast-container","os-tabs","os-tab","os-tabpanel","os-window-button","os-menu","os-menu-item","os-context-menu","os-context-menu-option","os-confirm-dialog","os-modal","os-user-search","os-role-picker","os-flyout","os-tab-chip","os-stack","os-cluster","os-icon","os-body","os-panel","os-row","os-grid","os-display","os-empty-state","os-key","os-code","os-badge","os-ribbon","os-tile","os-log","os-steps","os-step","os-table","os-spinner","os-relative-time","os-avatar","os-textarea","os-chip","os-tag-input","os-form","os-save-status","os-category-picker","os-crumb-chain","os-card","os-rating-summary","os-notice","os-progress-bar","os-field-row","os-repeater","os-token-field"],hw=new Set(Vi);let qi=null;function Jl(){return!!window.openStationComponents}function eN(){return window.openStationConfig?.componentsBundleUrl??""}function tN(e){return new Promise((t,n)=>{const o=()=>{if(Jl()){t();return}n(new Error("[openstation] component kit loaded but did not set `window.openStationComponents`."))},s=document.querySelector('script[data-os-components="1"]');if(s){Jl()?o():(s.addEventListener("load",o),s.addEventListener("error",()=>n(new Error("failed to load component kit"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osComponents="1",i.addEventListener("load",o),i.addEventListener("error",()=>n(new Error("failed to load component kit"))),document.head.appendChild(i)})}function nN(e){const t=e.filter(n=>!hw.has(n));t.length===0||typeof console>"u"||console.error(`[openstation] wp.os.loadComponents(): not a component — ${t.map(n=>`<${n}>`).join(", ")}. The kit registers ${Vi.length} tags; see docs/components-reference.md for the list. The others in this call still loaded.`)}async function oN(e){if(e){if(nN(e),e.filter(o=>hw.has(o)&&!customElements.get(o)).length===0)return}else if(Jl())return;const t=eN();t&&(qi||(qi=tN(t).catch(n=>{throw qi=null,n})),await qi)}const sN=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","dockPlacement","icons","iconSet","files","confirm","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","openNewWindow","cloneTemplate","onWindow","createInfiniteList","startOAuth","repaintLoadingOverlays","loadVendorScript","getWallpaperSurfaces","wallpaper","games","registerModule","loadModules","whenReady","ready","isReady","setDefaultWindow","refreshMenu","config","ai","dragBridge","dragManager","registerCommand","unregisterCommand","listCommands","registerDestructiveAdminAction","unregisterDestructiveAdminAction","listDestructiveAdminActions","registerSettingsTab","unregisterSettingsTab","listSettingsTabs","registerDockRailRenderer","unregisterDockRailRenderer","listDockRailRenderers","openOsSettings","getOsSettings","subscribeOsSettings","updateOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","getNavItems","getNav","renderIcon","applyTileClasses","applyTileElement","applyTileTooltip","dispatchTileRendered","isDockElement","registerDockSelector","registerTitleBarButton","unregisterTitleBarButton","listTitleBarButtons","registerWindowAction","unregisterWindowAction","listWindowActions","registerUnfocusEffect","unregisterUnfocusEffect","listUnfocusEffects","registerWindowReveal","unregisterWindowReveal","listWindowReveals","relations","registerWindowLinkRenderer","unregisterWindowLinkRenderer","listWindowLinkRenderers","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","desktopThemes","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","getConnection","broadcast","subscribe","announceContentChange","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","selection","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","getWindowParams","debug","registerNativeUrlRemap","fetch"]);function iN(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:l,registerWindow:c,openWindowById:d,openNewWindowById:u,loadWindowScriptById:f,placeSystemTile:p,setDefaultWindow:w,refreshMenu:m,openOsSettings:h,aiAssistant:y,dragBridge:v,dragManager:A,connect:D,getConnection:_,wallpaperSuspend:O,mio:P,config:$}=e,F={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,iconSet:xv,files:r,confirm:Bn,saveSession:a,hooks:cv(),HOOKS:b,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:k=>{bn(k),s.apply()},registerWidget:k=>{yl(k)},widgetLayer:l,widgets:{redock:k=>{l?.redock(k)}},loadVendorScript:_e,getWallpaperSurfaces:()=>P1(t),wallpaper:O,mio:P,games:Kp,registerWindow:c,openWindow:d,openNewWindow:u,loadWindowScript:f,loadComponents:oN,fetch:(k,W,N)=>Yl(t,k,W,N),repaintLoadingOverlays:Pf,cloneTemplate:Mm,onWindow:QI,createInfiniteList:H1,startOAuth:V1,registerSystemTile:k=>{p(k),L(b.DOCK_ITEM_APPENDED,{id:k.id})},registerModule:Lp,loadModules:Na,whenReady:_d,ready:_d,isReady:uv,setDefaultWindow:w,refreshMenu:m,config:$,ai:y,dragBridge:v,dragManager:A,registerCommand:_i,unregisterCommand:sh,listCommands:ih,registerDestructiveAdminAction:A0,unregisterDestructiveAdminAction:Wf,listDestructiveAdminActions:C0,registerSettingsTab:ah,unregisterSettingsTab:lh,listSettingsTabs:ch,registerDockRailRenderer:Pd,unregisterDockRailRenderer:Nv,listDockRailRenderers:Ov,openOsSettings:h,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:k=>s.subscribeOsSettings(k),updateOsSettings:(k,W={})=>{if(typeof k.wallpaper=="string"&&(s.state.wallpaper=k.wallpaper),typeof k.accent=="string"&&(s.state.accent=k.accent),typeof k.dockSize=="string"&&(s.state.dockSize=k.dockSize),typeof k.windowRadius=="string"&&(s.state.windowRadius=k.windowRadius),typeof k.adminBarMode=="string"&&(s.state.adminBarMode=k.adminBarMode),typeof k.desktopLayout=="string"&&(s.state.desktopLayout=k.desktopLayout),typeof k.dockPlacement=="string"&&(s.state.dockPlacement=k.dockPlacement),typeof k.desktopTheme=="string"&&(s.state.desktopTheme=k.desktopTheme),typeof k.unfocusEffect=="string"&&(s.state.unfocusEffect=k.unfocusEffect),typeof k.windowReveal=="string"&&(s.state.windowReveal=k.windowReveal),typeof k.windowRevealDuration=="number"&&(s.state.windowRevealDuration=k.windowRevealDuration),typeof k.dockRailRenderer=="string"&&(s.state.dockRailRenderer=k.dockRailRenderer),typeof k.windowLinkRenderer=="string"&&(s.state.windowLinkRenderer=k.windowLinkRenderer),(k.windowLinkVisibility==="focus"||k.windowLinkVisibility==="always"||k.windowLinkVisibility==="off")&&(s.state.windowLinkVisibility=k.windowLinkVisibility),typeof k.windowLinksEnabled=="boolean"&&(s.state.windowLinksEnabled=k.windowLinksEnabled),typeof k.windowLinkRaiseOnFocus=="boolean"&&(s.state.windowLinkRaiseOnFocus=k.windowLinkRaiseOnFocus),typeof k.windowLinkHighlight=="boolean"&&(s.state.windowLinkHighlight=k.windowLinkHighlight),k.ai&&typeof k.ai=="object"&&(s.state.ai={...s.state.ai,...k.ai}),typeof k.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=k.nativePostsEnabled),typeof k.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=k.nativePagesEnabled),typeof k.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=k.nativeUsersEnabled),typeof k.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=k.nativePluginsEnabled),typeof k.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=k.nativeCommentsEnabled),typeof k.stationHomeEnabled=="boolean"&&(s.state.stationHomeEnabled=k.stationHomeEnabled),typeof k.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=k.foldersSharingEnabled),typeof k.showPostStatusRibbons=="boolean"&&(s.state.showPostStatusRibbons=k.showPostStatusRibbons),typeof k.developerModeEnabled=="boolean"&&(s.state.developerModeEnabled=k.developerModeEnabled),Array.isArray(k.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=k.nativePostsHiddenColumns.filter(N=>typeof N=="string"&&N!=="").slice(0,32)),k.navPlacement&&typeof k.navPlacement=="object"){const N=["both","rail","desktop","hidden"],g={};for(const[C,U]of Object.entries(k.navPlacement))typeof C!="string"||C===""||typeof U!="string"||!N.includes(U)||(g[C]=U);s.state.navPlacement=g}if(Array.isArray(k.navOrder)&&(s.state.navOrder=k.navOrder.filter(N=>typeof N=="string"&&N!=="").slice(0,256)),k.dockPromotedPositions&&typeof k.dockPromotedPositions=="object"){const g={};for(const[C,U]of Object.entries(k.dockPromotedPositions)){if(typeof C!="string"||C===""||!U||typeof U!="object")continue;const V=U;if(!(typeof V.x!="number"||typeof V.y!="number"||!Number.isFinite(V.x)||!Number.isFinite(V.y)||Math.abs(V.x)>1e5||Math.abs(V.y)>1e5)&&(g[C]={x:V.x,y:V.y},Object.keys(g).length>=256))break}s.state.dockPromotedPositions=g}s.save(W),(typeof k.wallpaper=="string"||typeof k.accent=="string"||typeof k.dockSize=="string"||typeof k.windowRadius=="string"||typeof k.adminBarMode=="string"||typeof k.desktopLayout=="string"||typeof k.dockPlacement=="string"||typeof k.dockRailRenderer=="string"||typeof k.desktopTheme=="string")&&s.apply(),(k.navPlacement||k.navOrder)&&o?.refresh()},deriveWindowId:(k,W)=>ae(k,W??$.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:k=>o?.getSystemTile(k)??null,getMenuItems:()=>o?.getMenuItems()??[],getNavItems:()=>o?.getNavItems()??[],getNav:()=>o?.getNav()??null,renderIcon:Ro,applyTileClasses:_1,applyTileElement:E1,applyTileTooltip:k1,dispatchTileRendered:S1,isDockElement:C1,registerDockSelector:I1,registerTitleBarButton:ki,unregisterTitleBarButton:rA,listTitleBarButtons:lA,registerWindowAction:uA,unregisterWindowAction:fA,listWindowActions:hA,registerUnfocusEffect:Ii,unregisterUnfocusEffect:GA,listUnfocusEffects:nl,registerWindowReveal:Ue,unregisterWindowReveal:u_,listWindowReveals:au,relations:M0,registerWindowLinkRenderer:gh,unregisterWindowLinkRenderer:gA,listWindowLinkRenderers:wh,registerWindowTheme:qh,unregisterWindowTheme:Kh,listWindowThemes:Yh,desktopThemes:{list:__,getActive:Xr,setActive:Ia,subscribe:k_,resolveIcon:Vs,resolveIconColor:Zr,applyRecommendedOsSettings:k=>{const W=k??Xr()??"";if(W==="")return{};const N=Q1(s.state,W,{force:!0});return Object.keys(N).length>0&&(s.save(),s.apply()),N}},applyWindowTheme:(k,W)=>{const N=t.getById(k);N&&N.setAppearanceTheme(W)},registerWindowControl:Co,unregisterWindowControl:Jh,listWindowControls:Qh,applyWindowControls:(k,W)=>{const N=t.getById(k);N&&N.setAppearanceControls(W)},registerWindowSlot:om,unregisterWindowSlot:dl,listWindowSlots:sm,applyWindowSlot:(k,W,N)=>{const g=t.getById(k);g&&g.setAppearanceSlot(W,N)},registerWindowNotice:cm,unregisterWindowNotice:hl,listWindowNotices:dm,dismissWindowNotice:PC,undismissWindowNotice:WC,registerWindowChrome:FC,unregisterWindowChrome:hm,listWindowChromes:mm,applyWindowChrome:(k,W)=>{const N=t.getById(k);N&&N.setAppearanceChrome(W)},connect:D,getConnection:_,broadcast:Ai,subscribe:In,announceContentChange:Qa,registerPalette:Mg,unregisterPalette:lT,listPalettes:cT,openPalette:Dl,devtools:dw,createSharedStore:re,presence:vT,selection:PT,activity:ke,heartbeat:Te,showToast:Q,notify:Ha,pwa:{promptInstall:lL,undismissInstallHint:cL,getState:wo,subscribe:Zp,requestNotificationPermission:jS,getNotificationPermission:VS},renderKeyedList:F1,clearKeyedList:B1,registerNamespace:(k,W)=>{if(typeof k!="string"||k===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!W||typeof W!="object"){console.warn(`[openstation] registerNamespace("${k}"): api must be an object`);return}if(sN.has(k)){console.warn(`[openstation] registerNamespace("${k}"): name is reserved by the shell — pick a plugin-specific key`);return}F[k]=W},getWindowConfig:k=>{const W=window.openStationWindowConfig;if(!W||typeof W!="object")return;const N=W[k];return N===void 0?void 0:N},getWindowParams:k=>{const W=t.getById(k);if(W)return{...W.config.params??{}}},registerNativeUrlRemap:St,debug:{window:k=>{const W=($.nativeWindows??[]).find(z=>z.id===k);if(!W)return null;const N=W.scriptUrl||"";let g="unknown",C=!1;N&&(document.querySelector(`script[data-os-vendor="${N.replace(/"/g,'\\"')}"]`)?(g="lazy",C=!0):Array.from(document.querySelectorAll("script[src]")).find(x=>x.src===N)&&(g="eager",C=!0));const U=window.openStationWindowConfig,V=!!(U&&typeof U=="object"&&Object.prototype.hasOwnProperty.call(U,k));return{id:k,scriptHandle:W.scriptHandle||"",scriptUrl:N,loadPath:g,tagInDom:C,configPresent:V,extras:{hasTranslations:!!W.scriptTranslations,l10nCount:(W.scriptL10n??[]).length,beforeCount:(W.scriptBefore??[]).length,afterCount:(W.scriptAfter??[]).length}}}}};return F}function rN(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const Ql=re("desktop-mode/layout",()=>({layout:"classic"}));function mw(e){Ql.state.layout!==e&&(Ql.state.layout=e,Ql.notify())}class gw{constructor(t){this.shape=t}title(){return this.shape.title}icon(){return this.shape.icon}previewUrl(){return this.shape.previewUrl}ref(){return this.shape.ref}exists(){return this.shape.exists}}class aN extends gw{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const jo=new Map,ec=new Set;function Ve(e){if(!e.type)throw new Error("[openstation] registerType: `type` is required.");if(!e.label)throw new Error("[openstation] registerType: `label` is required.");jo.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),L("os.files.type-registered",e.type,e),yw()}function lN(e){jo.delete(e)&&(L("os.files.type-unregistered",e),yw())}function cN(e){const t=jo.get(e);return t||null}function ww(){const e=Array.from(jo.values()).slice(),t=Y("os.files.types",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>o.sort!==s.sort?o.sort-s.sort:o.label.localeCompare(s.label)),n}function xt(e){const t=jo.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new aN(e,e.type)}function dN(e){return ec.add(e),()=>ec.delete(e)}function yw(){for(const e of ec)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const Ki=new Map,tc=new Set;let nc={};function bw(e){nc={...e},rc()}function oc(){return{...nc}}function Be(e){if(!e.id)throw new Error("[openstation] registerOpener: `id` is required.");if(!e.label)throw new Error("[openstation] registerOpener: `label` is required.");if(!Array.isArray(e.types)||e.types.length===0)throw new Error("[openstation] registerOpener: `types` must be a non-empty array.");if(!e.handler||typeof e.handler!="object")throw new Error("[openstation] registerOpener: `handler` is required.");Ki.set(e.id,{id:e.id,label:e.label,types:e.types.slice(),isDefault:!!e.isDefault,sort:typeof e.sort=="number"?e.sort:100,appliesTo:typeof e.appliesTo=="function"?e.appliesTo:void 0,handler:e.handler}),L("os.files.opener-registered",e.id,e),rc()}function uN(e){Ki.delete(e)&&(L("os.files.opener-unregistered",e),rc())}function fN(e){return Ki.get(e)??null}function vw(){const e=Array.from(Ki.values()).slice(),t=Y("os.files.openers",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>{const i=typeof o.sort=="number"?o.sort:100,r=typeof s.sort=="number"?s.sort:100;return i!==r?i-r:o.label.localeCompare(s.label)}),n}function sc(e,t){return vw().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function ic(e,t){const n=sc(e,t);if(n.length===0)return null;const o=nc[e];let s=null;return o&&(s=n.find(r=>r.id===o)??null),s||(s=n.find(r=>r.isDefault)??null),s||(s=n[0]),Y("os.files.resolve-opener",s,e)??null}function _w(e){return tc.add(e),()=>tc.delete(e)}function rc(){for(const e of tc)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let Vo=null;function pN(e){Vo=e}async function qo(e,t){if(!Vo)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=ic(e.type(),e);if(!n)return L("os.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;L("os.files.opening",{file:e,openerId:n.id});try{const o=n.handler;if(o.kind==="url"){const s=await o.url(e);if(!s)return!1;const i=o.windowId?o.windowId(e):Vo.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),l=Vo.openUrl({id:i,url:s,title:r,icon:a});return L("os.files.opened",{file:e,openerId:n.id,kind:"url"}),l}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=Vo.openNativeWindow(o.windowId,s);return L("os.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),L("os.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return L("os.files.open-failed",{reason:"handler-threw",type:e.type(),ref:e.ref(),openerId:n.id,error:o}),console.error("[openstation] file opener threw:",o),!1}}const hN="dashicons-portfolio";function mN(){Ve({type:"shortcut",label:"Plugin shortcut",sort:1}),Ve({type:"folder",label:"Folder",sort:5}),Ve({type:"post",label:"Post",sort:10}),Ve({type:"attachment",label:"Media",sort:20}),Ve({type:"upload",label:"Uploaded file",sort:25}),Ve({type:"user",label:"User",sort:30}),Ve({type:"term",label:"Taxonomy term",sort:40}),Ve({type:"comment",label:"Comment",sort:50}),Ve({type:"bookmark",label:"Bookmark",sort:60}),Ve({type:"link",label:"Web link",sort:70}),Ve({type:"embed",label:"Embedded web window",sort:80})}const qe=re("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function Ew(e){qe.state.activeAgent=e,qe.state.transcripts[e.id]||(qe.state.transcripts[e.id]=[]),qe.state.conversationIds||(qe.state.conversationIds={},qe.state.conversationsRev=0),qe.notify()}const kw="desktop-mode/v1/agents/conversations";async function Sw(e,t,n={}){const o=await Fe(ot(e.restRoot,t),{...n,headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce,...n.headers??{}}},{source:"desktop-mode/agents",silent:!0}),s=await o.json().catch(()=>null);if(!o.ok){const i=s&&typeof s=="object"&&typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new Error(i)}return s}function gN(e){return e.filter(t=>!t.pending)}async function wN(e,t){const n=qe.state,o=gN(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await Sw(t,`${kw}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await Sw(t,kw,{method:"POST",body:JSON.stringify({agentId:e.id,messages:o})});n.conversationIds[e.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,qe.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const Aw={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function Cw(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function Iw(e){if(e.type==="shortcut"){const t=e.data;let n=Aw[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=Cw(t.ref);return!n||!o?null:{kind:n,id:o,title:String(t.title??"")||`#${o}`}}if(e.type==="desktop-file"){const n=e.data.placement?.file;if(!n)return null;const o=Aw[String(n.type??"")],s=Cw(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function yN(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function bN(e){return le(E('The user dropped the %1$s "%2$s" (id %3$s) onto you. Handle it according to your instructions, using your tools as needed.',"desktop-mode"),e.kind,e.title,String(e.id))}function vN(e){return{kind:e.kind,id:e.id,title:e.title}}function xw(e,t="agents"){Ew(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function _N(e,t,n,o,s){Ew(e);const i=qe.state.transcripts[e.id],r=i.filter(l=>!l.pending&&l.role!=="error").map(l=>({role:l.role,text:l.text}));i.push({role:"user",text:t,at:Date.now(),attachment:s});const a={role:"agent",text:E("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(a),qe.notify();try{const l=await Fe(ot(n.restRoot,`desktop-mode/v1/agents/${e.id}/invoke`),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":n.restNonce},body:JSON.stringify({message:t,source:o,history:r})},{source:"desktop-mode/agents"}),c=await l.json().catch(()=>null);if(!l.ok){const u=c&&typeof c=="object"&&typeof c.message=="string"?c.message:`HTTP ${l.status}`;throw new Error(u)}const d=c;a.text=d.text||E("The agent finished without a text answer.","desktop-mode"),a.toolCalls=d.toolCalls,Array.isArray(d.callToActions)&&d.callToActions.length>0&&(a.callToActions=d.callToActions)}catch(l){a.role="error",a.text=l instanceof Error?l.message:String(l)}a.pending=!1,qe.notify(),wN(e,n)}function EN(e,t,n){return xw(e,"agents-drop"),_N(e,bN(t),n,"drag",vN(t))}let ac=null;function Lw(e){ac=e}function Ko(){if(!ac)throw new Error("[openstation] files REST client called before installRestDeps().");return ac}function kN(){return Ko()}class lc extends Error{constructor(t){super(`Row was changed by ${t.actor.name||"another session"} (parent="${t.current.parentName}")`),this.name="FilesConflictError",this.status=409,this.detail=t}}async function pe(e,t){const{baseUrl:n,nonce:o}=Ko(),s=ot(n,e),i=new Headers(t.headers??{});i.set("X-WP-Nonce",o),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Fe(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),a=await r.text();let l=null,c=null;if(a)try{l=JSON.parse(a)}catch(d){l=null,c=d}if(!r.ok){if(r.status===409){const u=l?.data?.data??l?.data;if(u&&typeof u=="object")throw new lc(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(e=0){return pe(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function Yo(e){return pe("/placements",{method:"POST",body:JSON.stringify(e)})}function Hn(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),pe(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function cc(e){return pe(`/placements/${e}`,{method:"DELETE"})}async function Yi(e,t){const{baseUrl:n,nonce:o}=Ko(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Fe(i,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o},credentials:"same-origin",body:JSON.stringify({items:[{id:e,type:t}]})},{source:"desktop-mode/files"});if(!r.ok)throw new Error(`[openstation] restore ${r.status}`);return await r.json()}function dc(){return pe("/folders",{method:"GET"})}function uc(e){return pe("/folders",{method:"POST",body:JSON.stringify(e)})}function Tw(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),pe(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function fc(e){return pe(`/folders/${e}`,{method:"DELETE"})}function Nw(e){return pe("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function Dw(e){return pe(`/folders/${e}/shares`,{method:"GET"})}function Rw(e,t){return pe(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function Ow(e,t,n){return pe(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function Mw(e,t){return pe(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function Pw(e,t){return pe(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function Ww(e,t){return pe(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function $w(e){return pe(`/folders/${e}/leave`,{method:"POST"})}function SN(){return pe("/folder-sharing-tables/purge",{method:"POST"})}function Uw(e){return pe(`/uploads/${e}/shares`,{method:"GET"})}function Fw(e,t){return pe(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function Bw(e,t){return pe(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function Hw(e,t){return pe(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function zw(e,t){return pe(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function Gw(e){return pe(`/uploads/${e}/leave`,{method:"POST"})}function AN(e,t){return pe(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function jw(e,t){return pe("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function Yt(e){const{baseUrl:t,nonce:n}=Ko(),o=ot(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function Vw(e){const{baseUrl:t,nonce:n}=Ko(),o=ot(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const CN=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:lc,acceptFileShare:Hw,acceptShare:Pw,createFolder:uc,createPlacement:Yo,deleteFolder:fc,deletePlacement:cc,denyFileShare:zw,denyShare:Ww,ensureUploadPath:jw,getFilesRestDeps:kN,getFolderZipUrl:Vw,getUploadDownloadUrl:Yt,installRestDeps:Lw,inviteFileShare:Fw,inviteShare:Rw,leaveFileShare:Gw,leaveShare:$w,listFileShares:Uw,listFolders:dc,listPlacements:Le,listShares:Dw,purgeFolderSharingTables:SN,renameUpload:AN,restoreTrashedItem:Yi,revokeFileShare:Bw,revokeShare:Mw,saveAssociations:Nw,updateFolder:Tw,updatePlacement:Hn,updateShareCapability:Ow},Symbol.toStringTag,{value:"Module"})),IN="desktop-mode/files";function Je(){return re(IN,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function zn(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function at(e,t){const n=Je(),o=new Map(n.state.placementsByFolder);o.set(e,t.slice());const s=new Set(n.state.hydratedFolders);s.add(e),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),zn({kind:"placements-set",folderId:e})}function Xi(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=Je(),o=new Map(n.state.placementsByFolder);for(const[a,l]of o)if(l.findIndex(d=>d&&d.id===e.id)>=0&&a!==e.parentId){const d=l.filter(Boolean),u=d.findIndex(f=>f.id===e.id);u>=0&&d.splice(u,1),o.set(a,d)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),zn({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function Xo(e,t="local"){const n=Je(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(l=>l&&l.id===e)>=0){const l=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,l),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),zn({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function Zi(e){const t=Je(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),zn({kind:"folders-set"})}function pc(e,t="local"){const n=Je(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),zn({kind:"folder-upserted",folderRowId:e.id,source:t})}function hc(e,t="local"){const n=Je(),o=new Map(n.state.folders);o.delete(e);const s=new Map(n.state.placementsByFolder);s.delete(e),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),zn({kind:"folder-removed",folderRowId:e,source:t})}function mc(e){return Je().subscribe(e)}function Lt(){return Je().getState()}function qw(e){const t=Lt(),n=t.placementsByFolder.get(e.parentId)?.find(o=>o&&o.id===e.id);if(n)return n;for(const o of t.placementsByFolder.values()){const s=o.find(i=>i&&i.id===e.id);if(s)return s}return e}const se={getState:Lt,subscribe:mc,setFolderPlacements:at,upsertPlacement:Xi,upsertFolder:pc,removePlacement:Xo,removeFolder:hc,currentPlacement:qw},xN=de`:host{display:inline-block}`,LN=de`: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 ) )}`,Es=class Es extends Se{render(){return J`<span class="banner" part="banner"><slot></slot></span>`}};Es.props=["placement","tone"],Es.styles=[LN],Es.help=void 0;let gc=Es;xe("os-ribbon",gc);const ie="os-file-tile",Kw={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function TN(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function NN(){return window.wp?.os?.dragManager??null}const DN=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],Jn=class Jn extends Se{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null,this._onSettingsSave=t=>{t.detail?.phase==="saved"&&this._paint()}}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this.click())},this.addEventListener("keydown",this._keydownHandler)),document.addEventListener("os-settings-save-lifecycle",this._onSettingsSave),this._paint()}disconnectedCallback(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null),this._keydownHandler&&(this.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),document.removeEventListener("os-settings-save-lifecycle",this._onSettingsSave)}requestUpdate(){this.isConnected&&this._paint()}attributeChangedCallback(t,n,o){if(n!==o){if(t==="selected"||t==="selectable"||t==="aria-selected"){this._paintSelection();return}super.attributeChangedCallback(t,n,o)}}_paintSelection(){const t=this.hasAttribute("selected"),n=this.hasAttribute("selectable");if(this.classList.toggle(`${ie}--selected`,t),this.setAttribute("role",n?"option":"listitem"),n){const o=t?"true":"false";this.getAttribute("aria-selected")!==o&&this.setAttribute("aria-selected",o)}else this.removeAttribute("aria-selected")}render(){return J``}_paint(){const t=this.getAttribute("type")??"",n=this.getAttribute("ref")??"",o=this.getAttribute("label")??"",s=this.getAttribute("icon")??"",i=this.getAttribute("thumbnail")??"",r=this.getAttribute("kind")??"entry",a=this.getAttribute("status")??"",l=this.hasAttribute("selected"),c=this.hasAttribute("selectable"),d=this.hasAttribute("missing"),u=this.hasAttribute("access-gated"),f=[ie,`${ie}--folder`,`${ie}--missing`,`${ie}--access-gated`,`${ie}--selected`];for(const y of f)this.classList.remove(y);this.classList.add(ie),r==="folder"&&this.classList.add(`${ie}--folder`),d&&this.classList.add(`${ie}--missing`),u&&this.classList.add(`${ie}--access-gated`),l&&this.classList.add(`${ie}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",c?"option":"listitem"),c?this.setAttribute("aria-selected",l?"true":"false"):this.removeAttribute("aria-selected"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const w=[`${ie}__visual`,`${ie}__label`,`${ie}__lock`];for(const y of w)this.querySelectorAll(`:scope > .${y}`).forEach(v=>v.remove());this.querySelectorAll(":scope > os-ribbon").forEach(y=>y.remove());const m=document.createElement("span");if(m.className=`${ie}__visual`,i){const y=document.createElement("img");y.src=i,y.alt="",y.loading="lazy",y.decoding="async",y.className=`${ie}__preview`,y.draggable=!1,m.appendChild(y)}else if(s){const y=Ro(s,{title:o,className:`${ie}__icon`});m.appendChild(y)}this.appendChild(m);const h=document.createElement("span");if(h.className=`${ie}__label`,h.textContent=o,this.appendChild(h),u){const y=document.createElement("span");y.className=`${ie}__lock dashicons dashicons-lock`,y.setAttribute("aria-hidden","true"),this.appendChild(y)}if(a&&a!=="publish"&&Kw[a]&&TN()){const y=document.createElement("os-ribbon");y.setAttribute("placement","top-end"),y.setAttribute("tone",RN(a)),y.textContent=Kw[a],this.appendChild(y)}fv(this),L("os.tile.rendered",{tile:this}),this._wireDragOut()}_wireDragOut(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null);const t=this.getAttribute("drag-kind");if(!t)return;const n=o=>{if(o.button!==0)return;const s=NN();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,a=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,l=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-l.left,offsetY:o.clientY-l.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};Jn.shadow=!1,Jn.props=DN,Jn.styles=[xN],Jn.help=void 0;let wc=Jn;function RN(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}xe("os-tile",wc);function ON(e){const t=document.createElement("os-tile");if(t.setAttribute("type",e.type),t.setAttribute("ref",e.ref),t.setAttribute("label",e.label),e.icon&&t.setAttribute("icon",e.icon),e.thumbnail&&t.setAttribute("thumbnail",e.thumbnail),e.role&&t.setAttribute("kind",e.role),e.status&&t.setAttribute("status",e.status),e.missing&&t.setAttribute("missing",""),e.accessGated&&t.setAttribute("access-gated",""),e.dataset)for(const[o,s]of Object.entries(e.dataset))s!=null&&(t.dataset[o]=String(s));if(Array.isArray(e.extraClasses))for(const o of e.extraClasses)o&&t.classList.add(o);const n=Y("os.tile.class",t.className,e);return n&&n!==t.className&&(t.className=n),typeof e.x=="number"&&typeof e.y=="number"&&(t.style.position="absolute",t.style.left=`${e.x}px`,t.style.top=`${e.y}px`),t}function MN(e,t){const n=document.createElement("div");n.className="os-drag-stack";const o=e.getBoundingClientRect();n.style.width=`${o.width}px`,n.style.height=`${o.height}px`;const s=e.cloneNode(!0);s.removeAttribute("id"),s.removeAttribute("selected"),s.removeAttribute("aria-selected"),s.classList.remove(`${ie}--selected`),s.style.left="0px",s.style.top="0px",s.style.position="relative",n.appendChild(s);const i=document.createElement("span");return i.className="os-drag-stack__count",i.textContent=String(t),n.appendChild(i),n}function Yw(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:xt(e.file).title()}function PN(e,t){const n=xt(e.file),o=n.previewUrl(),s=Yw(e),i=e.meta&&typeof e.meta.iconUrl=="string"?e.meta.iconUrl.trim():"";return{type:e.file.type,ref:e.file.ref,label:s,thumbnail:o||void 0,icon:o?void 0:Bm(e.file.ref)||i||Vs(C_(e.file.type))||n.icon(),x:e.x,y:e.y,dataset:{placementId:e.id,folderId:t},meta:e.meta,missing:!e.file.exists,accessGated:!!e.accessGated,ariaLabel:s}}function WN(e,t){const n=ON(PN(e,t)),o=Y("os.files.tile-class",ie,e);o&&o!==ie&&(n.className=o);const s=Y("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=qw(e),a=xt(r.file);if(r.accessGated){Q({message:`You don’t have permission to open "${r.file.title||a.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}qo(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),L("os.files.tile-rendered",{tile:n,placement:e}),n}function Xt(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const Zo=new Map;function Ji(e,t){const n=Zo.get(e);return n?n.push(t):Zo.set(e,[t]),()=>{const o=Zo.get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&Zo.delete(e)}}function yc(e,t){const n=Zo.get(e);if(n)return n.find(o=>o.appliesTo(t))}function $N(e,t){return yc(e,t)?.acceptLabel}function UN(e,t){const n=yc(e.type,t);return n?n.accept(e.data,t):!1}function FN(e,t,n){const o=yc(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function BN(e,t,n){const o=t.slice().sort((s,i)=>{const r=typeof s.sort=="number"?s.sort:100,a=typeof i.sort=="number"?i.sort:100;return r!==a?r-a:s.label.localeCompare(i.label)});o.length!==0&&RT(e,{actions:o,scope:"files.tile",dataset:{placementId:String(n.placementIds[0]??""),placementIds:n.placementIds.join(",")},onOpened:s=>{L("os.files.tile-menu.opened",{placementId:n.placementIds[0],placementIds:n.placementIds.slice(),items:s})},onClosed:()=>{L("os.files.tile-menu.closed",{})}})}function bc(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function Zt(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function Qi(e){const t=()=>{const n=e.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};t()||queueMicrotask(()=>void t())}const Me="os-create-folder-dialog";let Jo=null;function vc(){Jo&&(Jo.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),Jo.remove(),Jo=null,L("os.files.create-folder.closed",{}))}function _c(e){if(vc(),Y("os.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${Me}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=Me,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${Me}-title`);const i=document.createElement("h2");i.id=`${Me}-title`,i.className=`${Me}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${Me}__field`,r.id=`${Me}-input`,r.setAttribute("label",e.label??"Folder name"),r.setAttribute("value",n),r.setAttribute("autocomplete","off"),r.setAttribute("spellcheck","false"),s.appendChild(r);const a=document.createElement("p");a.className=`${Me}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const l=document.createElement("div");l.className=`${Me}__actions`;const c=document.createElement("os-button");c.className=`${Me}__btn ${Me}__btn--secondary`,c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className=`${Me}__btn ${Me}__btn--primary`,d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(d),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),Jo=o,Qi(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=()=>{vc(),e.onCancel?.()},w=async()=>{const h=bc(r).trim();if(!h){f("Please enter a name."),Qi(r);return}a.hidden=!0,u(!0);try{await e.onSubmit(h),vc()}catch(y){u(!1),f(y instanceof Error?y.message:"Could not create the folder."),Qi(r)}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void w()),o.addEventListener("click",h=>{h.target===o&&p()});const m=h=>{h.key==="Escape"?(h.preventDefault(),p()):h.key==="Enter"&&!h.isComposing&&(h.preventDefault(),w())};s.addEventListener("keydown",m),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",m)})}function er(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function HN(e){return e.id<=0||er(e)!==null}function Xw(e){e.length!==0&&Ok(e)}function Gn(e,t,n){Qa(e,t,n,"desktop-files")}function tr(e){const t=window.wp?.os;if(!t?.showToast)return;const o=(e instanceof Error?e.message:String(e)).replace(/^\[openstation\][^:]*:\s*/,"").replace(/^openstation_files_[a-z_]+\s*/,"");t.showToast({message:o||"Could not move this item to the recycle bin.",duration:5e3})}function Ec(e,t){const n=window.wp?.os;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function Zw(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";se.removePlacement(t);try{await cc(t),Gn(s,"trashed",[t]),Ec(`"${o}" moved to Trash`,async()=>{try{await Yi(t,"placement");const i=await Le(n);se.setFolderPlacements(n,i.placements),Gn(s,"untrashed",[t])}catch(i){console.error("[openstation] restore failed:",i)}})}catch(i){console.error("[openstation] deletePlacement failed:",i),tr(i),Le(n).then(r=>{se.setFolderPlacements(n,r.placements)})}}async function Jw(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";se.removePlacement(n),se.removeFolder(t);try{await fc(t),Gn("folder","trashed",[t]),Ec(`"${s}" moved to Trash`,async()=>{try{await Yi(t,"folder");const i=await Le(o);se.setFolderPlacements(o,i.placements),Gn("folder","untrashed",[t])}catch(i){console.error("[openstation] restore folder failed:",i)}})}catch(i){console.error("[openstation] deleteFolder failed:",i),tr(i),Le(o).then(r=>{se.setFolderPlacements(o,r.placements)})}}async function Qw(e){if(e.length===0)return;if(e.length===1)return zN(e[0]);const t=new Set;for(const l of e)if(t.add(l.parentId),se.removePlacement(l.id),l.file?.type==="folder"){const c=parseInt(l.file.ref,10);c&&se.removeFolder(c)}const n=async()=>{for(const l of t)try{const c=await Le(l);se.setFolderPlacements(l,c.placements)}catch(c){console.error("[openstation] files: re-hydrate failed:",c)}},o=await Promise.allSettled(e.map(async l=>{if(l.file?.type==="folder"){const c=parseInt(l.file.ref,10);if(!c)throw new Error("folder placement without a folder id");return await fc(c),{id:c,kind:"folder",restoreId:c,restoreKind:"folder"}}return await cc(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){tr(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&&Gn(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`;Ec(a,async()=>{const l=await Promise.allSettled(s.map(u=>Yi(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&&Gn(u,"untrashed",f)}d>0&&tr(new Error(`${d} of ${s.length} items could not be restored.`))})}function zN(e){return e.file?.type==="folder"?Jw(e):Zw(e)}const GN=5,ey=e=>Qw(e);async function jN(e){if(!(e.length>GN&&!await Bn({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await qo(xt(t.file))}function VN(e){const t=parseInt(e.file.ref,10);t&&_c({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:e.file.title,onSubmit:async n=>{const o=n.trim();if(!o||o===e.file.title)return;const s=e.file.title,i={...e,file:{...e.file,title:o}};se.upsertPlacement(i);try{const r=se.getState().folders.get(t)?.updatedAtMs??0,a=await Tw(t,{name:o},r);se.upsertFolder(a);const l=await Le(e.parentId);se.setFolderPlacements(e.parentId,l.placements)}catch(r){console.error("[openstation] rename folder failed:",r),se.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function qN(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=window.wp?.os?.myWordpress,s=(typeof e.file.postType=="string"?e.file.postType:"post")==="page"?"pages":"posts";n?.openDetail({entityId:s,postId:t,postTitle:e.file.title||`#${t}`})}function KN(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>jN(i),onClick:()=>{qo(xt(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>qN(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>VN(e)}),e.canTrash!==!1&&t.push({id:"delete-folder",multiId:"trash",label:"Move folder to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:i=>`Move ${i} items to Trash`,bulk:ey,onClick:()=>Jw(e)});else{const i=er(e),r=e.file.type==="shortcut";if(i||r){const a=i??e.file.ref;t.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,multi:!0,bulkLabel:l=>`Hide ${l} items from desktop`,bulk:l=>{Xw(l.map(c=>er(c)??c.file.ref).filter(c=>!!c))},onClick:()=>Xw([a])})}else e.canTrash!==!1&&t.push({id:"remove",multiId:"trash",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:a=>`Move ${a} items to Trash`,bulk:ey,onClick:()=>Zw(e)})}const o=Y("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const Tt=16,ty=88,ny=104,YN=20,XN=16,kc=ty+YN,Sc=ny+XN;function Qo(e,t){const n=Math.max(0,Math.round((e-Tt)/kc)),o=Math.max(0,Math.round((t-Tt)/Sc));return Jt(n,o)}function Jt(e,t){return{col:e,row:t,x:Tt+e*kc,y:Tt+t*Sc}}const ZN=5,JN=4;function QN(e){const t=e?.clientHeight??0;return t<=0?ZN:Math.max(1,Math.floor((t-Tt)/Sc))}function eD(e){const t=e?.clientWidth??0;return t<=0?JN:Math.max(1,Math.floor((t-Tt)/kc))}const oy=999;function nr(e,t="column",n){if(t==="row"){const s=eD(n);for(let i=0;i<oy;i++)for(let r=0;r<s;r++)if(!e.has(Ie(r,i)))return Jt(r,i);return Jt(0,0)}const o=QN(n);for(let s=0;s<oy;s++)for(let i=0;i<o;i++)if(!e.has(Ie(s,i)))return Jt(s,i);return Jt(0,0)}function sy(e,t,n="column",o){const s=new Set(t),i=[];for(let r=0;r<e;r++){const a=nr(s,n,o);s.add(Ie(a.col,a.row)),i.push(a)}return i}function Nt(e,t,n,o,s="column"){const i=Qo(e,t);return n.has(Ie(i.col,i.row))?nr(n,s,o):i}function iy(e,t){const n=new Set;for(const o of e){const s=Qo(o.x,o.y);n.add(Ie(s.col,s.row))}return n}function Ie(e,t){return`${e},${t}`}function tD(e){const t=String(e),{placementsByFolder:n}=Je().state;for(const o of n.values())for(const s of o)if(s.file?.type==="folder"&&s.file.ref===t)return s.file}function nD(e,t){const n=tD(e);if(n)return xt(n);const o=Je().state.folders.get(e);return xt({type:"folder",ref:String(e),title:o?.name||t||"Folder",icon:hN,previewUrl:"",exists:!0})}function ry(e){return e instanceof lc}function oD(e){const t=e.detail.actor.name||"Someone else",n=e.detail.current.parentName||"another folder";return e.detail.reason==="trashed"?"This item is in the recycle bin.":e.detail.reason==="forbidden"?"You no longer have access.":e.detail.reason==="gone"?"This item was deleted.":`${t} moved this to "${n}".`}function ay(e){const t=oD(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{qo(nD(n,e.detail.current.parentName))}}),Q({message:t,action:o,duration:7e3})}const es=new Map;function ly(e,t){return es.set(e,t),()=>{es.get(e)===t&&es.delete(e)}}function sD(e,t){const n=es.get(e.type);return n?n.accept(e.data,t):!1}function iD(e,t,n){const o=es.get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function jn(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function or(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}const cy="application/x-wp-media-attachment",dy="data-files-drop-active";function uy(){const e=window.wp?.os?.dragBridge;if(!e)return null;try{return e.getPayload()}catch{return null}}function fy(e){if(!e||typeof e.id!="number")return null;switch(e.kind){case"attachment":case"post":case"user":return{kind:e.kind,ref:String(e.id),title:e.title};default:return null}}function rD(e){if(!e)return null;let t="";try{t=e.getData(cy)}catch{return null}if(!t)return null;try{const n=JSON.parse(t),o=typeof n.id=="number"?n.id:Number(n.id);return!Number.isFinite(o)||o<=0?null:{kind:"attachment",ref:String(o),title:typeof n.title=="string"?n.title:void 0}}catch{return null}}function py(e){const t=e.dataTransfer?.types,n=t?Array.from(t):[];return n.includes("Files")?!1:n.includes(cy)?!0:fy(uy())!==null}function hy(e,t,n){if(!(e instanceof Element)||!t.contains(e))return!1;let o=e;for(;o&&o!==t;){if(o===n)return!0;if(o.classList.contains("wp-window")||o.id==="os-widgets")return!1;o=o.parentElement}return o===t}function my(e,t){if(!(e instanceof Element))return null;const n=e.closest(`.${ie}`);return!(n instanceof HTMLElement)||!t.contains(n)?null:n.dataset.fileType==="folder"?n:null}function aD(e){const{host:t,container:n,folderId:o}=e;let s=null;const i=()=>{t.removeAttribute(dy),s&&(s.classList.remove(`${ie}--drop-target`),s=null)},r=c=>{if(!py(c))return;if(!hy(c.target,t,n)){i();return}c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),t.setAttribute(dy,"");const d=my(c.target,n);d!==s&&(s?.classList.remove(`${ie}--drop-target`),d?.classList.add(`${ie}--drop-target`),s=d)},a=c=>{const d=c.relatedTarget;d instanceof Node&&t.contains(d)||i()},l=c=>{if(!py(c))return;if(!hy(c.target,t,n)){i();return}i(),c.preventDefault(),c.stopPropagation();const d=fy(uy())??rD(c.dataTransfer);if(!d)return;const u=my(c.target,n);let f=o;if(u){const p=parseInt(u.getAttribute("ref")??"",10);!Number.isNaN(p)&&p>0&&(f=p)}e.fileEntities([d],f)};return t.addEventListener("dragover",r),t.addEventListener("dragleave",a),t.addEventListener("drop",l),()=>{i(),t.removeEventListener("dragover",r),t.removeEventListener("dragleave",a),t.removeEventListener("drop",l)}}function lD(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o}}function ts(){return window.wp?.os?.dragManager??null}const cD="os-files-layer";function sr(e){return e===0?"column":"row"}function dD(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function gy(e,t=0){const n=sr(t),o=document.createElement("div");o.className=cD,o.setAttribute("role","list"),o.dataset.folderId=String(t),e.appendChild(o);let s="";const i=I=>{const x=se.getState().placementsByFolder.get(t)??[],B=new Map;for(const M of x)M&&B.set(String(M.id),M);return I.map(M=>B.get(M)).filter(M=>!!M)},r=new Set,a=new Set,l=xT(o,{itemSelector:`.${ie}`,background:e,surface:"files",scope:String(t),keyOf:I=>I.dataset.placementId??null,onChange:I=>{const x=i(I),B=x.length===1?x[0]:null;for(const M of r)try{M(B)}catch(j){console.error("[openstation] files: selection listener threw:",j)}for(const M of a)try{M(x)}catch(j){console.error("[openstation] files: selection listener threw:",j)}}}),c=()=>i(l.keys()),d=I=>{const x=new Map,B=new Set;let M=0;for(const R of I){if(!Pe(R))continue;const H=Jt(0,M);x.set(R.id,{x:H.x,y:H.y}),B.add(Ie(H.col,H.row)),M+=1}const j=new Map;for(const R of I){if(x.has(R.id))continue;const H=Qo(R.x,R.y),T=Ie(H.col,H.row);if(!B.has(T)){B.add(T);continue}const K=Nt(R.x,R.y,B,e,n);B.add(Ie(K.col,K.row)),j.set(R.id,{x:K.x,y:K.y})}return{pinnedSlots:x,displaced:j}},u=(I,x,B,M)=>{const j=B.get(x.id),R=M.get(x.id);j?Xt(I,j.x,j.y):R?Xt(I,R.x,R.y):Xt(I,x.x,x.y)},f=(I,x,B)=>{const M=WN(I,t),j=x.get(I.id);if(j){if(Xt(M,j.x,j.y),M.classList.add(`${ie}--pinned`),_y(M,I,l,c),wy(I)){const H=ts();H&&y.set(I.id,vy(H,M,I))}return M}const R=B.get(I.id);if(R&&Xt(M,R.x,R.y),gD(M,I,t,l,c),_y(M,I,l,c),I.file.type==="folder"){const H=parseInt(I.file.ref,10);if(H>0){const T=ts();if(T){const K=mD(T,M,H);h.set(I.id,K)}}}else if(wy(I)){const H=ts();H&&y.set(I.id,vy(H,M,I))}return M},p=I=>{const x=new Map;for(const R of o.querySelectorAll("[data-placement-id]")){const H=R.dataset.placementId??"",T=parseInt(H,10);if(H===""||Number.isNaN(T)&&H!=="-0")return!1;x.set(T,R)}const B=new Set;for(const R of I)B.add(R.id);for(const R of I){const H=x.get(R.id);if(!H)continue;if(H.dataset.fileType!==R.file.type||H.dataset.fileRef!==R.file.ref||H.classList.contains(`${ie}--pinned`)!==Pe(R))return!1}for(const[R,H]of x){if(B.has(R))continue;const T=h.get(R);if(T){try{T()}catch{}h.delete(R)}const K=y.get(R);if(K){try{K()}catch{}y.delete(R)}H.remove()}const{pinnedSlots:M,displaced:j}=d(I);for(const R of I){const H=x.get(R.id);if(H){u(H,R,M,j),by(H,R);continue}o.appendChild(f(R,M,j))}return l.refresh(),L("os.files.grid-rendered",{folderId:t,count:I.length}),!0},w=I=>{const B=(I.placementsByFolder.get(t)??[]).slice().sort((H,T)=>{const K=Pe(H)?0:1,q=Pe(T)?0:1;return K-q}),M=uD(B);if(M===s||(s=M,hD(B,o,e,n))||p(B))return;o.replaceChildren();for(const[,H]of h)try{H()}catch{}h.clear();for(const[,H]of y)try{H()}catch{}y.clear();const{pinnedSlots:j,displaced:R}=d(B);for(const H of B)o.appendChild(f(H,j,R));l.refresh(),L("os.files.grid-rendered",{folderId:t,count:B.length})},m=[],h=new Map,y=new Map;let v=null,A=null;const D=I=>{if(v||I.payload.type!=="desktop-file")return;const x=document.createElement("div");x.className="os-files-drop-preview",x.setAttribute("aria-hidden","true"),o.appendChild(x),v=x;const B=I.payload.ghost,M=B?.offsetX??0,j=B?.offsetY??0,H=I.payload.data?.placement?.id,T=(ce,ve)=>{const ye=o.getBoundingClientRect(),he=Math.max(0,ce-ye.left-M),Ee=Math.max(0,ve-ye.top-j),ze=se.getState().placementsByFolder.get(t)??[],Cr=rr(ze,H),$e=Nt(he,Ee,Cr,e,n);x.style.transform=`translate3d(${$e.x}px, ${$e.y}px, 0)`},K=I.payload.source.getBoundingClientRect();T(K.left+M,K.top+j);const q=ce=>{T(ce.clientX,ce.clientY)};document.addEventListener("pointermove",q),A=q},_=()=>{A&&(document.removeEventListener("pointermove",A),A=null),v&&(v.remove(),v=null)},O={id:`os-files-canvas-${t}`,element:e,accept:I=>{if(I.type!=="desktop-file"&&I.type!=="shortcut")return sD(I,{folderId:t,host:e});if(t>0&&I.type==="desktop-file"){const x=I.data;for(const B of jn(x)){if(B.file?.type!=="folder")continue;const M=parseInt(B.file.ref,10);if(!Number.isNaN(M)&&yy(M,t))return!1}}return!0},onEnter:I=>{e.setAttribute("data-files-drop-active",""),(I.payload.type==="desktop-file"||I.payload.type==="shortcut")&&D(I)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),_()},onDrop:(I,x)=>{if(e.removeAttribute("data-files-drop-active"),_(),I.payload.type!=="desktop-file"&&I.payload.type!=="shortcut"){iD(I,x,{folderId:t,host:e});return}const B=o.getBoundingClientRect(),M=I.payload.ghost,j=M?.offsetX??0,R=M?.offsetY??0,H=Math.max(0,x.clientX-B.left-j),T=Math.max(0,x.clientY-B.top-R),K=se.getState().placementsByFolder.get(t)??[];if(I.payload.type==="desktop-file"){const q=I.payload.data,ce=jn(q),ve=new Set(ce.map(Ee=>Ee.id)),ye=rr(K,ve),he=Nt(H,T,ye,e,n);ye.add(Ie(he.col,he.row));for(const Ee of ce){let ze=he;if(Ee.id!==q.placement.id){const $e=Ee.x-q.placement.x,ln=Ee.y-q.placement.y;ze=Nt(Math.max(0,he.x+$e),Math.max(0,he.y+ln),ye,e,n),ye.add(Ie(ze.col,ze.row))}const Cr={...Ee,x:ze.x,y:ze.y,parentId:t};if(se.upsertPlacement(Cr),L("os.files.tile-manually-placed",{folderId:t,placementId:Ee.id}),ir(Ee)){const $e=er(Ee);$e&&pD($e,ze.x,ze.y);continue}Hn(Ee.id,{x:ze.x,y:ze.y,parentId:t},Ee.updatedAtMs).then($e=>{se.upsertPlacement($e,"remote")}).catch($e=>{ry($e)?ay($e):console.error("[openstation] files: drag persist failed",$e),se.upsertPlacement(Ee)})}return}if(I.payload.type==="shortcut"){const q=I.payload.data;Ac(or(q),t,e)}}},P=ts();if(P&&m.push(P.registerDropTarget(O)),m.push(aD({host:e,container:o,folderId:t,fileEntities:(I,x)=>{Ac(I,x,x===t?e:null)}})),!se.getState().hydratedFolders.has(t)){const I=dD(t);I&&se.setFolderPlacements(t,I)}w(se.getState()),queueMicrotask(()=>C());const $=se.subscribe(I=>{w(I),C()});let F=()=>{};const k=new Promise(I=>{F=I});se.getState().hydratedFolders.has(t)?queueMicrotask(F):Le(t).then(I=>{se.setFolderPlacements(t,I.placements)}).catch(I=>{console.error("[openstation] files: failed to hydrate folder",t,I)}).finally(()=>{F()});const W=I=>{const x=new Set;for(let B=0;B<I;B+=1)x.add(Ie(0,B));return x},N=(I,x)=>{const B=I.slice();switch(x){case"name-asc":B.sort((M,j)=>M.file.title.localeCompare(j.file.title));break;case"name-desc":B.sort((M,j)=>j.file.title.localeCompare(M.file.title));break;case"date-asc":B.sort((M,j)=>M.updatedAtMs-j.updatedAtMs);break;case"date-desc":B.sort((M,j)=>j.updatedAtMs-M.updatedAtMs);break}return B},g=I=>{const x=se.getState().placementsByFolder.get(t);if(!x||x.length===0)return;const B=x.filter(H=>Pe(H)),M=x.filter(H=>!Pe(H)),j=N(M,I),R=sy(j.length,W(B.length),n,e);j.forEach((H,T)=>{const{x:K,y:q}=R[T],ce={...H,x:K,y:q,sortOrder:T};se.upsertPlacement(ce),!ir(H)&&Hn(H.id,{x:K,y:q,sortOrder:T}).catch(ve=>{console.error("[openstation] files: sort persist failed",ve)})})},C=()=>{const I=se.getState().placementsByFolder.get(t);if(!I||I.length===0)return;const x=e.clientWidth>0?e.clientWidth:1/0,B=e.clientHeight>0?e.clientHeight:1/0;if(!I.some(T=>T.x+ty>x||T.y+ny>B))return;const j=I.filter(T=>Pe(T)),R=I.filter(T=>!Pe(T)),H=sy(R.length,W(j.length),n,e);R.forEach((T,K)=>{const q=o.querySelector(`[data-placement-id="${T.id}"]`);q&&Xt(q,H[K].x,H[K].y)})};let U=e.clientWidth,V=e.clientHeight,z=null;return typeof ResizeObserver<"u"&&(z=new ResizeObserver(()=>{const I=e.clientWidth,x=e.clientHeight;I===U&&x===V||(U=I,V=x,C())}),z.observe(e)),{host:e,folderId:t,onSelectionChange(I){return r.add(I),()=>{r.delete(I)}},onSelectionChanged(I){return a.add(I),()=>{a.delete(I)}},getSelection:c,selectAll:()=>l.model.selectAll(),clearSelection:()=>l.model.clear(),sort:g,reflow:C,hydrated:k,dispose(){$(),z?.disconnect(),z=null;for(const I of m)try{I()}catch{}m.length=0;for(const I of h.values())try{I()}catch{}h.clear();for(const I of y.values())try{I()}catch{}y.clear(),l.destroy(),r.clear(),a.clear(),o.remove()}}}function uD(e){if(e.length===0)return"0";const t=[];for(const n of e)t.push(`${n.id}:${n.parentId}:${n.x}:${n.y}:${n.sortOrder}:${n.updatedAtMs}:${n.file.type}:${n.file.ref}:${n.file.title}:${n.file.icon}:${Pe(n)?1:0}`);return t.join("|")}function Pe(e){return!!e.file.pinned}function ir(e){return HN(e)}const fD="desktop-mode-recycle-bin";function wy(e){return!(e.file?.type==="folder"||e.file?.ref===fD)}function rr(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,a)=>{const l=Pe(r)?0:1,c=Pe(a)?0:1;return l-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(Pe(r))s.add(Ie(0,i)),i+=1;else{const a=Qo(r.x,r.y);s.add(Ie(a.col,a.row))}return s}function Ac(e,t,n){const o=se.getState().placementsByFolder.get(t)??[],s=rr(o),i=sr(t);for(const r of e){const a=nr(s,i,n);s.add(Ie(a.col,a.row)),Yo({parentId:t,type:r.kind,ref:r.ref,x:a.x,y:a.y}).then(l=>{se.upsertPlacement(l),L("os.files.shortcut-dropped",{folderId:t,placement:l})}).catch(l=>{console.error("[openstation] shortcut drop failed:",l)})}}function yy(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=se.getState();for(const a of o.placementsByFolder.values())for(const l of a){if(l.file?.type!=="folder")continue;const c=parseInt(l.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,l.parentId)}const s=new Set;let i=t,r=256;for(;i>0&&r-- >0;){if(i===e||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function pD(e,t,n){const o=window.wp?.os;if(!o?.getOsSettings||!o?.updateOsSettings)return;const s=o.getOsSettings().dockPromotedPositions??{};o.updateOsSettings({dockPromotedPositions:{...s,[e]:{x:t,y:n}}})}function hD(e,t,n,o){const s=Array.from(t.querySelectorAll("[data-placement-id]"));if(s.length!==e.length)return!1;const i=new Map;for(const d of s){const u=d.dataset.placementId??"",f=parseInt(u,10);if(u===""||Number.isNaN(f)&&u!=="-0")return!1;i.set(f,d)}for(const d of e){const u=i.get(d.id);if(!u||u.dataset.fileType!==d.file.type||u.dataset.fileRef!==d.file.ref||u.classList.contains(`${ie}--pinned`)!==Pe(d))return!1}const r=new Map,a=new Set;let l=0;for(const d of e){if(!Pe(d))continue;const u=Jt(0,l);r.set(d.id,{x:u.x,y:u.y}),a.add(Ie(u.col,u.row)),l+=1}const c=new Map;for(const d of e){if(r.has(d.id))continue;const u=Qo(d.x,d.y),f=Ie(u.col,u.row);if(!a.has(f)){a.add(f);continue}const p=Nt(d.x,d.y,a,n,o);a.add(Ie(p.col,p.row)),c.set(d.id,{x:p.x,y:p.y})}for(const d of e){const u=i.get(d.id);if(!u)continue;const f=r.get(d.id)??c.get(d.id)??{x:d.x,y:d.y};Xt(u,f.x,f.y),by(u,d)}return!0}function by(e,t){const n=Yw(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function vy(e,t,n){const o={placement:n};let s=null;return e.registerDropTarget({id:`os-files-tile-${n.id}-reject`,element:t,get acceptLabel(){return s?$N(s,o):void 0},accept:i=>(s=i.type,UN(i,o)),onEnter:()=>{t.classList.add(`${ie}--drop-target`)},onLeave:()=>{t.classList.remove(`${ie}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${ie}--drop-target`),FN(i,r,o)}})}function mD(e,t,n,o){const s={id:`os-files-folder-${n}-tile-${t.dataset.placementId??"?"}`,element:t,accept:i=>{if(i.type!=="desktop-file"&&i.type!=="shortcut")return!1;if(i.type==="desktop-file"){const r=i.data;for(const a of jn(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||ir(a))return!1;if(a.file.type==="folder"){const l=parseInt(a.file.ref,10);if(!Number.isNaN(l)&&yy(l,n))return!1}}}return!0},onEnter:()=>{t.classList.add(`${ie}--drop-target`)},onLeave:()=>{t.classList.remove(`${ie}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${ie}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a=se.getState().placementsByFolder.get(n)??[],l=rr(a),c=sr(n);for(const d of jn(r)){const u=nr(l,c);l.add(Ie(u.col,u.row)),se.upsertPlacement({...d,x:u.x,y:u.y,parentId:n}),Hn(d.id,{x:u.x,y:u.y,parentId:n},d.updatedAtMs).then(f=>{se.upsertPlacement(f,"remote")}).catch(f=>{ry(f)?ay(f):console.error("[openstation] files: move-into-folder persist failed",f),se.upsertPlacement(d)})}return}if(i.payload.type==="shortcut"){const r=i.payload.data;Ac(or(r),n)}}};return e.registerDropTarget(s)}function gD(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=ts();if(!r)return;const l=se.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||l.x,parseFloat(e.style.top)||l.y;const c=o.model.has(String(l.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===l.id)?d:[l];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(l.id)])};document.addEventListener("os.drag.start",f);const p=()=>{document.removeEventListener("os.drag.start",f),document.removeEventListener("pointerup",p)};document.addEventListener("pointerup",p)}if(u.length>1){const f=[],p=()=>{for(const m of f)m.classList.remove(`${ie}--dragging`);f.length=0,document.removeEventListener("os.drag.start",w),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},w=()=>{for(const m of u){const h=e.parentElement?.querySelector(`[data-placement-id="${m.id}"]`);h&&h!==e&&(h.classList.add(`${ie}--dragging`),f.push(h))}};document.addEventListener("os.drag.start",w),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:e,data:{placement:l,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:lD(l)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?MN(e,u.length):void 0,hint:u.length>1?{accept:`Move ${u.length} items here`,reject:`Can’t drop ${u.length} items here`,neutral:`Moving ${u.length} items`}:void 0}},origin:i})})}function _y(e,t,n,o){e.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=se.currentPlacement(t);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),a=r.length>0?r:[i],l=jg(a,KN);BN({x:s.clientX,y:s.clientY},l,{placementIds:a.map(c=>c.id)})})}function Qt(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,o=0;for(;n>=1024&&o<t.length-1;)n/=1024,o++;const s=n>=100||o===0?0:1;return`${n.toFixed(s)} ${t[o]}`}const Vn="os-folder-status-bar";function wD(e,t,n={}){const o=document.createElement("div");o.className=Vn,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const a=Lt().placementsByFolder.get(t)??[],l=a.filter(p=>p.file.type==="folder").length,c=a.length-l;let d=0;for(const p of a)if(p.file.type==="upload"){const w=Number(p.file.sizeBytes??0);Number.isFinite(w)&&w>0&&(d+=w)}const u={folderId:t,selectedCount:n.selection?.count()??0,totals:{files:c,folders:l,total:a.length,bytes:d}},f=yD(u);bD(o,f)};s();const i=mc(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function yD(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:ky(n,"file","files")+(t>0?`, ${ky(t,"folder","folders")}`:"")+(o>0?` (${Qt(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=Y("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function bD(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,l=typeof r.sort=="number"?r.sort:100;return a!==l?a-l:i.label.localeCompare(r.label)},o=t.filter(i=>(i.align??"start")==="start").sort(n),s=t.filter(i=>i.align==="end").sort(n);e.replaceChildren(),e.appendChild(Ey("start",o)),e.appendChild(Ey("end",s))}function Ey(e,t){const n=document.createElement("div");n.className=`${Vn}__cluster ${Vn}__cluster--${e}`;for(const o of t)n.appendChild(vD(o));return n}function vD(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${Vn}__segment`,n.dataset.segmentId=e.id,t&&(n.type="button",n.addEventListener("click",s=>e.onClick(s))),e.icon){const s=document.createElement("span");s.className=`${Vn}__icon dashicons ${e.icon.replace(/[^a-zA-Z0-9_-]/g,"")}`,s.setAttribute("aria-hidden","true"),n.appendChild(s)}const o=document.createElement("span");return o.className=`${Vn}__label`,o.textContent=e.label,n.appendChild(o),n}function ky(e,t,n){return`${e} ${e===1?t:n}`}const ar="os-icon-canvas-menu";let ns=null,lr=null,Cc=null,os=null,ss=null;function _D(e,t){t.openOnBackgroundClick;const n=i=>{ED(i.target)||Sy(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(Cc===e&&ns){en();return}const a=kD(t),l=Y("os.icon-canvas.menu",a,t.scope),c=Array.isArray(l)?l:a,d=++o;Us(()=>d===o,()=>SD(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),en()}}}function ED(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function Sy(e){return e instanceof Element?e.closest(`.${ar}`)!==null:!1}function kD(e){const n=[{id:"sort-by",label:E("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:E("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:E("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:E("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:E("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function Ay(e){return e.slice().sort((t,n)=>{const o=typeof t.sort=="number"?t.sort:100,s=typeof n.sort=="number"?n.sort:100;return o!==s?o-s:t.label.localeCompare(n.label)})}function SD(e,t,n){if(en(),e.length===0)return;Cc=n;const o=Ay(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(ar),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;for(const r of o){i.set(r.id,r);const a=Cy(s,r);cr(r)&&a.addEventListener("mouseenter",()=>{Iy(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,l=i.get(a.id);if(l){if(cr(l)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${l.id}"]`);c&&Iy(l,c);return}en(),l.onClick?.()}}),document.body.appendChild(s),ns=s,Wl(s),queueMicrotask(()=>{os=r=>{Sy(r.target)||en()},ss=r=>{r.key==="Escape"&&en()},document.addEventListener("mousedown",os),document.addEventListener("keydown",ss)})}function Cy(e,t){const n=document.createElement("os-context-menu-option");return n.dataset.menuItemId=t.id,n.setAttribute("value",t.id),t.heading&&n.setAttribute("heading",""),t.disabled&&n.setAttribute("disabled",""),t.icon&&n.setAttribute("icon",AD(t.icon)),cr(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function Iy(e,t){if(xy(),!cr(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(ar,`${ar}--flyout`);const o=new Map;for(const s of Ay(e.children??[]))o.set(s.id,s),Cy(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),en(),r.onClick?.())}),document.body.appendChild(n),lr=n,Kg(n,t)}function cr(e){return Array.isArray(e.children)&&e.children.length>0}function xy(){lr&&(lr.remove(),lr=null)}function en(){xy(),ns&&(ns.remove(),ns=null),Cc=null,os&&(document.removeEventListener("mousedown",os),os=null),ss&&(document.removeEventListener("keydown",ss),ss=null)}function AD(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const tn="os-breadcrumbs";function CD(e,t,n={}){if(e.replaceChildren(),e.classList.add(tn),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${tn}__back`,s.setAttribute("aria-label",E("Back","desktop-mode")),s.title=E("Back","desktop-mode");const i=document.createElement("span");i.className="dashicons dashicons-arrow-left-alt2",i.setAttribute("aria-hidden","true"),s.appendChild(i),n.backDisabled&&(s.disabled=!0);const r=n.onBack;s.addEventListener("click",()=>{s.disabled||r()}),e.appendChild(s)}const o=document.createElement("nav");o.className=`${tn}__crumbs`,o.setAttribute("aria-label",E("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const l=document.createElement("span");l.className=`${tn}__sep`,l.setAttribute("aria-hidden","true"),l.textContent="›",o.appendChild(l)}if(!s.onClick){const l=document.createElement("span");l.className=`${tn}__crumb ${tn}__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=`${tn}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}function dr(e){const t=document.createElement("a");t.href=e,t.setAttribute("download",""),t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async function is(e,t={}){const n=await Fe(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":ID(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function ID(){return window.wp?.os?.config?.restNonce??""}function xD(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function rs(e){return ot(xD(),e)}function LD(e,t){const n=Y("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(TD(e));return}t.replaceChildren(BD()),ND(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(HD(o))})}function TD(e){const t=document.createElement("div");t.className="os-files__access-gated";const n=document.createElement("div");n.className="os-files__access-gated-ring";const o=document.createElement("span");o.className="dashicons dashicons-lock os-files__access-gated-glyph",o.setAttribute("aria-hidden","true"),n.appendChild(o),t.appendChild(n);const s=document.createElement("h2");s.className="os-files__access-gated-title",s.textContent="No permission to view",t.appendChild(s);const i=document.createElement("p");i.className="os-files__access-gated-sub";const r=e.file.title||e.file.type;i.textContent=`You don’t have access to "${r}". The folder owner shared this folder with you, but your role doesn’t include permission to open this item.`,t.appendChild(i);const a=document.createElement("p");return a.className="os-files__access-gated-hint",a.textContent="Ask the owner to grant access on the underlying item, or to remove it from the shared folder.",t.appendChild(a),t}async function ND(e){const t=e.file;switch(t.type){case"post":return DD(t.ref,t);case"folder":return $D(t);case"shortcut":return UD(t);case"attachment":return PD(t.ref,t);case"upload":return WD(t);case"user":return RD(t.ref,t);case"term":return OD(t);case"comment":return MD(t.ref,t);case"bookmark":return FD(t);default:return Qe(t)}}async function DD(e,t){const n=parseInt(e,10);if(!n)return Qe(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await is(rs(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return Qe(t);const s=lt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=ur(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="os-my-wordpress__article-meta";const a=[];if(a.push(Ly(o.date)),o.status&&o.status!=="publish"&&a.push(o.status),r.textContent=a.join(" · "),s.appendChild(r),o.content?.rendered){const u=document.createElement("div");u.className="os-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const c=window.wp?.os?.myWordpress;if(c){const u=document.createElement("os-button");u.setAttribute("variant","secondary"),u.textContent=E("Explore details","desktop-mode"),u.title=E("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),u.addEventListener("click",()=>{const f=typeof t.postType=="string"?t.postType:"post";c.openDetail({entityId:f==="page"?"pages":"posts",postId:n,postTitle:ur(o.title.rendered)||`#${n}`})}),l.appendChild(u)}const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=E("Open in editor","desktop-mode"),d.addEventListener("click",()=>{const u=window.wp?.os?.config?.adminUrl;if(!u)return;const f=`${u}post.php?post=${n}&action=edit`,p=window.wp?.os?.windowManager,m=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${m}-edit-${n}`,url:f,title:ur(o.title.rendered),icon:t.icon})}),l.appendChild(d),s.appendChild(l),s}async function RD(e,t){const n=parseInt(e,10);if(!n)return Qe(t);let o=null;try{o=await is(rs(`desktop-mode/v1/user-stats/${n}`))}catch{return Qe(t)}const s=lt("os-my-wordpress__user"),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.profile.avatarUrl){const c=document.createElement("img");c.className="os-my-wordpress__user-avatar",c.src=o.profile.avatarUrl,c.alt="",i.appendChild(c)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");if(a.className="os-my-wordpress__article-title",a.textContent=o.profile.name||t.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const c=document.createElement("div");c.className="os-my-wordpress__user-roles";for(const d of o.profile.roleLabels){const u=document.createElement("span");u.className="os-my-wordpress__user-role",u.textContent=d,c.appendChild(u)}r.appendChild(c)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const c=document.createElement("div");c.className="os-my-wordpress__user-bio",c.textContent=o.profile.description,s.appendChild(c)}const l=document.createElement("div");return l.className="os-my-wordpress__user-stats",l.appendChild(qn(o.counts.posts.total.toLocaleString(),E("Posts","desktop-mode"))),l.appendChild(qn(o.counts.pages.total.toLocaleString(),E("Pages","desktop-mode"))),l.appendChild(qn(o.counts.commentsReceived.toLocaleString(),E("Comments received","desktop-mode"))),s.appendChild(l),s}async function OD(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return Qe(e);let o=null;try{o=await is(rs(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return Qe(e)}const s=lt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=o.profile.name||e.title||`#${t}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const l=document.createElement("div");l.className="os-my-wordpress__article-content",l.innerHTML=o.profile.description,s.appendChild(l)}const a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(qn(o.counts.posts.total.toLocaleString(),E("Posts","desktop-mode"))),a.appendChild(qn(o.counts.commentsReceived.toLocaleString(),E("Comments","desktop-mode"))),a.appendChild(qn(o.counts.distinctAuthors.toLocaleString(),E("Authors","desktop-mode"))),s.appendChild(a),s}async function MD(e,t){const n=parseInt(e,10);if(!n)return Qe(t);let o=null;try{o=await is(rs(`desktop-mode/v1/comment-stats/${n}`))}catch{return Qe(t)}const s=lt(),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=`${Ly(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 PD(e,t){const n=parseInt(e,10);if(!n)return Qe(t);let o=null;try{o=await is(rs(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return Qe(t)}const s=lt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=ur(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="os-my-wordpress__article-hero";const l=o.media_details?.sizes;a.src=l?.large?.source_url??l?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),l=document.createElement("a");l.href=o.source_url,l.textContent=o.source_url,l.target="_blank",l.rel="noopener noreferrer",a.appendChild(l),s.appendChild(a)}return s}function WD(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("Uploaded file","desktop-mode"),t.appendChild(n);const o=typeof e.mime=="string"?e.mime:"",s=typeof e.sizeBytes=="number"?e.sizeBytes:0,i=typeof e.kind=="string"?e.kind:"file",r=document.createElement("p");r.className="os-my-wordpress__article-meta",r.textContent=[o,s>0?Qt(s):""].filter(Boolean).join(" · "),t.appendChild(r);const a=parseInt(e.ref,10),l=()=>{const c=document.createElement("p");return c.className="os-my-wordpress__article-meta os-files__no-preview",c.textContent=E("No preview available for this file type.","desktop-mode"),c};if(a>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=Yt(a),c.alt=e.title||"",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="video"){const c=document.createElement("video");c.className="os-my-wordpress__article-hero",c.controls=!0,c.preload="metadata",c.src=Yt(a),c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="audio"){const c=document.createElement("audio");c.controls=!0,c.preload="metadata",c.src=Yt(a),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else t.appendChild(l());if(a>0){const c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=E("Download","desktop-mode"),d.addEventListener("click",()=>{dr(Yt(a))}),c.appendChild(d),t.appendChild(c)}return t}function $D(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=E("Double-click to open.","desktop-mode"),t.appendChild(o),t}function UD(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=E("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function FD(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("Bookmark","desktop-mode"),t.appendChild(n);const o=typeof e.url=="string"?e.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",t.appendChild(s)}return t}function Qe(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||e.type,t.appendChild(n);const o=document.createElement("p");if(o.className="os-my-wordpress__article-meta",o.textContent=le(E("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="os-my-wordpress__article-meta",s.textContent=E("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function lt(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function qn(e,t){const n=document.createElement("div");n.className="os-my-wordpress__user-stat";const o=document.createElement("span");o.className="os-my-wordpress__user-stat-value",o.textContent=e,n.appendChild(o);const s=document.createElement("span");return s.className="os-my-wordpress__user-stat-label",s.textContent=t,n.appendChild(s),n}function BD(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function HD(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:E("Unknown error.","desktop-mode"),t}function ur(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function Ly(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function Ty(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=E("Select an item to preview it here.","desktop-mode"),e}function zD(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=le(E("%d items selected","desktop-mode"),e.length),t.appendChild(n);const o=new Map;for(const i of e){const r=i.file?.type||"item";o.set(r,(o.get(r)??0)+1)}const s=Array.from(o.entries()).sort((i,r)=>r[1]-i[1]||i[0].localeCompare(r[0])).map(([i,r])=>`${r} × ${i}`).join(" · ");if(s){const i=document.createElement("div");i.className="os-files-preview__selection-breakdown",i.textContent=s,t.appendChild(i)}return t}const fr="desktop-mode-embed-",GD=800,jD=600,Ic=360,xc=240,pr=16,Lc=new Map;function VD(e,t){const n=e.ref();if(!n)return;const o=window.wp?.os?.windowManager;if(!o)return;const s=t?.placement,i=s?.meta??null,r=s?`${fr}${s.id}`:`${fr}anon-${XD(n)}`,a=i?.name?.trim()??"",l=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:l,icon:e.icon(),minWidth:Ic,minHeight:xc},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:w,y:m,width:h,height:y}=YD(d,f,p);c.x=w,c.y=m,c.width=h,c.height=y}else c.width=Math.min(GD,Math.max(Ic,f-pr*2)),c.height=Math.min(jD,Math.max(xc,p-pr*2));s&&d&&Lc.set(r,{...d}),o.open(c)}let Ny=!1;function qD(){if(Ny)return;Ny=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(fr))return;const s=o.slice(fr.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=Lc.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(Lc.set(o,c),KD(i,c))};Z(b.WINDOW_DRAG_END,"os-embed-persist",e),Z(b.WINDOW_RESIZE_END,"os-embed-persist",e)}async function KD(e,t){try{const i={...(await Le(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await Hn(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function YD(e,t,n){const o=Math.max(Ic,Math.min(e.width,t-pr)),s=Math.max(xc,Math.min(e.height,n-pr)),i=Math.max(0,Math.min(e.x,Math.max(0,t-o))),r=Math.max(0,Math.min(e.y,Math.max(0,n-s)));return{x:i,y:r,width:o,height:s}}function XD(e){let t=0;for(let n=0;n<e.length;n++)t=(Math.imul(t,31)+e.charCodeAt(n))%2147483647;return Math.abs(t).toString(36)}function as(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function Dy(e){const t=typeof e.shape.url=="string"?e.shape.url:"";if(!t)return"";try{const n=new URL(t,window.location.href);if(n.protocol!=="http:"&&n.protocol!=="https:")return""}catch{return""}return t}function ZD(){Be({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${as()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Be({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${as()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Be({id:"agent-chat",label:E("Agent chat","desktop-mode"),types:["user"],isDefault:!0,sort:5,appliesTo:e=>e.shape.isAgent===!0,handler:{kind:"js",open:e=>{const t=e.shape;xw({id:Number.parseInt(t.ref,10),name:t.title,description:t.agentDescription??"",avatarUrl:t.previewUrl??""},"agents-open")}}}),Be({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${as()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),Be({id:"wp-term-editor",label:"Term editor",types:["term"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>{const[t,n]=e.ref().split(":");return`${as()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Be({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${as()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),Be({id:"desktop-mode-upload-download",label:"Download",types:["upload"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);t&&dr(Yt(t))}}}),Be({id:"desktop-mode-folder-window",label:"Open folder",types:["folder"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);if(!t)return;const n=window.wp?.os?.windowManager;if(!n)return;const o=`os-folder-${t}`,s=se.getState().folders.get(t),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),l=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:l,icon:e.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window");const d=[{folderId:t,title:e.title()}];let u=null;const f=document.createElement("header");c.appendChild(f);const p=document.createElement("div");p.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",c.appendChild(p);const w=()=>{const h=d.map((y,v)=>v===d.length-1?{label:y.title}:{label:y.title,onClick:()=>{d.length=v+1,m()}});CD(f,h,{onBack:()=>{d.length<=1||(d.pop(),m())},backDisabled:d.length<=1})},m=()=>{u?.(),u=null,p.replaceChildren();const h=document.createElement("div");h.className="os-folder-window__split",p.appendChild(h);const y=document.createElement("div");y.className="os-folder-window__layer",h.appendChild(y);const v=document.createElement("div");v.className="os-folder-window__preview",v.appendChild(Ty()),h.appendChild(v);const A=d[d.length-1],D=gy(y,A.folderId),_=D.onSelectionChanged(F=>{if(F.length===0){v.replaceChildren(Ty());return}if(F.length>1){v.replaceChildren(zD(F));return}LD(F[0],v)}),O=F=>{if(!(F.target instanceof Element))return;const k=F.target.closest(".os-file-tile");if(!k||k.dataset.fileType!=="folder")return;const W=parseInt(k.dataset.fileRef??"",10);if(!W)return;F.preventDefault(),F.stopPropagation();const N=k.querySelector(".os-file-tile__label")?.textContent??`#${W}`;d.push({folderId:W,title:N}),m()};y.addEventListener("dblclick",O,!0);const P=_D(y,{scope:`os-folder:${A.folderId}`,onSort:F=>D.sort(F),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{_c({onSubmit:async F=>{const k=await uc({name:F}),W=se.getState().placementsByFolder.get(A.folderId)??[],N=iy(W),g=Nt(Tt,Tt,N,y,sr(A.folderId)),C=await Yo({type:"folder",ref:String(k.id),parentId:A.folderId,x:g.x,y:g.y});se.upsertFolder(k),se.upsertPlacement(C)}})}}]}),$=wD(p,A.folderId,{selection:{count:()=>D.getSelection().length,subscribe:F=>D.onSelectionChanged(()=>F())}});u=()=>{_(),P.dispose(),$.dispose(),y.removeEventListener("dblclick",O,!0),D.dispose()},w()};m()},width:720,height:480,minWidth:360,minHeight:240})}}}),Be({id:"desktop-mode-shortcut-opener",label:"Open shortcut",types:["shortcut"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=e.shape,n=window.wp?.os;if(n){if(t.shortcutSystemTile&&n.getSystemTile){n.getSystemTile(t.shortcutSystemTile)?.onOpen();return}if(t.shortcutWindow&&n.openWindow){n.openWindow(t.shortcutWindow);return}if(t.shortcutUrl&&n.windowManager)try{const o=new URL(t.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}if(Ge(o.toString()))return;const s=n.config?.adminUrl,i=s?ae(o.toString(),s):`desktop-icon-${e.ref()}`,r=Pm(o.toString());n.windowManager.open({id:i,baseId:i,url:o.toString(),parentUrl:r?.url??o.toString(),title:e.title(),icon:e.icon(),submenu:r?.submenu,selfLabel:r?.selfLabel,multi:!!r?.multi})}catch{}}}}}),Be({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Dy(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Dy(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{VD(e,t)}}})}const JD="os-file-associations";let nn=null;function QD(){ah({id:JD,label:"File Associations",order:50,render(e){nn&&(nn(),nn=null),Ry(e),nn=_w(()=>{if(!e.isConnected){nn&&(nn(),nn=null);return}Ry(e)})}})}function Ry(e){e.replaceChildren();const t=ww();if(t.length===0){const i=document.createElement("p");i.className="os-file-associations__empty",i.textContent="No file types are registered.",e.appendChild(i);return}const n=document.createElement("p");n.className="os-file-associations__intro",n.textContent="Pick which app opens each kind of file when you double-click it on the desktop.",e.appendChild(n);const o=oc(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(eR(i.type,i.label,o));e.appendChild(s)}function eR(e,t,n){const o=document.createElement("div");o.className="os-file-associations__row",o.setAttribute("role","listitem"),o.dataset.fileType=e;const s=document.createElement("label");s.className="os-file-associations__label",s.textContent=t,o.appendChild(s);const i=sc(e);if(i.length===0){const c=document.createElement("span");return c.className="os-file-associations__none",c.textContent="No app available",o.appendChild(c),o}const r=ic(e),a=n[e]??r?.id??"",l=document.createElement("os-select");l.setAttribute("value",a),l.setAttribute("aria-label",`Default app for ${t}`),l.className="os-file-associations__select",s.htmlFor=`assoc-${e}`,l.id=`assoc-${e}`;for(const c of i){const d=document.createElement("os-option");d.setAttribute("value",c.id),d.textContent=c.isDefault?`${c.label} (default)`:c.label,l.appendChild(d)}return l.addEventListener("os-pick",c=>{const d=c.detail?.value;if(!d)return;const u={...oc(),[e]:d};bw(u),Nw(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(l),o}function tR(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,Zi(t),!0)}let Tc=null;function et(){return Tc||(Tc=re("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),Tc}function nR(e,t){const n=et();n.state.byFolder.set(e,t),n.notify()}function oR(e){if(!e||typeof e.folderId!="number")return;const t=et(),o=(t.state.byFolder.get(e.folderId)??[]).filter(s=>s.id!==e.id);o.push(e),t.state.byFolder.set(e.folderId,o),t.notify()}function sR(e,t){const n=et(),o=n.state.byFolder.get(e)??[];n.state.byFolder.set(e,o.filter(s=>s.id!==t)),n.notify()}function iR(e,t){return e.id===t.id&&e.folderId===t.folderId&&e.capability===t.capability&&e.invitedAtMs===t.invitedAtMs&&e.folderName===t.folderName&&e.fileName===t.fileName&&e.ownerName===t.ownerName}function Oy(e){const t=et(),n=new Map(t.state.pending.map(s=>[s.id,s]));let o=!1;for(const s of e){const i=s.targetType==="file"&&typeof s.folderId!="number"?{...s,folderId:0}:s;if(i.targetType==="file"){if(typeof i.fileId=="number"&&t.state.deniedFiles.has(i.fileId))continue}else if(t.state.deniedFolders.has(i.folderId))continue;const r=n.get(i.id);if(r){if(iR(r,i))continue;t.state.pending=t.state.pending.map(a=>a.id===i.id?i:a)}else t.state.pending.push(i);i.invitedAtMs>t.state.sharesVersion&&(t.state.sharesVersion=i.invitedAtMs),o=!0}o&&t.notify()}function hr(e,t={}){const n=et();n.state.pending=n.state.pending.filter(o=>o.id!==e),t.denied&&typeof t.folderId=="number"&&n.state.deniedFolders.add(t.folderId),t.denied&&typeof t.fileId=="number"&&n.state.deniedFiles.add(t.fileId),n.notify()}const rR=de`: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}`,ks=class ks extends Se{constructor(){super(...arguments),this._timer=null,this._abort=null,this._results=[],this._query="",this._open=!1,this._phase="idle",this._error="",this._dropdownStyle="",this._onScrollOrResize=()=>{},this._onInput=t=>{const n=t.target.value;this._query=n,this._scheduleSearch(n)},this._onFocus=()=>{if(this._results.length===0&&this._phase==="idle"){this._scheduleSearch(this._query);return}this._open=!0,this._positionDropdown(),this.requestUpdate()},this._onBlur=()=>{setTimeout(()=>{this._open=!1,this.requestUpdate()},150)},this._pick=t=>{this.emit("os-user-pick",{user:t}),this._results=[],this._open=!1,this._phase="idle",this._query="";const n=this.shadowRoot?.querySelector(".input");n&&(n.value=""),this.requestUpdate()}}connectedCallback(){super.connectedCallback(),this._onScrollOrResize=()=>{this._open&&(this._positionDropdown(),this.requestUpdate())},window.addEventListener("resize",this._onScrollOrResize),window.addEventListener("scroll",this._onScrollOrResize,!0)}disconnectedCallback(){this._timer&&clearTimeout(this._timer),this._abort&&this._abort.abort(),window.removeEventListener("resize",this._onScrollOrResize),window.removeEventListener("scroll",this._onScrollOrResize,!0)}_endpoint(){const t=this.getAttribute("endpoint");return t||window.openStationConfig?.filesUsersSearchUrl||""}_scheduleSearch(t){this._timer&&clearTimeout(this._timer),this._phase="loading",this._open=!0,this._positionDropdown(),this.requestUpdate(),this._timer=setTimeout(()=>this._runSearch(t),200)}async _runSearch(t){const n=this._endpoint();if(!n){this._phase="error",this._error="Search endpoint is not configured.",this._results=[],this._open=!0,this.requestUpdate();return}this._abort&&this._abort.abort();const o=new AbortController;this._abort=o;const s=this.getAttribute("exclude")||"",i=n+"?q="+encodeURIComponent(t)+"&exclude="+encodeURIComponent(s);try{const r={signal:o.signal,credentials:"same-origin"},a=await Fe(i,r,{source:"desktop-mode/files-user-search",silent:!0});if(!a.ok)throw new Error(`HTTP ${a.status}`);const l=await a.json();this._results=l&&Array.isArray(l.users)?l.users:[],this._phase="ready",this._error="",this._open=!0}catch(r){if(r.name==="AbortError")return;this._results=[],this._phase="error",this._error=r.message||"Search failed.",this._open=!0}this._positionDropdown(),this.requestUpdate()}_positionDropdown(){const t=this.shadowRoot?.querySelector(".input");if(!t)return;const n=t.getBoundingClientRect(),o=n.bottom+4,s=n.left,i=n.width,a=window.innerHeight-n.bottom,l=n.top,c=Math.max(120,Math.min(280,Math.max(a,l)-16));a<200&&l>a?this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${n.top-4-c}px`,`width:${i}px`,`max-height:${c}px`].join(";"):this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${o}px`,`width:${i}px`,`max-height:${c}px`].join(";")}_dropdownContent(){if(this._phase==="loading")return J`<div class="empty">Searching…</div>`;if(this._phase==="error")return J`<div class="empty error">${this._error}</div>`;if(this._results.length===0){const t=this._query?"No matches.":"No users available.";return J`<div class="empty">${t}</div>`}return this._results.map(t=>J` |
| 67 |
<button |
| 68 |
type="button" |
| 69 |
class="item" |
| 70 |
role="option" |
| 71 |
@mousedown=${n=>n.preventDefault()} |
| 72 |
@click=${()=>this._pick(t)} |
| 73 |
> |
| 74 |
<img class="avatar" src=${t.avatarUrl} alt="" /> |
| 75 |
<div> |
| 76 |
<div class="name">${t.name}</div> |
| 77 |
<div class="slug">${t.slug}</div> |
| 78 |
</div> |
| 79 |
</button> |
| 80 |
`)}render(){const t=this.getAttribute("placeholder")||"Search users…";return J` |
| 81 |
<input |
| 82 |
class="input" |
| 83 |
type="search" |
| 84 |
placeholder=${t} |
| 85 |
autocomplete="off" |
| 86 |
@input=${this._onInput} |
| 87 |
@focus=${this._onFocus} |
| 88 |
@blur=${this._onBlur} |
| 89 |
.value=${this._query} |
| 90 |
/> |
| 91 |
${this._open?J` |
| 92 |
<div class="dropdown" role="listbox" style=${this._dropdownStyle}> |
| 93 |
${this._dropdownContent()} |
| 94 |
</div> |
| 95 |
`:J``} |
| 96 |
`}};ks.props=["placeholder","exclude","endpoint"],ks.styles=[rR],ks.help=void 0;let Nc=ks;xe("os-user-search",Nc);const aR=de`: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}`,Ss=class Ss extends Se{constructor(){super(...arguments),this._onToggle=t=>{const n=!this._selectedSet().has(t);this.emit("os-role-toggle",{slug:t,selected:n})}}_selectedSet(){const t=this.getAttribute("selected")||"";return new Set(t.split(",").map(n=>n.trim()).filter(n=>n!==""))}_roles(){const t=this.getAttribute("roles");if(t)try{const n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return window.openStationConfig?.shareEligibleRoles||[]}render(){const t=this._roles();if(t.length===0)return J`<span class="empty">No eligible roles.</span>`;const n=this._selectedSet();return J` |
| 97 |
${t.map(o=>{const s=n.has(o.slug);return J` |
| 98 |
<button |
| 99 |
type="button" |
| 100 |
class="chip" |
| 101 |
aria-pressed=${s?"true":"false"} |
| 102 |
@click=${()=>this._onToggle(o.slug)} |
| 103 |
>${o.name}</button> |
| 104 |
`})} |
| 105 |
`}};Ss.props=["selected","roles"],Ss.styles=[aR],Ss.help=void 0;let Dc=Ss;xe("os-role-picker",Dc);const lR=de` ${ft}:host{display:inline-flex;position:relative;padding:3px;background:var( --os-ui-segmented-bg,var( --os-ui-hover,rgba( 0,0,0,0.05 ) ) );border-radius:8px;gap:2px}.os-segmented__thumb{position:absolute;top:3px;bottom:3px;left:0;width:var( --_thumb-w,0px );border-radius:6px;background-color:var( --os-ui-segmented-selected-bg,var( --os-ui-accent,#2271b1 ) );background-image:var( --os-ui-segmented-selected-image,none );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;transform:translateX( var( --_thumb-x,0px ) );pointer-events:none;opacity:0}:host( [ data-thumb ] ) .os-segmented__thumb{opacity:1}:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition:transform var( --_holo-t-slow ) var( --_holo-spring ),width var( --_holo-t-slow ) var( --_holo-ease ),opacity var( --_holo-t-fast ) linear}@media ( prefers-reduced-motion:reduce ){:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition-duration:1ms}}`,cR=de` ${ft} ${Da}:host{flex:1 1 auto;min-width:0}button{appearance:none;display:block;width:100%;padding:6px 13px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --os-ui-fg-muted,#646970 );cursor:pointer;border-radius:6px;transition:background-color var( --_holo-t ) ease,color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,background-position var( --_holo-t ) ease;white-space:nowrap}button:hover{color:var( --os-ui-fg,#1d2327 )}button:focus-visible{outline:none;box-shadow:var( --_holo-focus )}:host( [ aria-checked='true' ] ) button{color:var( --os-ui-segmented-selected-fg,var( --os-ui-fg-on-accent,#fff ) );transition-duration:var( --_holo-t-fast )}:host( [ aria-checked='true' ] ) button::before{display:none}`,As=class As extends Se{render(){return this.setAttribute("role","radio"),J` |
| 106 |
<button |
| 107 |
type="button" |
| 108 |
class="os-holo-sheen" |
| 109 |
@click=${()=>this._onPick()} |
| 110 |
> |
| 111 |
<slot></slot> |
| 112 |
</button> |
| 113 |
`}_onPick(){this.emit("os-segment-pick",{value:this.value})}};As.props=["value"],As.styles=[cR],As.help=void 0;let Rc=As;xe("os-segment",Rc);const Cs=class Cs extends Se{constructor(){super(...arguments),this._resizeObserver=null}connectedCallback(){super.connectedCallback(),this.addEventListener("os-segment-pick",t=>{const n=t.detail;t.stopPropagation(),this.value=n.value,this.emit("os-pick",{value:n.value})}),typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._placeThumb()),this._resizeObserver.observe(this))}disconnectedCallback(){this._resizeObserver?.disconnect(),this._resizeObserver=null}_placeThumb(){if(!this.shadowRoot?.querySelector(".os-segmented__thumb"))return;const n=this.value,o=Array.from(this.querySelectorAll(":scope > os-segment")).find(c=>c.getAttribute("value")===n);if(!o||this.offsetWidth===0){this.removeAttribute("data-thumb");return}const s=this.getBoundingClientRect(),i=s.width/this.offsetWidth,r=Math.abs(i-1)<.02?1:i;if(!(r>0))return;const a=o.getBoundingClientRect(),l=c=>`${Math.round(c*100)/100}px`;this.style.setProperty("--_thumb-x",l((a.left-s.left)/r)),this.style.setProperty("--_thumb-w",l(a.width/r)),this.setAttribute("data-thumb",""),this.hasAttribute("data-thumb-ready")||requestAnimationFrame(()=>this.setAttribute("data-thumb-ready",""))}set items(t){const n=this.querySelectorAll(":scope > os-segment");for(const i of Array.from(n))i.remove();for(const i of t){const r=document.createElement("os-segment");r.setAttribute("value",i.value),r.textContent=i.label,this.appendChild(r)}const o=this.value;!(o!==null&&t.some(i=>i.value===o))&&t.length>0?this.value=t[0].value:this.requestUpdate()}render(){const t=this.label||"";t&&this.setAttribute("aria-label",t),this.setAttribute("role","radiogroup");const n=this.value;return queueMicrotask(()=>{const o=this.querySelectorAll("os-segment");for(const s of Array.from(o)){const i=s.getAttribute("value");s.setAttribute("aria-checked",i===n?"true":"false")}this._placeThumb()}),J`<span class="os-segmented__thumb" aria-hidden="true"></span |
| 114 |
><slot></slot>`}};Cs.props=["value","label"],Cs.styles=[lR],Cs.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <os-segment> children where exactly one is active.",status:"stable",props:[{name:"value",type:"string",description:"Currently selected segment value. Mirrored onto child aria-checked."},{name:"label",type:"string",description:"aria-label for the radiogroup."}],slots:[{name:"(default)",description:'<os-segment value="…"> children.'}],events:[{name:"os-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--os-window-bg",description:"Pill background."},{name:"--os-ui-fg",description:"Active label colour."},{name:"--os-ui-fg-muted",description:"Inactive label colour."}],example:J` |
| 115 |
<os-segmented value="md" label="Dock size"> |
| 116 |
<os-segment value="sm">Small</os-segment> |
| 117 |
<os-segment value="md">Medium</os-segment> |
| 118 |
<os-segment value="lg">Large</os-segment> |
| 119 |
</os-segmented> |
| 120 |
`};let Oc=Cs;xe("os-segmented",Oc);const dR=de`: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}`,uR=de` ${ft}:host{display:flex;align-items:center;gap:12px;min-width:280px;max-width:420px;padding:10px 14px;background-color:var( --os-ui-toast-bg,var( --os-ui-modal-bg,#1d2327 ) );background-image:var( --os-ui-toast-bg-image,none );background-repeat:var( --os-ui-toast-bg-image-repeat,repeat );background-size:var( --os-ui-toast-bg-image-size,auto );background-position:var( --os-ui-toast-bg-image-position,center );color:var( --os-ui-fg-on-accent,#fff );border-radius:10px;border:1px solid var( --os-ui-border,rgba( 255,255,255,0.12 ) );box-shadow:0 10px 30px rgba( 0,0,0,0.4 ),0 2px 6px rgba( 0,0,0,0.18 ),inset 0 0 0 1px rgba( 255,255,255,0.04 );font-size:13px;line-height:1.4;opacity:0;transform:translateY( -10px ) scale( 0.97 );transition:opacity var( --_holo-t-fast ) linear,transform var( --_holo-t ) var( --_holo-spring );pointer-events:auto}:host( [ state='in' ] ){opacity:1;transform:translateY( 0 ) scale( 1 )}:host( [ state='out' ] ){opacity:0;transform:translateX( 16px ) scale( 0.97 );transition:opacity var( --_holo-t-fast ) linear,transform var( --_holo-t ) var( --_holo-ease )}.os-toast__label{flex:1}button[ hidden ]{display:none}button{flex-shrink:0;padding:4px 10px;border:none;border-radius:4px;background:var( --os-ui-hover,rgba( 255,255,255,0.12 ) );color:var( --os-ui-fg-on-accent,#fff );font:inherit;font-size:12px;font-weight:500;cursor:pointer;transition:background-color 0.12s ease}button:hover{background:var( --os-ui-scrim,rgba( 255,255,255,0.22 ) )}button:focus-visible{outline:2px solid var( --os-ui-border,rgba( 255,255,255,0.6 ) );outline-offset:2px}.os-toast__close{display:inline-flex;align-items:center;justify-content:center;padding:4px;border-radius:6px;background:transparent;color:var( --os-ui-fg-muted,rgba( 255,255,255,0.7 ) )}.os-toast__close:hover{background:var( --os-ui-hover,rgba( 255,255,255,0.14 ) );color:var( --os-ui-fg-on-accent,#fff )}@media ( prefers-reduced-motion:reduce ){:host{transition-duration:0.01ms}}`,Ar=class Ar extends Se{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return J`<slot></slot>`}};Ar.styles=[dR],Ar.help=void 0;let Mc=Ar;xe("os-toast-container",Mc);const Is=class Is extends Se{constructor(){super(...arguments),this._hovered=!1,this._focused=!1,this._onEnter=()=>{this._hovered=!0,this._syncHold()},this._onLeave=()=>{this._hovered=!1,this._syncHold()},this._onFocusIn=()=>{this._focused=!0,this._syncHold()},this._onFocusOut=t=>{const n=t.relatedTarget;n instanceof Node&&this._containsDeep(n)||(this._focused=!1,this._syncHold())}}connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.addEventListener("mouseenter",this._onEnter),this.addEventListener("mouseleave",this._onLeave),this.addEventListener("focusin",this._onFocusIn),this.addEventListener("focusout",this._onFocusOut)}disconnectedCallback(){this.removeEventListener("mouseenter",this._onEnter),this.removeEventListener("mouseleave",this._onLeave),this.removeEventListener("focusin",this._onFocusIn),this.removeEventListener("focusout",this._onFocusOut)}_containsDeep(t){let n=t;for(;n;){if(n===this)return!0;const o=n.parentNode;n=o instanceof ShadowRoot?o.host:o}return!1}_syncHold(){const t=this._hovered||this._focused;t!==this.hasAttribute("held")&&(t?this.setAttribute("held",""):this.removeAttribute("held"),this.emit("os-toast-hold",{held:t}))}render(){const t=this.action||"",n=this.hasAttribute("dismissible");return J` |
| 121 |
<span class="os-toast__label"><slot></slot></span> |
| 122 |
<button |
| 123 |
type="button" |
| 124 |
?hidden=${!t} |
| 125 |
@click=${o=>this._onAction(o)} |
| 126 |
> |
| 127 |
${t} |
| 128 |
</button> |
| 129 |
<button |
| 130 |
type="button" |
| 131 |
class="os-toast__close" |
| 132 |
aria-label=${E("Dismiss")} |
| 133 |
?hidden=${!n} |
| 134 |
@click=${o=>this._onDismiss(o)} |
| 135 |
> |
| 136 |
${Pr("close",{size:16})} |
| 137 |
</button> |
| 138 |
`}_onAction(t){t.preventDefault(),t.stopPropagation(),this.emit("os-toast-action",{})}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.emit("os-toast-dismiss",{})}};Is.props=["action","state","dismissible"],Is.styles=[uR],Is.help={title:"Toast",summary:'Single transient notification. Message is slotted; fade-in / fade-out is CSS-driven by flipping the state attribute between "in" and "out". Usually created via the showToast() helper rather than authored by hand.',status:"stable",props:[{name:"action",type:"string",description:"Optional action button label. When set, a button renders on the right and emits os-toast-action on click."},{name:"state",type:"'in' | 'out'",description:'Drives the CSS fade transition. Set to "in" when rendered, flip to "out" before removal.'},{name:"dismissible",type:"boolean",description:"When set, a close (×) button renders on the right and emits os-toast-dismiss on click. Use for persistent toasts the user must be able to close."},{name:"held",type:"boolean (reflected, read-only)",description:"Set by the component while the pointer is over the toast or focus is inside it. showToast() pauses the auto-dismiss timer for as long as it is present. Do not set it by hand — pass `persistent` for a toast that should never expire."}],slots:[{name:"(default)",description:"Message text."}],events:[{name:"os-toast-action",description:"Fires when the action button is clicked.",detail:"{}"},{name:"os-toast-dismiss",description:"Fires when the close (×) button is clicked.",detail:"{}"},{name:"os-toast-hold",description:"Fires when the toast starts or stops being attended to — pointer over it, or focus inside it. showToast() pauses the auto-dismiss timer while held is true.",detail:"{ held: boolean }"}],example:J` |
| 139 |
<os-toast state="in" action="Undo">Post moved to trash.</os-toast> |
| 140 |
`};let Pc=Is;xe("os-toast",Pc);function My(e,t){const n=document.createElement("os-segmented");n.setAttribute("value",e),n.setAttribute("label","Capability"),n.style.setProperty("--os-ui-segmented-bg","rgba(255,255,255,0.06)"),n.style.setProperty("--os-window-bg","var(--wp-admin-theme-color, #2271b1)"),n.style.setProperty("--os-ui-fg","#fff"),n.style.setProperty("--os-ui-fg-muted","rgba(255,255,255,0.65)");const o=document.createElement("os-segment");o.setAttribute("value","read"),o.textContent="Read",n.appendChild(o);const s=document.createElement("os-segment");return s.setAttribute("value","write"),s.textContent="Read + Write",n.appendChild(s),n.addEventListener("os-pick",i=>{const r=i.detail;t(r.value)}),n}function Wc(e,t,n={}){const o=document.createElement("os-button");o.setAttribute("variant","ghost"),o.setAttribute("aria-label",n.danger?"Remove":"Dismiss"),o.textContent=e;const s=n.danger?"#ff8080":"rgba(255,255,255,0.75)",i=n.danger?"1px solid rgba(255,128,128,0.45)":"1px solid rgba(255,255,255,0.18)";return o.style.setProperty("--os-ui-button-fg",s),o.style.setProperty("--os-ui-button-border",i),o.style.setProperty("--os-ui-button-padding","6px 12px"),o.style.setProperty("--os-ui-button-border-radius","7px"),o.style.setProperty("--os-ui-button-min-height","34px"),o.style.minWidth="34px",o.style.fontSize="18px",o.style.lineHeight="1",o.addEventListener("click",t),o}async function $c(e){const t=document.createElement("os-modal");t.setAttribute("open",""),t.setAttribute("size","lg"),t.setAttribute("title",`Share "${e.folderName}"`),document.body.appendChild(t);let n=[],o=[];const s=()=>{t.innerHTML="";const l=document.createElement("div");l.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",l.textContent=e.ownerName?`Owner: ${e.ownerName} — cannot be changed`:"Owner cannot be changed",t.appendChild(l);const c=document.createElement("div");c.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const d=document.createElement("div");d.textContent="Add people",d.style.cssText="font-weight:600;",c.appendChild(d);const u=document.createElement("os-user-search"),f=n.filter(_=>_.principalType==="user").map(_=>_.principalRef).concat(o.filter(_=>_.kind==="user").map(_=>_.ref));u.setAttribute("exclude",f.join(",")),u.setAttribute("placeholder","Search users…"),u.addEventListener("os-user-pick",_=>{const O=_.detail;o.push({kind:"user",ref:String(O.user.id),label:O.user.name,cap:"read"}),s()}),c.appendChild(u),t.appendChild(c);const p=document.createElement("div");p.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const w=document.createElement("div");w.textContent="Add roles",w.style.cssText="font-weight:600;",p.appendChild(w);const m=document.createElement("os-role-picker"),h=n.filter(_=>_.principalType==="role").map(_=>_.principalRef),y=o.filter(_=>_.kind==="role").map(_=>_.ref);if(m.setAttribute("selected",[...h,...y].join(",")),m.addEventListener("os-role-toggle",_=>{const O=_.detail,P=n.find($=>$.principalType==="role"&&$.principalRef===O.slug);if(P){O.selected||r(P);return}if(O.selected){const $=(window.openStationConfig?.shareEligibleRoles??[]).find(F=>F.slug===O.slug);o.push({kind:"role",ref:O.slug,label:$?$.name:O.slug,cap:"read"})}else o=o.filter($=>!($.kind==="role"&&$.ref===O.slug));s()}),p.appendChild(m),t.appendChild(p),o.length>0){const _=document.createElement("div");_.style.cssText="border:1px dashed rgba(255,255,255,0.18);border-radius:8px;padding:10px;margin-bottom:14px;";const O=document.createElement("div");O.textContent="New invites (not sent yet)",O.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",_.appendChild(O);for(const $ of o){const F=document.createElement("div");F.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const k=document.createElement("span");k.textContent=$.kind==="role"?`Role: ${$.label}`:$.label,k.style.flex="1",F.appendChild(k);const W=My($.cap,g=>{$.cap=g});F.appendChild(W);const N=Wc("×",()=>{o=o.filter(g=>!(g.kind===$.kind&&g.ref===$.ref)),s()});F.appendChild(N),_.appendChild(F)}const P=document.createElement("os-button");P.setAttribute("variant","primary"),P.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,P.style.marginTop="8px",P.addEventListener("click",async()=>{if(o.length===0)return;P.setAttribute("busy",""),P.setAttribute("disabled","");const $=o.slice();let F=0,k=null;for(const W of $)try{await Rw(e.folderId,{principalType:W.kind,principalRef:W.ref,capability:W.cap}),F++}catch(N){k=N;break}F>0&&(o=o.slice(F));try{await i()}catch{}Q(k?{message:`Could not send invites: ${k.message}`}:{message:F===1?"Invite sent.":`${F} invites sent.`}),P.removeAttribute("busy"),P.removeAttribute("disabled"),s()}),_.appendChild(P),t.appendChild(_)}const v=document.createElement("div");if(v.textContent="Who has access",v.style.cssText="font-weight:600;margin:8px 0 6px;",t.appendChild(v),n.length===0){const _=document.createElement("div");_.textContent="Only you can see this folder.",_.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(_)}else for(const _ of n){const O=document.createElement("div");O.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const P=document.createElement("div");if(P.style.flex="1",P.textContent=_.principalType==="role"?`Role: ${_.displayName}`:_.displayName,_.state==="pending"){const W=document.createElement("span");W.textContent=" · pending",W.style.cssText="opacity:0.6;font-size:12px;",P.appendChild(W)}else if(_.state==="denied"){const W=document.createElement("span");W.textContent=" · denied",W.style.cssText="color:#d63638;font-size:12px;",P.appendChild(W)}O.appendChild(P);const $=_.capability==="write"?"write":"read",F=My($,W=>{a(_,W)});O.appendChild(F);const k=Wc("×",()=>{r(_)},{danger:!0});O.appendChild(k),t.appendChild(O)}const A=document.createElement("div");A.setAttribute("slot","footer"),A.style.display="flex",A.style.justifyContent="flex-end",A.style.gap="10px",A.style.flexWrap="wrap";const D=document.createElement("os-button");D.setAttribute("variant","secondary"),D.textContent="Done",D.addEventListener("click",()=>t.remove()),A.appendChild(D),t.appendChild(A)},i=async()=>{try{n=(await Dw(e.folderId)).shares,nR(e.folderId,n)}catch(l){Q({message:`Could not load shares: ${l.message}`})}s()},r=async l=>{try{await Mw(e.folderId,l.id),sR(e.folderId,l.id),await i(),Q({message:"Access revoked."})}catch(c){Q({message:`Could not revoke: ${c.message}`})}},a=async(l,c)=>{try{const d=await Ow(e.folderId,l.id,c);oR(d),await i()}catch(d){Q({message:`Could not update capability: ${d.message}`})}};t.addEventListener("os-modal-cancel",()=>t.remove()),s(),await i()}async function fR(e){const t=document.createElement("os-modal");t.setAttribute("open",""),t.setAttribute("size","md"),t.setAttribute("title",`Share "${e.fileName}"`),document.body.appendChild(t);let n=[];const o=async()=>{try{n=(await Uw(e.fileId)).shares}catch(i){Q({message:`Could not load shares: ${i.message}`})}s()},s=()=>{t.innerHTML="";const i=document.createElement("div");i.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",i.textContent="People you share with can view and download this file. Only you can move, rename, or delete it.",t.appendChild(i);const r=document.createElement("div");r.textContent="Add people",r.style.cssText="font-weight:600;margin-bottom:6px;",t.appendChild(r);const a=document.createElement("os-user-search");a.setAttribute("exclude",n.map(u=>u.principalRef).join(",")),a.setAttribute("placeholder","Search users…"),a.addEventListener("os-user-pick",u=>{const f=u.detail;(async()=>{try{await Fw(e.fileId,f.user.id),Q({message:`Invite sent to ${f.user.name}.`})}catch(p){Q({message:`Could not invite: ${p.message}`})}await o()})()}),t.appendChild(a);const l=document.createElement("div");if(l.textContent="Who has access",l.style.cssText="font-weight:600;margin:14px 0 6px;",t.appendChild(l),n.length===0){const u=document.createElement("div");u.textContent="Only you can see this file.",u.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(u)}else for(const u of n){const f=document.createElement("div");f.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const p=document.createElement("div");p.style.flex="1";const w=u.displayName;if(p.textContent=w||`User #${u.principalRef}`,u.state==="pending"){const y=document.createElement("span");y.textContent=" · pending",y.style.cssText="opacity:0.6;font-size:12px;",p.appendChild(y)}else if(u.state==="denied"){const y=document.createElement("span");y.textContent=" · denied",y.style.cssText="color:#d63638;font-size:12px;",p.appendChild(y)}f.appendChild(p);const m=document.createElement("span");m.textContent="Read + download",m.style.cssText="opacity:0.6;font-size:12px;",f.appendChild(m);const h=Wc("×",()=>{(async()=>{try{await Bw(e.fileId,u.id),Q({message:"Access revoked."})}catch(y){Q({message:`Could not revoke: ${y.message}`})}await o()})()},{danger:!0});f.appendChild(h),t.appendChild(f)}const c=document.createElement("div");c.setAttribute("slot","footer"),c.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;";const d=document.createElement("os-button");d.setAttribute("variant","secondary"),d.textContent="Done",d.addEventListener("click",()=>t.remove()),c.appendChild(d),t.appendChild(c)};t.addEventListener("os-modal-cancel",()=>t.remove()),s(),await o()}function Py(e){return new Promise(t=>{const n=document.createElement("os-modal");n.setAttribute("open",""),n.setAttribute("title",e.fileName?`${e.ownerName??"Someone"} shared "${e.fileName}" with you`:"File shared with you");const o=document.createElement("div");o.innerHTML=` |
| 141 |
<p style="margin: 0 0 12px;">Accept the invite to add this file to your desktop.</p> |
| 142 |
<p style="margin: 0; opacity: 0.75;">Access level: <strong>Read + download</strong></p> |
| 143 |
`,n.appendChild(o);const s=document.createElement("div");s.setAttribute("slot","footer"),s.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;";const i=document.createElement("os-button");i.setAttribute("variant","secondary"),i.textContent="Decide later",i.addEventListener("click",()=>{n.remove(),t("dismissed")});const r=document.createElement("os-button");r.setAttribute("variant","danger"),r.textContent="Deny",r.addEventListener("click",async()=>{r.setAttribute("busy",""),r.setAttribute("disabled","");try{await zw(e.fileId,e.id),et().state.deniedFiles.add(e.fileId),et().notify(),n.remove(),t("denied")}catch(l){Q({message:`Could not deny: ${l.message}`}),r.removeAttribute("busy"),r.removeAttribute("disabled")}});const a=document.createElement("os-button");a.setAttribute("variant","primary"),a.textContent="Accept",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await Hw(e.fileId,e.id);try{const l=await Le(0);at(0,l.placements)}catch{}n.remove(),t("accepted")}catch(l){Q({message:`Could not accept: ${l.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}}),s.appendChild(i),s.appendChild(r),s.appendChild(a),n.appendChild(s),n.addEventListener("os-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}function Wy(e){return new Promise(t=>{const n=document.createElement("os-modal");n.setAttribute("open",""),n.setAttribute("title",e.folderName?`${e.ownerName??"Someone"} shared "${e.folderName}" with you`:"Folder shared with you");const o=document.createElement("div"),s=e.capability==="write"?"Read + Write":"Read";o.innerHTML=` |
| 144 |
<p style="margin: 0 0 12px;">Accept the invite to add this folder to your desktop.</p> |
| 145 |
<p style="margin: 0; opacity: 0.75;">Access level: <strong>${s}</strong></p> |
| 146 |
`,n.appendChild(o);const i=document.createElement("div");i.setAttribute("slot","footer"),i.style.display="flex",i.style.justifyContent="flex-end",i.style.gap="10px",i.style.flexWrap="wrap";const r=document.createElement("os-button");r.setAttribute("variant","secondary"),r.textContent="Decide later",r.addEventListener("click",()=>{n.remove(),t("dismissed")});const a=document.createElement("os-button");a.setAttribute("variant","danger"),a.textContent="Deny",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await Ww(e.folderId,e.id),et().state.deniedFolders.add(e.folderId),et().notify(),n.remove(),t("denied")}catch(c){Q({message:`Could not deny: ${c.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}});const l=document.createElement("os-button");l.setAttribute("variant","primary"),l.textContent="Accept",l.addEventListener("click",async()=>{l.setAttribute("busy",""),l.setAttribute("disabled","");try{await Pw(e.folderId,e.id);try{const c=await Le(0);at(0,c.placements)}catch{}n.remove(),t("accepted")}catch(c){Q({message:`Could not accept: ${c.message}`}),l.removeAttribute("busy"),l.removeAttribute("disabled")}}),i.appendChild(r),i.appendChild(a),i.appendChild(l),n.appendChild(i),n.addEventListener("os-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}const pR=Object.freeze(Object.defineProperty({__proto__:null,openFileShareModal:fR,openPendingFileInviteModal:Py,openPendingInviteModal:Wy,openShareSettingsModal:$c},Symbol.toStringTag,{value:"Module"}));function $y(){return Number(window.openStationConfig?.currentUserId??0)}function hR(e){window.wp?.os?.windowManager?.getById?.(e)?.close?.()}function Uc(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function Uy(e){const t=Lt().folders.get(e);return t?Number(t.ownerId):0}function Fy(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function mR(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function gR(e){return Number(e.file.ownerId??0)}function wR(){Qn("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!Uc())return e;const n=mR(t);if(n===null)return e;const o=Uy(n)||gR(t),s=$y();if(o===s){const r=!!t.file.shareSummary?.shared?"Manage sharing…":"Share folder…";e.push({id:"desktop-mode/folder-share",label:r,icon:"dashicons-share",sort:30,onClick:()=>{$c({folderId:n,folderName:t.file.title||`Folder ${n}`})}})}else o>0&&e.push({id:"desktop-mode/folder-leave",label:"Leave shared folder",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await Bn({title:"Leave this folder?",message:"The folder will be removed from your desktop. The original and its contents are not deleted; the owner keeps them.",confirmLabel:"Leave",danger:!0}))try{await $w(n),Xo(t.id);try{const a=await Le(0);at(0,a.placements)}catch{}const r=`os-folder-${n}`;hR(r),Q({message:"You left the shared folder."})}catch(r){Q({message:`Could not leave: ${r.message}`})}}});return e}),ki({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!Uc())return!1;const t=e.config.baseId??e.id,n=Fy(t);return n===null?!1:Uy(n)===$y()},onClick:e=>{if(!Uc())return;const t=e.config.baseId??e.id,n=Fy(t);n!==null&&$c({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),Z("os.files.tile-rendered","desktop-mode/folder-share",e=>{const{tile:t,placement:n}=e;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||t.querySelector(".os-file-tile__share-badge"))return;const s=document.createElement("span");s.className="os-file-tile__share-badge dashicons dashicons-share",s.setAttribute("aria-label","Shared folder"),s.title="Shared folder",s.style.cssText=["position:absolute","top:6px","inset-inline-end:6px","background:rgba(0,0,0,0.55)","color:#fff","border-radius:50%","width:18px","height:18px","font-size:12px","line-height:18px","text-align:center","pointer-events:none"].join(";"),t.appendChild(s)})}const By=new Set;function yR(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function bR(){const e=et(),t=n=>{if(yR()){for(const o of n.pending)if(!By.has(o.id)){if(By.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;Py({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?hr(o.id):i==="denied"&&hr(o.id,{denied:!0,fileId:s})});continue}Wy({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?hr(o.id):s==="denied"&&hr(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function vR(){return Number(window.openStationConfig?.currentUserId??0)}function Hy(){return window.openStationConfig?.desktopStorage??{}}function _R(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function ER(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function kR(){Qn("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&Hy().zipAvailable){const i=Number(t.file.ref);return Number.isFinite(i)&&i>0&&e.push({id:"desktop-mode/folder-zip-download",label:"Download as .zip",icon:"dashicons-download",sort:45,onClick:()=>{dr(Vw(i))}}),e}const n=ER(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{dr(Yt(n))}});const o=Number(t.file.ownerId??0),s=vR();return o===s&&_R()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{Promise.resolve().then(()=>pR).then(i=>{i.openFileShareModal({fileId:n,fileName:t.file.title||`File ${n}`})})}}):o>0&&o!==s&&t.parentId===0&&e.push({id:"desktop-mode/upload-leave",label:"Leave shared file",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await Bn({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 Gw(n),Xo(t.id);try{const r=await Le(0);at(0,r.placements)}catch{}Q({message:"You left the shared file."})}catch(r){Q({message:`Could not leave: ${r.message}`})}}}),e}),Qn("os.wallpaper-context-menu","desktop-mode/uploads",e=>(Hy().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>zy(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>zy(!0)})),e))}function zy(e){const t=document.createElement("input");t.type="file",e?t.setAttribute("webkitdirectory",""):t.multiple=!0,t.style.display="none",document.body.appendChild(t),t.addEventListener("change",()=>{const n=t.files?Array.from(t.files):[];t.remove(),n.length!==0&&SR(n,e)}),t.click()}async function SR(e,t){const n=window.openStationConfig,o=n?.dropConfig??{enabled:!1,allowedMimes:[],maxSize:0},s=await Promise.resolve().then(()=>eP),{accepted:i,rejected:r}=s.partitionByPolicy(e,o);if(r.length>0&&Q({message:r.length===1?r[0].message:`${r.length} files can't be uploaded.`}),i.length===0)return;const a=i.map(({file:c,mime:d})=>({file:c,mime:d,fields:s.defaultFields(c,d),relativePath:t?c.webkitRelativePath??"":""}));await(await Promise.resolve().then(()=>Zb)).openUploadDialog({entries:a,context:{surface:"folder",folderId:0,x:0,y:0},mediaUrl:n?.mediaUrl??"",restNonce:n?.restNonce??"",filesUrl:n?.filesUrl,storage:n?.desktopStorage,forceDesktop:t,preferDesktop:!0,mediaMaxBytes:o.maxSize})}mN(),ZD(),qD(),QD(),tR(),wR(),kR();const Fc=window.openStationConfig?.serverPendingShares;Array.isArray(Fc)&&Fc.length>0&&Oy(Fc),bR();const He={DesktopFile:gw,registerType:Ve,unregisterType:lN,getType:cN,getTypes:ww,resolve:xt,subscribe:dN,registerOpener:Be,unregisterOpener:uN,getOpener:fN,getOpeners:vw,getOpenersForType:sc,resolveOpener:ic,subscribeOpeners:_w,getUserAssociations:oc,open:qo,registerTilePayloadHandler:Ji,rest:CN,store:{get:Je,getState:Lt,subscribe:mc,setFolderPlacements:at,upsertPlacement:Xi,removePlacement:Xo,setFolders:Zi,upsertFolder:pc,removeFolder:hc}},Gy="__synthFromDockItem";function AR(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function CR(e,t){const n=!!e.tile,o=t[e.id];return{id:AR(e.id),parentId:0,x:o?o.x:0,y:o?o.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Gy]:e.id},file:{type:"shortcut",ref:n?e.id:`dock-promoted:${e.id}`,title:e.title,icon:e.icon,previewUrl:"",exists:!0,...n?{shortcutSystemTile:e.id}:{shortcutUrl:e.menu?.url??""}}}}let Bc=!1;const Hc=new Map;function IR(e){const t=window.wp?.os;if(!t?.getOsSettings||!t?.updateOsSettings)return;const o={...t.getOsSettings().dockPromotedPositions??{}};let s=!1;for(const i of e)i in o&&(delete o[i],s=!0);s&&t.updateOsSettings({dockPromotedPositions:o})}function xR(e,t,n={}){if(!Bc){Bc=!0;try{const s=He.store.getState().placementsByFolder.get(0)??[],i=new Set(e.map(d=>d.id)),r=new Map;for(const d of s){const u=d.meta&&typeof d.meta=="object"?d.meta[Gy]:null;typeof u=="string"&&r.set(u,d)}const a=new Set;for(const d of t)d.entry&&a.add(d.entry.id);const l=new Map;for(const d of s){const u=d?.file?.ref;typeof u=="string"&&a.has(u)&&l.set(u,d)}for(const d of e)d.entry||r.has(d.id)||He.store.upsertPlacement(CR(d,n));const c=[];for(const[d,u]of r)i.has(d)||(He.store.removePlacement(u.id),n[d]&&c.push(d));c.length>0&&IR(c);for(const d of t){const u=d.entry;if(!u)continue;const f=l.get(u.id);if(!i.has(d.id)){f&&(Hc.set(u.id,f),He.store.removePlacement(f.id));continue}if(!f){const p=Hc.get(u.id);p&&(He.store.upsertPlacement(p),Hc.delete(u.id))}}}finally{Bc=!1}}}function LR(e){queueMicrotask(e);const t=He.store.subscribe(e),n="desktop-mode/shortcuts-sync";return Z(b.DOCK_ITEM_APPENDED,n,e),()=>{t(),Tr(b.DOCK_ITEM_APPENDED,n)}}const TR=de`: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}}`,jy={xs:20,sm:24,md:40,lg:64,xl:96},Vy=new Set(["online","inactive","offline"]),xs=class xs extends Se{constructor(){super(...arguments),this._presenceHandler=null,this._imgFailed=!1,this._onPointerMove=null,this._onPointerEnter=null,this._onPointerLeave=null,this._tiltRaf=0,this._pendingTiltX="0deg",this._pendingTiltY="0deg",this._pendingGlareX="50%",this._pendingGlareY="50%"}connectedCallback(){super.connectedCallback(),this._maybeAttachPresenceListener(),this._attachHoverEffect()}disconnectedCallback(){this._presenceHandler&&(document.removeEventListener("os-presence-changed",this._presenceHandler),this._presenceHandler=null),this._detachHoverEffect()}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),t==="src"&&(this._imgFailed=!1),(t==="user-id"||t==="presence")&&this._maybeAttachPresenceListener()}render(){const t=this._attr("src"),n=this._attr("name")||"",o=this._attr("alt"),s=o!==null?o:n,i=this._attr("size"),r=this._resolveSize(i),a=this._presenceForRender(),l=this._attr("clickable")!==null;this.style.setProperty("--os-ui-avatar-size",`${r}px`);const c=t&&!this._imgFailed?"":this._initialsBg(n),d=t&&!this._imgFailed?J`<img |
| 147 |
src=${t} |
| 148 |
alt=${s} |
| 149 |
@error=${()=>this._onImgError()} |
| 150 |
loading="lazy" |
| 151 |
/>`:this._initials(n),u=a?J`<span |
| 152 |
class=${`os-avatar__dot os-avatar__dot--${a}`} |
| 153 |
aria-label=${this._presenceLabel(a)} |
| 154 |
></span>`:J``;return l?J` |
| 155 |
<button |
| 156 |
type="button" |
| 157 |
class="os-avatar__tile" |
| 158 |
aria-label=${s||"User"} |
| 159 |
style=${c?`background:${c};`:""} |
| 160 |
@click=${f=>this._onClick(f)} |
| 161 |
>${d}</button> |
| 162 |
${u} |
| 163 |
`:J` |
| 164 |
<div |
| 165 |
class="os-avatar__tile" |
| 166 |
role="img" |
| 167 |
aria-label=${s||"User"} |
| 168 |
style=${c?`background:${c};`:""} |
| 169 |
>${d}</div> |
| 170 |
${u} |
| 171 |
`}_attr(t){return this.getAttribute(t)}_resolveSize(t){if(!t)return 32;if(t in jy)return jy[t];const n=Number(t);return Number.isFinite(n)&&n>0?n:32}_initials(t){const n=t.trim();return n?Array.from(n)[0]?.toUpperCase()??"?":"?"}_initialsBg(t){const n=vn(t);return`linear-gradient(135deg, hsl(${n} 62% 55%), hsl(${(n+24)%360} 58% 42%))`}_presenceForRender(){const t=this._attr("presence");return t&&Vy.has(t)?t:null}_presenceLabel(t){switch(t){case"online":return"Online";case"inactive":return"Inactive";case"offline":return"Offline"}}_onImgError(){this._imgFailed=!0,this.requestUpdate()}_onClick(t){const n=this._attr("user-id"),o={userId:n!==null&&Number(n)||null,originalEvent:t};this.emit("os-avatar-click",o)}_attachHoverEffect(){typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(this._onPointerEnter=()=>{this.style.setProperty("--os-ui-avatar-hover","1")},this._onPointerLeave=()=>{this.style.setProperty("--os-ui-avatar-hover","0"),this._pendingTiltX="0deg",this._pendingTiltY="0deg",this._pendingGlareX="50%",this._pendingGlareY="50%",this._flushTilt()},this._onPointerMove=n=>{const o=this.getBoundingClientRect();if(o.width===0||o.height===0)return;const s=(n.clientX-o.left)/o.width-.5,i=(n.clientY-o.top)/o.height-.5,r=14;this._pendingTiltY=`${(s*r).toFixed(2)}deg`,this._pendingTiltX=`${(-i*r).toFixed(2)}deg`;const a=Math.max(0,Math.min(100,(s+.5)*100)),l=Math.max(0,Math.min(100,(i+.5)*100));this._pendingGlareX=`${a.toFixed(1)}%`,this._pendingGlareY=`${l.toFixed(1)}%`,this._tiltRaf||(this._tiltRaf=requestAnimationFrame(()=>this._flushTilt()))},this.addEventListener("pointerenter",this._onPointerEnter),this.addEventListener("pointerleave",this._onPointerLeave),this.addEventListener("pointermove",this._onPointerMove))}_flushTilt(){this._tiltRaf=0,this.style.setProperty("--os-ui-avatar-tilt-x",this._pendingTiltX),this.style.setProperty("--os-ui-avatar-tilt-y",this._pendingTiltY),this.style.setProperty("--os-ui-avatar-glare-x",this._pendingGlareX),this.style.setProperty("--os-ui-avatar-glare-y",this._pendingGlareY)}_detachHoverEffect(){this._onPointerMove&&(this.removeEventListener("pointermove",this._onPointerMove),this._onPointerMove=null),this._onPointerEnter&&(this.removeEventListener("pointerenter",this._onPointerEnter),this._onPointerEnter=null),this._onPointerLeave&&(this.removeEventListener("pointerleave",this._onPointerLeave),this._onPointerLeave=null),this._tiltRaf&&(cancelAnimationFrame(this._tiltRaf),this._tiltRaf=0)}_maybeAttachPresenceListener(){const t=this._attr("user-id"),n=this._attr("presence"),o=!!t&&!n;o&&!this._presenceHandler?(this._presenceHandler=s=>{const i=s.detail;i&&String(i.userId)===String(t)&&i.newStatus&&Vy.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)}};xs.props=["src","alt","name","size","presence","userId","clickable"],xs.styles=[TR],xs.help=void 0;let zc=xs;xe("os-avatar",zc);const NR=de`:host{display:inline-flex;align-items:center;gap:6px;font-size:var( --os-ui-save-status-font-size,11px );line-height:1;color:var( --os-ui-save-status-fg,currentColor );vertical-align:middle;min-width:0;opacity:1;pointer-events:auto}.os-save-status__indicator{display:inline-flex;align-items:center;justify-content:center;width:var( --os-ui-save-status-size,12px );height:var( --os-ui-save-status-size,12px );border-radius:50%;flex-shrink:0;box-sizing:border-box;background:var( --os-ui-save-status-bg,transparent );border:2px solid var( --os-ui-save-status-idle-color,color-mix( in srgb,var( --wp-admin-theme-color,#2271b1 ) 55%,transparent ) );color:var( --wp-admin-theme-color,#2271b1 );transition:background-color 0.2s ease,border-color 0.2s ease,box-shadow 0.2s ease}:host( [ phase='pending' ] ) .os-save-status__indicator,:host( [ phase='saving' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:os-save-status-pulse 1.2s ease-in-out infinite}:host( [ animation='modem' ][ phase='pending' ] ) .os-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:os-save-status-modem-stutter 1.8s ease-in-out infinite,os-save-status-modem-glow 2.4s ease-in-out infinite}@keyframes os-save-status-modem-stutter{0%,4%{opacity:1}5%,30%{opacity:0.22}31%,36%{opacity:1}37%,39%{opacity:0.22}40%,44%{opacity:1}45%,67%{opacity:0.22}68%,76%{opacity:1}77%,100%{opacity:0.22}}@keyframes os-save-status-modem-glow{0%,12%{box-shadow:0 0 0 0 transparent}13%,22%{box-shadow:0 0 4px 0 currentColor}23%,50%{box-shadow:0 0 0 0 transparent}51%,58%{box-shadow:0 0 4px 0 currentColor}59%,84%{box-shadow:0 0 0 0 transparent}85%,94%{box-shadow:0 0 5px 0 currentColor}95%,100%{box-shadow:0 0 0 0 transparent}}@media ( prefers-reduced-motion:reduce ){:host( [ phase='pending' ] ) .os-save-status__indicator,:host( [ phase='saving' ] ) .os-save-status__indicator,:host( [ animation='modem' ][ phase='pending' ] ) .os-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .os-save-status__indicator{animation:none;opacity:0.85}}:host( [ phase='saved' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-saved-bg,var( --os-ui-success-fg,#1d6f42 ) );border-color:transparent;color:var( --os-ui-save-status-saved-bg,var( --os-ui-success-fg,#1d6f42 ) )}:host( [ phase='failed' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) );border-color:transparent;color:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) );animation:os-save-status-pulse 0.8s ease-in-out 2}:host( [ variant='ring' ] ) .os-save-status__indicator{background:transparent}:host( [ variant='ring' ][ phase='pending' ] ) .os-save-status__indicator,:host( [ variant='ring' ][ phase='saving' ] ) .os-save-status__indicator{background:transparent;border-color:var( --os-ui-save-status-ring-color,var( --os-ui-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) ) );animation:os-save-status-ring-pulse 1.6s var( --os-ui-ease-loop,ease-in-out ) infinite}:host( [ variant='ring' ][ phase='failed' ] ) .os-save-status__indicator{background:transparent;border-color:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) );animation:os-save-status-ring-alert 0.62s var( --os-ui-ease-out,ease-out ) 1}:host( [ variant='ring' ][ phase='failed' ] ) .os-save-status__glyph{color:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) )}:host( [ variant='ring' ][ phase='saved' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-saved-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;animation:os-save-status-ring-land 0.42s var( --os-ui-ease-out,ease-out ) 1}:host( [ variant='ring' ][ phase='saved' ] ) .os-save-status__glyph,:host( [ variant='ring' ][ phase='failed' ] ) .os-save-status__glyph{animation:os-save-status-glyph-in 0.24s var( --os-ui-ease-out,ease-out ) 0.08s 1 backwards}@keyframes os-save-status-ring-pulse{0%,100%{opacity:0.45;scale:0.9}50%{opacity:1;scale:1}}@keyframes os-save-status-ring-land{0%{scale:0.82}55%{scale:1.06}100%{scale:1}}@keyframes os-save-status-ring-alert{0%{scale:0.9}25%{scale:1.08}50%{scale:0.98}75%{scale:1.04}100%{scale:1}}@keyframes os-save-status-glyph-in{0%{opacity:0;scale:0.4}100%{opacity:1;scale:1}}@media ( prefers-reduced-motion:reduce ){:host( [ variant='ring' ] ) .os-save-status__indicator,:host( [ variant='ring' ] ) .os-save-status__glyph{animation:none;opacity:1;scale:1}}@keyframes os-save-status-pulse{0%,100%{opacity:0.55;transform:scale( 0.9 )}50%{opacity:1;transform:scale( 1 )}}:host( [ mode='pill' ] ) .os-save-status{display:inline-flex;align-items:center;gap:6px;padding:2px 10px;border-radius:999px;background:var( --os-ui-save-status-pill-bg,transparent );font-weight:500;white-space:nowrap}:host( [ mode='pill' ][ phase='saving' ] ) .os-save-status,:host( [ mode='pill' ][ phase='pending' ] ) .os-save-status{background:var( --os-ui-save-status-pill-bg,var( --os-ui-hover,rgba( 0,0,0,0.04 ) ) );color:var( --os-ui-save-status-pill-fg,var( --os-ui-fg-muted,#50575e ) )}:host( [ mode='pill' ][ phase='saved' ] ) .os-save-status{background:var( --os-ui-save-status-pill-bg,rgba( 30,132,73,0.12 ) );color:var( --os-ui-save-status-pill-fg,var( --os-ui-success-fg,#1d6f42 ) )}:host( [ mode='pill' ][ phase='failed' ] ) .os-save-status{background:var( --os-ui-save-status-pill-bg,rgba( 214,54,56,0.12 ) );color:var( --os-ui-save-status-pill-fg,var( --os-ui-danger-hover,#a02622 ) )}.os-save-status__label{min-width:0;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host( [ phase='saved' ] ) .os-save-status__glyph,:host( [ phase='failed' ] ) .os-save-status__glyph{display:inline-block;color:var( --os-ui-fg-on-accent,#fff );width:calc( var( --os-ui-save-status-size,12px ) * 0.66 );height:calc( var( --os-ui-save-status-size,12px ) * 0.66 )}.os-save-status__glyph{display:none}.os-save-status__glyph svg{display:block;width:100%;height:100%}`,qy="os-settings-save-lifecycle",DR=2200,RR=6e3,Ls=class Ls extends Se{constructor(){super(...arguments),this._autoTimer=null,this._docListener=null}connectedCallback(){super.connectedCallback(),this.auto!==null&&this._installAutoListener()}disconnectedCallback(){this._removeAutoListener(),this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback(t,n,o),(t==="auto"||t==="event")&&(this._removeAutoListener(),this.auto!==null&&this._installAutoListener()),t==="phase"){this._scheduleAutoClear();const s={phase:this.phase??"idle",error:this.error??void 0};this.emit("os-save-status-change",s)}}render(){const t=this.phase??"idle",n=this.mode??"dot",s=(this.error??"")||this._labelForPhase(t);return s?this.setAttribute("title",s):this.removeAttribute("title"),this.setAttribute("aria-live",t==="failed"?"assertive":"polite"),this.setAttribute("role",t==="failed"?"alert":"status"),J` |
| 172 |
<span class="os-save-status"> |
| 173 |
<span class="os-save-status__indicator" aria-hidden="true"> |
| 174 |
<span class="os-save-status__glyph">${this._renderGlyph(t)}</span> |
| 175 |
</span> |
| 176 |
${n==="pill"?J`<span class="os-save-status__label" |
| 177 |
>${this._labelForPhase(t)}</span |
| 178 |
>`:J``} |
| 179 |
</span> |
| 180 |
`}_renderGlyph(t){return t==="saved"?OR():t==="failed"?MR():""}_labelForPhase(t){switch(t){case"pending":case"saving":return this["saving-label"]??"Saving…";case"saved":return this["saved-label"]??"Saved";case"failed":return(this.error??"")||"Couldn’t save";default:return this["idle-label"]??""}}_installAutoListener(){const t=this.event||qy;this._docListener=n=>{const o=n.detail;!o||typeof o.phase!="string"||(this.phase=o.phase,o.error?this.error=o.error:o.phase!=="failed"&&this.error&&this.removeAttribute("error"))},document.addEventListener(t,this._docListener)}_removeAutoListener(){if(!this._docListener)return;const t=this.event||qy;document.removeEventListener(t,this._docListener),this._docListener=null}_scheduleAutoClear(){this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null);const t=this.phase??"idle",n=this._autoClearMsFor(t);n<=0||(this._autoTimer=window.setTimeout(()=>{this._autoTimer=null,this.phase="idle"},n))}_autoClearMsFor(t){if(t==="saved"){const n=this["auto-clear-saved-ms"];return parseInt(n||"",10)||DR}if(t==="failed"){const n=this["auto-clear-failed-ms"];return parseInt(n||"",10)||RR}return 0}};Ls.props=["phase","mode","variant","animation","auto","event","error","saving-label","saved-label","idle-label","auto-clear-saved-ms","auto-clear-failed-ms"],Ls.styles=[NR],Ls.help=void 0;let Gc=Ls;xe("os-save-status",Gc);function OR(){return J` |
| 181 |
<svg |
| 182 |
viewBox="0 0 12 12" |
| 183 |
aria-hidden="true" |
| 184 |
focusable="false" |
| 185 |
fill="none" |
| 186 |
stroke="currentColor" |
| 187 |
stroke-width="2" |
| 188 |
stroke-linecap="round" |
| 189 |
stroke-linejoin="round" |
| 190 |
> |
| 191 |
<path d="M2.5 6 L5 8.5 L9.5 4" /> |
| 192 |
</svg> |
| 193 |
`}function MR(){return J` |
| 194 |
<svg |
| 195 |
viewBox="0 0 12 12" |
| 196 |
aria-hidden="true" |
| 197 |
focusable="false" |
| 198 |
fill="currentColor" |
| 199 |
> |
| 200 |
<path |
| 201 |
d="M5 2 H7 V7 H5 z M5 8.5 H7 V10.5 H5 z" |
| 202 |
/> |
| 203 |
</svg> |
| 204 |
`}const PR=de` ${ft} ${Ra}: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}`,Ts=class Ts extends Se{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),xp(this)}render(){const t=this._attr("label")||"",n=this._attr("value")??"",o=this._attr("placeholder")||"",s=this._boolAttr("disabled"),i=this._boolAttr("readonly"),r=this._attr("aria-label")||t,a=this._attr("name")||"",l=Number(this._attr("rows"))||3,c=this._attr("maxlength"),d=this._attr("minlength"),u=this._boolAttr("invalid"),p=`${this.id||"os-unnamed"}__field`;return J` |
| 205 |
${t?J`<label class="os-textarea__label" for=${p}>${t}</label>`:J``} |
| 206 |
<textarea |
| 207 |
id=${p} |
| 208 |
part="textarea" |
| 209 |
.value=${n} |
| 210 |
placeholder=${o} |
| 211 |
?disabled=${s} |
| 212 |
?readonly=${i} |
| 213 |
rows=${l} |
| 214 |
maxlength=${c??""} |
| 215 |
minlength=${d??""} |
| 216 |
name=${a} |
| 217 |
aria-invalid=${u?"true":"false"} |
| 218 |
aria-label=${r||""} |
| 219 |
@input=${w=>this._onInput(w)} |
| 220 |
@change=${w=>this._onChange(w)} |
| 221 |
@keydown=${w=>this._onKeyDown(w)} |
| 222 |
></textarea> |
| 223 |
`}_attr(t){return this.getAttribute(t)}_boolAttr(t){return this.getAttribute(t)!==null}_onInput(t){const n=t.target;this._textareaEl=n,this.setAttribute("value",n.value),this.emit("os-input-change",{value:n.value}),this._boolAttr("auto-grow")&&this._autosize(n)}_onChange(t){const n=t.target;this.emit("os-input-commit",{value:n.value})}_onKeyDown(t){if(this._boolAttr("submit-on-enter")&&t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey&&!t.ctrlKey){t.preventDefault();const n=t.target;this.emit("os-submit",{value:n.value})}}_autosize(t){const n=Number(this._attr("max-rows"))||8,o=window.getComputedStyle(t),s=parseFloat(o.fontSize)||13,i=o.lineHeight,r=i==="normal"?s*1.45:parseFloat(i)||s*1.45,a=parseFloat(o.paddingTop)||0,l=parseFloat(o.paddingBottom)||0,c=r*n+a+l;t.style.height="auto";const d=Math.min(t.scrollHeight,c);t.style.height=`${d}px`}refreshAutosize(){this._textareaEl&&this._boolAttr("auto-grow")&&this._autosize(this._textareaEl)}focusInput(){(this.shadowRoot??this).querySelector("textarea")?.focus()}clear(){this.setAttribute("value","");const n=(this.shadowRoot??this).querySelector("textarea");n&&(n.value="",this._boolAttr("auto-grow")&&this._autosize(n))}};Ts.props=["label","value","placeholder","disabled","readonly","ariaLabel","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],Ts.styles=[PR],Ts.help=void 0;let jc=Ts;xe("os-textarea",jc);const WR=de`: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}`,$R={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 UR(e){const t=(e??"").trim();return t===""||t.length>4096||!/^(https?:\/\/|data:image\/)/i.test(t)||/['"()\\<>\s]/.test(t)?"":t}const Ns=class Ns extends Se{constructor(){super(...arguments),this._activateWired=!1}static get observedAttributes(){return[...super.observedAttributes,"aria-label"]}render(){const t=UR(this["icon-src"]||this.getAttribute("icon-src")||""),n=t?"":this.icon||"",o=$R[n]||"",s=this.getAttribute("aria-label")||"";return t?J` |
| 224 |
<button type="button" aria-label="${s}"> |
| 225 |
<span |
| 226 |
class="themed-icon" |
| 227 |
aria-hidden="true" |
| 228 |
style="-webkit-mask: url('${t}') center / contain no-repeat; mask: url('${t}') center / contain no-repeat;" |
| 229 |
></span> |
| 230 |
<slot></slot> |
| 231 |
</button> |
| 232 |
`:J` |
| 233 |
<button type="button" aria-label="${s}"> |
| 234 |
<svg |
| 235 |
width="14" |
| 236 |
height="14" |
| 237 |
viewBox="0 0 12 12" |
| 238 |
aria-hidden="true" |
| 239 |
focusable="false" |
| 240 |
></svg> |
| 241 |
<slot></slot> |
| 242 |
</button> |
| 243 |
<span data-svg-buffer style="display:none">${o}</span> |
| 244 |
`}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paintSvg()),queueMicrotask(()=>this._wireActivateEvent())}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),queueMicrotask(()=>this._paintSvg())}_paintSvg(){const t=this.shadowRoot;if(!t)return;const n=t.querySelector("svg"),o=t.querySelector("[data-svg-buffer]");if(n&&o){const s=o.textContent||"";n.innerHTML!==s&&(n.innerHTML=s)}}_wireActivateEvent(){if(this._activateWired)return;const t=this.shadowRoot;if(!t)return;const n=t.querySelector("button");n&&(this._activateWired=!0,n.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("os-button-activate",{bubbles:!0,composed:!0,cancelable:!0}))}))}};Ns.props=["icon","icon-src","active","danger"],Ns.styles=[WR],Ns.help=void 0;let Vc=Ns;xe("os-window-button",Vc);const on=["butter","blush","sky","mint","lilac","peach"];function FR(e){return on.includes(e)?e:on[0]}function qc(e){return e.toLowerCase().replace(/[^a-z0-9_-]/g,"")||on[0]}function Ky(e){const t=on.indexOf(FR(e));return on[(t+1)%on.length]}const Yy="cubic-bezier(0.2, 0.7, 0.2, 1)",Xy="cubic-bezier(0.5, 0, 0.9, 0.4)",BR="cubic-bezier(0.2, 0.7, 0.3, 1.15)";function Kn(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ct(e,t,n){return typeof e.animate!="function"?Promise.resolve():e.animate(t,n).finished.then(()=>{}).catch(()=>{})}async function HR(e){const t=e.restRotation??0;if(Kn()){Zy(e.rippleHost,400);return}const n=e.tempo??1,o=e.fallDistance??30;await ct(e.pin,[{opacity:0,transform:`translate(8px, ${-o}px) rotate(${t-16}deg) scale(1.9)`},{opacity:1,offset:.35},{opacity:1,transform:`translate(0, 0) rotate(${t}deg) scale(0.92)`}],{duration:170*n,easing:Xy,fill:"forwards"}),Zy(e.rippleHost,420*n);const s=ct(e.paper,[{transform:"scale(1) translateY(0) skewX(0)"},{transform:"scale(0.982) translateY(2px) skewX(0)",offset:.08},{transform:"scale(1.01) translateY(0) skewX(0.6deg)",offset:.32},{transform:"scale(0.996) translateY(0) skewX(-0.4deg)",offset:.55},{transform:"scale(1) translateY(0) skewX(0)"}],{duration:370*n,easing:"linear"}),i=ct(e.pin,[{transform:`rotate(${t}deg) scale(0.92)`},{transform:`rotate(${t+1.5}deg) scale(1.07)`,offset:.25},{transform:`rotate(${t-1}deg) scale(0.98)`,offset:.5},{transform:`rotate(${t}deg) scale(1)`}],{duration:370*n,easing:Yy,fill:"forwards"});await Promise.all([s,i])}function Zy(e,t){const n=document.createElement("span");n.className="os-pinned-note__ripple",n.setAttribute("aria-hidden","true"),e.appendChild(n),ct(n,[{boxShadow:"0 0 0 0 rgba(0, 0, 0, 0.28)",opacity:.35},{boxShadow:"0 0 0 26px rgba(0, 0, 0, 0)",opacity:0}],{duration:t,easing:"ease-out"}).then(()=>n.remove()),window.setTimeout(()=>n.remove(),t+100)}function zR(e){if(Kn())return{onPointerMove:()=>{},setBias:()=>{},stop:()=>{}};const t=14;let n=0,o=0,s=0,i=0,r=null,a=0,l=0,c=0,d=0,u=!0;const f=p=>{if(!u)return;const w=Math.min(.05,d?(p-d)/1e3:.016);d=p,p-a>80&&(l*=.85),s=Math.max(-14,Math.min(14,-l*.055))+i,o+=(-120*(n-s)-t*o)*w,n+=o*w,e.style.transform=`rotate(${n.toFixed(2)}deg)`,c=window.requestAnimationFrame(f)};return c=window.requestAnimationFrame(f),{onPointerMove(p){const w=performance.now();if(r!==null&&w>a){const m=(p-r)/(w-a)*16.7;l=l*.7+m*.3}r=p,a=w},setBias(p){i=p},stop(){u=!1,window.cancelAnimationFrame(c),e.style.transform=""}}}async function GR(e){if(Kn()){await ct(e.flyback,[{opacity:1},{opacity:0}],{duration:120,easing:"linear",fill:"forwards"});return}const t=e.swing?ct(e.swing,[{transform:"rotate(0deg)"},{transform:"rotate(9deg)",offset:.35},{transform:"rotate(-4deg)",offset:.7},{transform:"rotate(0deg)"}],{duration:330,easing:"linear",fill:"forwards"}):Promise.resolve(),n=ct(e.flyback,[{left:`${e.flyback.offsetLeft}px`,top:`${e.flyback.offsetTop}px`},{left:`${e.homeX}px`,top:`${e.homeY}px`}],{duration:330,easing:BR,fill:"forwards"});await Promise.all([n,t])}async function jR(e){if(Kn()){await ct(e.clone,[{opacity:1},{opacity:0}],{duration:150,easing:"linear",fill:"forwards"});return}e.pin&&ct(e.pin,[{transform:"translate(0, 0) rotate(0deg)",opacity:1},{transform:"translate(2px, -16px) rotate(-30deg)",opacity:0}],{duration:200,easing:Yy,fill:"forwards"});const t=e.clone.getBoundingClientRect(),n=e.binX-(t.left+t.width/2),o=e.binY-(t.top+t.height/2),s="polygon(4% 8%, 38% 2%, 68% 7%, 96% 3%, 98% 42%, 92% 71%, 97% 94%, 60% 98%, 30% 93%, 3% 97%, 6% 62%, 2% 34%)",i="polygon(10% 14%, 42% 6%, 64% 12%, 90% 8%, 94% 38%, 86% 66%, 92% 88%, 58% 94%, 34% 86%, 10% 92%, 14% 58%, 8% 36%)";await ct(e.paper,[{transform:"translate(0, 0) scale(0.88) rotate(0deg)",borderRadius:"2px",opacity:1},{transform:`translate(${n*.3}px, ${o*.3}px) scale(0.6) rotate(12deg)`,clipPath:s,offset:.3},{transform:`translate(${n*.6}px, ${o*.6}px) scale(0.34) rotate(24deg)`,clipPath:i,offset:.6,opacity:1},{transform:`translate(${n}px, ${o}px) scale(0.12) rotate(38deg)`,borderRadius:"50%",clipPath:i,opacity:0}],{duration:400,easing:Xy,delay:60,fill:"forwards"})}function VR(e){let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t>>>1||1}function Jy(e){let t=2166136261;const n=`os-note-${e}`;for(let i=0;i<n.length;i++)t^=n.charCodeAt(i),t=Math.imul(t,16777619)>>>0;const o=t>>>3,s=t>>>5;return{rotation:(t%45-22)/10,pinOffsetX:o%21-10,pinRotation:s%17-8}}const qR=.57,KR=.525,YR=56,XR=52;function ZR(e){return`${e.replace(/\/$/,"")}/assets/images/pushpin.svg`}function JR(e){const t=document.createElement("img");return t.src=ZR(e),t.alt="",t.width=YR,t.height=XR,t.draggable=!1,t.className="os-pinned-note__pin-img",t}let Kc=null;function QR(e){Kc=e}function eO(){if(!Kc)throw new Error("[openstation] notes REST client called before installNotesRestDeps().");return Kc}function tO(e){const t=window.openStationConfig;return typeof t?.restNonce=="string"&&t.restNonce?t.restNonce:e}class Qy extends Error{constructor(t){super("Note was changed by another session."),this.status=409,this.name="NotesConflictError",this.current=t}}function nO(e){return e instanceof Qy}async function Yn(e,t){const{baseUrl:n,nonce:o}=eO(),s=e?ot(n,e):n,i=new Headers(t.headers??{});i.set("X-WP-Nonce",tO(o)),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Fe(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/notes"}),a=await r.text();let l=null;if(a)try{l=JSON.parse(a)}catch{l=null}if(!r.ok){if(r.status===409){const d=l?.data?.current;throw new Qy(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 eb(){return Yn("",{method:"GET"})}function oO(e){return Yn("",{method:"POST",body:JSON.stringify(e)})}function sO(e,t){return Yn(`/${e}`,{method:"PATCH",body:JSON.stringify(t)})}function iO(e){return Yn(`/${e}`,{method:"DELETE"})}function tb(e){return Yn(`/${e}/restore`,{method:"POST"})}function rO(e){return Yn(`/${e}/convert`,{method:"POST"})}const aO="openstation_notes_subscribe",lO="openstation_notes";let nb=!1,Yc=null;function cO(e){Yc=e,!nb&&(nb=!0,Te.contribute(aO,()=>Yc?.getHeartbeatSubscription()),Te.subscribe(lO,t=>{Yc?.applyHeartbeatPayload(t)}))}const dO="wpd_note",uO="note-draft",Xn="note",fO="os-note-created";function mr(e,t){Qa(dO,e,t,"desktop-mode/notes")}function ob(){const e=window.wp?.os;return e&&typeof e.showToast=="function"?e:null}async function pO(e,t){t.onEvict(e.id);try{await iO(e.id),mr("trashed",[e.id]),ob()?.showToast?.({message:E("Note moved to Trash","desktop-mode"),duration:6e3,action:{label:E("Undo","desktop-mode"),onClick:()=>{tb(e.id).then(n=>{mr("untrashed",[e.id]),t.onRestore(n)}).catch(n=>{console.error("[openstation] notes: restore failed:",n)})}}})}catch(n){console.error("[openstation] notes: trash failed:",n),t.onRestore(e),ob()?.showToast?.({message:E("Could not move the note to the Trash.","desktop-mode"),duration:5e3})}}function gr(){return window.wp?.os??null}function hO(e){const t=gr();if(!t?.windowManager?.open||!t.deriveWindowId)return window.location.href=e,null;const n=t.deriveWindowId(e);return t.windowManager.open({id:n,baseId:n,url:e,title:E("Edit draft","desktop-mode"),icon:"dashicons-admin-post"}),n}async function mO(e,t){t.onEvict(e.id);try{const n=await rO(e.id);mr("trashed",[e.id]);const o=hO(n.editUrl);gr()?.showToast?.({message:E("Note converted to a draft post","desktop-mode"),duration:6e3,action:{label:E("Undo","desktop-mode"),onClick:()=>{o&&gr()?.windowManager?.getById?.(o)?.close?.(),tb(e.id).then(s=>{mr("untrashed",[e.id]),t.onRestore(s)}).catch(s=>{console.error("[openstation] notes: convert undo failed:",s)})}}})}catch(n){console.error("[openstation] notes: convert failed:",n),t.onRestore(e),gr()?.showToast?.({message:E("Could not convert the note to a post.","desktop-mode"),duration:5e3})}}const gO=208,wO=1e3,yO=800,bO=10,vO=1;function _O(){return window.wp?.os?.dragManager??null}function wr(e){return e.seed||Math.abs(e.id)||1}const EO='<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>',kO=Ot("trash",{size:20});class SO{constructor(t){this.root=null,this.liveRegion=null,this.controllers=new Map,this.zCounter=1,this.highWaterMs=0,this.tempIdCounter=0,this.host=t.host,this.pluginUrl=t.pluginUrl,this.canCreatePosts=t.canCreatePosts??!1,this.onError=t.onError}async boot(){try{const{notes:t}=await eb();t.forEach(n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"none"})}),cO(this)}catch(t){t instanceof Error&&console.debug("[openstation] Pinned notes unavailable:",t.message)}}upsertNote(t,n={animate:"none"}){this.ensureRoot(),this.zCounter=Math.max(this.zCounter,t.z);const o=this.controllers.get(t.id);if(o)return o.replace(t),o;const s=new AO({layer:this,note:t});return this.controllers.set(t.id,s),this.root?.appendChild(s.element),n.animate!=="none"&&s.playInsertion(n.animate==="thunk"?1:.7),s}removeNote(t){const n=this.controllers.get(t);n&&(this.controllers.delete(t),n.dispose(),n.element.remove())}rekeyNote(t,n){this.controllers.delete(t),this.controllers.set(n.note.id,n)}has(t){return this.controllers.has(t)}get(t){return this.controllers.get(t)}nextTempId(){return this.tempIdCounter-=1,this.tempIdCounter}bringToFront(t){this.zCounter+=1,t.setZ(this.zCounter)}bumpHighWater(t){Number.isFinite(t)&&t>this.highWaterMs&&(this.highWaterMs=t)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}clampPosition(t,n){const{width:o,height:s}=this.hostSize(),i=Math.max(0,1-gO/o),r=Math.max(0,1-120/s);return{x:Math.min(i,Math.max(0,t)),y:Math.min(r,Math.max(0,n))}}normalizedFromClient(t,n){const o=this.host.getBoundingClientRect(),{width:s,height:i}=this.hostSize();return this.clampPosition((t-o.left)/s,(n-o.top)/i)}createNoteAt(t){const n=t.text??"",o=qc(t.color??on[0]),s=t.isPublic===!0,{x:i,y:r}=this.clampPosition(t.x,t.y),a=VR(n||`${i},${r}`),l=this.nextTempId(),c=this.upsertNote({id:l,text:n,color:o,x:i,y:r,z:1,public:s,seed:a,ownerId:0,ownerName:"",ownerAvatar:"",canEdit:!0,updatedAtMs:0},{animate:"thunk"});return this.bringToFront(c),t.focus&&c.focusEditor(),oO({text:n,color:o,x:i,y:r,public:s,seed:a}).then(d=>{this.bumpHighWater(d.updatedAtMs),c.replace(d),this.rekeyNote(l,c),c.flushPendingEdits()}).catch(d=>{this.removeNote(l),this.notifyError(E("Could not pin the note. Please try again.","desktop-mode")),console.error("[openstation] notes: create failed:",d)}),c}announce(t){this.ensureRoot(),this.liveRegion&&(this.liveRegion.textContent=t)}notifyError(t){this.onError?.(t)}trashNote(t){pO(t,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}convertNote(t){!this.canCreatePosts||!t.canEdit||mO(t,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}getHeartbeatSubscription(){return{knownIds:Array.from(this.controllers.keys()).filter(t=>t>0),sinceMs:this.highWaterMs}}applyHeartbeatPayload(t){for(const n of t.notes??[]){this.bumpHighWater(n.updatedAtMs);const o=this.controllers.get(n.id);o?o.shouldReplaceFromRemote(n)&&o.replace(n):this.upsertNote(n,{animate:"move"})}for(const n of t.removed??[])this.removeNote(n);typeof t.serverTimeMs=="number"&&Number.isFinite(t.serverTimeMs)&&this.bumpHighWater(t.serverTimeMs),t.truncated&&this.reloadFromServer()}async reloadFromServer(){try{const{notes:t}=await eb(),n=new Set;for(const o of t){n.add(o.id),this.bumpHighWater(o.updatedAtMs);const s=this.controllers.get(o.id);s?s.shouldReplaceFromRemote(o)&&s.replace(o):this.upsertNote(o,{animate:"move"})}for(const o of Array.from(this.controllers.keys()))o>0&&!n.has(o)&&this.removeNote(o)}catch{}}ensureRoot(){if(this.root)return this.root;const t=document.createElement("section");t.className="os-notes",t.setAttribute("aria-label",E("Pinned notes","desktop-mode"));const n=document.createElement("div");return n.className="os-notes__live screen-reader-text",n.setAttribute("aria-live","polite"),t.appendChild(n),this.host.appendChild(t),this.root=t,this.liveRegion=n,t}}class AO{constructor(t){this.editor=null,this.statusEl=null,this.colorDot=null,this.visibilityBtn=null,this.saveTimer=null,this.zTimer=null,this.patchChain=Promise.resolve(),this.pendingText=null,this.disposed=!1,this.moveMode=!1,this.moveOrigin=null,this.dragCleanup=null,this.lastPointer=null,this.layer=t.layer,this.note=t.note,this.jitter=Jy(wr(t.note)),this.element=document.createElement("article"),this.paperEl=document.createElement("div"),this.pinEl=document.createElement(this.note.canEdit?"button":"span"),this.paint(),this.applyPosition(),this.setZ(this.note.z),this.element.addEventListener("pointerdown",()=>this.layer.bringToFront(this),{capture:!0})}paint(){const t=this.note;this.element.className="os-pinned-note",this.element.dataset.noteId=String(t.id),this.element.dataset.noteColor=qc(t.color),this.element.dataset.owner=t.canEdit?"me":"other",this.element.setAttribute("role",t.canEdit?"group":"note"),this.element.setAttribute("aria-label",t.canEdit?E("Pinned note","desktop-mode"):le(E("Note by %s","desktop-mode"),t.ownerName)),this.element.style.setProperty("--dm-note-rot",`${this.jitter.rotation}deg`),this.element.style.setProperty("--dm-pin-dx",`${this.jitter.pinOffsetX}px`),this.element.style.setProperty("--dm-pin-rot",`${this.jitter.pinRotation}deg`),this.pinEl.className="os-pinned-note__pin",this.pinEl.appendChild(JR(this.layer.pluginUrl)),t.canEdit?(this.pinEl.setAttribute("type","button"),this.pinEl.setAttribute("aria-pressed","false"),this.pinEl.setAttribute("aria-label",E("Move note. Drag the pin, or press Enter then use the arrow keys.","desktop-mode")),this.pinEl.addEventListener("pointerdown",n=>this.startDrag(n)),this.pinEl.addEventListener("click",n=>{n.detail===0&&!this.moveMode&&this.toggleMoveMode()}),this.pinEl.addEventListener("keydown",n=>this.onPinKeydown(n)),this.pinEl.addEventListener("blur",()=>this.exitMoveMode(!1))):this.pinEl.setAttribute("aria-hidden","true"),this.paperEl.className="os-pinned-note__paper",t.canEdit?this.paintOwnerPaper():this.paintViewerPaper(),this.element.append(this.pinEl,this.paperEl)}paintOwnerPaper(){const t=document.createElement("div");t.className="os-pinned-note__meta";const n=document.createElement("os-save-status");n.setAttribute("mode","icon"),n.setAttribute("phase","idle"),n.className="os-pinned-note__status",this.statusEl=n;const o=document.createElement("button");o.type="button",o.className="os-pinned-note__color-dot",this.colorDot=o,this.refreshColorDot(),o.addEventListener("click",()=>this.cycleColor()),t.append(n,o);const s=document.createElement("div");s.className="os-pinned-note__actions";const i=document.createElement("os-window-button");if(i.className="os-pinned-note__visibility",this.visibilityBtn=i,this.refreshVisibility(),i.addEventListener("os-button-activate",()=>this.togglePublic()),s.appendChild(i),this.layer.canCreatePosts){const d=document.createElement("os-window-button");d.className="os-pinned-note__convert",d.innerHTML=EO;const u=E("Convert to a draft post","desktop-mode");d.setAttribute("title",u),d.setAttribute("aria-label",u),d.addEventListener("os-button-activate",()=>this.layer.convertNote(this.note)),s.appendChild(d)}const r=document.createElement("os-window-button");r.className="os-pinned-note__trash",r.innerHTML=kO;const a=E("Move to Trash","desktop-mode");r.setAttribute("title",a),r.setAttribute("aria-label",a),r.addEventListener("os-button-activate",()=>this.confirmTrash()),s.appendChild(r);const l=document.createElement("os-textarea");l.className="os-pinned-note__editor",l.setAttribute("aria-label",E("Note text","desktop-mode")),l.setAttribute("rows","5"),l.setAttribute("auto-grow",""),l.setAttribute("max-rows","10"),l.setAttribute("value",this.note.text),["keydown","keypress","keyup"].forEach(d=>{l.addEventListener(d,u=>u.stopPropagation())}),l.addEventListener("os-input-change",d=>{const u=d.detail;this.pendingText=u.value,this.setPhase("pending"),this.scheduleSave()}),l.addEventListener("os-input-commit",()=>this.flushSave()),this.editor=l;const c=document.createElement("div");c.className="os-pinned-note__footer",c.appendChild(s),this.paperEl.append(t,l,c)}paintViewerPaper(){const t=document.createElement("div");t.className="os-pinned-note__body",t.textContent=this.note.text;const n=document.createElement("div");n.className="os-pinned-note__attribution",n.title=le(E("Pinned by %s","desktop-mode"),this.note.ownerName);const o=document.createElement("os-avatar");o.setAttribute("size","20"),o.setAttribute("name",this.note.ownerName),this.note.ownerAvatar&&o.setAttribute("src",this.note.ownerAvatar);const s=document.createElement("span");s.className="os-pinned-note__attribution-name",s.textContent=this.note.ownerName,n.append(o,s),this.paperEl.append(t,n)}refreshColorDot(){if(!this.colorDot)return;const t=Ky(this.note.color);this.colorDot.style.setProperty("--dm-note-next-paper",`var(--dm-note-${t})`),this.colorDot.setAttribute("aria-label",le(E("Change paper color (next: %s)","desktop-mode"),t))}refreshVisibility(){if(!this.visibilityBtn)return;const t=this.note.public;this.visibilityBtn.innerHTML="";const n=document.createElement("span");n.className=`dashicons ${t?"dashicons-admin-site-alt3":"dashicons-lock"}`,n.setAttribute("aria-hidden","true"),this.visibilityBtn.appendChild(n),this.visibilityBtn.setAttribute("title",E(t?"Public note — everyone can see it. Click to make private.":"Private note. Click to share with every desktop user.","desktop-mode")),this.visibilityBtn.classList.toggle("is-public",t)}replace(t){const n=t.id!==this.note.id,o=wr(t)!==wr(this.note),s=t.color!==this.note.color,i=t.x!==this.note.x||t.y!==this.note.y,r=t.z!==this.note.z;if(this.note=t,r&&(this.element.style.zIndex=String(t.z)),n&&(this.element.dataset.noteId=String(t.id)),o&&(this.jitter=Jy(wr(t)),this.element.style.setProperty("--dm-note-rot",`${this.jitter.rotation}deg`),this.element.style.setProperty("--dm-pin-dx",`${this.jitter.pinOffsetX}px`),this.element.style.setProperty("--dm-pin-rot",`${this.jitter.pinRotation}deg`)),s&&(this.element.dataset.noteColor=qc(t.color),this.refreshColorDot()),i&&this.applyPosition(),this.note.canEdit)this.pendingText===null&&this.editor?.setAttribute("value",t.text),this.refreshVisibility();else{const a=this.paperEl.querySelector(".os-pinned-note__body");a&&(a.textContent=t.text)}}shouldReplaceFromRemote(t){return this.pendingText!==null||this.saveTimer!==null?!1:t.updatedAtMs>=this.note.updatedAtMs}setZ(t){this.element.style.zIndex=String(t),!(t===this.note.z||!this.note.canEdit)&&(this.note={...this.note,z:t},!(this.note.id<=0)&&(this.zTimer!==null&&window.clearTimeout(this.zTimer),this.zTimer=window.setTimeout(()=>{this.zTimer=null,this.queuePatch({z:this.note.z})},yO)))}applyPosition(){this.element.style.left=`${(this.note.x*100).toFixed(3)}%`,this.element.style.top=`${(this.note.y*100).toFixed(3)}%`}moveTo(t,n){const o=this.layer.clampPosition(t,n);this.note={...this.note,x:o.x,y:o.y},this.applyPosition(),this.note.id>0&&this.queuePatch({x:o.x,y:o.y})}playInsertion(t=1){return HR({pin:this.pinEl,paper:this.paperEl,rippleHost:this.element,restRotation:this.jitter.pinRotation,fallDistance:t>=1?30:12,tempo:t})}focusEditor(){window.setTimeout(()=>this.editor?.focusInput?.(),0)}dispose(){this.disposed=!0,this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.zTimer!==null&&(window.clearTimeout(this.zTimer),this.zTimer=null),this.dragCleanup?.(),this.dragCleanup=null}setPhase(t){this.statusEl?.setAttribute("phase",t)}scheduleSave(){this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.flushSave()},wO)}flushPendingEdits(){this.flushSave()}flushSave(){if(this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.pendingText===null||this.note.id<=0)return;const t=this.pendingText;this.pendingText=null,this.note={...this.note,text:t},this.setPhase("saving"),this.queuePatch({text:t})}cycleColor(){const t=Ky(this.note.color);this.note={...this.note,color:t},this.element.dataset.noteColor=t,this.refreshColorDot(),this.note.id>0&&this.queuePatch({color:t})}togglePublic(){const t=!this.note.public;this.note={...this.note,public:t},this.refreshVisibility(),t&&!Kn()&&this.visibilityBtn&&this.visibilityBtn.animate?.([{transform:"scale(1)"},{transform:"scale(1.25)"},{transform:"scale(1)"}],{duration:300,easing:"ease-out"}),this.layer.announce(E(t?"Note is now public.":"Note is now private.","desktop-mode")),this.note.id>0&&this.queuePatch({public:t})}confirmTrash(){Bn({title:E("Move note to the Trash?","desktop-mode"),message:E("You can restore it from the Trash later.","desktop-mode"),confirmLabel:E("Move to Trash","desktop-mode"),danger:!0}).then(t=>{t&&this.layer.trashNote(this.note)})}queuePatch(t){this.patchChain=this.patchChain.then(async()=>{if(!(this.disposed||this.note.id<=0))try{const n=await sO(this.note.id,{...t,updatedAtMs:this.note.updatedAtMs});if(this.disposed)return;const o=n.public!==this.note.public;this.note={...this.note,updatedAtMs:n.updatedAtMs,public:n.public},o&&this.refreshVisibility(),this.setPhase("saved")}catch(n){if(this.disposed)return;if(nO(n)&&n.current){this.pendingText=null,this.replace(n.current),this.setPhase("idle"),this.layer.notifyError(E("This note was changed in another session — showing the latest version.","desktop-mode"));return}this.setPhase("failed"),console.error("[openstation] notes: save failed:",n)}})}startDrag(t){if(!this.note.canEdit||this.note.id<=0)return;const n=_O();if(!n)return;t.preventDefault(),this.element.ownerDocument.defaultView?.getSelection()?.removeAllRanges();const o=this.buildGhost(),s=this.element.getBoundingClientRect(),i={noteId:this.note.id,canEdit:this.note.canEdit,updatedAtMs:this.note.updatedAtMs};n.start({payload:{type:Xn,source:this.element,data:i,ghost:{element:o.root,offsetX:o.tipX,offsetY:o.tipY,hint:{neutral:E("Drop on the desktop to pin","desktop-mode"),accept:E("Pin here","desktop-mode"),reject:E("Can’t pin here","desktop-mode")}}},origin:t,onClickOnly:()=>{this.teardownDragListeners(),this.toggleMoveMode()},onCancel:()=>{this.teardownDragListeners(),this.snapBack(s)},onCommit:()=>{this.teardownDragListeners(),this.layer.has(this.note.id)&&this.playInsertion(.7)}})&&this.installDragListeners(o)}buildGhost(){const t=this.element.getBoundingClientRect(),o=(this.pinEl.querySelector("img")??this.pinEl).getBoundingClientRect(),s=o.left-t.left+o.width*qR,i=o.top-t.top+o.height*KR,r=document.createElement("div");r.className="os-pinned-note-ghost",r.style.width=`${t.width}px`,r.style.height=`${t.height}px`;const a=document.createElement("div");a.className="os-pinned-note-ghost__swing",a.style.transformOrigin=`${s}px ${i}px`;const l=this.pinEl.cloneNode(!0);l.removeAttribute("aria-pressed"),l.setAttribute("aria-hidden","true");const c=this.paperEl.cloneNode(!0);return c.classList.add("os-pinned-note-ghost__paper"),a.dataset.noteColor=this.element.dataset.noteColor??"",a.append(l,c),r.appendChild(a),{root:r,swing:a,pin:l,paper:c,tipX:s,tipY:i}}installDragListeners(t){this.teardownDragListeners();let n=null;const o=a=>{a.detail?.payload?.data?.noteId===this.note.id&&(n=zR(t.swing))},s=a=>{const l=a.detail;this.lastPointer={x:l.clientX,y:l.clientY},n?.onPointerMove(l.clientX)},i=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.add("os-pinned-note-ghost--doom"),n?.setBias(6))},r=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.remove("os-pinned-note-ghost--doom"),n?.setBias(0))};document.addEventListener(we.START,o),document.addEventListener(we.MOVE,s),document.addEventListener(we.ENTER,i),document.addEventListener(we.LEAVE,r),this.dragCleanup=()=>{n?.stop(),n=null,document.removeEventListener(we.START,o),document.removeEventListener(we.MOVE,s),document.removeEventListener(we.ENTER,i),document.removeEventListener(we.LEAVE,r)}}teardownDragListeners(){this.dragCleanup?.(),this.dragCleanup=null}async snapBack(t){if(!this.lastPointer||Kn()){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 GR({flyback:n.root,swing:n.swing,homeX:t.left,homeY:t.top})}finally{n.root.remove()}this.playInsertion(.63)}async playCrumpleAt(t,n){const o=this.buildGhost();o.root.classList.add("os-pinned-note-ghost--flyback"),o.root.style.position="fixed",o.root.style.left=`${t-o.tipX}px`,o.root.style.top=`${n-o.tipY}px`,o.root.style.zIndex="2147483647",o.root.style.pointerEvents="none",document.body.appendChild(o.root);try{await jR({clone:o.root,pin:o.pin,paper:o.paper,binX:t,binY:n+24})}finally{o.root.remove()}}toggleMoveMode(){this.moveMode?this.exitMoveMode(!0):this.enterMoveMode()}enterMoveMode(){this.note.canEdit&&(this.moveMode=!0,this.moveOrigin={x:this.note.x,y:this.note.y},this.element.classList.add("os-pinned-note--move-mode"),this.pinEl.setAttribute("aria-pressed","true"),this.layer.announce(E("Moving note. Arrow keys to move, Enter to place, Escape to cancel, Delete to move to the Trash.","desktop-mode")))}exitMoveMode(t){this.moveMode&&(this.moveMode=!1,this.element.classList.remove("os-pinned-note--move-mode"),this.pinEl.setAttribute("aria-pressed","false"),t?(this.moveTo(this.note.x,this.note.y),this.layer.announce(E("Note placed.","desktop-mode")),this.playInsertion(.7)):this.moveOrigin&&(this.note={...this.note,...this.moveOrigin},this.applyPosition()),this.moveOrigin=null)}onPinKeydown(t){if(!this.moveMode)return;const{width:n,height:o}=this.layer.hostSize(),s=t.shiftKey?vO:bO,i=s/n,r=s/o;switch(t.key){case"ArrowLeft":this.nudge(-i,0);break;case"ArrowRight":this.nudge(i,0);break;case"ArrowUp":this.nudge(0,-r);break;case"ArrowDown":this.nudge(0,r);break;case"Enter":case" ":this.exitMoveMode(!0);break;case"Escape":this.exitMoveMode(!1),this.layer.announce(E("Move cancelled.","desktop-mode"));break;case"Delete":case"Backspace":this.exitMoveMode(!1),this.confirmTrash();break;default:return}t.preventDefault(),t.stopPropagation()}nudge(t,n){const o=this.layer.clampPosition(this.note.x+t,this.note.y+n);this.note={...this.note,...o},this.applyPosition()}}const ls=new Map;function CO(e,t){return ls.set(e,t),()=>{ls.get(e)===t&&ls.delete(e)}}function IO(e){const t=ls.get(e.type);return t?t.accept(e.data):!1}function xO(e,t){const n=ls.get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}function sb(e,t,n){const o=e.host.getBoundingClientRect(),s=t.payload.ghost?.offsetX??0,i=t.payload.ghost?.offsetY??0,{width:r,height:a}=e.hostSize();return e.clampPosition((n.clientX-s-o.left)/r,(n.clientY-i-o.top)/a)}function LO(e,t,n){const o=t.payload.data,s=String(o.text??"");if(!s.trim())return;const{x:i,y:r}=sb(e,t,n);e.createNoteAt({x:i,y:r,text:s,color:String(o.color??""),isPublic:o.isPublic===!0})}function TO(e,t,n){const o=t.payload.data,s=e.get(o.noteId);if(!s)return;const{x:i,y:r}=sb(e,t,n);s.moveTo(i,r)}function NO(e){const t=[],n=o=>o.folderId===0;return t.push(ly(uO,{accept:(o,s)=>n(s)&&!!String(o.text??"").trim(),onDrop:(o,s)=>LO(e,o,s)})),t.push(ly(Xn,{accept:(o,s)=>n(s)&&o.canEdit===!0,onDrop:(o,s)=>TO(e,o,s)})),t.push(CO(Xn,{accept:o=>o.canEdit===!0,onDrop:(o,s)=>{const i=o.payload.data,r=e.get(i.noteId);if(!r)return;const a=r.note;r.playCrumpleAt(s.clientX,s.clientY),e.trashNote(a)}})),()=>{t.forEach(o=>o())}}const Xc="data-os-posts-drop-active",ib="desktop-mode-posts",DO='.os-dock__item[data-menu-slug="menu-posts"],.os-dock__item[data-menu-slug="editphp"]',RO="[data-os-posts-root]";function OO(){return window.wp?.os?.dragManager??null}function MO(e){return e.type!==Xn?!1:e.data.canEdit===!0}function PO(e){if(!e)return!1;let t=e,n="";try{const i=new URL(e,window.location.origin);t=i.pathname,n=i.search}catch{}if(!(/(?:^|\/)(?:edit\.php|post-new\.php)$/.test(t)||!t.includes("/")&&(t==="edit.php"||t==="post-new.php")))return!1;const s=new URLSearchParams(n).get("post_type");return!s||s==="post"}function WO(e){const t=e.placement.file;if(!t||t.type!=="shortcut")return!1;const n=typeof t.shortcutUrl=="string"?t.shortcutUrl:"";return PO(n)}function rb(e,t){if(t.payload.type!==Xn)return;const n=t.payload.data;if(typeof n.noteId!="number")return;const o=e.get(n.noteId);o&&e.convertNote(o.note)}let ab=!1,cs=null,ds=null,lb=null;function cb(e,t,n,o){return e.registerDropTarget({id:n,element:o,acceptLabel:E("Convert to post","desktop-mode"),accept:s=>MO(s),onEnter:()=>{o.setAttribute(Xc,"")},onLeave:()=>{o.removeAttribute(Xc)},onDrop:s=>{o.removeAttribute(Xc),rb(t,s)}})}function $O(e,t){const n=e.debug().listTargets().find(o=>o.id===t);return n?n.element:null}function UO(e){if(ab||!e.canCreatePosts)return;const t=OO();if(!t)return;ab=!0,Ji(Xn,{appliesTo:o=>WO(o),acceptLabel:E("Convert to post","desktop-mode"),accept:o=>o.canEdit===!0,onDrop:o=>rb(e,o)});const n=()=>{const o=document.querySelector(DO);if(!(o instanceof HTMLElement)){cs?.(),cs=null;return}cs&&$O(t,"notes-convert-dock")===o||(cs?.(),cs=cb(t,e,"notes-convert-dock",o))};n(),Z(b.DOCK_AFTER_RENDER,"desktop-mode/notes/convert-dock-target",n),typeof MutationObserver<"u"&&(lb=new MutationObserver(()=>{n()}),lb.observe(document.body,{childList:!0,subtree:!0})),Z(b.WINDOW_OPENED,"desktop-mode/notes/convert-window-target",o=>{if(o.windowId!==ib)return;ds?.(),ds=null;const s=document.querySelector(RO);s instanceof HTMLElement&&(ds=cb(t,e,"notes-convert-window",s))}),Z(b.WINDOW_CLOSED,"desktop-mode/notes/convert-window-cleanup",o=>{o.windowId===ib&&(ds?.(),ds=null)})}const db="new-note";function FO(e){Qn("os.wallpaper-context-menu","desktop-mode/notes",(t,n)=>{if(!Array.isArray(t)||t.some(i=>i.id===db))return t;const{x:o,y:s}=n??{x:0,y:0};return[...t,{id:db,label:E("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{const i=e.normalizedFromClient(o,s);e.createNoteAt({...i,focus:!0})}}]})}function BO(e){const t=e.config.notesUrl;if(typeof t!="string"||!t)return null;QR({baseUrl:t,nonce:e.config.restNonce??""});const n=new SO({host:e.host,pluginUrl:e.config.pluginUrl??"",canCreatePosts:e.config.canCreatePosts??!1,onError:e.onError});return NO(n),UO(n),FO(n),document.addEventListener(fO,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 HO={id:"clock",get label(){return E("Clock")},get description(){return E("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("os-widget-clock");const t=document.createElement("div");t.className="os-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="os-widget-clock__date",e.appendChild(n);const o=()=>{const a=new Date;t.textContent=a.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=a.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})};o();const s=1e3-Date.now()%1e3;let i=null;const r=window.setTimeout(()=>{o(),i=window.setInterval(o,1e3)},s);return()=>{window.clearTimeout(r),i!==null&&window.clearInterval(i)}}};function zO(){yl(HO)}async function GO(){const e=window;if(e.openStationReleaseCard)return e.openStationReleaseCard;const t=e.openStationConfig?.releaseCardBundleUrl??"";if(!t)return null;try{await _e(t)}catch{return null}return e.openStationReleaseCard??null}function ub(e,t){if(t){const o=E('WordPress %1$s "%2$s" is available.');return le(o,e,t)}const n=E("WordPress %s is available.");return le(n,e)}async function jO(e){const{update:t,openUrl:n}=e;if(!t||typeof t.version!="string"||!t.version||typeof t.url!="string"||!t.url)return;const o=t.version,s=typeof t.branch=="string"&&t.branch?t.branch:o,i=t.crossing===!0,a=`desktop-mode/core-update:${typeof t.available=="string"&&t.available?t.available:o}`;if(Ti(a))return;const l=`${a}:no-art`,c=()=>n({url:t.url,title:E("WordPress Updates")}),u=e.resolveArt&&e.loadImage&&e.showCard?null:await GO(),f=e.resolveArt??u?.resolveReleaseArt,p=e.loadImage??u?.preloadImage,w=e.showCard??u?.showReleaseCard,m=f?await f(s,i):null;if(m&&m.artUrl&&p&&w&&await p(m.artUrl)){w({message:ub(o,i?m.name:""),artUrl:m.artUrl,dismissKey:a,onUpdate:c});return}Ti(l)||Q({message:ub(o,""),persistent:!0,dismissible:!0,onDismiss:()=>Ni(l),action:{label:E("Update now"),onClick:c}})}function fb(e){const{notices:t,openUrl:n,keyPrefix:o="core-notice"}=e;if(Array.isArray(t))for(const s of t){if(!s||typeof s.id!="string"||!s.id||typeof s.message!="string"||!s.message)continue;const i=`desktop-mode/${o}:${s.id}`;if(Ti(i))continue;const r=s.actionLabel,a=s.actionUrl,l=s.title||r||"";let c;r&&a&&(c={label:r,onClick:()=>n({url:a,title:l})}),Q({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>Ni(i),action:c})}}const Zc="desktop-mode/starter",VO="desktop-mode/dev-mode-gate";let pb=!1;function qO({osSettings:e,layer:t}){if(pb)return;pb=!0,Qn(b.WIDGETS,VO,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==Zc));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(Zc):t.unmount(Zc),Di())})}function KO(e){const{layer:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await _e(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter})}catch(d){L(b.SHELL_ERROR,{scope:"widget-script-load",id:c.id,error:d});return}o.add(c.scriptUrl)}},i=c=>(window.openStationWidgets||{})[c]??null,r=c=>({id:c.id,label:c.label,description:c.description,icon:c.icon,movable:c.movable,resizable:c.resizable,minWidth:c.minWidth||void 0,minHeight:c.minHeight||void 0,maxWidth:c.maxWidth||void 0,maxHeight:c.maxHeight||void 0,defaultWidth:c.defaultWidth||void 0,defaultHeight:c.defaultHeight||void 0,mount:async(d,u)=>{await s(c);const f=i(c.id);if(!f){const p=new Error(`[openstation] No mount callback on window.openStationWidgets["${c.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`);throw L(b.SHELL_ERROR,{scope:"widget-missing-mount",id:c.id,error:p}),p}return f(d,u)}}),a=async c=>{if(n.has(c.id))return;const d=r(c);try{yl(d)}catch(u){L(b.SHELL_ERROR,{scope:"widget-register",id:c.id,error:u});return}n.add(c.id),Di(),t&&t.mountIfEnabled(c.id)},l=c=>{n.has(c)&&(t?.unmount(c),hI(c),n.delete(c),Di())};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 hb=new Set(Vi),YO=2e3,Jc=new Set,mb=new WeakSet;let gb=!1;function XO(e,t){const n=e.length,o=t.length;if(n===0)return o;if(o===0)return n;const s=new Array(o+1);for(let i=0;i<=o;i++)s[i]=i;for(let i=1;i<=n;i++){let r=s[0];s[0]=i;for(let a=1;a<=o;a++){const l=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=l}}return s[o]}function ZO(e){let t=null,n=1/0;for(const o of hb){const s=XO(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function JO(e){return e.startsWith("os-")?e.slice(4):e}function QO(e,t){if(Jc.has(e))return;if(Jc.add(e),hb.has(e)){const s=JO(e);console.error(`[wp.os] <${e}> is in the DOM but its module was never imported, so the tag will not upgrade and the component will render as inert HTML. |
| 245 |
|
| 246 |
Fix — side-effect-import the component module from wherever you render it: |
| 247 |
|
| 248 |
import '<rel>/ui/components/${s}/${s}'; |
| 249 |
|
| 250 |
Or pull every os-* component in one go (heavier — only do this from an entry bundle): |
| 251 |
|
| 252 |
import '<rel>/ui/components'; |
| 253 |
|
| 254 |
See docs/components-reference.md for the full list.`,` |
| 255 |
First offending element:`,t);return}const o=ZO(e);if(o){console.error(`[wp.os] <${e}> is not a registered os-* component. Did you mean <${o}>? |
| 256 |
|
| 257 |
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'.`,` |
| 258 |
First offending element:`,t);return}console.error(`[wp.os] <${e}> looks like a os-* tag but no component by that name exists. |
| 259 |
|
| 260 |
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.`,` |
| 261 |
First offending element:`,t)}function wb(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||Jc.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||QO(t,e)},YO)}function yb(e){e instanceof Element&&(wb(e),e.shadowRoot&&yr(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];wb(o),o.shadowRoot&&yr(o.shadowRoot)}}function yr(e){if(mb.has(e))return;mb.add(e),yb(e),new MutationObserver(n=>{for(let o=0;o<n.length;o++){const s=n[o].addedNodes;for(let i=0;i<s.length;i++){const r=s[i];r.nodeType===1&&yb(r)}}}).observe(e,{childList:!0,subtree:!0})}function eM(){const e=Element.prototype,t=e.attachShadow;if(t.__wpdPatched)return;const n=function(o){const s=t.call(this,o);return s.mode==="open"&&yr(s),s};n.__wpdPatched=!0,e.attachShadow=n}function tM(){gb||typeof document>"u"||(gb=!0,eM(),yr(document))}const bb={appearance:{radius:56,bodyColor:789263,bodyAlpha:1,hueStart:296.5,hueSpan:-52.5,hueAngle:225,hueDrift:0,hueSpin:0,hueLoop:!0,saturation:1,lightness:.75,iridescence:0,outlineWidth:3,glow:10,glowBlur:!0,eyeColor:16776191,eyeScale:.3},physics:{points:12,shapePreset:"blob",shapeLobes:3,shapeAmount:1,shapeAngle:0,shapeShuffle:60,radialStiffness:460,edgeStiffness:540,bendStiffness:170,pressure:2400,damping:9,airDamping:.5,magnetStrength:2200,magnetRange:260,magnetGrip:.24,magnetDamping:7,floatAmplitude:10,floatSpeed:1.1,idleWobble:.085,idleWobbleSpeed:.55,speedStretch:.3,friction:.86,restitution:.2,dragStiffness:480,throwBoost:1,minStretch:.55,maxStretch:1.7,minAngularGap:.25,limitIterations:3,dragMaxAccel:9e3,subStep:1/240,maxSubSteps:8}},te={radius:[16,220],bodyAlpha:[0,1],hueStart:[-720,720],hueSpan:[-360,360],hueDrift:[-180,180],hueAngle:[-360,360],hueSpin:[-180,180],saturation:[0,1],lightness:[.15,1],iridescence:[0,2],outlineWidth:[.5,24],glow:[0,20],eyeScale:[.05,.6],points:[12,128],shapeLobes:[0,8],shapeAmount:[0,1.4],shapeAngle:[-360,360],shapeShuffle:[0,3600],radialStiffness:[0,2e3],edgeStiffness:[0,4e3],bendStiffness:[0,2e3],pressure:[0,8e3],damping:[0,30],airDamping:[0,20],magnetStrength:[0,8e3],magnetRange:[0,2e3],magnetGrip:[0,.6],magnetDamping:[0,40],floatAmplitude:[0,200],floatSpeed:[0,20],idleWobble:[0,.4],idleWobbleSpeed:[0,8],speedStretch:[0,.8],friction:[0,1],restitution:[0,1],dragStiffness:[1,4e3],throwBoost:[0,4],minStretch:[.1,1],maxStretch:[1,4],minAngularGap:[0,.9],limitIterations:[0,8],dragMaxAccel:[100,2e5],subStep:[1/1e3,1/30],maxSubSteps:[1,32]};function ne(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function vb(e,t){if(typeof e=="number"&&Number.isFinite(e))return Math.min(16777215,Math.max(0,Math.floor(e)));if(typeof e=="string"){const n=e.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{6}$/.test(n))return Number.parseInt(n,16);if(/^[0-9a-fA-F]{3}$/.test(n)){const[o,s,i]=n.split("");return Number.parseInt(`${o}${o}${s}${s}${i}${i}`,16)}}return t}function _b(e,t){return typeof e=="boolean"?e:t}const nM=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function oM(e,t){return nM.includes(e)?e:t}function us(e,t=bb){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:ne(o.radius,t.appearance.radius,te.radius),bodyColor:vb(o.bodyColor,t.appearance.bodyColor),bodyAlpha:ne(o.bodyAlpha,t.appearance.bodyAlpha,te.bodyAlpha),hueStart:ne(o.hueStart,t.appearance.hueStart,te.hueStart),hueSpan:ne(o.hueSpan,t.appearance.hueSpan,te.hueSpan),hueDrift:ne(o.hueDrift,t.appearance.hueDrift,te.hueDrift),hueLoop:_b(o.hueLoop,t.appearance.hueLoop),hueAngle:ne(o.hueAngle,t.appearance.hueAngle,te.hueAngle),hueSpin:ne(o.hueSpin,t.appearance.hueSpin,te.hueSpin),saturation:ne(o.saturation,t.appearance.saturation,te.saturation),lightness:ne(o.lightness,t.appearance.lightness,te.lightness),iridescence:ne(o.iridescence,t.appearance.iridescence,te.iridescence),outlineWidth:ne(o.outlineWidth,t.appearance.outlineWidth,te.outlineWidth),glow:ne(o.glow,t.appearance.glow,te.glow),glowBlur:_b(o.glowBlur,t.appearance.glowBlur),eyeColor:vb(o.eyeColor,t.appearance.eyeColor),eyeScale:ne(o.eyeScale,t.appearance.eyeScale,te.eyeScale)},r={points:Math.round(ne(s.points,t.physics.points,te.points)),shapePreset:oM(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(ne(s.shapeLobes,t.physics.shapeLobes,te.shapeLobes)),shapeAmount:ne(s.shapeAmount,t.physics.shapeAmount,te.shapeAmount),shapeAngle:ne(s.shapeAngle,t.physics.shapeAngle,te.shapeAngle),shapeShuffle:ne(s.shapeShuffle,t.physics.shapeShuffle,te.shapeShuffle),radialStiffness:ne(s.radialStiffness,t.physics.radialStiffness,te.radialStiffness),edgeStiffness:ne(s.edgeStiffness,t.physics.edgeStiffness,te.edgeStiffness),bendStiffness:ne(s.bendStiffness,t.physics.bendStiffness,te.bendStiffness),pressure:ne(s.pressure,t.physics.pressure,te.pressure),damping:ne(s.damping,t.physics.damping,te.damping),airDamping:ne(s.airDamping,t.physics.airDamping,te.airDamping),magnetStrength:ne(s.magnetStrength,t.physics.magnetStrength,te.magnetStrength),magnetRange:ne(s.magnetRange,t.physics.magnetRange,te.magnetRange),magnetGrip:ne(s.magnetGrip,t.physics.magnetGrip,te.magnetGrip),magnetDamping:ne(s.magnetDamping,t.physics.magnetDamping,te.magnetDamping),floatAmplitude:ne(s.floatAmplitude,t.physics.floatAmplitude,te.floatAmplitude),floatSpeed:ne(s.floatSpeed,t.physics.floatSpeed,te.floatSpeed),idleWobble:ne(s.idleWobble,t.physics.idleWobble,te.idleWobble),idleWobbleSpeed:ne(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,te.idleWobbleSpeed),speedStretch:ne(s.speedStretch,t.physics.speedStretch,te.speedStretch),friction:ne(s.friction,t.physics.friction,te.friction),restitution:ne(s.restitution,t.physics.restitution,te.restitution),dragStiffness:ne(s.dragStiffness,t.physics.dragStiffness,te.dragStiffness),throwBoost:ne(s.throwBoost,t.physics.throwBoost,te.throwBoost),minStretch:ne(s.minStretch,t.physics.minStretch,te.minStretch),maxStretch:ne(s.maxStretch,t.physics.maxStretch,te.maxStretch),minAngularGap:ne(s.minAngularGap,t.physics.minAngularGap,te.minAngularGap),dragMaxAccel:ne(s.dragMaxAccel,t.physics.dragMaxAccel,te.dragMaxAccel),limitIterations:Math.round(ne(s.limitIterations,t.physics.limitIterations,te.limitIterations)),subStep:ne(s.subStep,t.physics.subStep,te.subStep),maxSubSteps:Math.round(ne(s.maxSubSteps,t.physics.maxSubSteps,te.maxSubSteps))};return{appearance:i,physics:r}}const Eb="desktop-mode-mio-position",kb="os-mio",sM="os-mio-toggle",iM=`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"> |
| 262 |
<defs><linearGradient id="mio" x1="19" y1="19" x2="5" y2="5" gradientUnits="userSpaceOnUse"> |
| 263 |
<stop offset="0" stop-color="#3f6dff"/><stop offset=".5" stop-color="#a855f7"/><stop offset="1" stop-color="#ff4fd8"/> |
| 264 |
</linearGradient></defs> |
| 265 |
<circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/> |
| 266 |
<rect x="8" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 267 |
<rect x="13.1" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 268 |
</svg>`)}`;class rM{constructor(t){this.layer=null,this.handle=null,this.parked=null,this.generation=0,this.loading=null,this.look=wa(),this.options=t,this.enabled=t.enabled,this.look=Qf(t.savedLook),this.config=this.resolveConfig()}boot(){this.enabled&&this.mount()}api(){return{isEnabled:()=>this.enabled,enable:()=>this.setEnabled(!0),disable:()=>{this.setEnabled(!1)},toggle:()=>this.setEnabled(!this.enabled),getPosition:()=>this.handle?.getPosition()??null,setPosition:(t,n)=>this.handle?.setPosition(t,n),getConfig:()=>this.config,setConfig:t=>{this.config=us(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=G0(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=us({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=wa(),this.config=this.resolveConfig(),this.handle?.applyConfig(this.config),this.commitLook()}}}async setEnabled(t){t!==this.enabled&&(this.enabled=t,this.generation++,this.options.persist(t),L(t?"os.mio.enabled":"os.mio.disabled",{}),L(b.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount())}resolveConfig(){const t=us(this.options.serverConfig,bb),n=Y("os.mio.config",t),o=us(n,t);return us({appearance:this.look.appearance,physics:this.look.physics},o)}commitLook(){this.options.persistLook?.({appearance:{...this.look.appearance},physics:{...this.look.physics}})}ensureLayer(){if(this.layer&&this.layer.isConnected)return this.layer;const t=document.getElementById(kb);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=kb,n.className="os-mio",n.setAttribute("aria-hidden","true"),this.options.shell.appendChild(n),this.layer=n,n}async mount(){const t=this.generation;if(this.handle)return;const n=this.parked;if(n){this.parked=null,n.layer.style.removeProperty("display"),n.handle.applyConfig(this.config),n.handle.setAnimating(!0),this.handle=n.handle,this.layer=n.layer;return}try{await this.loadBundle()}catch(i){console.warn("[desktop-mode/mio] bundle failed to load.",i);return}if(t!==this.generation||!this.enabled)return;const o=window.openStationMountMio;if(typeof o!="function"){console.warn("[desktop-mode/mio] bundle loaded but did not publish window.openStationMountMio.");return}const s=await o({host:this.ensureLayer(),config:this.config,position:aM(),savePosition:Sb});if(!s){this.layer?.remove(),this.layer=null;return}if(t!==this.generation||!this.enabled){const i=this.layer;this.layer=null,s.setAnimating(!1),i?(i.style.display="none",this.parked={handle:s,layer:i}):s.destroy();return}this.handle=s}unmount(){const t=this.handle,n=this.layer;if(this.handle=null,this.layer=null,!t||!n){n?.remove();return}const o=t.getPosition();o&&Sb(o),t.setAnimating(!1),n.style.display="none",this.parked={handle:t,layer:n}}loadBundle(){if(typeof window.openStationMountMio=="function")return Promise.resolve();if(!this.loading){if(!this.options.bundleUrl)return Promise.reject(new Error("No Mio bundle URL in the shell config."));this.loading=_e(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function aM(){try{const e=window.localStorage.getItem(Eb);if(!e)return null;const t=JSON.parse(e);return typeof t?.x!="number"||typeof t?.y!="number"||!Number.isFinite(t.x)||!Number.isFinite(t.y)?null:{x:t.x,y:t.y}}catch{return null}}function Sb(e){try{window.localStorage.setItem(Eb,JSON.stringify(e))}catch{}}const Ab=8,lM=e=>`<rect x="28" y="5" width="8" height="12" rx="2" fill="currentColor" transform="rotate(${360/Ab*e} 32 32)"/>`,cM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'+Array.from({length:Ab},(e,t)=>lM(t)).join("")+'<circle cx="32" cy="32" r="15.5" fill="none" stroke="currentColor" stroke-width="9"/></svg>',dM=`data:image/svg+xml;base64,${btoa(cM)}`,uM='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 4c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8Zm0 1.5c3.4 0 6.2 2.7 6.5 6l-1.2-.6-.8-.4c-.1 0-.2 0-.3-.1H16c-.1-.2-.4-.2-.7 0l-2.9 2.1L9 11.3h-.7L5.5 13v-1.1c0-3.6 2.9-6.5 6.5-6.5Zm0 13c-2.7 0-5-1.7-6-4l2.8-1.7 3.5 1.2h.4s.2 0 .4-.2l2.9-2.1.4.2c.6.3 1.4.7 2.1 1.1-.5 3.1-3.2 5.4-6.4 5.4Z"/></svg>',fM=2400,Cb="os-notch";function pM(e,t){document.getElementById(Cb)?.remove();const n=document.createElement("button");n.type="button",n.id=Cb,n.className="os-notch",n.setAttribute("aria-label",E("Open the site assistant"));const o=document.createElement("span");o.className="os-notch__glyph",o.setAttribute("aria-hidden","true"),o.innerHTML=uM,n.appendChild(o);const s=document.createElement("span");s.className="os-notch__label",s.setAttribute("aria-hidden","true"),s.textContent=E("Site assistant"),n.appendChild(s);const i=document.createElement("span");i.className="os-notch__message",i.setAttribute("aria-live","polite"),n.appendChild(i),n.addEventListener("click",t);let r=null;const a=l=>{r!==null&&window.clearTimeout(r),i.textContent=l,n.classList.add("os-notch--speaking"),r=window.setTimeout(()=>{r=null,n.classList.remove("os-notch--speaking"),window.setTimeout(()=>{n.classList.contains("os-notch--speaking")||(i.textContent="")},200)},fM)};return e.appendChild(n),{say:a,destroy:()=>{r!==null&&window.clearTimeout(r),n.remove()}}}function hM(){return document.fullscreenElement!==null}function mM(){if(hM()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function Ib(e){const t=document.createElement("span");return t.className="os-shortcuts__chord",e.forEach((n,o)=>{if(o>0){const i=document.createElement("span");i.className="os-shortcuts__plus",i.textContent="+",t.appendChild(i)}const s=document.createElement("kbd");s.className="os-shortcuts__kbd",s.textContent=n,t.appendChild(s)}),t}function gM(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const c=document.createElement("h2");c.className="os-shortcuts__heading",c.textContent=e.heading,t.appendChild(c)}const n=document.createElement("div");n.className="os-shortcuts__scroller";const o=document.createElement("table");o.className="os-shortcuts__table";const s=e.headers??{},i=["key","outside","inside","showDesktop"],r=document.createElement("thead"),a=document.createElement("tr");for(const c of i){const d=document.createElement("th");d.scope="col",d.textContent=s[c]??"",a.appendChild(d)}r.appendChild(a),o.appendChild(r);const l=document.createElement("tbody");for(const c of e.rows??[]){const d=document.createElement("tr"),u=document.createElement("td");if(u.className="os-shortcuts__key-cell",u.appendChild(Ib(c.keys??[])),c.note){const f=document.createElement("span");f.className="os-shortcuts__note",f.textContent=c.note,u.appendChild(f)}d.appendChild(u);for(const f of["outside","inside","showDesktop"]){const p=document.createElement("td");p.textContent=c[f]??"",d.appendChild(p)}l.appendChild(d)}return o.appendChild(l),n.appendChild(o),t.appendChild(n),t}function wM(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const o=document.createElement("h2");o.className="os-shortcuts__heading",o.textContent=e.heading,t.appendChild(o)}const n=document.createElement("ul");n.className="os-shortcuts__list";for(const o of e.items??[]){const s=document.createElement("li");s.className="os-shortcuts__item",s.appendChild(Ib(o.keys??[]));const i=document.createElement("span");i.className="os-shortcuts__description",i.textContent=o.description??"",s.appendChild(i),n.appendChild(s)}return t.appendChild(n),t}function yM(e){e.innerHTML="";const t=document.createElement("div");t.className="os-shortcuts";const n=window.openStationAdminBar?.shortcuts;if(!n){const o=document.createElement("p");o.className="os-shortcuts__empty",o.textContent="Keyboard shortcuts are unavailable.",t.appendChild(o),e.appendChild(t);return}n.contextual&&t.appendChild(gM(n.contextual)),n.general&&t.appendChild(wM(n.general)),e.appendChild(t)}const Qc="openstation-shortcuts",bM=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round"><rect x="5" y="14" width="54" height="36" rx="7"/><path d="M17 26h2M27 26h2M37 26h2M47 26h2M22 39h20"/></svg>')}`;function vM(e){e({id:Qc,baseId:Qc,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:bM,native:!0,render:yM,width:760,height:560,minWidth:480,minHeight:360})}const xb="openstation-rebrand",_M=1200,EM="a[href], button:not([disabled])";async function kM(e){const t=e.seenIntrosUrl;if(t)try{await Fe(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:xb})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function SM(){const e=document.createElement("div");e.className="os-announce",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","os-announce-title"),e.setAttribute("aria-describedby","os-announce-desc");const t=document.createElement("div");t.className="os-announce__card",e.appendChild(t);const n=document.createElement("div");n.className="os-announce__hero",t.appendChild(n);const o=document.createElement("span");o.className="os-announce__eyebrow";const s=document.createElement("span");s.className="os-announce__eyebrow-dot",s.setAttribute("aria-hidden","true"),o.appendChild(s),o.appendChild(document.createTextNode(E("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=E("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=E("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",t.appendChild(a);const l=document.createElement("p");l.id="os-announce-desc",l.textContent=E("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),a.appendChild(l);const c=document.createElement("p");c.textContent=E("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=E("Everything is already set up. You don't need to install any new plugins, so you can keep using the same features as before."),a.appendChild(d);const u=document.createElement("div");u.className="os-announce__actions",t.appendChild(u);const f=document.createElement("button");return f.type="button",f.className="os-announce__btn os-announce__btn--primary",f.dataset.rebrandDismiss="",f.textContent=E("Got it"),u.appendChild(f),e}async function AM(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(xb))return;await new Promise(c=>window.setTimeout(c,_M));const n=SM(),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?.(),kM(t))};function l(c){if(!n.isConnected){document.removeEventListener("keydown",l,!0);return}if(c.key==="Escape"){c.preventDefault(),a();return}if(c.key!=="Tab")return;const d=Array.from(n.querySelectorAll(EM));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 CM=new Set(["post"]);function Lb(){const e=window.wp?.os?.myWordpress;return e&&typeof e.trashEntity=="function"?e:null}const ed="data-os-trash-drop-active",sn="desktop-mode-recycle-bin",IM=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${sn}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${sn}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${sn}"]`}];let Tb=!1;const td=new Map;let fs=null,Nb=null;function xM(e){return e.payload.type==="desktop-file"}function LM(e){return e.payload.type==="shortcut"}function TM(e){if(!e.kind||!e.ref||!e.entityId||!CM.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return!Number.isFinite(t)||t<=0?!1:Lb()!==null}function Db(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:E("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const s=o.data,i=s?.placement;if(!i)return!1;const r=jn(s);return r.length>1?r.every(a=>a.file?.ref!==sn&&a.canTrash!==!1):i.file?.ref===sn?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=or(s);return i.length>0&&i.every(r=>TM(r))}return IO(o)},onEnter:()=>{n.setAttribute(ed,"")},onLeave:()=>{n.removeAttribute(ed)},onDrop:(o,s)=>{if(n.removeAttribute(ed),xM(o)){Qw(jn(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&xO(o,s))&&LM(o)){const i=Lb();if(!i?.trashEntity)return;const r=i.trashEntity,l=or(o.payload.data).map(c=>({entityId:c.entityId,ref:Number.parseInt(c.ref,10)})).filter(c=>!!c.entityId&&Number.isFinite(c.ref)&&c.ref>0);if(l.length===0)return;Promise.allSettled(l.map(c=>r(c.entityId,c.ref))).then(c=>{const d=c.filter(f=>f.status==="rejected");for(const f of d)console.error("[openstation] recycle-bin: shortcut trash failed:",f.reason);const u=l.length-d.length;(u>1||d.length>0)&&Q({message:d.length>0?`${u} moved to Trash · ${d.length} could not be moved`:`${u} items moved to Trash`,duration:d.length>0?6e3:4e3})})}}})}function NM(e){if(Tb)return;Tb=!0;const t=()=>{for(const{id:n,selector:o}of IM){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=td.get(n);if(!i){r?.deregister(),td.delete(n);continue}r&&r.el===i||(r?.deregister(),td.set(n,{el:i,deregister:Db(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),Z(b.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),Z(b.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){Nb=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;Nb.observe(n,{childList:!0,subtree:!0})}Z(b.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==sn)return;fs?.(),fs=null;const o=document.querySelector("[data-os-recycle-bin-root]");o instanceof HTMLElement&&(fs=Db(e,"recycle-bin-window",o))}),Z(b.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===sn&&(fs?.(),fs=null)})}function nd(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function DM(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function Rb(e){return{appliesTo(t){return nd(t)!==null},accept(t,n){const o=nd(n);if(!o)return!1;const s=Iw({type:e,data:t});return yN(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:E("Send to agent","desktop-mode"),onDrop(t,n,o){const s=nd(o);if(!s)return;const i=Iw({type:t.payload.type,data:t.payload.data}),r=DM();!i||!r||EN({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let Ob=!1;function RM(){Ob||(Ob=!0,Ji("shortcut",Rb("shortcut")),Ji("desktop-file",Rb("desktop-file")))}let Mb=!1,rn=0;function OM(){Mb||(Mb=!0,Te.contribute("openstation_files_subscribe",()=>{const e=Lt(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:rn,sharesVersion:et().state.sharesVersion}}),Te.subscribe("openstation_files",e=>{MM(e)}))}function MM(e){const t=e.folders??[];for(const i of t)pc(i,"remote"),i.updatedAtMs>rn&&(rn=i.updatedAtMs);const n=e.placements??[];for(const i of n)Xi(i,"remote"),i.updatedAtMs>rn&&(rn=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])hc(i,"remote");for(const i of o.placements??[])Xo(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>rn&&(rn=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&Oy(s),e.truncated){const i=Array.from(Lt().hydratedFolders);for(const r of i)Le(r).then(a=>{at(r,a.placements)}).catch(()=>{})}}let Pb=!1;const PM=[];function WM(){if(Pb)return;Pb=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||$M()};PM.push(In("os.placement.changed",e),In("os.shortcut.changed",e),In("os.folder.changed",e))}function $M(){dc().then(t=>{Zi(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from(Lt().hydratedFolders);for(const t of e)Le(t).then(n=>{at(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const ps="os-wallpaper-menu";let Zn=null;function Wb(){return Zn!==null}let $b=0;function UM(e,t,n,o={}){hs();const s=++$b;Us(()=>s===$b,()=>FM(e,t,n,o))}function FM(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,w=typeof f.sort=="number"?f.sort:100;return p!==w?p-w:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(ps),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const l=()=>{r&&(r.remove(),r=null,a=null)};for(const u of n){i.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.heading&&f.setAttribute("heading",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",Ub(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 w=s.querySelector(`[data-menu-item-id="${p.id}"]`);w&&c(p,w);return}hs(),p.onClick(new MouseEvent("click"))}});function c(u,f){l();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(ps,`${ps}--flyout`),p.dataset.parentId=u.id;const w=(u.children??[]).slice().sort((m,h)=>{const y=typeof m.sort=="number"?m.sort:100,v=typeof h.sort=="number"?h.sort:100;return y!==v?y-v:m.label.localeCompare(h.label)});for(const m of w){const h=document.createElement("os-context-menu-option");h.dataset.menuItemId=m.id,h.setAttribute("value",m.id),m.icon&&h.setAttribute("icon",Ub(m.icon)),m.disabled&&h.setAttribute("disabled",""),m.checked&&h.setAttribute("checked",""),h.textContent=m.label,h.addEventListener("os-context-menu-pick",y=>{y.stopPropagation(),hs(),m.onClick(new MouseEvent("click"))}),p.appendChild(h)}document.body.appendChild(p),r=p,a=u,Kg(p,f)}e.appendChild(s),Zn=s,Wl(s);const d=Vg(s,{close:()=>hs(),siblingSelectors:[`.${ps}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),L("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function hs(){Zn&&(document.querySelectorAll(`.${ps}--flyout`).forEach(e=>e.remove()),Zn.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),Zn.remove(),Zn=null,L("os.wallpaper-menu.closed",{}))}function BM(e){const t=[{id:"create-folder",label:e.labels.createFolder,icon:"dashicons-portfolio",sort:10,onClick:()=>e.createFolder()},{id:"new-url",label:e.labels.newUrl,icon:"dashicons-admin-links",sort:12,onClick:()=>e.createUrl()},{id:"add-widget",label:e.labels.addWidget,icon:"dashicons-screenoptions",sort:15,onClick:()=>e.addWidget()},{id:"sort-by",label:e.labels.sortHeading,icon:"dashicons-sort",sort:16,onClick:()=>{},children:[{id:"sort-name-asc",label:e.labels.sortNameAsc,sort:10,checked:e.currentSortMode==="name-asc",onClick:()=>e.sortIcons("name-asc")},{id:"sort-name-desc",label:e.labels.sortNameDesc,sort:20,checked:e.currentSortMode==="name-desc",onClick:()=>e.sortIcons("name-desc")},{id:"sort-date-desc",label:e.labels.sortDateDesc,sort:30,checked:e.currentSortMode==="date-desc",onClick:()=>e.sortIcons("date-desc")},{id:"sort-date-asc",label:e.labels.sortDateAsc,sort:40,checked:e.currentSortMode==="date-asc",onClick:()=>e.sortIcons("date-asc")}]},...e.includeShowDesktop===!1?[]:[{id:"show-desktop",label:e.labels.showDesktop,icon:"dashicons-desktop",sort:20,onClick:()=>e.toggleShowDesktop()}],{id:"os-settings",label:e.labels.osSettings,icon:"dashicons-admin-generic",sort:30,onClick:()=>e.openOsSettings()}],n=(e.serverItems??[]).map(i=>HM(i,e)),o=[...t,...n],s=Y("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function HM(e,t){return{id:e.id,label:e.label,icon:e.icon,sort:e.sort,disabled:e.disabled,onClick:()=>{if(e.callbackId){const n=t.serverCallbacks?.[e.callbackId];if(typeof n=="function")return n()}L("os.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function Ub(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const ms="os-url-dialog";let gs=null;function od(){gs&&(gs.dispatchEvent(new CustomEvent("url-dialog-closed")),gs.remove(),gs=null,L("os.files.url-dialog.closed",{}))}function zM(e){if(od(),Y("os.files.url-dialog",null,e)===!1)return;const n=document.createElement("div");n.className=`${ms}__overlay os-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${ms} os-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${ms}-title`);const s=document.createElement("h2");if(s.id=`${ms}-title`,s.className="os-create-folder-dialog__title",s.textContent=e.title,o.appendChild(s),e.description){const h=document.createElement("p");h.className=`${ms}__description`,h.textContent=e.description,o.appendChild(h)}const i=document.createElement("os-text-field");i.className="os-create-folder-dialog__field",i.setAttribute("label",e.nameLabel??"Name"),i.setAttribute("value",e.initialName??""),i.setAttribute("placeholder","My web app"),i.setAttribute("autocomplete","off"),o.appendChild(i);const r=document.createElement("os-text-field");r.className="os-create-folder-dialog__field",r.setAttribute("label",e.urlLabel??"URL"),r.setAttribute("value",e.initialUrl??"https://"),r.setAttribute("placeholder","https://example.com"),r.setAttribute("type","url"),r.setAttribute("autocomplete","off"),o.appendChild(r);const a=document.createElement("p");a.className="os-create-folder-dialog__error",a.hidden=!0,a.setAttribute("role","alert"),o.appendChild(a);const l=document.createElement("div");l.className="os-create-folder-dialog__actions";const c=document.createElement("os-button");c.className="os-create-folder-dialog__btn os-create-folder-dialog__btn--secondary",c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className="os-create-folder-dialog__btn os-create-folder-dialog__btn--primary",d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(d),o.appendChild(l),n.appendChild(o),document.body.appendChild(n),gs=n,Qi(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=()=>{od(),e.onCancel?.()},w=async()=>{const h=bc(r).trim();if(!h){f("Please enter a URL.");return}const y=/^[a-z][a-z0-9+\-.]*:/i.test(h)?h:`https://${h}`;try{new URL(y)}catch{f("That doesn't look like a valid URL.");return}const v=bc(i).trim();a.hidden=!0,u(!0);try{await e.onSubmit({name:v,url:y}),od()}catch(A){u(!1),f(A instanceof Error?A.message:"Could not save.")}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void w()),n.addEventListener("click",h=>{h.target===n&&p()});const m=h=>{h.key==="Escape"?(h.preventDefault(),p()):h.key==="Enter"&&!h.isComposing&&(h.preventDefault(),w())};o.addEventListener("keydown",m),n.addEventListener("url-dialog-closed",()=>{o.removeEventListener("keydown",m)})}const Fb=[];let sd=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(sd){Promise.resolve().then(o);return}Fb.push(o)}},ready(o){n.whenReady(o)},isReady(){return sd}};t.wp.os=n})();const br="desktop-mode-os-settings";let id=[],vr=Number.POSITIVE_INFINITY,rd=!1;function Ke(e,t=1500){if(id.push(e),t<vr&&(vr=t),rd)return;rd=!0;const n=()=>{const o=id;id=[],vr=Number.POSITIVE_INFINITY,rd=!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:vr}):window.setTimeout(n,0)}function Bb(){const e=window.openStationConfig;if(!e)return;const t=document.getElementById("os-area");if(!t)return;const n=new c0(t),o=document.getElementById("os-wallpaper"),s=e.pluginUrl||"";let i=null;o&&(i=new Fp(o,s));const r=document.getElementById("os-widgets");let a=null;zO(),Pk(),r&&(a=new zI(r,s)),Lp({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const l=new dS({mediaUrl:e.mediaUrl,restNonce:e.restNonce,canUpload:!!e.canUpload,isAdmin:!!e.currentUserIsAdmin,extendedOptions:e.extendedOptions??null,extendedOptionsUrl:e.extendedOptionsUrl??"",osSettingsPanelBundleUrl:e.osSettingsPanelBundleUrl??"",canManageDesktopThemes:!!e.canManageDesktopThemes,desktopThemesUrl:e.desktopThemesUrl??""},i??new Fp(document.createElement("div"),s));l.apply();const c=document.getElementById("os-shell"),d=new rM({shell:c??document.body,bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:l.state.mioEnabled,persist:S=>{l.state.mioEnabled=S,l.save()},savedLook:l.state.mioStyle,persistLook:S=>{l.state.mioStyle=S,l.save()}}),u=d.api();d.boot(),a&&qO({osSettings:l,layer:a});const f=new bx({aiSearchUrl:e.aiSearchUrl??"",restNonce:e.restNonce,adminUrl:e.adminUrl,isAiAvailable:()=>e.aiAssistant?.available===!0&&e.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>l.getOsSettingsSnapshot().ai.enabled!==!1},e.aiAssistantBundleUrl??"");f.attachAsk(Sx({config:()=>e,fallbackContext:()=>({close:()=>f.close(),openInWindow:(S,G,X)=>{n.open({url:S,title:G,icon:X??"dashicons-admin-generic"})},confirm:S=>Bn({message:S})})}));const p=new mL,w=new NL;document.addEventListener(we.START,S=>{const X=S.detail?.payload;if(!X||X.type!=="shortcut"&&X.type!=="desktop-file")return;const oe=X.data?.bridgePayload;oe&&p.start(oe)}),document.addEventListener(we.END,()=>{p.end()}),Ke(()=>GL(w)),Ke(()=>sT(n)),window.addEventListener("message",S=>{if(S.origin!==window.location.origin)return;const G=S.data;!G||G.type!=="os-drop-failed"||Q({message:"Could not insert into the editor."})}),Mg({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>f.open(),close:()=>f.close(),isOpen:()=>f.isOpen}),dT(),u0(n),g0(n),Ke(()=>{new JC({manager:n,adminUrl:e.adminUrl}).install(),QC(n);const S=new aI({manager:n,adminUrl:e.adminUrl});S.install(),document.addEventListener(ym,()=>S.install(),{once:!0})}),document.addEventListener("os-open-ai",()=>{Dl("desktop-mode-ai-assistant")}),document.addEventListener("click",S=>{const G=S.target;!(G instanceof Element)||!G.closest("#wp-admin-bar-command-palette")||(S.preventDefault(),S.stopImmediatePropagation(),Dl("desktop-mode-ai-assistant"))},!0);const m=document.getElementById("os-dock"),h=document.getElementById("os-shell"),y=h?.querySelector(".os-shell__body");let v=null,A=!1;const D=S=>S.some(G=>!!G.windowId&&n.getAllByBaseIdOnActiveDesktop(G.windowId).length>0),_=nx({manager:n,appendSystemTile:S=>v?.appendSystemTile(S),removeSystemTile:S=>v?.removeSystemTile(S)}),O=_.sync;_0({getSnapshot:()=>l.getOsSettingsSnapshot(),openById:(S,G)=>_.openById(S,G),adminUrl:e.adminUrl});const P=S=>{const G=ae(S,e.adminUrl),X=v?v.getMenuItems():e.dockItems??[];for(const oe of X){if(ae(oe.url,e.adminUrl)===G)return{title:oe.title,icon:oe.icon,url:oe.url,submenu:oe.submenu,selfLabel:oe.selfLabel,multi:oe.multi};for(const ge of oe.submenu??[])if(ae(ge.url,e.adminUrl)===G)return{title:ge.title,icon:oe.icon,url:oe.url,multi:oe.multi}}return null};if($0({adminUrl:e.adminUrl,deriveSlug:S=>ae(S,e.adminUrl),openWindow:S=>{n.open(S)},findDockEntry:P}),St({id:"desktop-mode-dashboard",nativeWindowId:"desktop-mode-dashboard",matches:(S,G)=>S0(G),enabled:S=>S.stationHomeEnabled===!0}),St({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(S,G)=>{if(!G.pathname.endsWith("/edit.php"))return!1;const X=G.searchParams.get("post_type");return!X||X==="post"},enabled:S=>S.nativePostsEnabled===!0}),St({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(S,G)=>G.pathname.endsWith("/edit.php")?G.searchParams.get("post_type")==="page":!1,enabled:S=>S.nativePagesEnabled===!0}),St({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(S,G)=>G.pathname.endsWith("/users.php"),enabled:S=>S.nativeUsersEnabled===!0}),St({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(S,G)=>{if(v0(G))return!1;const X=G.pathname;return X.endsWith("/profile.php")?!0:X.endsWith("/user-edit.php")?G.searchParams.has("user_id"):!1},enabled:S=>S.nativeUsersEnabled===!0,onMatch:(S,G)=>{const X=parseInt(G.searchParams.get("user_id")??"0",10);X>0&&pS(X)}}),St({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(S,G)=>G.pathname.endsWith("/edit-comments.php"),enabled:S=>S.nativeCommentsEnabled===!0,onMatch:(S,G)=>{const X=parseInt(G.searchParams.get("p")??"0",10);X>0?$p(X):mS()}}),St({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(S,G)=>{const X=G.pathname;return X.endsWith("/plugins.php")||X.endsWith("/plugin-install.php")},enabled:S=>S.nativePluginsEnabled===!0,onMatch:(S,G)=>{const X=G.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>yP).then(oe=>{oe.setPluginsWindowTab(X)})}}),m&&h&&y&&e.dockItems){t.classList.add("os-area--with-dock");const S=l.getOsSettingsSnapshot(),G=S.desktopLayout,X=S.dockPlacement,oe=be=>{zm(t,be,{openWindow:_.openById,manager:n,deriveWindowId:Ce=>ae(Ce,e.adminUrl)})};v=wx({shellRoot:h,shellBody:y,bottomDockEl:m,desktopArea:t,windowManager:n,adminUrl:e.adminUrl,renderIcons:oe,getSettings:()=>{const be=l.getOsSettingsSnapshot();return{navPlacement:be.navPlacement,navOrder:be.navOrder}}},G,e.dockItems,e.desktopIcons,X),lC({windowManager:n,adminUrl:e.adminUrl,getMenuItems:()=>v?.getMenuItems()??[],getSystemItem:be=>v?.getSystemTile(be)??null}),pM(h,()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))});const ge=rL(e.pwa?.appName||"WordPress",Q),wt={id:K_,title:"System",icon:X_,navKind:"control",placeable:!0,order:Ys.system,onOpen:$,get submenu(){const be=[{title:"OpenStation Preferences",url:"",windowId:br,onSelect:()=>$()}];return e.homeUrl&&be.push({title:"View site",url:e.homeUrl}),be.push({title:"Fullscreen",url:"",onSelect:mM},{title:"Keyboard shortcuts",url:"",windowId:Qc,onSelect:()=>vM(Ce=>{n.open(Ce)})},{title:"Report a bug",url:"",windowId:$o,onSelect:()=>F()}),!sg()&&!A&&be.push({title:ge.title,url:"",onSelect:ge.onOpen}),e.logoutUrl&&be.push({title:"Log out",url:"",onSelect:()=>{window.location.assign(e.logoutUrl)}}),be},isOpen:()=>D(wt.submenu??[])};v.appendSystemTile(wt),ig().then(be=>{A=be})}function $(S={}){const G={extended:"features",effects:"windows"},X=S.tabId?G[S.tabId]:void 0;X&&(S={...S,tabId:X}),S.tabId&&(l.activeTabId=S.tabId),n.open({id:br,baseId:br,url:"#os-settings",title:"OpenStation Preferences",icon:dM,native:!0,render:oe=>l.renderPanel(oe),width:820,height:720,minWidth:560,minHeight:480}),S.tabId&&l.focusTab(S.tabId)}function F(){xa("desktop-mode-bug-report"),n.open({id:$o,baseId:$o,url:`#${$o}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:S=>zx(S),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("os-open-bug-report",()=>{F()}),v&&(v.appendSystemTile(J_()),v.appendSystemTile({id:sM,title:"Mio",icon:iM,navKind:"control",placeable:!0,order:Ys.mio,isOpen:()=>u.isEnabled(),onOpen:()=>{u.toggle()}}),v.appendSystemTile({id:q_,title:"Overview",icon:Y_,navKind:"control",placeable:!0,order:Ys.overview,isOpen:()=>n._overviewActive,onOpen:()=>{n._overviewActive?n.exitOverview():n.enterOverview()}}));const k=v?.getPrimary()??null;O(Array.isArray(e.nativeWindows)?e.nativeWindows:[]);const W=c1(e.session);function N(S){return S==="desktop-mode-dashboard"&&l.getOsSettingsSnapshot().stationHomeEnabled!==!0?!1:S===br?($(),!0):S===$o?(F(),!0):_.openById(S)}const g=typeof e.soloWindow=="string"?e.soloWindow:"";g&&queueMicrotask(()=>{if(N(g))return;const S=g.startsWith("os-game-")?g.slice(8):"";if(S){Kp.launch(S).catch(G=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",G)});return}typeof console<"u"&&console.error(`[openstation] solo window "${g}" is not registered; nothing to paint.`)});const C=W&&!g?u1(n,e,t,N).catch(S=>{typeof console<"u"&&console.error("[openstation] session restore failed:",S)}):Promise.resolve(),U=e.defaultWindow?.enabled!==!1,V=e.defaultWindow?.url??"",z=typeof V=="string"&&V.startsWith("native:");!g&&p1({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:W,defaultEnabled:U,isNativeDefault:z})&&C.then(()=>f1(n,e).catch(S=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",S)}));const I=w1(n,e);b1(I);const x=async S=>{try{const G=await Yl(n,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:S})},{source:"desktop-mode/default-window"});if(!G.ok)throw new Error(`HTTP ${G.status}`);const X=await G.json();e.defaultWindow=X,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:X}))}catch(G){L(b.SHELL_ERROR,{scope:"default-window-save",error:G}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",G)}};if(n.onToggleStartupRequested=S=>{const G=e.defaultWindow,X=!!S.config.native,oe=X?`native:${S.id}`:S.getCurrentUrl(),ge=X?G?.url===oe:Ad(G?.url??"")===Ad(oe),wt=!!G?.enabled&≥x(wt?null:oe)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!W&&z){const S=V.slice(7);queueMicrotask(()=>{N(S)})}const B=S=>{v?.appendSystemTile(S)},M=KO({layer:a});M(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const j=$S({osSettings:l});j(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),Z(b.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",S=>{const G=S?.wallpapers;Array.isArray(G)&&j(G)});const R=FS();R(Array.isArray(e.serverGames)?e.serverGames:[]);const H=BS();H(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const T=tA();T(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const K=sA();K(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const q=cA();q(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const ce=mA();ce(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const ve=qA();ve(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const ye=KA();ye(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),ZA({manager:n,osSettings:l}),mE({osSettings:l}),P0({manager:n}),IA({manager:n,osSettings:l}),NA({manager:n,openUrl:S=>{if(S.windowId&&_.openById(S.windowId,{source:"related-entities",...S.params?{params:S.params}:{}})||!S.url||Ge(S.url))return;const G=ae(S.url,e.adminUrl);n.open({id:G,baseId:G,url:S.url,title:S.label,icon:S.icon||"dashicons-admin-links"})}}),zA({manager:n});const he=JA();he(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),kC()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),CC(),IC()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),TC()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),um(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),HC()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const ln=VC(n);DA(n),Ke(()=>RA()),w0(),Z("os.shell.toast","desktop-mode/shell-toast",S=>{!S||typeof S.message!="string"||Q({message:S.message,action:S.action,duration:S.duration})});const gd=e,NP=gd.recycleBinCount;xx(Number(NP)||0,typeof gd.recycleBinCountUrl=="string"?gd.recycleBinCountUrl:""),Wx({getRecycleBinCount:Ix}),window.__openStationConnectionBridge=ln,Z(b.WINDOW_CLOSED,"desktop-mode/connection-cleanup",S=>{S?.windowId&&ln.onWindowClosed(S.windowId)}),Z(b.IFRAME_READY,"desktop-mode/connection-rearm",S=>{S?.windowId&&ln.onIframeReady(S.windowId)});const DP=ZI(n),RP=S=>{if(v){v.applyDesktopIcons(S);return}zm(t,S,{openWindow:_.openById,manager:n,deriveWindowId:G=>ae(G,e.adminUrl)})},wd=()=>{v&&xR(v.getNav().desktop,v.getNavItems(),l.getOsSettingsSnapshot().dockPromotedPositions)},OP=l1({layoutDispatcher:v,desktopArea:t,config:e,syncNativeWindows:O,syncServerWidgets:M,syncServerWallpapers:j,syncServerCommands:T,syncServerSettingsTabs:K,syncServerTitleBarButtons:q,syncServerWindowActions:ce,syncServerUnfocusEffects:ve,syncServerWindowLinkRenderers:ye,syncServerDockRailRenderers:he,syncServerGames:R,syncServerDesktopThemes:H,renderIcons:RP,refreshRootPlacements:()=>{Le(0).then(S=>{at(0,S.placements)}).catch(()=>{})},syncShortcuts:wd});document.addEventListener(wp,()=>{v&&v.setLayout(v.getLayout());for(const S of n._stack)try{S.repaintWindowControls(),S.repaintThemedChrome()}catch(G){L(b.SHELL_ERROR,{scope:"desktop-theme-repaint",id:S.id,error:G})}}),l.subscribeOsSettings(S=>{if(!v)return;const G=v.getLayout(),X=v.getDockPlacement();v.setDockPlacement(S.dockPlacement),v.setLayout(S.desktopLayout),Os.dock=v.getPrimary(),Os.sideDock=v.getSide(),Os.desktopLayout=S.desktopLayout,Os.dockPlacement=v.getDockPlacement(),G===S.desktopLayout&&X===S.dockPlacement&&v.refresh(),wd(),mw(S.desktopLayout)}),LR(wd),mw(l.getOsSettingsSnapshot().desktopLayout);const Os=iN({manager:n,dock:k,layoutDispatcher:v,osSettings:l,iconsApi:ux,filesApi:He,saveSession:I,widgetLayer:a,registerWindow:DP,openWindowById:_.openById,openNewWindowById:_.openNewById,loadWindowScriptById:_.loadScriptById,placeSystemTile:B,setDefaultWindow:x,refreshMenu:OP,openOsSettings:$,aiAssistant:f,dragBridge:p,dragManager:w,connect:ln.connect,getConnection:ln.getConnection,mio:u,wallpaperSuspend:{suspend:S=>i?.suspend(S),resume:S=>i?.resume(S),isSuspended:()=>i?.isSuspended()??!1},config:e});rN(Os),Ke(()=>NM(w)),Ke(()=>RM()),HS(),cE(),e.gamesEnabled!==!1&&ZS({currentUserId:Number(e.currentUserId)||0}),Ke(()=>WT()),Ke(()=>UT()),Ke(()=>JT({currentUserId:Number(e.currentUserId)||0})),BO({host:t,config:e,onError:S=>{Q({message:S})}}),pN({openUrl:({id:S,url:G,title:X,icon:oe})=>(Ge(G)||n.open({id:S,baseId:S,url:G,title:X,icon:oe}),!0),openNativeWindow:S=>_.openById(S),deriveWindowId:S=>ae(S,e.adminUrl)}),bw(e.userFileAssociations??{}),jO({update:e.coreUpdate,openUrl:({url:S,title:G})=>{Ge(S)||n.open({id:"update-core",baseId:"update-core",url:S,title:G,icon:"dashicons-update"})}});const Qb=({url:S,title:G})=>{if(Ge(S))return;const X=ae(S,e.adminUrl);n.open({id:X,baseId:X,url:S,title:G,icon:"dashicons-info"})};if(fb({notices:e.coreNotices,openUrl:Qb}),fb({notices:e.pluginNotices,openUrl:Qb,keyPrefix:"plugin-notice"}),AM({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){Lw({baseUrl:e.filesUrl,nonce:e.restNonce});const S=document.getElementById("os-area");if(S){const G=gy(S,0),X=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},oe=setTimeout(X,2e3);G.hydrated.then(()=>{clearTimeout(oe),X()})}}Ke(()=>OM()),Ke(()=>WM()),Ke(()=>pT()),L(b.COMPONENTS_REGISTERED,{tags:[...Vi]}),rT(),dL(e,Q);const ev=()=>{gv(e.shellOverlaysBundleUrl??""),hv(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(ev,{timeout:1500}):window.setTimeout(ev,0),L(b.INIT,{config:e}),sd=!0;const MP=Fb.splice(0);for(const S of MP)try{S()}catch(G){L(b.SHELL_ERROR,{scope:"when-ready-cb",error:G}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",G)}l.apply(),a?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),a?.disposeAll()}),v1(),QT(n,e);const tv=(S,G=!0)=>{const X=He.store.getState().placementsByFolder.get(0)??[],oe=S(X),ge=Math.max(1,Math.floor((t.clientHeight-16)/110)),wt=new Set;let be=0;for(const Ce of oe){const Re=Nt(16+Math.floor(be/ge)*96,16+be%ge*110,wt,t);wt.add(`${Re.col},${Re.row}`),be++,!(Ce.x===Re.x&&Ce.y===Re.y)&&(He.store.upsertPlacement({...Ce,x:Re.x,y:Re.y,sortOrder:be}),!(!G||ir(Ce))&&Hn(Ce.id,{x:Re.x,y:Re.y,sortOrder:be}).catch(yt=>{console.error("[openstation] relayout persist failed",yt)}))}},nv=S=>G=>{const X=G.slice();switch(S){case"name-asc":X.sort((oe,ge)=>oe.file.title.localeCompare(ge.file.title));break;case"name-desc":X.sort((oe,ge)=>ge.file.title.localeCompare(oe.file.title));break;case"date-asc":X.sort((oe,ge)=>oe.updatedAtMs-ge.updatedAtMs);break;case"date-desc":X.sort((oe,ge)=>ge.updatedAtMs-oe.updatedAtMs);break}return X},yd="desktop-mode:root-sort-mode",PP=S=>S==="name-asc"||S==="name-desc"||S==="date-asc"||S==="date-desc";let Ir=(()=>{try{const S=window.localStorage.getItem(yd);return PP(S)?S:null}catch{return null}})();const ov=S=>{Ir=S;try{S?window.localStorage.setItem(yd,S):window.localStorage.removeItem(yd)}catch{}};if(Z("os.files.tile-manually-placed","desktop-mode/root-sort-clear",S=>{S?.folderId===0&&ov(null)}),typeof ResizeObserver<"u"){let S=t.clientWidth,G=t.clientHeight;new ResizeObserver(()=>{if(!Ir)return;const oe=t.clientWidth,ge=t.clientHeight;oe===S&&ge===G||(S=oe,G=ge,tv(nv(Ir),!1))}).observe(t)}let sv=!1;t.addEventListener("pointerdown",S=>{S.isPrimary&&(sv=S.target===t)}),t.addEventListener("click",S=>{l.state.showDesktopOnWallpaperClick&&S.target===t&&sv&&(t.classList.contains("os-area--overview")||Wb()||w.recentlyEndedDrag()||LT()||n.toggleShowDesktop())}),t.addEventListener("contextmenu",S=>{if(S.target!==t)return;S.preventDefault();const G=S.clientX,X=S.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(Wb()){hs();return}const oe={x:G,y:X},ge=()=>{const Ce=t.getBoundingClientRect(),Re=Math.max(0,oe.x-Ce.left),yt=Math.max(0,oe.y-Ce.top),Ms=iy(He.store.getState().placementsByFolder.get(0)??[]);return Nt(Re,yt,Ms,t)},wt=(Ce,Re)=>{zM({title:Ce,description:Re,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:yt,url:Ms})=>{const iv=ge(),WP=await Yo({type:"link",ref:Ms,parentId:0,x:iv.x,y:iv.y,meta:yt?{name:yt}:void 0});He.store.upsertPlacement(WP)}})},be=BM({createFolder:()=>{_c({onSubmit:async Ce=>{const Re=await uc({name:Ce}),yt=ge(),Ms=await Yo({type:"folder",ref:String(Re.id),parentId:0,x:yt.x,y:yt.y});He.store.upsertFolder(Re),He.store.upsertPlacement(Ms)}})},createUrl:()=>wt("New URL","Opens the URL in a new browser tab."),addWidget:()=>a?.openPicker(),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>$(),sortIcons:Ce=>{ov(Ce),tv(nv(Ce))},currentSortMode:Ir,includeShowDesktop:!l.state.showDesktopOnWallpaperClick,position:{x:G,y:X},labels:{createFolder:"New folder",showDesktop:"Show desktop",osSettings:"OpenStation Preferences",sortHeading:"Sort by",sortNameAsc:"Name (A → Z)",sortNameDesc:"Name (Z → A)",sortDateAsc:"Date (oldest first)",sortDateDesc:"Date (newest first)",newUrl:"New URL",addWidget:"Add widget"},serverItems:e.serverWallpaperMenuItems??[]});UM(document.body,{x:G,y:X},be)})()}),Promise.resolve().then(()=>TP).then(S=>{S.bootOsFileDrop({config:e.dropConfig,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.desktopStorage})}),document.dispatchEvent(new CustomEvent("os-init",{detail:{config:e,restored:W}}))}tM(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Bb):Bb();const ue={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"},GM=32;function jM(e){if(!e)return[];const t=[];for(let n=0;n<e.length;n++){const o=e[n];if(o.kind!=="file")continue;const s=typeof o.webkitGetAsEntry=="function"?o.webkitGetAsEntry():null;s&&t.push(s)}return t}function VM(e){const t=e.createReader();return new Promise((n,o)=>{const s=[],i=()=>{t.readEntries(r=>{if(r.length===0){n(s);return}s.push(...r),i()},o)};i()})}function qM(e){return new Promise((t,n)=>{e.file(t,n)})}async function KM(e){const t={files:[],emptyDirs:[],hadDirectory:!1};for(const n of e)await Hb(n,"",t,0);return t}async function Hb(e,t,n,o){if(o>GM)return;if(e.isFile){try{const r=await qM(e);n.files.push({file:r,relativePath:t?`${t}${r.name}`:""})}catch{}return}if(!e.isDirectory)return;n.hadDirectory=!0;const s=`${t}${e.name}`;let i=[];try{i=await VM(e)}catch{i=[]}if(i.length===0){n.emptyDirs.push(s);return}for(const r of i)await Hb(r,`${s}/`,n,o+1)}const zb=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function ws(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;if(typeof n.includes=="function")return n.includes("Files");if(typeof n.contains=="function")return n.contains("Files");for(let o=0;o<n.length;o++)if(n[o]==="Files")return!0;return!1}function _r(e){const t=e?.closest?.(".os-window");if(!t)return;const n=/^wp-window-(.+)$/.exec(t.id||"");return n?n[1]:void 0}function YM(e){if(!e)return;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e){const o=_r(n);return o||n.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0}}function Gb(e){const t=window;if(t.__openStationOsFileDropMounted)return t.__openStationOsFileDropMounted;if(!e.config.enabled)return ZM();const n=XM();let o=0,s=null;const i=()=>{o=0,n.classList.remove("is-active"),s!==null&&(clearTimeout(s),s=null)},r=()=>{s!==null&&clearTimeout(s),s=setTimeout(i,250)},a=m=>{ws(m)&&(m.preventDefault(),o++,n.classList.add("is-active"),r())},l=m=>{if(ws(m)){if(m.defaultPrevented){i();return}m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="copy"),r()}},c=()=>{o=Math.max(0,o-1),o===0&&n.classList.remove("is-active")},d=m=>{if(!ws(m))return;if(m.defaultPrevented){i();return}m.preventDefault(),i();const h=jM(m.dataTransfer?.items),y=jb(m);if(h.some(A=>A.isDirectory)){Vb(h,y,e);return}const v=m.dataTransfer?.files?Array.from(m.dataTransfer.files):[];v.length!==0&&ad(v,y,e)},u=()=>i(),f=()=>{document.visibilityState==="hidden"&&i()},p=m=>{if(m.origin!==window.location.origin)return;const h=m.data;if(!h||h.type!=="os-file-drop"||!Array.isArray(h.files)||h.files.length===0)return;const y=h.files.filter(D=>D instanceof File);if(y.length===0)return;const v=YM(m.source);if(!v)return;const A={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"),ad(y,A,e)};window.addEventListener("dragenter",a),window.addEventListener("dragover",l),window.addEventListener("dragleave",c),window.addEventListener("drop",d),window.addEventListener("dragend",u),document.addEventListener("visibilitychange",f),window.addEventListener("blur",u),window.addEventListener("message",p);const w={dispose:()=>{window.removeEventListener("dragenter",a),window.removeEventListener("dragover",l),window.removeEventListener("dragleave",c),window.removeEventListener("drop",d),window.removeEventListener("dragend",u),document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",u),window.removeEventListener("message",p),n.remove(),delete window.__openStationOsFileDropMounted}};return t.__openStationOsFileDropMounted=w,w}function XM(){const e=document.querySelector(".os-drop-overlay");if(e)return e;const t=document.createElement("div");t.className="os-drop-overlay",t.setAttribute("aria-hidden","true"),t.style.cssText=["position:fixed","inset:0","pointer-events:none","z-index:200","opacity:0","transition:opacity 120ms ease","background:radial-gradient(circle at center, rgba(34,113,177,0.18) 0%, rgba(34,113,177,0.06) 60%, transparent 100%)","box-shadow:inset 0 0 0 3px rgba(34,113,177,0.55)"].join(";");const n=document.createElement("div");n.style.cssText=["position:absolute","top:50%","left:50%","transform:translate(-50%,-50%)","padding:14px 22px","border-radius:12px","background:rgba(20,20,24,0.78)","color:#fff","font:600 14px/1.2 -apple-system,BlinkMacSystemFont,sans-serif","letter-spacing:0.02em"].join(";"),n.textContent="Drop to upload",t.appendChild(n),document.body.appendChild(t);const o=document.createElement("style");return o.textContent=".os-drop-overlay.is-active{opacity:1!important;}",document.head.appendChild(o),t}function ZM(){const e=o=>{if(!ws(o))return;const s=o.target;s?.closest&&zb.some(i=>s.closest(i))||o.preventDefault()};window.addEventListener("dragover",e),window.addEventListener("drop",e);const t=window,n={dispose:()=>{window.removeEventListener("dragover",e),window.removeEventListener("drop",e),delete t.__openStationOsFileDropMounted}};return t.__openStationOsFileDropMounted=n,n}function jb(e){const t=e.clientX,n=e.clientY;let o=e.target;for(;o&&o!==document.body;){if(o.classList.contains("os-file-tile")&&o.dataset.fileType==="folder"){const s=Number(o.dataset.fileRef??0);if(Number.isFinite(s)&&s>0)return{surface:"folder",folderId:s,x:t,y:n}}if(o.tagName==="IFRAME")return{surface:"iframe",windowId:_r(o),x:t,y:n};if(o.classList.contains("os-window")||o.hasAttribute("data-window-id")){const s=_r(o)??(o.getAttribute("data-window-id")||void 0),i=s?/^os-folder-(\d+)/.exec(s):null;return i?{surface:"folder",folderId:Number(i[1]),windowId:s,x:t,y:n}:{surface:"window",windowId:s,x:t,y:n}}if(o.dataset?.folderId!==void 0){const s=Number(o.dataset.folderId);return Number.isFinite(s)&&s>0?{surface:"folder",folderId:s,x:t,y:n}:{surface:"wallpaper",x:t,y:n}}if(o.id==="os-wallpaper"||o.classList.contains("os-wallpaper")||o.classList.contains("os-desktop"))return{surface:"wallpaper",x:t,y:n};o=o.parentElement}return{surface:"unknown",x:t,y:n}}async function ad(e,t,n){const o=Y(ue.FILES_DETECTED,e,t);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=ld(o,n.config);if(i.length>0&&(L(ue.FILES_REJECTED,{rejections:i,context:t}),Q({message:i.length===1?i[0].message:`${i.length} files couldn't be uploaded.`})),s.length===0)return;const r=s.map(({file:a,mime:l})=>{const c={file:a,mime:l,fields:cd(a,l)},d=Y(ue.DIALOG_FIELDS,c,t);return!d||typeof d!="object"||!("fields"in d)||typeof d.fields!="object"?c:d});await n.openDialog(r,t)}async function Vb(e,t,n){if(!n.storage?.canUpload||!n.filesUrl){Q({message:"Folder uploads need desktop storage, which is not available for your account."});return}const o=await KM(e),s=Y(ue.FILES_DETECTED,o.files.map(u=>u.file),t);if(!Array.isArray(s))return;const i=new Set(s),r=o.files.filter(u=>i.has(u.file));if(r.length===0&&o.emptyDirs.length===0)return;const{accepted:a,rejected:l}=ld(r.map(u=>u.file),n.config);l.length>0&&(L(ue.FILES_REJECTED,{rejections:l,context:t}),Q({message:l.length===1?l[0].message:`${l.length} files couldn't be uploaded.`}));const c=new Map(r.map(u=>[u.file,u.relativePath])),d=a.map(({file:u,mime:f})=>({file:u,mime:f,fields:cd(u,f),relativePath:c.get(u)??""}));d.length===0&&o.emptyDirs.length===0||await n.openDialog(d,t,{forceDesktop:!0,emptyDirs:o.emptyDirs})}function ld(e,t){const n=[],o=[];for(const s of e){if(s.size===0){o.push({file:s,reason:"empty",message:`“${s.name}” is empty.`});continue}if(t.maxSize>0&&s.size>t.maxSize){o.push({file:s,reason:"size",message:`“${s.name}” exceeds the ${QM(t.maxSize)} upload limit.`});continue}const i=qb(s,t.allowedMimes,t.extToMime);if(!i){o.push({file:s,reason:"mime",message:`“${s.name}” is not an allowed file type.`});continue}n.push({file:s,mime:i})}return{accepted:n,rejected:o}}function qb(e,t,n){if(t.length===0)return null;const o=e.type.toLowerCase();if(o&&t.includes(o))return o;const s=Kb(e.name);if(!s)return null;if(n){for(const[r,a]of Object.entries(n))if(r.split("|").includes(s)&&t.includes(a))return a;return null}const i=JM[s];return i&&t.includes(i)?i:null}const JM={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 Kb(e){const t=e.lastIndexOf(".");return t<0?"":e.slice(t+1).toLowerCase()}function cd(e,t){const n=Yb(e.name),o=Kb(n),s=o?n.slice(0,n.length-o.length-1):n,i=Xb(s);return{title:i,altText:t.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function Yb(e){return e.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function Xb(e){const t=e.replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Upload"}function QM(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}const eP=Object.freeze(Object.defineProperty({__proto__:null,IFRAME_PASSTHROUGH_SELECTORS:zb,classifyDropTarget:jb,defaultFields:cd,dragHasFiles:ws,handleFiles:ad,handleTreeDrop:Vb,humanize:Xb,mountOsFileDropManager:Gb,partitionByPolicy:ld,resolveAllowedMime:qb,sanitizeFilename:Yb,windowIdFromElement:_r},Symbol.toStringTag,{value:"Module"})),tP=de` ${ft} ${Ra}: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}`,Ds=class Ds extends Se{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),xp(this)}render(){const t=this.label||"",n=this.value??"",o=this.placeholder||"",s=this.disabled!==null,i=this.readonly!==null,r=this.autocomplete,a=this.type||"text",l=a==="password";let c=r||"off";l&&(!r||c==="off")&&(c="new-password");const d=this.maxlength,u=this.minlength,f=this.pattern||"",p=this.name||"",w=this.suffix||"",m=this.invalid!==null,h=this.reveal!==null,y=a==="password",v=y&&!(h&&this._revealed);let A;y||h&&this._revealed?A="text":A=a;const D=h?"os-text-field__row os-text-field__row--has-reveal":"os-text-field__row",_=v?"os-text-field__input os-text-field__input--masked":"os-text-field__input",P=`${this.id||"os-unnamed"}__input`;return J` |
| 269 |
${t?J`<label |
| 270 |
class="os-text-field__label" |
| 271 |
for=${P} |
| 272 |
>${t}</label>`:J``} |
| 273 |
<span class=${D}> |
| 274 |
<input |
| 275 |
id=${P} |
| 276 |
class=${_} |
| 277 |
type=${A} |
| 278 |
.value=${n} |
| 279 |
placeholder=${o} |
| 280 |
?disabled=${s} |
| 281 |
?readonly=${i} |
| 282 |
autocomplete=${c} |
| 283 |
maxlength=${d??""} |
| 284 |
minlength=${u??""} |
| 285 |
pattern=${f} |
| 286 |
name=${p} |
| 287 |
aria-invalid=${m?"true":"false"} |
| 288 |
aria-label=${t||""} |
| 289 |
@input=${$=>this._onInput($)} |
| 290 |
@change=${$=>this._onChange($)} |
| 291 |
@keydown=${$=>this._onKeyDown($)} |
| 292 |
/> |
| 293 |
${w?J`<span class="os-text-field__suffix">${w}</span>`:J``} |
| 294 |
${h?this._renderRevealButton(s):J``} |
| 295 |
</span> |
| 296 |
`}_renderRevealButton(t){const n=this._revealed?"Hide":"Show";return J` |
| 297 |
<button |
| 298 |
type="button" |
| 299 |
class="os-text-field__reveal" |
| 300 |
aria-label=${n} |
| 301 |
aria-pressed=${this._revealed?"true":"false"} |
| 302 |
?disabled=${t} |
| 303 |
tabindex="0" |
| 304 |
@click=${()=>this._onToggleReveal()} |
| 305 |
> |
| 306 |
${this._revealed?oP():nP()} |
| 307 |
</button> |
| 308 |
`}_onToggleReveal(){this._revealed=!this._revealed,this.requestUpdate()}_onInput(t){const n=t.target;this.value=n.value,this.emit("os-input-change",{value:n.value})}_onChange(t){const n=t.target;this.emit("os-input-commit",{value:n.value})}_onKeyDown(t){if(t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey){const n=t.target;this.emit("os-submit",{value:n.value})}}};Ds.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],Ds.styles=[tP],Ds.help=void 0;let dd=Ds;xe("os-text-field",dd);function nP(){return J` |
| 309 |
<svg |
| 310 |
viewBox="0 0 16 16" |
| 311 |
width="14" |
| 312 |
height="14" |
| 313 |
fill="none" |
| 314 |
stroke="currentColor" |
| 315 |
stroke-width="1.5" |
| 316 |
stroke-linecap="round" |
| 317 |
stroke-linejoin="round" |
| 318 |
aria-hidden="true" |
| 319 |
focusable="false" |
| 320 |
> |
| 321 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 322 |
<circle cx="8" cy="8" r="2" /> |
| 323 |
</svg> |
| 324 |
`}function oP(){return J` |
| 325 |
<svg |
| 326 |
viewBox="0 0 16 16" |
| 327 |
width="14" |
| 328 |
height="14" |
| 329 |
fill="none" |
| 330 |
stroke="currentColor" |
| 331 |
stroke-width="1.5" |
| 332 |
stroke-linecap="round" |
| 333 |
stroke-linejoin="round" |
| 334 |
aria-hidden="true" |
| 335 |
focusable="false" |
| 336 |
> |
| 337 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 338 |
<circle cx="8" cy="8" r="2" /> |
| 339 |
<line x1="2" y1="2" x2="14" y2="14" /> |
| 340 |
</svg> |
| 341 |
`}async function sP(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=Y(ue.BEFORE_UPLOAD,t,e.context);if(!n)throw new ud;const o=new FormData,s=n.fields.filename!==n.file.name?new File([n.file],n.fields.filename,{type:n.mime||n.file.type}):n.file;return o.append("file",s),o.append("title",n.fields.title),o.append("alt_text",n.fields.altText),o.append("caption",n.fields.caption),o.append("description",n.fields.description),new Promise((i,r)=>{const a=new XMLHttpRequest;a.open("POST",e.mediaUrl,!0),a.withCredentials=!0,a.setRequestHeader("X-WP-Nonce",e.restNonce),a.responseType="text";let l=!1,c=!1,d=!1;const u=()=>{if(d=!0,!c){l=!0;try{a.abort()}catch{}}};L(ue.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:u}),a.upload.addEventListener("progress",f=>{L(ue.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:f.loaded,total:f.lengthComputable?f.total:0,indeterminate:!f.lengthComputable})}),a.upload.addEventListener("load",()=>{c=!0,L(ue.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:n.file.size,total:n.file.size,indeterminate:!1})}),a.addEventListener("error",()=>{if(l)return;const f=new Error("Network error during upload.");L(ue.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),r(f)}),a.addEventListener("abort",()=>{const f=new Er;L(ue.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),r(f)}),a.addEventListener("load",()=>{if(l)return;if(a.status<200||a.status>=300){const w=rP(a),m=new Error(w);L(ue.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}let f;try{f=JSON.parse(a.responseText)}catch(w){const m=w instanceof Error?w:new Error("Could not parse server response.");L(ue.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}if(d&&f.id){iP(e.mediaUrl,e.restNonce,f.id);const w=new Er;L(ue.UPLOAD_FAILED,{file:n.file,error:w,context:e.context}),r(w);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(ue.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:e.context}),i(p)}),a.send(o)})}class ud extends Error{constructor(){super("Upload cancelled by os.drop.before-upload filter."),this.name="UploadCancelledError"}}class Er extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function iP(e,t,n){const o=`${e.replace(/\/$/,"")}/${n}?force=true`,s=new XMLHttpRequest;return s.open("DELETE",o,!0),s.withCredentials=!0,s.setRequestHeader("X-WP-Nonce",t),new Promise(i=>{s.addEventListener("loadend",()=>{(s.status<200||s.status>=300)&&console.warn(`[os-file-drop] late-cancel cleanup failed for attachment ${n} (HTTP ${s.status}). The attachment remains in the Media Library; delete it manually.`),i()}),s.addEventListener("error",()=>{console.warn(`[os-file-drop] late-cancel cleanup network error for attachment ${n}. The attachment remains in the Media Library; delete it manually.`),i()});try{s.send()}catch(r){console.warn(`[os-file-drop] late-cancel cleanup could not be dispatched for attachment ${n}:`,r),i()}})}function rP(e){const t=`Upload failed (HTTP ${e.status}).`,n=e.responseText;if(!n)return t;try{const o=JSON.parse(n);if(o&&typeof o.message=="string")return o.message}catch{}return t}async function aP(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=Y(ue.BEFORE_UPLOAD,t,e.context);if(!n)throw new ud;const o=new FormData,s=n.fields.filename!==n.file.name?new File([n.file],n.fields.filename,{type:n.mime||n.file.type}):n.file;o.append("file",s),o.append("parentId",String(e.parentId)),e.relativePath&&o.append("relativePath",e.relativePath),e.coords&&(o.append("x",String(e.coords.x)),o.append("y",String(e.coords.y)));const i=`${e.filesUrl.replace(/\/$/,"")}/uploads`;return new Promise((r,a)=>{const l=new XMLHttpRequest;l.open("POST",i,!0),l.withCredentials=!0,l.setRequestHeader("X-WP-Nonce",e.restNonce),l.responseType="text";let c=!1;const d=()=>{c=!0;try{l.abort()}catch{}};L(ue.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:d}),l.upload.addEventListener("progress",f=>{L(ue.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:f.loaded,total:f.lengthComputable?f.total:0,indeterminate:!f.lengthComputable})});const u=f=>{L(ue.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),a(f)};l.addEventListener("error",()=>{c||u(new Error("Network error during upload."))}),l.addEventListener("abort",()=>u(new Er)),l.addEventListener("load",()=>{if(c)return;if(l.status<200||l.status>=300){u(new Error(lP(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}Xi(f.placement,"local");const p={placement:f.placement,storedFileId:f.storedFileId};L(ue.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:e.context}),r(p)}),l.send(o)})}function lP(e,t){if(e.status===413)return`“${t}” is larger than this server accepts.`;const n=`Upload failed (HTTP ${e.status}).`,o=e.responseText;if(!o)return n;try{const s=JSON.parse(o);if(s&&typeof s.message=="string"&&s.message)return s.message}catch{}return n}function cP(e,t){const n=Math.max(0,Math.round((e-16)/96)),o=Math.max(0,Math.round((t-16)/110));return{x:16+n*96,y:16+o*110}}const dP=/^(image|video|audio)\//;function fd(e){return e.desktopAllowed?e.forceDesktop||e.preferDesktop?"desktop":e.surface==="window"||e.surface==="iframe"?"media":(e.folderId??0)>0?"desktop":e.mimes.length>0&&e.mimes.every(n=>dP.test(n))?"media":"desktop":"media"}let an=null;async function uP(e){if(e.entries.length===0&&!e.emptyDirs?.length)return;if(an){an.replace(e);return}const t=!!(e.storage?.canUpload&&e.filesUrl);let n=fd({desktopAllowed:t,surface:e.context.surface,folderId:e.context.folderId,forceDesktop:e.forceDesktop,preferDesktop:e.preferDesktop,mimes:e.entries.map(d=>d.mime)});const o=document.createElement("os-modal");o.setAttribute("open",""),o.setAttribute("size","md"),document.body.appendChild(o);const s=()=>{const d=e.entries.length;let u="Media Library";n==="desktop"&&(u=(e.context.folderId??0)>0?"this folder":"Desktop");let f=`Upload ${d} files to ${u}`;d===0?f=(e.context.folderId??0)>0?"Create folders in this folder":"Create folders on Desktop":d===1&&(f=`Upload to ${u}`),o.setAttribute("title",f)};s();const i=e.entries.map(d=>({...d.fields})),r=()=>{if(o.innerHTML="",t&&!e.forceDesktop){const m=document.createElement("div");m.style.cssText="display:flex;align-items:center;gap:10px;margin-bottom:14px;";const h=document.createElement("span");h.textContent="Upload to",h.style.cssText="font-weight:600;",m.appendChild(h);const y=document.createElement("os-segmented");y.setAttribute("value",n),y.setAttribute("label","Destination"),y.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",y.appendChild(v);const A=document.createElement("os-segment");A.setAttribute("value","media"),A.textContent="Media Library",y.appendChild(A),y.addEventListener("os-pick",D=>{n=D.detail.value,s(),r()}),m.appendChild(y),o.appendChild(m)}else if(e.forceDesktop){const m=document.createElement("div");m.style.cssText="opacity:0.7;font-size:12px;margin-bottom:14px;",m.textContent="Folder uploads land in your desktop storage, preserving the folder structure.",o.appendChild(m)}const d=n==="desktop"?e.storage?.maxBytes??0:e.mediaMaxBytes??0;if(d>0){const m=document.createElement("div");m.className="os-upload-dialog__max-size",m.style.cssText="opacity:0.6;font-size:12px;margin-bottom:14px;",m.textContent=`Maximum file size: ${Qt(d)}`,o.appendChild(m)}const u=document.createElement("div");u.style.cssText="display:flex;flex-direction:column;gap:18px;max-height:60vh;overflow:auto;padding-right:6px;",e.entries.forEach((m,h)=>{u.appendChild(a(m,i[h],h+1))}),o.appendChild(u);const f=document.createElement("div");f.setAttribute("slot","footer"),f.style.cssText="display:flex;gap:8px;justify-content:flex-end;";const p=document.createElement("os-button");p.setAttribute("variant","secondary"),p.textContent="Cancel",p.addEventListener("click",()=>{o.remove()});const w=document.createElement("os-button");w.setAttribute("variant","primary"),e.entries.length===0?w.textContent="Create folders":w.textContent=e.entries.length===1?"Upload":`Upload ${e.entries.length} files`,w.addEventListener("click",()=>{l(w,p)}),f.appendChild(p),f.appendChild(w),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 w=document.createElement("div");w.style.cssText="display:flex;gap:10px;align-items:center;font-weight:600;";const m=document.createElement("span");m.textContent=e.entries.length===1?"":`#${f} · `,m.style.opacity="0.6";const h=document.createElement("span");h.textContent=d.file.name,h.style.cssText="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const y=document.createElement("span");if(y.textContent=`${d.mime||"unknown"} · ${Qt(d.file.size)}`,y.style.cssText="opacity:0.6;font-size:12px;",w.appendChild(m),w.appendChild(h),w.appendChild(y),p.appendChild(w),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(ys("Filename",u.filename,v=>u.filename=v)),p}return p.appendChild(ys("Title",u.title,v=>u.title=v)),p.appendChild(ys("Filename",u.filename,v=>u.filename=v)),d.mime.startsWith("image/")&&p.appendChild(ys("Alt text",u.altText,v=>u.altText=v)),p.appendChild(ys("Caption",u.caption,v=>u.caption=v)),p.appendChild(fP("Description",u.description,v=>u.description=v)),p},l=async(d,u)=>{an===c&&(an=null),d.disabled=!0,u.disabled=!0,d.textContent="Uploading…";const f=e.entries.length;let p=0,w=0,m=0;const h=[],y=e.context.folderId??0;let v=!1;for(let D=0;D<f;D++){const _=e.entries[D];try{if(n==="desktop"&&e.filesUrl){const P=!_.relativePath&&!v&&e.context.surface==="wallpaper"?cP(e.context.x,e.context.y):void 0;P&&(v=!0),await aP({file:_.file,mime:_.mime,fields:i[D],context:e.context,filesUrl:e.filesUrl,restNonce:e.restNonce,parentId:y,relativePath:_.relativePath??"",coords:P})}else await sP({file:_.file,mime:_.mime,fields:i[D],context:e.context,mediaUrl:e.mediaUrl,restNonce:e.restNonce});p++}catch(O){if(O instanceof ud){m++;continue}if(O instanceof Er){m++;continue}w++;const P=O instanceof Error?O.message:"Upload failed.";h.push(`“${_.file.name}” — ${P}`)}}if(n==="desktop"&&e.emptyDirs?.length)for(const D of e.emptyDirs)try{await jw(y,D)}catch{}const A=e.entries.some(D=>D.relativePath)||!!e.emptyDirs?.length;if(n==="desktop"&&A)try{const[D,_]=await Promise.all([dc(),Le(y)]);Zi(D.folders),at(y,_.placements)}catch{}o.remove(),pP({total:f,successes:p,failures:w,cancelled:m,failureDetails:h,destination:n})},c={replace:d=>{e.entries=d.entries,e.emptyDirs=d.emptyDirs,e.forceDesktop=d.forceDesktop,e.preferDesktop=d.preferDesktop,e.context=d.context,e.mediaMaxBytes=d.mediaMaxBytes??e.mediaMaxBytes,i.length=0;for(const u of d.entries)i.push({...u.fields});n=fd({desktopAllowed:t,surface:d.context.surface,folderId:d.context.folderId,forceDesktop:d.forceDesktop,preferDesktop:d.preferDesktop,mimes:d.entries.map(u=>u.mime)}),s(),r()}};an=c,r(),await new Promise(d=>{const u=()=>{an===c&&(an=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 ys(e,t,n){const o=document.createElement("os-text-field");return o.setAttribute("label",e),o.setAttribute("value",t),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function fP(e,t,n){const o=document.createElement("os-textarea");return o.setAttribute("label",e),o.setAttribute("value",t),o.setAttribute("rows","3"),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function pP(e){const{total:t,successes:n,failures:o,cancelled:s,failureDetails:i}=e,r=e.destination==="desktop"?"your desktop":"Media Library";if(t===0){e.destination==="desktop"&&Q({message:"Folder created on your desktop."});return}if(t===1){n===1?Q({message:`Uploaded to ${r}.`}):o===1&&i[0]?Q({message:i[0]}):s===1&&Q({message:"Upload cancelled."});return}if(n===t){Q({message:`Uploaded ${n} files to ${r}.`});return}if(s===t){Q({message:"All uploads cancelled."});return}if(o===t){Q({message:o===1&&i[0]?i[0]:`${o} uploads failed.`});return}const a=[];n>0&&a.push(`Uploaded ${n} file${n===1?"":"s"}.`),s>0&&a.push(`Cancelled ${s}.`),o>0&&a.push(`Failed ${o}.`),Q({message:a.join(" ")})}const Zb=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:uP,resolveDefaultDestination:fd},Symbol.toStringTag,{value:"Module"})),hP={tab:null,requestedAt:0};let kr=null;function pd(){if(kr)return kr;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(kr=t("desktop-mode/plugins-window/tab-target",()=>({...hP})),kr)}function mP(e){const t=pd();if(t){t.state.tab=e,t.state.requestedAt=Date.now(),t.notify();return}const n=window;n._wpdPluginsWindowTab={tab:e,requestedAt:Date.now()}}function gP(){const e=pd();if(e){const o=e.state.tab;return o!==null&&(e.state.tab=null,e.state.requestedAt=0,e.notify()),o}const t=window,n=t._wpdPluginsWindowTab;return n?(t._wpdPluginsWindowTab={tab:null,requestedAt:0},n.tab):null}function wP(e){const t=pd();return t?t.subscribe(n=>e({...n})):()=>{}}const yP=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:gP,setPluginsWindowTab:mP,subscribePluginsWindowTab:wP},Symbol.toStringTag,{value:"Module"})),bP=de` ${ft} ${Op}: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}}`,Rs=class Rs extends Se{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return J`<div class="root" part="root"> |
| 342 |
<div class="header" part="header" hidden> |
| 343 |
<span class="label" part="label"></span> |
| 344 |
<span class="percent" part="percent"></span> |
| 345 |
</div> |
| 346 |
<div class="track" part="track"> |
| 347 |
<div class="fill" part="fill"></div> |
| 348 |
</div> |
| 349 |
</div>`}requestUpdate(){super.requestUpdate(),queueMicrotask(()=>this._paint())}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paint())}_paint(){const t=this.shadowRoot;if(!t)return;const n=this._readMax(),o=this.hasAttribute("indeterminate")||n<=0,s=o?0:this._readValue(n),i=o?0:s/n,r=Math.round(i*100),a=this.getAttribute("label")??"",l=this.hasAttribute("show-percent"),c=t.querySelector(".fill");c&&!o?c.style.width=`${(i*100).toFixed(2)}%`:c&&o&&c.style.removeProperty("width");const d=t.querySelector(".header"),u=t.querySelector(".label"),f=t.querySelector(".percent");if(d&&u&&f){const w=a||l&&!o;d.hidden=!w,u.textContent=a,f.hidden=!(l&&!o),f.textContent=`${r}%`}this._syncAria(n,s,o,a);const p=t.querySelector(".track");p&&(p.setAttribute("role","progressbar"),p.setAttribute("aria-valuemin","0"),o?(p.removeAttribute("aria-valuenow"),p.removeAttribute("aria-valuemax")):(p.setAttribute("aria-valuemax",String(n)),p.setAttribute("aria-valuenow",String(s))),a?p.setAttribute("aria-label",a):p.removeAttribute("aria-label"))}_syncAria(t,n,o,s){this.setAttribute("role","progressbar"),this.setAttribute("aria-valuemin","0"),o?(this.removeAttribute("aria-valuenow"),this.removeAttribute("aria-valuemax")):(this.setAttribute("aria-valuemax",String(t)),this.setAttribute("aria-valuenow",String(n)));const i=this.getAttribute("aria-label");s?(i===null||i===this._ownedAriaLabel)&&(this.setAttribute("aria-label",s),this._ownedAriaLabel=s):i!==null&&i===this._ownedAriaLabel&&(this.removeAttribute("aria-label"),this._ownedAriaLabel=null)}_readMax(){const t=this.getAttribute("max");if(t===null)return 100;const n=parseFloat(t);return Number.isFinite(n)?n:100}_readValue(t){const n=parseFloat(this.getAttribute("value")??"0");return!Number.isFinite(n)||n<0?0:n>t?t:n}};Rs.props=["value","max","indeterminate","tone","label","showPercent"],Rs.styles=[bP],Rs.help=void 0;let hd=Rs;xe("os-progress-bar",hd);const tt=new Map;let gt=null;function vP(){if(document.body.hasAttribute("data-os-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const e="desktop-mode/os-file-drop-hud";Z(ue.UPLOAD_STARTED,e,t=>_P(t.file,t.fields,t.abort)),Z(ue.UPLOAD_PROGRESS,e,t=>EP(t.file,t.loaded,t.total,t.indeterminate)),Z(ue.AFTER_UPLOAD,e,t=>kP(t.file,t.fields,t.result)),Z(ue.UPLOAD_FAILED,e,t=>SP(t.file,t.error))}function _P(e,t,n){const o=AP(),s=document.createElement("div");s.className="os-upload-hud__row";const i=document.createElement("div");i.className="os-upload-hud__meta";const r=document.createElement("div");r.className="os-upload-hud__name",r.textContent=t.filename||e.name,r.title=t.filename||e.name;const a=document.createElement("div");a.className="os-upload-hud__status",a.textContent="Uploading…",i.append(r,a);const l=document.createElement("os-progress-bar");l.setAttribute("indeterminate",""),l.setAttribute("show-percent","");const c=document.createElement("div");c.className="os-upload-hud__actions";const d=document.createElement("os-button");d.setAttribute("variant","tertiary"),d.setAttribute("size","small"),d.textContent="Cancel",d.addEventListener("click",()=>{const u=tt.get(e);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):md(u))}),c.appendChild(d),s.append(i,l,c),o.querySelector(".os-upload-hud__list").appendChild(s),tt.set(e,{file:e,abort:n,root:s,bar:l,statusEl:a,cancelBtn:d,state:"running",lingerTimer:null}),Sr()}function EP(e,t,n,o){const s=tt.get(e);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${Qt(t)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(t)),s.statusEl.textContent=`${Qt(t)} / ${Qt(n)}`))}function kP(e,t,n){const o=tt.get(e);o&&(o.state="success",o.bar.removeAttribute("indeterminate"),o.bar.setAttribute("value","100"),o.bar.setAttribute("max","100"),o.bar.setAttribute("tone","success"),o.statusEl.textContent="Uploaded",o.cancelBtn.textContent="Dismiss",o.lingerTimer=setTimeout(()=>md(o),2500),Sr(),ke.publish("os/upload-hud-complete",{filename:t.filename||n.filename,attachmentId:n.id}))}function SP(e,t){const n=tt.get(e);n&&(n.bar.removeAttribute("indeterminate"),n.bar.setAttribute("tone","danger"),n.cancelBtn.textContent="Dismiss",n.cancelBtn.disabled=!1,t.name==="UploadAbortedError"?(n.state="aborted",n.statusEl.textContent="Cancelled"):(n.state="failed",n.statusEl.textContent=t.message||"Upload failed"),Sr())}function md(e){e.lingerTimer&&clearTimeout(e.lingerTimer),tt.delete(e.file),e.root.remove(),Sr(),tt.size===0&>&&(gt.hidden=!0)}function AP(){if(gt&>.isConnected)return gt.hidden=!1,gt;const e=document.createElement("div");e.className="os-upload-hud",e.setAttribute("role","region"),e.setAttribute("aria-label","Uploads");const t=document.createElement("div");t.className="os-upload-hud__header";const n=document.createElement("div");n.className="os-upload-hud__title",n.textContent="Uploads";const o=document.createElement("button");o.type="button",o.className="os-upload-hud__close",o.setAttribute("aria-label","Hide upload panel"),o.textContent="×",o.addEventListener("click",()=>{for(const i of[...tt.values()])i.state!=="running"&&md(i);tt.size===0&&(e.hidden=!0)}),t.append(n,o);const s=document.createElement("div");return s.className="os-upload-hud__list",e.append(t,s),document.body.appendChild(e),gt=e,e}function Sr(){if(!gt)return;const e=gt.querySelector(".os-upload-hud__title");if(!e)return;const t=tt.size,n=[...tt.values()].filter(o=>o.state==="running").length;n>0?e.textContent=n===t?`Uploading ${n} file${n===1?"":"s"}…`:`${n} of ${t} uploading…`:t>0?e.textContent=`Uploads (${t})`:e.textContent="Uploads"}function CP(){if(document.body.hasAttribute("data-os-suppress-media-library-refresh"))return;const e=window;e.__wpdMediaLibraryRefresher||(e.__wpdMediaLibraryRefresher=!0,Z(ue.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>IP()))}function IP(){const e=document.querySelectorAll("iframe");for(const t of Array.from(e))if(xP(Jb(t)))try{t.contentWindow?.location.reload()}catch{const n=Jb(t);n&&t.setAttribute("src",n)}}function Jb(e){try{return e.contentWindow?.location.href??e.src??""}catch{return e.src??""}}function xP(e){return e?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(e):!1}function LP(e){const t=e.config||{enabled:!1,allowedMimes:[],maxSize:0};vP(),CP(),Gb({config:t,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.storage,openDialog:async(n,o,s)=>{const{openUploadDialog:i}=await Promise.resolve().then(()=>Zb);await i({entries:n,context:o,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.storage,forceDesktop:s?.forceDesktop,emptyDirs:s?.emptyDirs,mediaMaxBytes:t.maxSize})}})}const TP=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:ue,bootOsFileDrop:LP},Symbol.toStringTag,{value:"Module"}));return xr.clampGeometryToViewport=ql,Object.defineProperty(xr,Symbol.toStringTag,{value:"Module"}),xr}({}); |
| 350 |
|