| 1 |
(function(){"use strict";function w(){const i=window.wp?.hooks;if(!i)throw new Error("[desktop-mode] `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 i}function L(i,e,...t){return w().applyFilters(i,e,...t)}function S(i,...e){w().doAction(i,...e)}const _={INIT:"desktop-mode.init",WALLPAPERS:"desktop-mode.wallpapers",UNFOCUS_EFFECTS:"desktop-mode.unfocus-effects",WALLPAPER_MOUNTING:"desktop-mode.wallpaper.mounting",WALLPAPER_MOUNTED:"desktop-mode.wallpaper.mounted",WALLPAPER_UNMOUNTING:"desktop-mode.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"desktop-mode.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"desktop-mode.wallpaper.visibility",IFRAME_READY:"desktop-mode.iframe.ready",IFRAME_ERROR:"desktop-mode.iframe.error",IFRAME_NETWORK_COMPLETED:"desktop-mode.iframe.network-completed",SHELL_ERROR:"desktop-mode.shell.error",BROADCAST:"desktop-mode.broadcast",MONITOR_ENTRY:"desktop-mode.monitor.entry",WALLPAPER_SURFACES:"desktop-mode.wallpaper.surfaces",WINDOW_GEOMETRY:"desktop-mode.window.geometry",WINDOW_OPENED:"desktop-mode.window.opened",WINDOW_CONTENT_LOADING:"desktop-mode.window.content-loading",WINDOW_CONTENT_LOADED:"desktop-mode.window.content-loaded",WINDOW_LOADING_OVERLAY:"desktop-mode.window.loading-overlay",WINDOW_REOPENED:"desktop-mode.window.reopened",WINDOW_CLOSING:"desktop-mode.window.closing",WINDOW_CLOSED:"desktop-mode.window.closed",WINDOW_FOCUSED:"desktop-mode.window.focused",WINDOW_BLURRED:"desktop-mode.window.blurred",WINDOW_MINIMIZED:"desktop-mode.window.minimized",WINDOW_RESTORED:"desktop-mode.window.restored",WINDOW_MAXIMIZED:"desktop-mode.window.maximized",WINDOW_UNMAXIMIZED:"desktop-mode.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"desktop-mode.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"desktop-mode.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"desktop-mode.window.auto-exit-fullscreen",WINDOW_BOUNDS_CHANGED:"desktop-mode.window.bounds-changed",WINDOW_MOVED:"desktop-mode.window.moved",WINDOW_RESIZED:"desktop-mode.window.resized",WINDOW_DRAG_START:"desktop-mode.window.drag-start",WINDOW_DRAG_END:"desktop-mode.window.drag-end",WINDOW_RESIZE_START:"desktop-mode.window.resize-start",WINDOW_RESIZE_END:"desktop-mode.window.resize-end",WINDOW_DETACHED:"desktop-mode.window.detached",WINDOW_RELOADED:"desktop-mode.window.reloaded",WINDOW_TITLE_CHANGED:"desktop-mode.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"desktop-mode.window.highlight-changed",WINDOW_BODY_RESIZED:"desktop-mode.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"desktop-mode.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"desktop-mode.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"desktop-mode.native-window.before-close",WINDOW_CHROME_THEME:"desktop-mode.window.chrome.theme",WINDOW_CHROME_CONTROLS:"desktop-mode.window.chrome.controls",WINDOW_CHROME_SLOT:"desktop-mode.window.chrome.slot",WINDOW_CHROME_RENDER:"desktop-mode.window.chrome.render",WINDOW_CHROME_APPLIED:"desktop-mode.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"desktop-mode.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"desktop-mode.desktop-icon.clicked",DESKTOP_ICONS_RENDERED:"desktop-mode.desktop-icons.rendered",ICON_BADGE_CHANGED:"desktop-mode.icon.badge-changed",COMPONENTS_REGISTERED:"desktop-mode.components.registered",DOCK_ITEM_APPENDED:"desktop-mode.dock.item-appended",DOCK_ITEM_REMOVED:"desktop-mode.dock.item-removed",DOCK_BEFORE_RENDER:"desktop-mode.dock.before-render",DOCK_AFTER_RENDER:"desktop-mode.dock.after-render",DOCK_TILE_CLASS:"desktop-mode.dock.tile-class",DOCK_TILE_ELEMENT:"desktop-mode.dock.tile-element",DOCK_TILE_RENDERED:"desktop-mode.dock.tile-rendered",DOCK_TILE_TOOLTIP:"desktop-mode.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"desktop-mode.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"desktop-mode.dock.peek-card-element",OVERVIEW_ENTERING:"desktop-mode.overview.entering",OVERVIEW_ENTERED:"desktop-mode.overview.entered",OVERVIEW_EXITING:"desktop-mode.overview.exiting",OVERVIEW_EXITED:"desktop-mode.overview.exited",OVERVIEW_WINDOW_HOVER:"desktop-mode.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"desktop-mode.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"desktop-mode.overview.window-click",ARRANGE_CASCADE_STARTING:"desktop-mode.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"desktop-mode.arrange.cascade.applied",ARRANGE_TILE_STARTING:"desktop-mode.arrange.tile.starting",ARRANGE_TILE_APPLIED:"desktop-mode.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"desktop-mode.arrange.tile.dimensions",ARRANGE_SNAP_CHANGED:"desktop-mode.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"desktop-mode.arrange.snap.cell-size",ARRANGE_CUSTOM_ACTION:"desktop-mode.arrange.custom-action",SNAP_ZONE_PENDING:"desktop-mode.snap.zone-pending",SNAP_ZONE_CANCELED:"desktop-mode.snap.zone-canceled",SNAP_ZONE_COMMITTED:"desktop-mode.snap.zone-committed",SNAP_SPLIT_FILLED:"desktop-mode.snap.split-filled",WIDGETS:"desktop-mode.widgets",WIDGET_MOUNTING:"desktop-mode.widget.mounting",WIDGET_MOUNTED:"desktop-mode.widget.mounted",WIDGET_UNMOUNTING:"desktop-mode.widget.unmounting",WIDGET_MOUNT_FAILED:"desktop-mode.widget.mount-failed",WIDGET_ADDED:"desktop-mode.widget.added",WIDGET_REMOVED:"desktop-mode.widget.removed",DESKTOP_CREATED:"desktop-mode.desktop.created",DESKTOP_CLOSED:"desktop-mode.desktop.closed",DESKTOP_SWITCHED:"desktop-mode.desktop.switched",PRIMARY_DESKTOP_ID:"desktop-mode.primary-desktop-id",WINDOWS_BEFORE_CLOSE_ALL:"desktop-mode.windows.before-close-all",WINDOWS_CLOSE_ALL:"desktop-mode.windows.close-all",WINDOWS_AFTER_CLOSE_ALL:"desktop-mode.windows.after-close-all",COMMAND_BEFORE_RUN:"desktop-mode.command.before-run",COMMAND_AFTER_RUN:"desktop-mode.command.after-run",COMMAND_ERROR:"desktop-mode.command.error",SHELL_RESIZED:"desktop-mode.shell.resized",SHELL_VISIBILITY:"desktop-mode.shell.visibility",CONNECTION_OPENED:"desktop-mode.connection.opened",CONNECTION_CLOSED:"desktop-mode.connection.closed",CONNECTION_MESSAGE:"desktop-mode.connection.message",IFRAME_CONNECTION_REQUEST:"desktop-mode.iframe.connection-request",FILE_DROP_FILES_DETECTED:"desktop-mode.drop.files-detected",FILE_DROP_FILES_REJECTED:"desktop-mode.drop.files-rejected",FILE_DROP_DIALOG_FIELDS:"desktop-mode.drop.dialog-fields",FILE_DROP_BEFORE_UPLOAD:"desktop-mode.drop.before-upload",FILE_DROP_UPLOAD_STARTED:"desktop-mode.drop.upload-started",FILE_DROP_UPLOAD_PROGRESS:"desktop-mode.drop.upload-progress",FILE_DROP_AFTER_UPLOAD:"desktop-mode.drop.after-upload",FILE_DROP_UPLOAD_FAILED:"desktop-mode.drop.upload-failed"},b="wpd-confirm-dialog";let u=null;function p(){return typeof window.customElements<"u"&&!!window.customElements.get(b)}function C(i){return new Promise((e,t)=>{const o=document.querySelector('script[data-desktop-mode-shell-overlays="1"]'),d=()=>{if(p()){e();return}t(new Error("[desktop-mode] shell-overlays bundle loaded but did not register the overlay components."))};if(o){p()?d():(o.addEventListener("load",d),o.addEventListener("error",()=>t(new Error("failed to load shell-overlays bundle"))));return}const s=document.createElement("script");s.src=i,s.async=!0,s.dataset.desktopModeShellOverlays="1",s.addEventListener("load",d),s.addEventListener("error",()=>t(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(s)})}function R(i){return p()||!i?Promise.resolve():(u||(u=C(i)),u)}function T(){return window.desktopModeConfig?.shellOverlaysBundleUrl??""}async function W(i){return await R(T()),new Promise(e=>{const t=document.createElement("wpd-confirm-dialog");t.setAttribute("open",""),i.title&&t.setAttribute("title",i.title),t.setAttribute("message",i.message),i.confirmLabel&&t.setAttribute("confirm-label",i.confirmLabel),i.cancelLabel&&t.setAttribute("cancel-label",i.cancelLabel),i.danger&&t.setAttribute("danger",""),i.hideCancel&&t.setAttribute("hide-cancel",""),i.dismissable&&t.setAttribute("dismissable","");const o=s=>{t.remove(),e(s)};t.addEventListener("wpd-confirm",()=>o(!0)),t.addEventListener("wpd-cancel",()=>o(!1)),document.body.appendChild(t),(t.shadowRoot?.querySelector(".dialog")??t).focus?.()})}const v="X-WP-Nonce";function M(i,e){const t=$();if(!t)return e;const o=P(i);if(!o||!U(o))return e;const d=e?.headers??(typeof Request<"u"&&i instanceof Request?i.headers:void 0),s=new Headers(d??{});return s.has(v)?e:(s.set(v,t),{...e??{},headers:s})}function $(){if(typeof window>"u")return;const e=window.desktopModeConfig?.restNonce;return typeof e=="string"&&e.length>0?e:void 0}function P(i){try{const e=typeof window<"u"&&window.location?window.location.href:void 0;return typeof i=="string"?new URL(i,e):i instanceof URL?i:typeof Request<"u"&&i instanceof Request?new URL(i.url,e):null}catch{return null}}function U(i){return typeof window>"u"||!window.location||i.origin!==window.location.origin?!1:!!(i.pathname.includes("/wp-json/")||i.searchParams.has("rest_route"))}function F(i,e,t={}){const o=window.wp?.desktop?.fetch;if(typeof o=="function")return o(i,e,t);const d=M(i,e);return fetch(i,d)}const O="__desktopModeSharedStores";function H(){const i=window;let e=i[O];return e||(e=new Map,i[O]=e),e}function G(i,e){const t=H();let o=t.get(i);o||(o={state:e(),listeners:new Set,rebuild:e},t.set(i,o));const d={get state(){return o.state},set state(s){o.state=s},getState(){return o.state},notify(){for(const s of Array.from(o.listeners))try{s(o.state)}catch(n){console.error(`[desktop-mode/shared-store:${i}] subscriber threw:`,n)}},subscribe(s){return o.listeners.add(s),()=>{o.listeners.delete(s)}},setState(s){const n=o.state;if(typeof n!="object"||n===null){console.warn(`[desktop-mode/shared-store:${i}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(n,s),d.notify()},reset(){const s=o.rebuild(),n=o.state;if(typeof n=="object"&&n!==null&&typeof s=="object"&&s!==null){const r=n;for(const a of Object.keys(r))delete r[a];Object.assign(r,s)}else o.state=s;o.listeners.clear()}};return d}const N=G("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),m=N.state.registry,D=N.state.listeners;function y(){return Array.from(m.values())}function c(){return Array.from(m.values()).filter(i=>i.eager===!0)}function h(i){return m.get(i.toLowerCase())??null}function I(i){const e=i.trim().toLowerCase();return e===""?y():y().filter(t=>t.slug.toLowerCase().startsWith(e)||t.label.toLowerCase().includes(e))}function x(i){return D.add(i),()=>{D.delete(i)}}function g(i){if(!i.startsWith("/"))return{isCommand:!1,slug:"",args:"",hasArgsPart:!1};const e=i.slice(1),t=e.indexOf(" ");return t===-1?{isCommand:!0,slug:e,args:"",hasArgsPart:!1}:{isCommand:!0,slug:e.slice(0,t),args:e.slice(t+1),hasArgsPart:!0}}function B(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function f(i){return i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,t,o)=>/^https?:\/\//i.test(o.trim())?`<a href="${o.trim()}" target="_blank" rel="noopener noreferrer">${t}</a>`:t).replace(/\*\*([^*\n]+?)\*\*/g,"<strong>$1</strong>").replace(/(?<![*\w])\*([^*\n]+?)\*(?![*\w])/g,"<em>$1</em>").replace(/(?<![_\w])_([^_\n]+?)_(?![_\w])/g,"<em>$1</em>").replace(/`([^`\n]+?)`/g,"<code>$1</code>")}function q(i){if(!i)return"";const t=B(i).split(/\n\s*\n/),o=[];for(const d of t){const s=d.split(/\n/).map(a=>a.trim()).filter(a=>a!=="");if(s.length===0)continue;const n=s.every(a=>/^[-*]\s+/.test(a)),r=s.every(a=>/^\d+\.\s+/.test(a));if(n){const a=s.map(l=>`<li>${f(l.replace(/^[-*]\s+/,""))}</li>`);o.push(`<ul>${a.join("")}</ul>`)}else if(r){const a=s.map(l=>`<li>${f(l.replace(/^\d+\.\s+/,""))}</li>`);o.push(`<ol>${a.join("")}</ol>`)}else o.push(`<p>${f(s.join("<br>"))}</p>`)}return o.join("")}const E=`<svg viewBox="0 0 20 20" width="15" height="15" aria-hidden="true" focusable="false" fill="currentColor"> |
| 2 |
<path d="M10 2 L11.8 7.8 L17.5 9.5 L11.8 11.2 L10 17 L8.2 11.2 L2.5 9.5 L8.2 7.8 Z"/> |
| 3 |
</svg>`,K=`<svg viewBox="0 0 14 14" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" focusable="false"> |
| 4 |
<line x1="2" y1="2" x2="12" y2="12"/> |
| 5 |
<line x1="12" y1="2" x2="2" y2="12"/> |
| 6 |
</svg>`,V=`<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"> |
| 7 |
<polyline points="14,4 14,10 3,10"/> |
| 8 |
<polyline points="6,7 3,10 6,13"/> |
| 9 |
</svg>`,j=`<svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" class="desktop-mode-ai__spinner-icon"> |
| 10 |
<circle cx="10" cy="10" r="7" stroke-opacity="0.25"/> |
| 11 |
<path d="M10 3 A7 7 0 0 1 17 10" stroke-opacity="1"/> |
| 12 |
</svg>`,A=`<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> |
| 13 |
<polyline points="6,3 11,8 6,13"/> |
| 14 |
</svg>`,z=["Find my post about…","Where can I see categories?","Do I have any spam comments?","Take me to plugin settings"];class Z{constructor(e){this._isOpen=!1,this._isSearching=!1,this._previousFocus=null,this._currentStream=null,this._selectedCommand=0,this._keyboardNav=!1,this._selectedSuggestion=0,this._currentSuggestions=[],this._suggestToken=0,this.ask=()=>{throw new Error("[desktop-mode] wp.desktop.ai.ask called before the shell finished booting.")},this._aiSearchUrl=e.aiSearchUrl,this._aiSearchStreamUrl=e.aiSearchStreamUrl,this._restNonce=e.restNonce,this._getTransport=e.getTransport??(()=>"off"),this._el=this._buildDOM(),document.body.appendChild(this._el),this._input=this._el.querySelector(".desktop-mode-ai__input"),this._submitBtn=this._el.querySelector(".desktop-mode-ai__submit"),this._closeBtn=this._el.querySelector(".desktop-mode-ai__close"),this._resultsEl=this._el.querySelector(".desktop-mode-ai__results"),this._bindEvents(),this._renderSuggestions(),x(()=>{this._isOpen&&(this._input.value.startsWith("/")?this._renderCommandMode():this._input.value===""&&c().length>0&&this._renderCommandMode())})}open(){if(this._isOpen){this._input.focus(),this._input.select();return}this._isOpen=!0,this._previousFocus=this._el.ownerDocument.activeElement,this._input.value="",this._selectedCommand=0,this._submitBtn.classList.remove("has-value"),c().length>0?this._renderCommandMode():this._renderSuggestions(),this._el.removeAttribute("hidden"),this._el.offsetHeight,this._el.classList.add("is-open"),this._el.setAttribute("aria-hidden","false"),requestAnimationFrame(()=>this._input.focus())}close(){if(!this._isOpen)return;this._isOpen=!1,this._el.classList.remove("is-open"),this._el.setAttribute("aria-hidden","true"),this._closeStream(),this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1;const e=t=>{t.target!==this._el||t.propertyName!=="opacity"||(this._el.setAttribute("hidden",""),this._el.removeEventListener("transitionend",e),this._previousFocus instanceof HTMLElement&&this._previousFocus.focus())};this._el.addEventListener("transitionend",e)}toggle(){this._isOpen?this.close():this.open()}get isOpen(){return this._isOpen}attachAsk(e){this.ask=e}_bindEvents(){this._el.addEventListener("keydown",e=>{e.key==="Escape"&&(e.stopPropagation(),this.close())}),this._el.addEventListener("keydown",e=>{if(e.key!=="Tab")return;const t=[this._closeBtn,this._input,this._submitBtn].filter(n=>!n.disabled),o=t[0],d=t[t.length-1],s=this._el.ownerDocument.activeElement;e.shiftKey&&s===o?(e.preventDefault(),d.focus()):!e.shiftKey&&s===d&&(e.preventDefault(),o.focus())}),document.addEventListener("desktop-mode-open-ai",()=>this.open()),this._closeBtn.addEventListener("click",()=>this.close()),this._submitBtn.addEventListener("click",()=>this._onSubmit()),this._input.addEventListener("keydown",e=>{const t=g(this._input.value),o=t.isCommand===!1&&this._input.value===""&&c().length>0;if(t.isCommand&&!t.hasArgsPart||o){const d=this._sortCommands(o?c():I(t.slug).filter(s=>s.eager!==!0));if(e.key==="ArrowDown"){e.preventDefault(),this._selectedCommand=Math.min(this._selectedCommand+1,Math.max(0,d.length-1)),this._keyboardNav=!0,this._paintCommandSelection();return}if(e.key==="ArrowUp"){e.preventDefault(),this._selectedCommand=Math.max(0,this._selectedCommand-1),this._keyboardNav=!0,this._paintCommandSelection();return}if(e.key==="Tab"&&d.length>0&&!o){e.preventDefault();const s=d[this._selectedCommand]??d[0];this._input.value=`/${s.slug} `,this._submitBtn.classList.add("has-value"),this._selectedSuggestion=0,this._renderCommandMode();return}if(e.key==="Enter"&&!e.shiftKey){if(e.preventDefault(),d.length===0){this._showError(`Unknown command: /${t.slug}`);return}const s=d[this._selectedCommand]??d[0];this._runCommand(s,"");return}}if(t.isCommand&&t.hasArgsPart){const d=h(t.slug);if(!!d&&typeof d.suggest=="function"&&this._currentSuggestions.length>0){if(e.key==="ArrowDown"){e.preventDefault(),this._selectedSuggestion=Math.min(this._selectedSuggestion+1,this._currentSuggestions.length-1),this._paintSuggestionSelection();return}if(e.key==="ArrowUp"){e.preventDefault(),this._selectedSuggestion=Math.max(0,this._selectedSuggestion-1),this._paintSuggestionSelection();return}if(e.key==="Tab"){e.preventDefault();const n=this._currentSuggestions[this._selectedSuggestion];n&&(this._input.value=`/${t.slug} ${n.value}`);return}if(e.key==="Enter"&&!e.shiftKey&&d){e.preventDefault();const n=this._currentSuggestions[this._selectedSuggestion],r=n?n.value:t.args;this._runCommand(d,r);return}}}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this._onSubmit())}),this._input.addEventListener("input",()=>{const e=this._input.value.trim().length>0;this._submitBtn.classList.toggle("has-value",e),this._selectedCommand=0,this._selectedSuggestion=0,this._input.value.startsWith("/")?this._renderCommandMode():e||(c().length>0?this._renderCommandMode():this._renderSuggestions())}),this._resultsEl.addEventListener("mousemove",()=>{if(this._keyboardNav){this._keyboardNav=!1;const e=this._resultsEl.querySelector(".desktop-mode-ai__cmd-list");e&&e.classList.remove("desktop-mode-ai__cmd-list--kb-nav")}})}async _onSubmit(){const e=this._input.value.trim();if(!e||this._isSearching)return;const t=g(this._input.value);if(t.isCommand){const o=h(t.slug);if(!o){this._showError(`Unknown command: /${t.slug}`);return}await this._runCommand(o,t.args);return}await this._runSearch(e,null,0)}async _runCommand(e,t){if(this._isSearching)return;const o=L(_.COMMAND_BEFORE_RUN,{proceed:!0,slug:e.slug,args:t,command:e});if(o&&o.proceed===!1){this._showError(o.reason??`Command /${e.slug} was cancelled.`);return}this._isSearching=!0,this._submitBtn.disabled=!0,this._input.disabled=!0,this._showThinking(`Running /${e.slug}…`);const d={close:()=>{this._previousFocus=null,this.close()},openInWindow:(s,n,r)=>this._openInLegacyWindow(s,n,r),confirm:(s,n)=>this._confirm(s,n)};try{const s=await Promise.resolve(e.run(t,d));this._renderCommandResult(e,s),S(_.COMMAND_AFTER_RUN,{slug:e.slug,args:t,command:e,result:s})}catch(s){const n=s instanceof Error?s.message:String(s);this._showError(`Command /${e.slug} failed: ${n}`),S(_.COMMAND_ERROR,{slug:e.slug,args:t,command:e,error:s})}finally{this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1,this._input.focus()}}_confirm(e,t){return W({title:t?e:void 0,message:t??e})}_renderCommandResult(e,t){if(t==null){this._resultsEl.innerHTML="",this._resultsEl.hidden=!0;return}const o=typeof t=="string"?{answer_type:"chat",message:t,entity:null,admin_links:null,iterations:0,exhausted:!0,continue:null}:{answer_type:t.answer_type??"chat",message:t.message,entity:t.entity??null,admin_links:t.admin_links??null,iterations:0,exhausted:!0,continue:null};this._showResult("",o)}_runSearch(e,t,o){if(this._isSearching)return;this._isSearching=!0,this._submitBtn.disabled=!0,this._input.disabled=!0,this._showThinking("Thinking…"),this._getTransport()==="sse"&&typeof EventSource<"u"&&!!this._aiSearchStreamUrl?this._runSearchStream(e,t,o):this._runSearchFetch(e,t,o)}_runSearchStream(e,t,o){const d=new URL(this._aiSearchStreamUrl,window.location.origin);d.searchParams.set("nonce",this._restNonce),d.searchParams.set("query",e),t&&(d.searchParams.set("resume_tool",t),d.searchParams.set("start_offset",String(o))),this._closeStream();const s=new EventSource(d.toString());this._currentStream=s;const n=()=>{s.close(),this._currentStream=null,this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1,this._input.focus()};s.onmessage=r=>{let a;try{a=JSON.parse(r.data)}catch{return}if(!(!a||typeof a!="object"))switch(a.event){case"open":break;case"progress":typeof a.message=="string"&&this._showThinking(a.message);break;case"done":a.result&&this._showResult(e,a.result),n();break;case"error":this._showError(a.message??"Something went wrong.",a.code),n();break}},s.onerror=()=>{this._currentStream===s&&(this._showError("Lost connection to the assistant. Please try again."),n())}}async _runSearchFetch(e,t,o){try{const d={query:e};t&&(d.resume_tool=t,d.start_offset=o);const s=await F(this._aiSearchUrl,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":this._restNonce},body:JSON.stringify(d)},{source:"desktop-mode/ai-search"});if(!s.ok){const n=await s.json().catch(()=>({}));this._showError(n.message??`Server returned ${s.status}`,n.code);return}this._showResult(e,await s.json())}catch{this._showError("Network error — please check your connection and try again.")}finally{this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1,this._input.focus()}}_closeStream(){this._currentStream&&(this._currentStream.close(),this._currentStream=null)}_getDesktopShell(){return window.wp?.desktop??null}_openAiSettings(){const e=this._getDesktopShell();this._previousFocus=null,this.close(),e?.openOsSettings?.({tabId:"ai"})}_openInLegacyWindow(e,t,o){const d=this._getDesktopShell();if(!d||!d.windowManager){window.open(e,"_blank","noopener");return}const s=d.deriveWindowId?d.deriveWindowId(e):"desktop-mode-ai-"+e.replace(/[^a-z0-9]+/gi,"-").slice(0,80);d.windowManager.open({id:s,url:e,title:t,icon:o??"dashicons-admin-generic"}),this.close()}_renderCommandMode(){this._resultsEl.hidden=!1;const e=g(this._input.value);if(e.hasArgsPart){const n=h(e.slug);if(n){this._renderArgsMode(n,e.args);return}}const o=e.isCommand===!1&&this._input.value===""?c():I(e.slug).filter(n=>n.eager!==!0),d=this._sortCommands(o);if(d.length===0){this._resultsEl.innerHTML=` |
| 15 |
<div class="desktop-mode-ai__state desktop-mode-ai__state--empty"> |
| 16 |
<span>No commands matching <strong>/${this._esc(e.slug)}</strong>.</span> |
| 17 |
</div> |
| 18 |
`;return}this._selectedCommand>=d.length&&(this._selectedCommand=0);const s=d.map((n,r)=>` |
| 19 |
<button |
| 20 |
type="button" |
| 21 |
class="desktop-mode-ai__cmd-item${r===this._selectedCommand?" is-selected":""}" |
| 22 |
data-slug="${this._esc(n.slug)}" |
| 23 |
data-index="${r}" |
| 24 |
> |
| 25 |
${n.iconSvg?`<span class="desktop-mode-ai__cmd-icon desktop-mode-ai__cmd-icon--svg" aria-hidden="true">${n.iconSvg}</span>`:`<span class="desktop-mode-ai__cmd-icon dashicons ${this._esc(n.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span>`} |
| 26 |
<span class="desktop-mode-ai__cmd-body"> |
| 27 |
<span class="desktop-mode-ai__cmd-title"> |
| 28 |
${this._esc(n.label)} |
| 29 |
${n.hint?`<span class="desktop-mode-ai__cmd-hint">${this._esc(n.hint)}</span>`:""} |
| 30 |
</span> |
| 31 |
${n.description?`<span class="desktop-mode-ai__cmd-desc">${this._esc(n.description)}</span>`:""} |
| 32 |
</span> |
| 33 |
</button> |
| 34 |
`).join("");this._resultsEl.innerHTML=` |
| 35 |
<div class="desktop-mode-ai__cmd-list"> |
| 36 |
<p class="desktop-mode-ai__suggestions-label">Commands</p> |
| 37 |
${s} |
| 38 |
</div> |
| 39 |
`,this._resultsEl.querySelectorAll(".desktop-mode-ai__cmd-item").forEach(n=>{n.addEventListener("click",()=>{const r=n.dataset.slug??"";this._input.value=`/${r} `,this._submitBtn.classList.add("has-value"),this._input.focus(),this._renderCommandMode()}),n.addEventListener("mouseenter",()=>{if(this._keyboardNav)return;const r=parseInt(n.dataset.index??"0",10);Number.isNaN(r)||(this._selectedCommand=r,this._resultsEl.querySelectorAll(".desktop-mode-ai__cmd-item").forEach((a,l)=>a.classList.toggle("is-selected",l===r)))})})}_renderArgsMode(e,t){if(typeof e.suggest!="function"){this._currentSuggestions=[],this._resultsEl.innerHTML=this._renderCommandHeader(e,!0);return}const o=++this._suggestToken,d={close:()=>this.close(),openInWindow:(r,a,l)=>this._openInLegacyWindow(r,a,l),confirm:(r,a)=>this._confirm(r,a)};let s;try{s=e.suggest(t,d)}catch{s=[]}const n=r=>{o===this._suggestToken&&(this._currentSuggestions=r,this._selectedSuggestion>=r.length&&(this._selectedSuggestion=0),this._resultsEl.innerHTML=this._renderCommandHeader(e,!1)+this._renderSuggestionList(r),this._resultsEl.querySelectorAll(".desktop-mode-ai__cmd-suggest-item").forEach(a=>{a.addEventListener("click",()=>{const l=parseInt(a.dataset.index??"0",10),k=r[l];k&&(this._input.value=`/${e.slug} ${k.value}`,this._runCommand(e,k.value))}),a.addEventListener("mouseenter",()=>{const l=parseInt(a.dataset.index??"0",10);Number.isNaN(l)||(this._selectedSuggestion=l,this._paintSuggestionSelection())})}))};s&&typeof s.then=="function"?(this._resultsEl.innerHTML=this._renderCommandHeader(e,!1),s.then(r=>n(Array.isArray(r)?r:[])).catch(()=>n([]))):n(Array.isArray(s)?s:[])}_renderCommandHeader(e,t){return` |
| 40 |
<div class="desktop-mode-ai__cmd-active"> |
| 41 |
<span class="desktop-mode-ai__cmd-icon dashicons ${this._esc(e.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span> |
| 42 |
<div class="desktop-mode-ai__cmd-body"> |
| 43 |
<span class="desktop-mode-ai__cmd-title"> |
| 44 |
/${this._esc(e.slug)} |
| 45 |
${e.hint?`<span class="desktop-mode-ai__cmd-hint">${this._esc(e.hint)}</span>`:""} |
| 46 |
</span> |
| 47 |
${e.description?`<span class="desktop-mode-ai__cmd-desc">${this._esc(e.description)}</span>`:""} |
| 48 |
${t?'<span class="desktop-mode-ai__cmd-enter-hint">Press <kbd>↵</kbd> to run</span>':""} |
| 49 |
</div> |
| 50 |
</div> |
| 51 |
`}_renderSuggestionList(e){return e.length===0?` |
| 52 |
<div class="desktop-mode-ai__state desktop-mode-ai__state--empty"> |
| 53 |
<span>No suggestions — press <kbd>↵</kbd> to run with the text you typed.</span> |
| 54 |
</div> |
| 55 |
`:`<div class="desktop-mode-ai__cmd-suggest-list">${e.map((o,d)=>` |
| 56 |
<button |
| 57 |
type="button" |
| 58 |
class="desktop-mode-ai__cmd-suggest-item${d===this._selectedSuggestion?" is-selected":""}" |
| 59 |
data-index="${d}" |
| 60 |
> |
| 61 |
<span class="desktop-mode-ai__cmd-icon dashicons ${this._esc(o.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span> |
| 62 |
<span class="desktop-mode-ai__cmd-body"> |
| 63 |
<span class="desktop-mode-ai__cmd-suggest-label">${this._esc(o.label)}</span> |
| 64 |
${o.description?`<span class="desktop-mode-ai__cmd-desc">${this._esc(o.description)}</span>`:""} |
| 65 |
</span> |
| 66 |
</button> |
| 67 |
`).join("")}</div>`}_sortCommands(e){return e.slice().sort((t,o)=>{const d=typeof t.owner=="string"&&t.owner.startsWith("iframe:")?0:1,s=typeof o.owner=="string"&&o.owner.startsWith("iframe:")?0:1;return d-s})}_paintCommandSelection(){const e=this._resultsEl.querySelectorAll(".desktop-mode-ai__cmd-item");e.forEach((d,s)=>{d.classList.toggle("is-selected",s===this._selectedCommand)});const t=this._resultsEl.querySelector(".desktop-mode-ai__cmd-list");t&&t.classList.toggle("desktop-mode-ai__cmd-list--kb-nav",this._keyboardNav);const o=e[this._selectedCommand];o&&typeof o.scrollIntoView=="function"&&o.scrollIntoView({block:"nearest"})}_paintSuggestionSelection(){this._resultsEl.querySelectorAll(".desktop-mode-ai__cmd-suggest-item").forEach((e,t)=>{e.classList.toggle("is-selected",t===this._selectedSuggestion)})}_renderSuggestions(){this._resultsEl.hidden=!1,this._resultsEl.innerHTML=` |
| 68 |
<div class="desktop-mode-ai__suggestions"> |
| 69 |
<p class="desktop-mode-ai__suggestions-label">${this._esc("Try asking")}</p> |
| 70 |
<div class="desktop-mode-ai__suggestions-list"> |
| 71 |
${z.map(e=>`<button type="button" class="desktop-mode-ai__suggestion" data-prompt="${this._esc(e)}"> |
| 72 |
${this._esc(e)} |
| 73 |
</button>`).join("")} |
| 74 |
</div> |
| 75 |
</div> |
| 76 |
`,this._resultsEl.querySelectorAll(".desktop-mode-ai__suggestion").forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.prompt??"";this._input.value=t,this._submitBtn.classList.add("has-value"),this._input.focus()})})}_showThinking(e="Thinking…"){this._resultsEl.hidden=!1,this._resultsEl.innerHTML=` |
| 77 |
<div class="desktop-mode-ai__state desktop-mode-ai__state--thinking"> |
| 78 |
${j} |
| 79 |
<span>${this._esc(e)}</span> |
| 80 |
</div> |
| 81 |
`}_showError(e,t){if(this._resultsEl.hidden=!1,t==="desktop_mode_ai_disabled"){const o=this._esc(e),d=r=>`<button type="button" class="desktop-mode-ai__settings-link">${r}</button>`,s=/OS Settings.*?AI Settings/,n=s.test(o)?o.replace(s,r=>d(r)):`${o} ${d("AI Settings")}`;this._resultsEl.innerHTML=` |
| 82 |
<div class="desktop-mode-ai__state desktop-mode-ai__state--error"> |
| 83 |
<span>${n}</span> |
| 84 |
</div> |
| 85 |
`,this._resultsEl.querySelector(".desktop-mode-ai__settings-link")?.addEventListener("click",()=>this._openAiSettings());return}this._resultsEl.innerHTML=` |
| 86 |
<div class="desktop-mode-ai__state desktop-mode-ai__state--error"> |
| 87 |
<span>${this._esc(e)}</span> |
| 88 |
</div> |
| 89 |
`}_showResult(e,t){this._resultsEl.hidden=!1;const o=` |
| 90 |
<div class="desktop-mode-ai__bubble"> |
| 91 |
<span class="desktop-mode-ai__bubble-icon">${E}</span> |
| 92 |
<div class="desktop-mode-ai__bubble-text">${q(t.message||"")}</div> |
| 93 |
</div> |
| 94 |
`;let d="";t.answer_type==="entity"&&t.entity?d=this._renderEntityCard(t.entity):t.answer_type==="navigation"&&t.admin_links&&t.admin_links.length>0&&(d=this._renderAdminLinks(t.admin_links)),t.continue&&(d+=` |
| 95 |
<button type="button" class="desktop-mode-ai__continue-btn" |
| 96 |
data-tool="${this._esc(t.continue.tool)}" |
| 97 |
data-offset="${t.continue.offset}" |
| 98 |
data-query="${this._esc(e)}"> |
| 99 |
${this._esc(t.continue.label)} |
| 100 |
</button> |
| 101 |
`),this._resultsEl.innerHTML=o+d,this._resultsEl.querySelectorAll(".desktop-mode-ai__entity-open").forEach(n=>{n.addEventListener("click",()=>{const r=n.dataset.url??"",a=n.dataset.title??"",l=n.dataset.icon??"dashicons-admin-generic";r&&this._openInLegacyWindow(r,a,l)})}),this._resultsEl.querySelectorAll(".desktop-mode-ai__admin-link").forEach(n=>{n.addEventListener("click",()=>{const r=n.dataset.url??"",a=n.dataset.title??"",l=n.dataset.icon??"dashicons-admin-generic";r&&this._openInLegacyWindow(r,a,l)})});const s=this._resultsEl.querySelector(".desktop-mode-ai__continue-btn");s&&s.addEventListener("click",()=>{const n=s.dataset.tool??null,r=parseInt(s.dataset.offset??"0",10),a=s.dataset.query??e;this._runSearch(a,n,r)})}_renderEntityCard(e){const t=e.type==="comment",o=t?`Comment on “${this._esc(e.post_title??"post")}”`:this._esc(e.title??"Untitled"),d=this._esc(e.ai_summary||e.excerpt||""),s=e.type.charAt(0).toUpperCase()+e.type.slice(1),n=e.topic?`<span class="desktop-mode-ai__entity-topic">${this._esc(e.topic)}</span>`:"";let r;return t?r="dashicons-admin-comments":e.type==="page"?r="dashicons-admin-page":r="dashicons-admin-post",` |
| 102 |
<div class="desktop-mode-ai__entity"> |
| 103 |
<div class="desktop-mode-ai__entity-header"> |
| 104 |
${n} |
| 105 |
<span class="desktop-mode-ai__entity-type">${this._esc(s)}</span> |
| 106 |
</div> |
| 107 |
<h3 class="desktop-mode-ai__entity-title">${o}</h3> |
| 108 |
<p class="desktop-mode-ai__entity-summary">${d}</p> |
| 109 |
<button type="button" |
| 110 |
class="desktop-mode-ai__entity-open" |
| 111 |
data-url="${this._esc(e.edit_url)}" |
| 112 |
data-title="${this._esc(e.title??e.post_title??s)}" |
| 113 |
data-icon="${r}"> |
| 114 |
<span>${this._esc(`Open ${s.toLowerCase()} in desktop`)}</span> |
| 115 |
${A} |
| 116 |
</button> |
| 117 |
</div> |
| 118 |
`}_renderAdminLinks(e){return`<div class="desktop-mode-ai__admin-links">${e.map(o=>` |
| 119 |
<button type="button" |
| 120 |
class="desktop-mode-ai__admin-link" |
| 121 |
data-url="${this._esc(o.url)}" |
| 122 |
data-title="${this._esc(o.title)}" |
| 123 |
data-icon="${this._esc(o.icon)}"> |
| 124 |
<span class="desktop-mode-ai__admin-link-icon dashicons ${this._esc(o.icon)}" aria-hidden="true"></span> |
| 125 |
<span class="desktop-mode-ai__admin-link-body"> |
| 126 |
<span class="desktop-mode-ai__admin-link-title">${this._esc(o.title)}</span> |
| 127 |
<span class="desktop-mode-ai__admin-link-desc">${this._esc(o.description)}</span> |
| 128 |
</span> |
| 129 |
<span class="desktop-mode-ai__admin-link-arrow">${A}</span> |
| 130 |
</button> |
| 131 |
`).join("")}</div>`}_esc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}_buildDOM(){const e=document.createElement("div");return e.id="desktop-mode-ai-assistant",e.className="desktop-mode-ai",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label","AI Assistant"),e.setAttribute("aria-hidden","true"),e.setAttribute("hidden",""),e.innerHTML=` |
| 132 |
<div class="desktop-mode-ai__backdrop" aria-hidden="true"></div> |
| 133 |
<div class="desktop-mode-ai__panel"> |
| 134 |
<div class="desktop-mode-ai__header"> |
| 135 |
<span class="desktop-mode-ai__header-icon">${E}</span> |
| 136 |
<span class="desktop-mode-ai__header-label">AI Assistant</span> |
| 137 |
<button type="button" class="desktop-mode-ai__close" aria-label="Close"> |
| 138 |
${K} |
| 139 |
</button> |
| 140 |
</div> |
| 141 |
<div class="desktop-mode-ai__input-wrap"> |
| 142 |
<span class="desktop-mode-ai__input-icon">${E}</span> |
| 143 |
<input |
| 144 |
class="desktop-mode-ai__input" |
| 145 |
type="text" |
| 146 |
placeholder="How can I help?" |
| 147 |
autocomplete="off" |
| 148 |
spellcheck="false" |
| 149 |
aria-label="Ask the AI assistant" |
| 150 |
/> |
| 151 |
<button type="button" class="desktop-mode-ai__submit" aria-label="Send"> |
| 152 |
${V} |
| 153 |
</button> |
| 154 |
</div> |
| 155 |
<div class="desktop-mode-ai__results" hidden></div> |
| 156 |
<div class="desktop-mode-ai__footer"> |
| 157 |
<span class="desktop-mode-ai__footer-hint"> |
| 158 |
Your assistant for finding content and navigating wp-admin |
| 159 |
</span> |
| 160 |
<span class="desktop-mode-ai__footer-keys" aria-hidden="true"> |
| 161 |
<kbd>↵</kbd> ask |
| 162 |
</span> |
| 163 |
</div> |
| 164 |
</div> |
| 165 |
`,e}}const Y=i=>new Z(i);window.desktopModeCreateAiAssistant=Y})(); |
| 166 |
|