PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 0.9.6
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v0.9.6
1.1.10 1.1.9 1.1.8 1.1.7 1.1.6 1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.1 1.0.0 0.9.8 0.9.7 0.9.6 0.9.4 0.9.5 0.9.3 0.9.2 0.9.1 0.9.0 0.8.9 0.8.8 0.8.7 All 34 releases
desktop-mode / assets / js / ai-assistant.min.js

ai-assistant.min.js in OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin 0.9.6, at assets/js/ai-assistant.min.js

172 lines 37.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function(){"use strict";function S(){const o=window.wp?.hooks;if(!o)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 o}function L(o,e,...t){return S().applyFilters(o,e,...t)}function v(o,...e){S().doAction(o,...e)}const u={INIT:"desktop-mode.init",WALLPAPERS:"desktop-mode.wallpapers",GAMES:"desktop-mode.games",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",WALLPAPER_SUSPEND:"desktop-mode.wallpaper.suspend",WALLPAPER_PREVIEW_PARAMS:"desktop-mode.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"desktop-mode.wallpaper.settings-changed",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_FOCUS_ON_DRAG_HOVER:"desktop-mode.window.focus-on-drag-hover",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",WINDOW_CONTENT_CHANGED:"desktop-mode.window-links.content-changed",WINDOW_LINK_GROUPS_CHANGED:"desktop-mode.window-links.groups-changed",WINDOW_LINKS_CONTENT:"desktop-mode.window-links.content",WINDOW_LINK_GROUPS:"desktop-mode.window-links.groups",WINDOW_LINK_EDGES:"desktop-mode.window-links.edges",RELATED_ENTITIES_ITEMS:"desktop-mode.related-entities.items",WINDOW_LINK_RENDERERS:"desktop-mode.window-links.renderers",WINDOW_LINK_RENDERER:"desktop-mode.window-links.renderer",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",AUTH_LOST:"desktop-mode.auth.lost",AUTH_RESTORED:"desktop-mode.auth.restored"},b="wpd-confirm-dialog";let m=null;function p(){return typeof window.customElements<"u"&&!!window.customElements.get(b)}function R(o){return new Promise((e,t)=>{const s=document.querySelector('script[data-desktop-mode-shell-overlays="1"]'),n=()=>{if(p()){e();return}t(new Error("[desktop-mode] shell-overlays bundle loaded but did not register the overlay components."))};if(s){p()?n():(s.addEventListener("load",n),s.addEventListener("error",()=>t(new Error("failed to load shell-overlays bundle"))));return}const i=document.createElement("script");i.src=o,i.async=!0,i.dataset.desktopModeShellOverlays="1",i.addEventListener("load",n),i.addEventListener("error",()=>t(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(i)})}function C(o){return p()||!o?Promise.resolve():(m||(m=R(o)),m)}function T(){return window.desktopModeConfig?.shellOverlaysBundleUrl??""}async function W(o){return await C(T()),new Promise(e=>{const t=document.createElement("wpd-confirm-dialog");t.setAttribute("open",""),o.title&&t.setAttribute("title",o.title),t.setAttribute("message",o.message),o.confirmLabel&&t.setAttribute("confirm-label",o.confirmLabel),o.cancelLabel&&t.setAttribute("cancel-label",o.cancelLabel),o.danger&&t.setAttribute("danger",""),o.hideCancel&&t.setAttribute("hide-cancel",""),o.dismissable&&t.setAttribute("dismissable","");const s=i=>{t.remove(),e(i)};t.addEventListener("wpd-confirm",()=>s(!0)),t.addEventListener("wpd-cancel",()=>s(!1)),document.body.appendChild(t),(t.shadowRoot?.querySelector(".dialog")??t).focus?.()})}const O="X-WP-Nonce";function M(o,e){const t=P();if(!t)return e;const s=$(o);if(!s||!U(s))return e;const n=e?.headers??(typeof Request<"u"&&o instanceof Request?o.headers:void 0),i=new Headers(n??{});return i.has(O)?e:(i.set(O,t),{...e??{},headers:i})}function P(){if(typeof window>"u")return;const e=window.desktopModeConfig?.restNonce;return typeof e=="string"&&e.length>0?e:void 0}function $(o){try{const e=typeof window<"u"&&window.location?window.location.href:void 0;return typeof o=="string"?new URL(o,e):o instanceof URL?o:typeof Request<"u"&&o instanceof Request?new URL(o.url,e):null}catch{return null}}function U(o){return typeof window>"u"||!window.location||o.origin!==window.location.origin?!1:!!(o.pathname.includes("/wp-json/")||o.searchParams.has("rest_route"))}function F(o,e,t={}){const s=window.wp?.desktop?.fetch;if(typeof s=="function")return s(o,e,t);const n=M(o,e);return fetch(o,n)}const N="__desktopModeSharedStores";function H(){const o=window;let e=o[N];return e||(e=new Map,o[N]=e),e}function G(o,e){const t=H();let s=t.get(o);s||(s={state:e(),listeners:new Set,rebuild:e},t.set(o,s));const n={get state(){return s.state},set state(i){s.state=i},getState(){return s.state},notify(){for(const i of Array.from(s.listeners))try{i(s.state)}catch(d){console.error(`[desktop-mode/shared-store:${o}] subscriber threw:`,d)}},subscribe(i){return s.listeners.add(i),()=>{s.listeners.delete(i)}},setState(i){const d=s.state;if(typeof d!="object"||d===null){console.warn(`[desktop-mode/shared-store:${o}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(d,i),n.notify()},reset(){const i=s.rebuild(),d=s.state;if(typeof d=="object"&&d!==null&&typeof i=="object"&&i!==null){const r=d;for(const a of Object.keys(r))delete r[a];Object.assign(r,i)}else s.state=i;s.listeners.clear()}};return n}const A=G("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),h=A.state.registry,I=A.state.listeners;function E(){return Array.from(h.values())}function k(){return Array.from(h.values()).filter(o=>o.eager===!0)}function _(o){return h.get(o.toLowerCase())??null}function D(o){const e=o.trim().toLowerCase();return e===""?E():E().filter(t=>t.slug.toLowerCase().startsWith(e)||t.label.toLowerCase().includes(e))}function x(o){return I.add(o),()=>{I.delete(o)}}function c(o){if(!o.startsWith("/"))return{isCommand:!1,slug:"",args:"",hasArgsPart:!1};const e=o.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(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function f(o){return o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,t,s)=>/^https?:\/\//i.test(s.trim())?`<a href="${s.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(o){if(!o)return"";const t=B(o).split(/\n\s*\n/),s=[];for(const n of t){const i=n.split(/\n/).map(a=>a.trim()).filter(a=>a!=="");if(i.length===0)continue;const d=i.every(a=>/^[-*]\s+/.test(a)),r=i.every(a=>/^\d+\.\s+/.test(a));if(d){const a=i.map(l=>`<li>${f(l.replace(/^[-*]\s+/,""))}</li>`);s.push(`<ul>${a.join("")}</ul>`)}else if(r){const a=i.map(l=>`<li>${f(l.replace(/^\d+\.\s+/,""))}</li>`);s.push(`<ol>${a.join("")}</ol>`)}else s.push(`<p>${f(i.join("<br>"))}</p>`)}return s.join("")}const g=`<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>`,y=`<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=`<svg viewBox="0 0 20 20" width="15" height="15" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
15 <circle cx="9" cy="9" r="6"/>
16 <line x1="13.5" y1="13.5" x2="18" y2="18"/>
17 </svg>`,z=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true" focusable="false">
18 <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"/>
19 </svg>`,Y=["Find my post about…","Where can I see categories?","Do I have any spam comments?","Take me to plugin settings"];class X{constructor(e){this._isOpen=!1,this._isSearching=!1,this._previousFocus=null,this._currentStream=null,this._mode="commands",this._modeInput={commands:"",ai:""},this._lastAiResult=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._isAiAvailable=e.isAiAvailable??(()=>!1),this._isOverrideEnabled=e.isOverrideEnabled??(()=>!1),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._renderForMode()})}open(){if(this._isOpen){this._input.focus(),this._input.select();return}this._isOpen=!0,this._previousFocus=this._el.ownerDocument.activeElement,this._input.value="",this._modeInput={commands:"",ai:""},this._lastAiResult=null,this._selectedCommand=0,this._submitBtn.classList.remove("has-value"),this._mode=this._defaultMode(),this._updateModeUI(),this._renderForMode(),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}_aiModeAllowed(){return this._isAiAvailable()&&this._isOverrideEnabled()}_defaultMode(){return this._aiModeAllowed()?"ai":"commands"}_setMode(e){const t=e==="ai"&&!this._aiModeAllowed()?"commands":e;t!==this._mode&&(this._modeInput[this._mode]=this._input.value,this._mode=t,this._input.value=this._modeInput[t],this._submitBtn.classList.toggle("has-value",this._input.value.trim().length>0)),this._selectedCommand=0,this._selectedSuggestion=0,this._updateModeUI(),this._mode==="ai"&&this._lastAiResult&&this._lastAiResult.query===this._input.value.trim()?this._showResult(this._lastAiResult.query,this._lastAiResult.data):this._renderForMode(),this._input.focus()}_updateModeUI(){const e=this._aiModeAllowed(),t=this._el.querySelector(".desktop-mode-ai__modes");t&&(t.hidden=!e,t.querySelectorAll("[data-mode]").forEach(n=>{const i=n.dataset.mode===this._mode;n.classList.toggle("is-active",i),n.setAttribute("aria-pressed",String(i))})),this._input.placeholder=this._mode==="ai"?"How can I help?":"Search commands…";const s=this._el.querySelector(".desktop-mode-ai__input-icon");s&&(s.innerHTML=this._mode==="ai"?g:Z)}_isPickMode(e){return e.isCommand&&e.hasArgsPart?!1:e.isCommand||this._mode==="commands"?!0:this._input.value===""&&k().length>0}_commandMatches(){const e=c(this._input.value);if(e.isCommand)return this._sortCommands(D(e.slug).filter(s=>s.eager!==!0));if(this._mode==="ai")return this._sortCommands(k());const t=this._input.value.trim();return this._sortCommands(t===""?E():D(t))}_pickCommand(e){if(typeof e.suggest=="function"){this._input.value=`/${e.slug} `,this._submitBtn.classList.add("has-value"),this._input.focus(),this._renderCommandMode();return}this._runCommand(e,"")}_renderForMode(){if(c(this._input.value).isCommand||this._mode==="commands"){this._renderCommandMode();return}const t=k().length>0;if(this._input.value.trim()===""){t?this._renderCommandMode():this._renderSuggestions();return}this._resultsEl.querySelector(".desktop-mode-ai__bubble")||(t?this._renderCommandMode():this._resultsEl.querySelector(".desktop-mode-ai__suggestions")&&(this._resultsEl.innerHTML="",this._resultsEl.hidden=!0))}_bindEvents(){this._el.addEventListener("keydown",e=>{e.key==="Escape"&&(e.stopPropagation(),this.close())}),this._el.addEventListener("mousedown",e=>{const t=e.target;(!(t instanceof Element)||!t.closest(".desktop-mode-ai__panel"))&&this.close()}),this._el.addEventListener("keydown",e=>{if(e.key!=="Tab")return;const t=[this._closeBtn,this._input,this._submitBtn].filter(d=>!d.disabled),s=t[0],n=t[t.length-1],i=this._el.ownerDocument.activeElement;e.shiftKey&&i===s?(e.preventDefault(),n.focus()):!e.shiftKey&&i===n&&(e.preventDefault(),s.focus())}),document.addEventListener("desktop-mode-open-ai",()=>this.open()),this._closeBtn.addEventListener("click",()=>this.close()),this._el.querySelectorAll(".desktop-mode-ai__mode").forEach(e=>{e.addEventListener("click",()=>this._setMode(e.dataset.mode==="ai"?"ai":"commands"))}),this._submitBtn.addEventListener("click",()=>this._onSubmit()),this._input.addEventListener("keydown",e=>{const t=c(this._input.value);if(this._isPickMode(t)){const s=this._commandMatches();if(e.key==="ArrowDown"){e.preventDefault(),this._selectedCommand=Math.min(this._selectedCommand+1,Math.max(0,s.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"&&s.length>0&&t.isCommand){e.preventDefault();const n=s[this._selectedCommand]??s[0];this._input.value=`/${n.slug} `,this._submitBtn.classList.add("has-value"),this._selectedSuggestion=0,this._renderCommandMode();return}if(e.key==="Enter"&&!e.shiftKey){if(e.preventDefault(),s.length===0){t.isCommand&&this._showError(`Unknown command: /${t.slug}`);return}const n=s[this._selectedCommand]??s[0];this._pickCommand(n);return}}if(t.isCommand&&t.hasArgsPart){const s=_(t.slug);if(!!s&&typeof s.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 i=this._currentSuggestions[this._selectedSuggestion];i&&(this._input.value=`/${t.slug} ${i.value}`);return}if(e.key==="Enter"&&!e.shiftKey&&s){e.preventDefault();const i=this._currentSuggestions[this._selectedSuggestion],d=i?i.value:t.args;this._runCommand(s,d);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._renderForMode()}),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(){if(this._isSearching)return;const e=c(this._input.value);if(this._isPickMode(e)){const s=this._commandMatches(),n=s[this._selectedCommand]??s[0];n&&this._pickCommand(n);return}const t=this._input.value.trim();if(t){if(e.isCommand){const s=_(e.slug);if(!s){this._showError(`Unknown command: /${e.slug}`);return}await this._runCommand(s,e.args);return}await this._runSearch(t,null,0)}}async _runCommand(e,t){if(this._isSearching)return;const s=L(u.COMMAND_BEFORE_RUN,{proceed:!0,slug:e.slug,args:t,command:e});if(s&&s.proceed===!1){this._showError(s.reason??`Command /${e.slug} was cancelled.`);return}this._isSearching=!0,this._submitBtn.disabled=!0,this._input.disabled=!0,this._showThinking(`Running /${e.slug}`);const n={close:()=>{this._previousFocus=null,this.close()},openInWindow:(i,d,r)=>this._openInLegacyWindow(i,d,r),confirm:(i,d)=>this._confirm(i,d)};try{const i=await Promise.resolve(e.run(t,n));this._renderCommandResult(e,i),v(u.COMMAND_AFTER_RUN,{slug:e.slug,args:t,command:e,result:i})}catch(i){const d=i instanceof Error?i.message:String(i);this._showError(`Command /${e.slug} failed: ${d}`),v(u.COMMAND_ERROR,{slug:e.slug,args:t,command:e,error:i})}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._isOpen?this._renderForMode():(this._resultsEl.innerHTML="",this._resultsEl.hidden=!0);return}const s=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("",s)}_runSearch(e,t,s){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,s):this._runSearchFetch(e,t,s)}_runSearchStream(e,t,s){const n=new URL(this._aiSearchStreamUrl,window.location.origin);n.searchParams.set("nonce",this._restNonce),n.searchParams.set("query",e),t&&(n.searchParams.set("resume_tool",t),n.searchParams.set("start_offset",String(s))),this._closeStream();const i=new EventSource(n.toString());this._currentStream=i;const d=()=>{i.close(),this._currentStream=null,this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1,this._input.focus()};i.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),d();break;case"error":this._showError(a.message??"Something went wrong.",a.code),d();break}},i.onerror=()=>{this._currentStream===i&&(this._showError("Lost connection to the assistant. Please try again."),d())}}async _runSearchFetch(e,t,s){try{const n={query:e};t&&(n.resume_tool=t,n.start_offset=s);const i=await F(this._aiSearchUrl,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":this._restNonce},body:JSON.stringify(n)},{source:"desktop-mode/ai-search"});if(!i.ok){const d=await i.json().catch(()=>({}));this._showError(d.message??`Server returned ${i.status}`,d.code);return}this._showResult(e,await i.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}_openAssistantSettings(){const e=this._getDesktopShell();this._previousFocus=null,this.close(),e?.openOsSettings?.({tabId:"features"})}_openInLegacyWindow(e,t,s){const n=this._getDesktopShell();if(!n||!n.windowManager){window.open(e,"_blank","noopener");return}const i=n.deriveWindowId?n.deriveWindowId(e):"desktop-mode-ai-"+e.replace(/[^a-z0-9]+/gi,"-").slice(0,80);n.windowManager.open({id:i,url:e,title:t,icon:s??"dashicons-admin-generic"}),this.close()}_renderCommandMode(){this._resultsEl.hidden=!1;const e=c(this._input.value);if(e.hasArgsPart){const d=_(e.slug);if(d){this._renderArgsMode(d,e.args);return}}const t=this._commandMatches();if(t.length===0){const d=e.isCommand?`/${e.slug}`:this._input.value.trim();this._resultsEl.innerHTML=`
20 <div class="desktop-mode-ai__state desktop-mode-ai__state--empty">
21 <span>No commands matching <strong>${this._esc(d)}</strong>.</span>
22 </div>
23 `;return}this._selectedCommand>=t.length&&(this._selectedCommand=0);const s=this._isPickMode(e),n=t.map((d,r)=>`
24 <button
25 type="button"
26 class="desktop-mode-ai__cmd-item${s&&r===this._selectedCommand?" is-selected":""}"
27 data-slug="${this._esc(d.slug)}"
28 data-index="${r}"
29 >
30 ${d.iconSvg?`<span class="desktop-mode-ai__cmd-icon desktop-mode-ai__cmd-icon--svg" aria-hidden="true">${d.iconSvg}</span>`:`<span class="desktop-mode-ai__cmd-icon dashicons ${this._esc(d.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span>`}
31 <span class="desktop-mode-ai__cmd-body">
32 <span class="desktop-mode-ai__cmd-title">
33 ${this._esc(d.label)}
34 ${d.hint?`<span class="desktop-mode-ai__cmd-hint">${this._esc(d.hint)}</span>`:""}
35 </span>
36 ${d.description?`<span class="desktop-mode-ai__cmd-desc">${this._esc(d.description)}</span>`:""}
37 </span>
38 </button>
39 `).join(""),i=this._mode==="ai"?'<p class="desktop-mode-ai__suggestions-label">Suggested commands</p>':"";this._resultsEl.innerHTML=`
40 <div class="desktop-mode-ai__cmd-list">
41 ${i}
42 ${n}
43 </div>
44 `,this._resultsEl.querySelectorAll(".desktop-mode-ai__cmd-item").forEach(d=>{d.addEventListener("click",()=>{const r=d.dataset.slug??"",a=_(r);a&&this._pickCommand(a)}),d.addEventListener("mouseenter",()=>{if(this._keyboardNav)return;const r=parseInt(d.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 s=++this._suggestToken,n={close:()=>this.close(),openInWindow:(r,a,l)=>this._openInLegacyWindow(r,a,l),confirm:(r,a)=>this._confirm(r,a)};let i;try{i=e.suggest(t,n)}catch{i=[]}const d=r=>{s===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),w=r[l];w&&(this._input.value=`/${e.slug} ${w.value}`,this._runCommand(e,w.value))}),a.addEventListener("mouseenter",()=>{const l=parseInt(a.dataset.index??"0",10);Number.isNaN(l)||(this._selectedSuggestion=l,this._paintSuggestionSelection())})}))};i&&typeof i.then=="function"?(this._resultsEl.innerHTML=this._renderCommandHeader(e,!1),i.then(r=>d(Array.isArray(r)?r:[])).catch(()=>d([]))):d(Array.isArray(i)?i:[])}_renderCommandHeader(e,t){return`
45 <div class="desktop-mode-ai__cmd-active">
46 <span class="desktop-mode-ai__cmd-icon dashicons ${this._esc(e.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span>
47 <div class="desktop-mode-ai__cmd-body">
48 <span class="desktop-mode-ai__cmd-title">
49 /${this._esc(e.slug)}
50 ${e.hint?`<span class="desktop-mode-ai__cmd-hint">${this._esc(e.hint)}</span>`:""}
51 </span>
52 ${e.description?`<span class="desktop-mode-ai__cmd-desc">${this._esc(e.description)}</span>`:""}
53 ${t?'<span class="desktop-mode-ai__cmd-enter-hint">Press <kbd>↵</kbd> to run</span>':""}
54 </div>
55 </div>
56 `}_renderSuggestionList(e){return e.length===0?`
57 <div class="desktop-mode-ai__state desktop-mode-ai__state--empty">
58 <span>No suggestionspress <kbd></kbd> to run with the text you typed.</span>
59 </div>
60 `:`<div class="desktop-mode-ai__cmd-suggest-list">${e.map((s,n)=>`
61 <button
62 type="button"
63 class="desktop-mode-ai__cmd-suggest-item${n===this._selectedSuggestion?" is-selected":""}"
64 data-index="${n}"
65 >
66 <span class="desktop-mode-ai__cmd-icon dashicons ${this._esc(s.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span>
67 <span class="desktop-mode-ai__cmd-body">
68 <span class="desktop-mode-ai__cmd-suggest-label">${this._esc(s.label)}</span>
69 ${s.description?`<span class="desktop-mode-ai__cmd-desc">${this._esc(s.description)}</span>`:""}
70 </span>
71 </button>
72 `).join("")}</div>`}_sortCommands(e){return e.slice().sort((t,s)=>{const n=typeof t.owner=="string"&&t.owner.startsWith("iframe:")?0:1,i=typeof s.owner=="string"&&s.owner.startsWith("iframe:")?0:1;return n-i})}_paintCommandSelection(){const e=this._resultsEl.querySelectorAll(".desktop-mode-ai__cmd-item");e.forEach((n,i)=>{n.classList.toggle("is-selected",i===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 s=e[this._selectedCommand];s&&typeof s.scrollIntoView=="function"&&s.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=`
73 <div class="desktop-mode-ai__suggestions">
74 <p class="desktop-mode-ai__suggestions-label">${this._esc("Try asking")}</p>
75 <div class="desktop-mode-ai__suggestions-list">
76 ${Y.map(e=>`<button type="button" class="desktop-mode-ai__suggestion" data-prompt="${this._esc(e)}">
77 ${this._esc(e)}
78 </button>`).join("")}
79 </div>
80 </div>
81 `,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=`
82 <div class="desktop-mode-ai__state desktop-mode-ai__state--thinking">
83 ${j}
84 <span>${this._esc(e)}</span>
85 </div>
86 `}_showError(e,t){if(this._resultsEl.hidden=!1,t==="desktop_mode_ai_disabled"){const s=this._esc(e),n=r=>`<button type="button" class="desktop-mode-ai__settings-link">${r}</button>`,i=/OS Settings.*?Features/,d=i.test(s)?s.replace(i,r=>n(r)):`${s} ${n("Features")}`;this._resultsEl.innerHTML=`
87 <div class="desktop-mode-ai__state desktop-mode-ai__state--error">
88 <span>${d}</span>
89 </div>
90 `,this._resultsEl.querySelector(".desktop-mode-ai__settings-link")?.addEventListener("click",()=>this._openAssistantSettings());return}this._resultsEl.innerHTML=`
91 <div class="desktop-mode-ai__state desktop-mode-ai__state--error">
92 <span>${this._esc(e)}</span>
93 </div>
94 `}_showResult(e,t){e!==""&&(this._lastAiResult={query:e,data:t}),this._resultsEl.hidden=!1;const s=`
95 <div class="desktop-mode-ai__bubble">
96 <span class="desktop-mode-ai__bubble-icon">${g}</span>
97 <div class="desktop-mode-ai__bubble-text">${q(t.message||"")}</div>
98 </div>
99 `;let n="";t.answer_type==="entity"&&t.entity?n=this._renderEntityCard(t.entity):t.answer_type==="navigation"&&t.admin_links&&t.admin_links.length>0&&(n=this._renderAdminLinks(t.admin_links)),t.continue&&(n+=`
100 <button type="button" class="desktop-mode-ai__continue-btn"
101 data-tool="${this._esc(t.continue.tool)}"
102 data-offset="${t.continue.offset}"
103 data-query="${this._esc(e)}">
104 ${this._esc(t.continue.label)}
105 </button>
106 `),this._resultsEl.innerHTML=s+n,this._resultsEl.querySelectorAll(".desktop-mode-ai__entity-open").forEach(d=>{d.addEventListener("click",()=>{const r=d.dataset.url??"",a=d.dataset.title??"",l=d.dataset.icon??"dashicons-admin-generic";r&&this._openInLegacyWindow(r,a,l)})}),this._resultsEl.querySelectorAll(".desktop-mode-ai__admin-link").forEach(d=>{d.addEventListener("click",()=>{const r=d.dataset.url??"",a=d.dataset.title??"",l=d.dataset.icon??"dashicons-admin-generic";r&&this._openInLegacyWindow(r,a,l)})});const i=this._resultsEl.querySelector(".desktop-mode-ai__continue-btn");i&&i.addEventListener("click",()=>{const d=i.dataset.tool??null,r=parseInt(i.dataset.offset??"0",10),a=i.dataset.query??e;this._runSearch(a,d,r)})}_renderEntityCard(e){const t=e.type==="comment",s=t?`Comment on${this._esc(e.post_title??"post")}`:this._esc(e.title??"Untitled"),n=this._esc(e.ai_summary||e.excerpt||""),i=e.type.charAt(0).toUpperCase()+e.type.slice(1),d=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",`
107 <div class="desktop-mode-ai__entity">
108 <div class="desktop-mode-ai__entity-header">
109 ${d}
110 <span class="desktop-mode-ai__entity-type">${this._esc(i)}</span>
111 </div>
112 <h3 class="desktop-mode-ai__entity-title">${s}</h3>
113 <p class="desktop-mode-ai__entity-summary">${n}</p>
114 <button type="button"
115 class="desktop-mode-ai__entity-open"
116 data-url="${this._esc(e.edit_url)}"
117 data-title="${this._esc(e.title??e.post_title??i)}"
118 data-icon="${r}">
119 <span>${this._esc(`Open ${i.toLowerCase()} in desktop`)}</span>
120 ${y}
121 </button>
122 </div>
123 `}_renderAdminLinks(e){return`<div class="desktop-mode-ai__admin-links">${e.map(s=>`
124 <button type="button"
125 class="desktop-mode-ai__admin-link"
126 data-url="${this._esc(s.url)}"
127 data-title="${this._esc(s.title)}"
128 data-icon="${this._esc(s.icon)}">
129 <span class="desktop-mode-ai__admin-link-icon dashicons ${this._esc(s.icon)}" aria-hidden="true"></span>
130 <span class="desktop-mode-ai__admin-link-body">
131 <span class="desktop-mode-ai__admin-link-title">${this._esc(s.title)}</span>
132 <span class="desktop-mode-ai__admin-link-desc">${this._esc(s.description)}</span>
133 </span>
134 <span class="desktop-mode-ai__admin-link-arrow">${y}</span>
135 </button>
136 `).join("")}</div>`}_esc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}_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","Site Assistant"),e.setAttribute("aria-hidden","true"),e.setAttribute("hidden",""),e.innerHTML=`
137 <div class="desktop-mode-ai__backdrop" aria-hidden="true"></div>
138 <div class="desktop-mode-ai__panel">
139 <div class="desktop-mode-ai__header">
140 <span class="desktop-mode-ai__header-icon">${z}</span>
141 <span class="desktop-mode-ai__header-label">Site Assistant</span>
142 <div class="desktop-mode-ai__modes" role="group" aria-label="Assistant mode" hidden>
143 <button type="button" class="desktop-mode-ai__mode" data-mode="ai" aria-pressed="false">Ask AI</button>
144 <button type="button" class="desktop-mode-ai__mode" data-mode="commands" aria-pressed="false">Commands</button>
145 </div>
146 <button type="button" class="desktop-mode-ai__close" aria-label="Close">
147 ${K}
148 </button>
149 </div>
150 <div class="desktop-mode-ai__input-wrap">
151 <span class="desktop-mode-ai__input-icon">${g}</span>
152 <input
153 class="desktop-mode-ai__input"
154 type="text"
155 placeholder="How can I help?"
156 autocomplete="off"
157 spellcheck="false"
158 aria-label="Ask the assistant"
159 />
160 <button type="button" class="desktop-mode-ai__submit" aria-label="Send">
161 ${V}
162 </button>
163 </div>
164 <div class="desktop-mode-ai__results" hidden></div>
165 <div class="desktop-mode-ai__footer">
166 <span class="desktop-mode-ai__footer-hint">
167 Your assistant to quickly navigate and manage your entire site.
168 </span>
169 </div>
170 </div>
171 `,e}}const J=o=>new X(o);window.desktopModeCreateAiAssistant=J})();
172