PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.0
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.0
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 1.1.0, at assets/js/ai-assistant.min.js

170 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 D(){const n=window.wp?.hooks;if(!n)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 n}function P(n,e,...s){return D().applyFilters(n,e,...s)}function L(n,...e){D().doAction(n,...e)}const E={INIT:"os.init",WALLPAPERS:"os.wallpapers",GAMES:"os.games",UNFOCUS_EFFECTS:"os.unfocus-effects",WINDOW_REVEALS:"os.window-reveals",WALLPAPER_MOUNTING:"os.wallpaper.mounting",WALLPAPER_MOUNTED:"os.wallpaper.mounted",WALLPAPER_UNMOUNTING:"os.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"os.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"os.wallpaper.visibility",WALLPAPER_SUSPEND:"os.wallpaper.suspend",WALLPAPER_PREVIEW_PARAMS:"os.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"os.wallpaper.settings-changed",IFRAME_READY:"os.iframe.ready",IFRAME_ERROR:"os.iframe.error",IFRAME_NETWORK_COMPLETED:"os.iframe.network-completed",SHELL_ERROR:"os.shell.error",BROADCAST:"os.broadcast",MONITOR_ENTRY:"os.monitor.entry",WALLPAPER_SURFACES:"os.wallpaper.surfaces",DESKTOP_THEME_CHANGED:"os.os-theme.changed",DESKTOP_THEME_ICON:"os.os-theme.icon",DESKTOP_THEME_ICON_COLOR:"os.os-theme.icon-color",WALLPAPERS_SERVER_CHANGED:"os.wallpapers.server-changed",WINDOW_GEOMETRY:"os.window.geometry",WINDOW_OPENED:"os.window.opened",WINDOW_CONTENT_LOADING:"os.window.content-loading",WINDOW_CONTENT_LOADED:"os.window.content-loaded",WINDOW_LOADING_OVERLAY:"os.window.loading-overlay",WINDOW_REOPENED:"os.window.reopened",WINDOW_MENU_OPENED:"os.window.menu-opened",WINDOW_CLOSING:"os.window.closing",WINDOW_CLOSED:"os.window.closed",WINDOW_FOCUSED:"os.window.focused",WINDOW_BLURRED:"os.window.blurred",WINDOW_MINIMIZED:"os.window.minimized",WINDOW_RESTORED:"os.window.restored",WINDOW_MAXIMIZED:"os.window.maximized",WINDOW_UNMAXIMIZED:"os.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"os.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"os.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"os.window.auto-exit-fullscreen",WINDOW_FOCUS_ON_DRAG_HOVER:"os.window.focus-on-drag-hover",WINDOW_BOUNDS_CHANGED:"os.window.bounds-changed",WINDOW_MOVED:"os.window.moved",WINDOW_RESIZED:"os.window.resized",WINDOW_DRAG_START:"os.window.drag-start",WINDOW_DRAG_END:"os.window.drag-end",WINDOW_RESIZE_START:"os.window.resize-start",WINDOW_RESIZE_END:"os.window.resize-end",WINDOW_DETACHED:"os.window.detached",WINDOW_RELOADED:"os.window.reloaded",WINDOW_TITLE_CHANGED:"os.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"os.window.highlight-changed",WINDOW_BODY_RESIZED:"os.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"os.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"os.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"os.native-window.before-close",WINDOW_CHROME_THEME:"os.window.chrome.theme",WINDOW_CHROME_CONTROLS:"os.window.chrome.controls",WINDOW_CHROME_SLOT:"os.window.chrome.slot",WINDOW_CHROME_RENDER:"os.window.chrome.render",WINDOW_CHROME_APPLIED:"os.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"os.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"os.os-icon.clicked",DESKTOP_ICONS_RENDERED:"os.os-icons.rendered",ICON_BADGE_CHANGED:"os.icon.badge-changed",COMPONENTS_REGISTERED:"os.components.registered",DOCK_ITEM_APPENDED:"os.dock.item-appended",DOCK_ITEM_REMOVED:"os.dock.item-removed",DOCK_BEFORE_RENDER:"os.dock.before-render",DOCK_AFTER_RENDER:"os.dock.after-render",DOCK_REFRESH_ACTIVE:"os.dock.refresh-active",DOCK_TILE_CLASS:"os.dock.tile-class",DOCK_TILE_ELEMENT:"os.dock.tile-element",DOCK_TILE_RENDERED:"os.dock.tile-rendered",DOCK_TILE_TOOLTIP:"os.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"os.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"os.dock.peek-card-element",CONSTELLATION_PANEL:"os.constellation.panel",CONSTELLATION_OPENED:"os.constellation.opened",CONSTELLATION_CLOSED:"os.constellation.closed",OVERVIEW_ENTERING:"os.overview.entering",OVERVIEW_ENTERED:"os.overview.entered",OVERVIEW_EXITING:"os.overview.exiting",OVERVIEW_EXITED:"os.overview.exited",OVERVIEW_WINDOW_HOVER:"os.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"os.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"os.overview.window-click",ARRANGE_CASCADE_STARTING:"os.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"os.arrange.cascade.applied",ARRANGE_TILE_STARTING:"os.arrange.tile.starting",ARRANGE_TILE_APPLIED:"os.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"os.arrange.tile.dimensions",ARRANGE_SNAP_CHANGED:"os.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"os.arrange.snap.cell-size",ARRANGE_CUSTOM_ACTION:"os.arrange.custom-action",SNAP_ZONE_PENDING:"os.snap.zone-pending",SNAP_ZONE_CANCELED:"os.snap.zone-canceled",SNAP_ZONE_COMMITTED:"os.snap.zone-committed",SNAP_SPLIT_FILLED:"os.snap.split-filled",WIDGETS:"os.widgets",WIDGET_MOUNTING:"os.widget.mounting",WIDGET_MOUNTED:"os.widget.mounted",WIDGET_UNMOUNTING:"os.widget.unmounting",WIDGET_MOUNT_FAILED:"os.widget.mount-failed",WIDGET_ADDED:"os.widget.added",WIDGET_REMOVED:"os.widget.removed",DESKTOP_CREATED:"os.os.created",DESKTOP_CLOSED:"os.os.closed",DESKTOP_SWITCHED:"os.os.switched",PRIMARY_DESKTOP_ID:"os.primary-desktop-id",WINDOWS_BEFORE_CLOSE_ALL:"os.windows.before-close-all",WINDOWS_CLOSE_ALL:"os.windows.close-all",WINDOWS_AFTER_CLOSE_ALL:"os.windows.after-close-all",COMMAND_BEFORE_RUN:"os.command.before-run",COMMAND_AFTER_RUN:"os.command.after-run",COMMAND_ERROR:"os.command.error",SHELL_RESIZED:"os.shell.resized",SHELL_VISIBILITY:"os.shell.visibility",CONNECTION_OPENED:"os.connection.opened",CONNECTION_CLOSED:"os.connection.closed",CONNECTION_MESSAGE:"os.connection.message",IFRAME_CONNECTION_REQUEST:"os.iframe.connection-request",WINDOW_CONTENT_CHANGED:"os.window-links.content-changed",WINDOW_LINK_GROUPS_CHANGED:"os.window-links.groups-changed",WINDOW_LINKS_CONTENT:"os.window-links.content",WINDOW_LINK_GROUPS:"os.window-links.groups",WINDOW_LINK_EDGES:"os.window-links.edges",RELATED_ENTITIES_ITEMS:"os.related-entities.items",WINDOW_LINK_RENDERERS:"os.window-links.renderers",WINDOW_LINK_RENDERER:"os.window-links.renderer",EDITOR_PREVIEW_WINDOW_CONFIG:"os.editor-preview.window-config",EDITOR_PREVIEW_LIVE:"os.editor-preview.live",EDITOR_PREVIEW_OPENED:"os.editor-preview.opened",EDITOR_PREVIEW_CLOSED:"os.editor-preview.closed",FILE_DROP_FILES_DETECTED:"os.drop.files-detected",FILE_DROP_FILES_REJECTED:"os.drop.files-rejected",FILE_DROP_DIALOG_FIELDS:"os.drop.dialog-fields",FILE_DROP_BEFORE_UPLOAD:"os.drop.before-upload",FILE_DROP_UPLOAD_STARTED:"os.drop.upload-started",FILE_DROP_UPLOAD_PROGRESS:"os.drop.upload-progress",FILE_DROP_AFTER_UPLOAD:"os.drop.after-upload",FILE_DROP_UPLOAD_FAILED:"os.drop.upload-failed",AUTH_LOST:"os.auth.lost",AUTH_RESTORED:"os.auth.restored"},R="desktop-mode";function g(){return window.wp?.i18n}function l(n,e=R){return g()?.__(n,e)??n}function $(n,e,s=R){return g()?._x(n,e,s)??n}function _(n,...e){const s=g()?.sprintf;if(s)return s(n,...e);let t=0;return n.replace(/%(?:(\d+)\$)?[sd]/g,(r,i)=>{const o=i?Number.parseInt(i,10)-1:t++;return String(e[o]??"")})}const H="os-confirm-dialog";let f=null;function w(){return typeof window.customElements<"u"&&!!window.customElements.get(H)}function U(n){return new Promise((e,s)=>{const t=document.querySelector('script[data-os-shell-overlays="1"]'),r=()=>{if(w()){e();return}s(new Error("[openstation] shell-overlays bundle loaded but did not register the overlay components."))};if(t){w()?r():(t.addEventListener("load",r),t.addEventListener("error",()=>s(new Error("failed to load shell-overlays bundle"))));return}const i=document.createElement("script");i.src=n,i.async=!0,i.dataset.osShellOverlays="1",i.addEventListener("load",r),i.addEventListener("error",()=>s(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(i)})}function F(n){return w()||!n?Promise.resolve():(f||(f=U(n)),f)}function G(){return window.openStationConfig?.shellOverlaysBundleUrl??""}async function x(n){return await F(G()),new Promise(e=>{const s=document.createElement("os-confirm-dialog");s.setAttribute("open",""),n.title&&s.setAttribute("title",n.title),s.setAttribute("message",n.message),n.confirmLabel&&s.setAttribute("confirm-label",n.confirmLabel),n.cancelLabel&&s.setAttribute("cancel-label",n.cancelLabel),n.danger&&s.setAttribute("danger",""),n.hideCancel&&s.setAttribute("hide-cancel",""),n.dismissable&&s.setAttribute("dismissable","");const t=r=>{s.remove(),e(r)};s.addEventListener("os-confirm",()=>t(!0)),s.addEventListener("os-cancel",()=>t(!1)),document.body.appendChild(s)})}const C="X-WP-Nonce";function q(n,e){const s=B();if(!s)return e;const t=V(n);if(!t||!K(t))return e;const r=e?.headers??(typeof Request<"u"&&n instanceof Request?n.headers:void 0),i=new Headers(r??{});return i.has(C)?e:(i.set(C,s),{...e??{},headers:i})}function B(){if(typeof window>"u")return;const e=window.openStationConfig?.restNonce;return typeof e=="string"&&e.length>0?e:void 0}function V(n){try{const e=typeof window<"u"&&window.location?window.location.href:void 0;return typeof n=="string"?new URL(n,e):n instanceof URL?n:typeof Request<"u"&&n instanceof Request?new URL(n.url,e):null}catch{return null}}function K(n){return typeof window>"u"||!window.location||n.origin!==window.location.origin?!1:!!(n.pathname.includes("/wp-json/")||n.searchParams.has("rest_route"))}function y(n,e,s={}){const t=window.wp?.os?.fetch;if(typeof t=="function")return t(n,e,s);const r=q(n,e);return fetch(n,r)}function j(n){const e=document.createElement("textarea");return e.innerHTML=n,e.value}const Z='<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>',b="__openStationSharedStores";function z(){const n=window;let e=n[b];return e||(e=new Map,n[b]=e),e}function X(n,e){const s=z();let t=s.get(n);t||(t={state:e(),listeners:new Set,rebuild:e},s.set(n,t));const r={get state(){return t.state},set state(i){t.state=i},getState(){return t.state},notify(){for(const i of Array.from(t.listeners))try{i(t.state)}catch(o){console.error(`[desktop-mode/shared-store:${n}] subscriber threw:`,o)}},subscribe(i){return t.listeners.add(i),()=>{t.listeners.delete(i)}},setState(i){const o=t.state;if(typeof o!="object"||o===null){console.warn(`[desktop-mode/shared-store:${n}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(o,i),r.notify()},reset(){const i=t.rebuild(),o=t.state;if(typeof o=="object"&&o!==null&&typeof i=="object"&&i!==null){const a=o;for(const d of Object.keys(a))delete a[d];Object.assign(a,i)}else t.state=i;t.listeners.clear()}};return r}const T=X("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),O=T.state.registry,k=T.state.listeners;function v(){return Array.from(O.values())}function p(){return Array.from(O.values()).filter(n=>n.eager===!0)}function N(n){return O.get(n.toLowerCase())??null}function W(n){const e=n.trim().toLowerCase();return e===""?v():v().filter(s=>s.slug.toLowerCase().startsWith(e)||s.label.toLowerCase().includes(e))}function Y(n){return k.add(n),()=>{k.delete(n)}}function m(n){if(!n.startsWith("/"))return{isCommand:!1,slug:"",args:"",hasArgsPart:!1};const e=n.slice(1),s=e.indexOf(" ");return s===-1?{isCommand:!0,slug:e,args:"",hasArgsPart:!1}:{isCommand:!0,slug:e.slice(0,s),args:e.slice(s+1),hasArgsPart:!0}}function J(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function S(n){return n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,s,t)=>/^https?:\/\//i.test(t.trim())?`<a href="${t.trim()}" target="_blank" rel="noopener noreferrer">${s}</a>`:s).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(n){if(!n)return"";const e=J(n),s=[];let t=[],r=null;const i=()=>{t.length>0&&(s.push(`<p>${t.join("<br>")}</p>`),t=[])},o=()=>{r&&(s.push(`<${r.tag}>${r.items.join("")}</${r.tag}>`),r=null)};for(const a of e.split(/\n/)){const d=a.trim();if(d===""){i(),o();continue}const c=/^(#{1,6})\s+(.*)$/.exec(d);if(c){i(),o();const h=Math.min(6,c[1].length+2);s.push(`<h${h}>${S(c[2])}</h${h}>`);continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(d)){i(),o(),s.push("<hr>");continue}const u=/^[-*]\s+(.*)$/.exec(d),A=/^\d+\.\s+(.*)$/.exec(d);if(u||A){i();const h=u?"ul":"ol";(!r||r.tag!==h)&&(o(),r={tag:h,items:[]}),r.items.push(`<li>${S((u??A)[1])}</li>`);continue}o(),t.push(S(d))}return i(),o(),s.join("")}const I=`<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>`,ee=`<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>`,se=`<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>`,te=`<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="os-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>`,M=`<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>`,ie=`<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>`,ne=Z.replace("<svg ",'<svg width="18" height="18" aria-hidden="true" focusable="false" ');function oe(){return[l("Find my post about…"),l("Where can I see categories?"),l("Do I have any spam comments?"),l("Take me to plugin settings")]}class re{constructor(e){this._isOpen=!1,this._isSearching=!1,this._previousFocus=null,this._searchAbort=null,this._mode="commands",this._modeInput={commands:"",ai:""},this._lastAiResult=null,this._currentRemoteCommands=[],this._remoteSearchToken=0,this._selectedCommand=0,this._keyboardNav=!1,this._selectedSuggestion=0,this._currentSuggestions=[],this._suggestToken=0,this.ask=()=>{throw new Error("[openstation] wp.os.ai.ask called before the shell finished booting.")},this._aiSearchUrl=e.aiSearchUrl,this._restNonce=e.restNonce,this._adminUrl=e.adminUrl,this._isAiAvailable=e.isAiAvailable??(()=>!1),this._isOverrideEnabled=e.isOverrideEnabled??(()=>!1),this._el=this._buildDOM(),document.body.appendChild(this._el),this._input=this._el.querySelector(".os-ai__input"),this._submitBtn=this._el.querySelector(".os-ai__submit"),this._closeBtn=this._el.querySelector(".os-ai__close"),this._resultsEl=this._el.querySelector(".os-ai__results"),this._bindEvents(),this._renderSuggestions(),Y(()=>{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._currentRemoteCommands=[],this._remoteSearchToken++,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._abortSearch(),this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1;const e=s=>{s.target!==this._el||s.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 s=e==="ai"&&!this._aiModeAllowed()?"commands":e;s!==this._mode&&(this._modeInput[this._mode]=this._input.value,this._mode=s,this._input.value=this._modeInput[s],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(),s=this._el.querySelector(".os-ai__modes");s&&(s.hidden=!e,s.querySelectorAll("[data-mode]").forEach(r=>{const i=r.dataset.mode===this._mode;r.classList.toggle("is-active",i),r.setAttribute("aria-pressed",String(i))})),this._input.placeholder=this._mode==="ai"?l("How can I help?"):l("Search commands…");const t=this._el.querySelector(".os-ai__input-icon");t&&(t.innerHTML=this._mode==="ai"?I:ie)}_isPickMode(e){return e.isCommand&&e.hasArgsPart?!1:e.isCommand||this._mode==="commands"?!0:this._input.value===""&&p().length>0}_commandMatches(){const e=m(this._input.value);if(e.isCommand)return this._sortCommands(W(e.slug).filter(r=>r.eager!==!0));if(this._mode==="ai")return this._sortCommands(p());const s=this._input.value.trim();return[...this._sortCommands(s===""?v():W(s)),...this._currentRemoteCommands]}_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(m(this._input.value).isCommand||this._mode==="commands"){this._renderCommandMode();return}const s=p().length>0;if(this._input.value.trim()===""){s?this._renderCommandMode():this._renderSuggestions();return}this._resultsEl.querySelector(".os-ai__bubble")||(s?this._renderCommandMode():this._resultsEl.querySelector(".os-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 s=e.target;(!(s instanceof Element)||!s.closest(".os-ai__panel"))&&this.close()}),this._el.addEventListener("keydown",e=>{if(e.key!=="Tab")return;const s=[this._closeBtn,this._input,this._submitBtn].filter(o=>!o.disabled),t=s[0],r=s[s.length-1],i=this._el.ownerDocument.activeElement;e.shiftKey&&i===t?(e.preventDefault(),r.focus()):!e.shiftKey&&i===r&&(e.preventDefault(),t.focus())}),document.addEventListener("os-open-ai",()=>this.open()),this._closeBtn.addEventListener("click",()=>this.close()),this._el.querySelectorAll(".os-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 s=m(this._input.value);if(this._isPickMode(s)){const t=this._commandMatches();if(e.key==="ArrowDown"){e.preventDefault(),this._selectedCommand=Math.min(this._selectedCommand+1,Math.max(0,t.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"&&t.length>0&&s.isCommand){e.preventDefault();const r=t[this._selectedCommand]??t[0];this._input.value=`/${r.slug} `,this._submitBtn.classList.add("has-value"),this._selectedSuggestion=0,this._renderCommandMode();return}if(e.key==="Enter"&&!e.shiftKey){if(e.preventDefault(),t.length===0){s.isCommand&&this._showError(_(l("Unknown command: /%s"),s.slug));return}const r=t[this._selectedCommand]??t[0];this._pickCommand(r);return}}if(s.isCommand&&s.hasArgsPart){const t=N(s.slug);if(!!t&&typeof t.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=`/${s.slug} ${i.value}`);return}if(e.key==="Enter"&&!e.shiftKey&&t){e.preventDefault();const i=this._currentSuggestions[this._selectedSuggestion],o=i?i.value:s.args;this._runCommand(t,o);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;const s=m(this._input.value),t=this._input.value.trim();!s.isCommand&&this._mode==="commands"&&t.length>0?this._fetchRemoteCommands(t):(this._currentRemoteCommands=[],this._remoteSearchToken++),this._renderForMode()}),this._resultsEl.addEventListener("mousemove",()=>{if(this._keyboardNav){this._keyboardNav=!1;const e=this._resultsEl.querySelector(".os-ai__cmd-list");e&&e.classList.remove("os-ai__cmd-list--kb-nav")}})}async _onSubmit(){if(this._isSearching)return;const e=m(this._input.value);if(this._isPickMode(e)){const t=this._commandMatches(),r=t[this._selectedCommand]??t[0];r&&this._pickCommand(r);return}const s=this._input.value.trim();if(s){if(e.isCommand){const t=N(e.slug);if(!t){this._showError(_(l("Unknown command: /%s"),e.slug));return}await this._runCommand(t,e.args);return}await this._runSearch(s,null,0)}}async _runCommand(e,s){if(this._isSearching)return;const t=P(E.COMMAND_BEFORE_RUN,{proceed:!0,slug:e.slug,args:s,command:e});if(t&&t.proceed===!1){this._showError(t.reason??_(l("Command /%s was cancelled."),e.slug));return}this._isSearching=!0,this._submitBtn.disabled=!0,this._input.disabled=!0,this._showThinking(_(l("Running /%s…"),e.slug));const r={close:()=>{this._previousFocus=null,this.close()},openInWindow:(i,o,a)=>this._openInLegacyWindow(i,o,a),confirm:(i,o)=>this._confirm(i,o)};try{const i=await Promise.resolve(e.run(s,r));this._renderCommandResult(e,i),L(E.COMMAND_AFTER_RUN,{slug:e.slug,args:s,command:e,result:i})}catch(i){const o=i instanceof Error?i.message:String(i);this._showError(_(l("Command /%1$s failed: %2$s"),e.slug,o)),L(E.COMMAND_ERROR,{slug:e.slug,args:s,command:e,error:i})}finally{this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1,this._input.focus()}}_confirm(e,s){return x({title:s?e:void 0,message:s??e})}_renderCommandResult(e,s){if(s==null){this._isOpen?this._renderForMode():(this._resultsEl.innerHTML="",this._resultsEl.hidden=!0);return}const t=typeof s=="string"?{answer_type:"chat",message:s,entity:null,admin_links:null,iterations:0,exhausted:!0,continue:null}:{answer_type:s.answer_type??"chat",message:s.message,entity:s.entity??null,admin_links:s.admin_links??null,iterations:0,exhausted:!0,continue:null};this._showResult("",t)}_runSearch(e,s,t){this._isSearching||(this._isSearching=!0,this._submitBtn.disabled=!0,this._input.disabled=!0,this._showThinking(l("Thinking…")),this._runSearchRequest(e,s,t))}_abortSearch(){this._searchAbort&&(this._searchAbort.abort(),this._searchAbort=null)}async _runSearchRequest(e,s,t){this._abortSearch();const r=new AbortController;this._searchAbort=r;try{const i={query:e};s&&(i.resume_tool=s,i.start_offset=t);const o=await y(this._aiSearchUrl,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":this._restNonce},body:JSON.stringify(i),signal:r.signal},{source:"desktop-mode/ai-search"});if(r.signal.aborted)return;if(!o.ok){const a=await o.json().catch(()=>({}));this._showError(a.message??_(l("Server returned %d"),o.status),a.data?.settings_tab);return}this._showResult(e,await o.json())}catch{r.signal.aborted||this._showError(l("Network error — please check your connection and try again."))}finally{this._searchAbort===r&&(this._searchAbort=null,this._isSearching=!1,this._submitBtn.disabled=!1,this._input.disabled=!1,this._input.focus())}}async _fetchRemoteCommands(e){const s=++this._remoteSearchToken;try{if(await new Promise(i=>setTimeout(i,200)),s!==this._remoteSearchToken)return;const t=await y(`/wp-json/wp/v2/search?search=${encodeURIComponent(e)}&subtype=post,page`,{headers:{"X-WP-Nonce":this._restNonce}},{silent:!0});if(!t.ok)return;const r=await t.json().catch(()=>[]);if(s!==this._remoteSearchToken)return;this._currentRemoteCommands=r.map(i=>{const o=i.subtype==="page",a=new URL("post.php",this._adminUrl);a.searchParams.set("post",String(i.id)),a.searchParams.set("action","edit");const d=a.toString(),c=j(i.title||l("(No title)")),u=o?"dashicons-admin-page":"dashicons-admin-post";return{slug:`post-${i.id}`,label:c,description:this._entityTypeLabel(o?"page":"post"),icon:u,eager:!1,run:(A,h)=>{h.openInWindow(d,c,u)}}}),this._isOpen&&this._renderForMode()}catch{}}_getDesktopShell(){return window.wp?.os??null}_openAssistantSettings(e){const s=this._getDesktopShell();this._previousFocus=null,this.close(),s?.openOsSettings?.({tabId:e})}_openInLegacyWindow(e,s,t){const r=this._getDesktopShell();if(!r||!r.windowManager){window.open(e,"_blank","noopener");return}const i=r.deriveWindowId?r.deriveWindowId(e,this._adminUrl):"os-ai-"+e.replace(/[^a-z0-9]+/gi,"-").slice(0,80);r.windowManager.open({id:i,url:e,title:s,icon:t??"dashicons-admin-generic"}),this.close()}_renderCommandMode(){this._resultsEl.hidden=!1;const e=m(this._input.value);if(e.hasArgsPart){const o=N(e.slug);if(o){this._renderArgsMode(o,e.args);return}}const s=this._commandMatches();if(s.length===0){const o=e.isCommand?`/${e.slug}`:this._input.value.trim(),a=_(l("No commands matching %s."),`<strong>${this._esc(o)}</strong>`);this._resultsEl.innerHTML=`
18 <div class="os-ai__state os-ai__state--empty">
19 <span>${a}</span>
20 </div>
21 `;return}this._selectedCommand>=s.length&&(this._selectedCommand=0);const t=this._isPickMode(e),r=s.map((o,a)=>{const d=t&&a===this._selectedCommand?" is-selected":"",c=this._isEntityResultCommand(o);return`
22 <button
23 type="button"
24 class="os-ai__cmd-item${d}${c?" is-entity-result":""}"
25 data-slug="${this._esc(o.slug)}"
26 data-index="${a}"
27 >
28 ${o.iconSvg?`<span class="os-ai__cmd-icon os-ai__cmd-icon--svg" aria-hidden="true">${o.iconSvg}</span>`:`<span class="os-ai__cmd-icon dashicons ${this._esc(o.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span>`}
29 <span class="os-ai__cmd-body">
30 <span class="os-ai__cmd-title">
31 ${this._esc(o.label)}
32 ${o.hint?`<span class="os-ai__cmd-hint">${this._esc(o.hint)}</span>`:""}
33 </span>
34 ${o.description?`<span class="os-ai__cmd-desc">${this._esc(o.description)}</span>`:""}
35 </span>
36 </button>
37 `}).join(""),i=this._mode==="ai"&&p().length>0?`<p class="os-ai__suggestions-label">${this._esc(l("Suggested commands"))}</p>`:"";this._resultsEl.innerHTML=`
38 <div class="os-ai__cmd-list">
39 ${i}
40 ${r}
41 </div>
42 `,this._resultsEl.querySelectorAll(".os-ai__cmd-item").forEach(o=>{o.addEventListener("click",()=>{const a=parseInt(o.dataset.index??"",10);if(!Number.isNaN(a)){const c=this._commandMatches()[a];c&&this._pickCommand(c)}}),o.addEventListener("mouseenter",()=>{if(this._keyboardNav)return;const a=parseInt(o.dataset.index??"0",10);Number.isNaN(a)||(this._selectedCommand=a,this._resultsEl.querySelectorAll(".os-ai__cmd-item").forEach((d,c)=>d.classList.toggle("is-selected",c===a)))})})}_renderArgsMode(e,s){if(typeof e.suggest!="function"){this._currentSuggestions=[],this._resultsEl.innerHTML=this._renderCommandHeader(e,!0);return}const t=++this._suggestToken,r={close:()=>this.close(),openInWindow:(a,d,c)=>this._openInLegacyWindow(a,d,c),confirm:(a,d)=>this._confirm(a,d)};let i;try{i=e.suggest(s,r)}catch{i=[]}const o=a=>{t===this._suggestToken&&(this._currentSuggestions=a,this._selectedSuggestion>=a.length&&(this._selectedSuggestion=0),this._resultsEl.innerHTML=this._renderCommandHeader(e,!1)+this._renderSuggestionList(a),this._resultsEl.querySelectorAll(".os-ai__cmd-suggest-item").forEach(d=>{d.addEventListener("click",()=>{const c=parseInt(d.dataset.index??"0",10),u=a[c];u&&(this._input.value=`/${e.slug} ${u.value}`,this._runCommand(e,u.value))}),d.addEventListener("mouseenter",()=>{const c=parseInt(d.dataset.index??"0",10);Number.isNaN(c)||(this._selectedSuggestion=c,this._paintSuggestionSelection())})}))};i&&typeof i.then=="function"?(this._resultsEl.innerHTML=this._renderCommandHeader(e,!1),i.then(a=>o(Array.isArray(a)?a:[])).catch(()=>o([]))):o(Array.isArray(i)?i:[])}_renderCommandHeader(e,s){return`
43 <div class="os-ai__cmd-active">
44 <span class="os-ai__cmd-icon dashicons ${this._esc(e.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span>
45 <div class="os-ai__cmd-body">
46 <span class="os-ai__cmd-title">
47 /${this._esc(e.slug)}
48 ${e.hint?`<span class="os-ai__cmd-hint">${this._esc(e.hint)}</span>`:""}
49 </span>
50 ${e.description?`<span class="os-ai__cmd-desc">${this._esc(e.description)}</span>`:""}
51 ${s?`<span class="os-ai__cmd-enter-hint">${_(l("Press %s to run"),"<kbd>↵</kbd>")}</span>`:""}
52 </div>
53 </div>
54 `}_renderSuggestionList(e){return e.length===0?`
55 <div class="os-ai__state os-ai__state--empty">
56 <span>${_(l("No suggestions — press %s to run with the text you typed."),"<kbd>↵</kbd>")}</span>
57 </div>
58 `:`<div class="os-ai__cmd-suggest-list">${e.map((t,r)=>`
59 <button
60 type="button"
61 class="os-ai__cmd-suggest-item${r===this._selectedSuggestion?" is-selected":""}"
62 data-index="${r}"
63 >
64 <span class="os-ai__cmd-icon dashicons ${this._esc(t.icon??"dashicons-arrow-right-alt")}" aria-hidden="true"></span>
65 <span class="os-ai__cmd-body">
66 <span class="os-ai__cmd-suggest-label">${this._esc(t.label)}</span>
67 ${t.description?`<span class="os-ai__cmd-desc">${this._esc(t.description)}</span>`:""}
68 </span>
69 </button>
70 `).join("")}</div>`}_sortCommands(e){return e.slice().sort((s,t)=>{const r=typeof s.owner=="string"&&s.owner.startsWith("iframe:")?0:1,i=typeof t.owner=="string"&&t.owner.startsWith("iframe:")?0:1;return r-i})}_isEntityResultCommand(e){return this._currentRemoteCommands.includes(e)}_paintCommandSelection(){const e=this._resultsEl.querySelectorAll(".os-ai__cmd-item");e.forEach((r,i)=>{r.classList.toggle("is-selected",i===this._selectedCommand)});const s=this._resultsEl.querySelector(".os-ai__cmd-list");s&&s.classList.toggle("os-ai__cmd-list--kb-nav",this._keyboardNav);const t=e[this._selectedCommand];t&&typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"nearest"})}_paintSuggestionSelection(){this._resultsEl.querySelectorAll(".os-ai__cmd-suggest-item").forEach((e,s)=>{e.classList.toggle("is-selected",s===this._selectedSuggestion)})}_renderSuggestions(){this._resultsEl.hidden=!1,this._resultsEl.innerHTML=`
71 <div class="os-ai__suggestions">
72 <p class="os-ai__suggestions-label">${this._esc(l("Try asking"))}</p>
73 <div class="os-ai__suggestions-list">
74 ${oe().map(e=>`<button type="button" class="os-ai__suggestion" data-prompt="${this._esc(e)}">
75 ${this._esc(e)}
76 </button>`).join("")}
77 </div>
78 </div>
79 `,this._resultsEl.querySelectorAll(".os-ai__suggestion").forEach(e=>{e.addEventListener("click",()=>{const s=e.dataset.prompt??"";this._input.value=s,this._submitBtn.classList.add("has-value"),this._input.focus()})})}_showThinking(e=l("Thinking…")){this._resultsEl.hidden=!1,this._resultsEl.innerHTML=`
80 <div class="os-ai__state os-ai__state--thinking">
81 ${te}
82 <span>${this._esc(e)}</span>
83 </div>
84 `}_showError(e,s){if(this._resultsEl.hidden=!1,s){const t=`<button type="button" class="os-ai__settings-link">${this._esc(l("Open Preferences"))}</button>`;this._resultsEl.innerHTML=`
85 <div class="os-ai__state os-ai__state--error">
86 <span>${this._esc(e)} ${t}</span>
87 </div>
88 `,this._resultsEl.querySelector(".os-ai__settings-link")?.addEventListener("click",()=>this._openAssistantSettings(s));return}this._resultsEl.innerHTML=`
89 <div class="os-ai__state os-ai__state--error">
90 <span>${this._esc(e)}</span>
91 </div>
92 `}_showResult(e,s){e!==""&&(this._lastAiResult={query:e,data:s}),this._resultsEl.hidden=!1;const t=`
93 <div class="os-ai__bubble">
94 <span class="os-ai__bubble-icon">${I}</span>
95 <div class="os-ai__bubble-text">${Q(s.message||"")}</div>
96 </div>
97 `;let r="";s.answer_type==="entity"&&s.entity?r=this._renderEntityCard(s.entity):s.answer_type==="navigation"&&s.admin_links&&s.admin_links.length>0&&(r=this._renderAdminLinks(s.admin_links)),s.continue&&(r+=`
98 <button type="button" class="os-ai__continue-btn"
99 data-tool="${this._esc(s.continue.tool)}"
100 data-offset="${s.continue.offset}"
101 data-query="${this._esc(e)}">
102 ${this._esc(s.continue.label)}
103 </button>
104 `),this._resultsEl.innerHTML=t+r,this._resultsEl.querySelectorAll(".os-ai__entity-open").forEach(o=>{o.addEventListener("click",()=>{const a=o.dataset.url??"",d=o.dataset.title??"",c=o.dataset.icon??"dashicons-admin-generic";a&&this._openInLegacyWindow(a,d,c)})}),this._resultsEl.querySelectorAll(".os-ai__admin-link").forEach(o=>{o.addEventListener("click",()=>{const a=o.dataset.url??"",d=o.dataset.title??"",c=o.dataset.icon??"dashicons-admin-generic";a&&this._openInLegacyWindow(a,d,c)})});const i=this._resultsEl.querySelector(".os-ai__continue-btn");i&&i.addEventListener("click",()=>{const o=i.dataset.tool??null,a=parseInt(i.dataset.offset??"0",10),d=i.dataset.query??e;this._runSearch(d,o,a)})}_entityTypeLabel(e){switch(e){case"page":return l("Page");case"comment":return l("Comment");default:return l("Post")}}_entityOpenLabel(e){switch(e){case"page":return l("Open page in desktop");case"comment":return l("Open comment in desktop");default:return l("Open post in desktop")}}_renderEntityCard(e){const s=e.type==="comment",t=s?_(l("Comment on ā€œ%sā€"),this._esc(e.post_title??$("post","fallback name for the post a comment was left on"))):this._esc(e.title??l("Untitled")),r=this._esc(e.ai_summary||e.excerpt||""),i=this._entityTypeLabel(e.type),o=e.topic?`<span class="os-ai__entity-topic">${this._esc(e.topic)}</span>`:"";let a;return s?a="dashicons-admin-comments":e.type==="page"?a="dashicons-admin-page":a="dashicons-admin-post",`
105 <div class="os-ai__entity">
106 <div class="os-ai__entity-header">
107 ${o}
108 <span class="os-ai__entity-type">${this._esc(i)}</span>
109 </div>
110 <h3 class="os-ai__entity-title">${t}</h3>
111 <p class="os-ai__entity-summary">${r}</p>
112 <button type="button"
113 class="os-ai__entity-open"
114 data-url="${this._esc(e.edit_url)}"
115 data-title="${this._esc(e.title??e.post_title??i)}"
116 data-icon="${a}">
117 <span>${this._esc(this._entityOpenLabel(e.type))}</span>
118 ${M}
119 </button>
120 </div>
121 `}_renderAdminLinks(e){return`<div class="os-ai__admin-links">${e.map(t=>`
122 <button type="button"
123 class="os-ai__admin-link"
124 data-url="${this._esc(t.url)}"
125 data-title="${this._esc(t.title)}"
126 data-icon="${this._esc(t.icon)}">
127 <span class="os-ai__admin-link-icon dashicons ${this._esc(t.icon)}" aria-hidden="true"></span>
128 <span class="os-ai__admin-link-body">
129 <span class="os-ai__admin-link-title">${this._esc(t.title)}</span>
130 <span class="os-ai__admin-link-desc">${this._esc(t.description)}</span>
131 </span>
132 <span class="os-ai__admin-link-arrow">${M}</span>
133 </button>
134 `).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="os-ai",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",l("Site Assistant")),e.setAttribute("aria-hidden","true"),e.setAttribute("hidden",""),e.innerHTML=`
135 <div class="os-ai__backdrop" aria-hidden="true"></div>
136 <div class="os-ai__panel">
137 <div class="os-ai__header">
138 <span class="os-ai__header-icon">${ne}</span>
139 <span class="os-ai__header-label">${this._esc(l("Site Assistant"))}</span>
140 <div class="os-ai__modes" role="group" aria-label="${this._esc(l("Assistant mode"))}" hidden>
141 <button type="button" class="os-ai__mode" data-mode="ai" aria-pressed="false">${this._esc(l("Ask AI"))}</button>
142 <button type="button" class="os-ai__mode" data-mode="commands" aria-pressed="false">${this._esc(l("Commands"))}</button>
143 </div>
144 <button type="button" class="os-ai__close" aria-label="${this._esc(l("Close"))}">
145 ${ee}
146 </button>
147 </div>
148 <div class="os-ai__input-wrap">
149 <span class="os-ai__input-icon">${I}</span>
150 <input
151 class="os-ai__input"
152 type="text"
153 placeholder="${this._esc(l("How can I help?"))}"
154 autocomplete="off"
155 spellcheck="false"
156 aria-label="${this._esc(l("Ask the assistant"))}"
157 />
158 <button type="button" class="os-ai__submit" aria-label="${this._esc(l("Send"))}">
159 ${se}
160 </button>
161 </div>
162 <div class="os-ai__results" hidden></div>
163 <div class="os-ai__footer">
164 <span class="os-ai__footer-hint">
165 ${this._esc(l("Your assistant to quickly navigate and manage your entire site."))}
166 </span>
167 </div>
168 </div>
169 `,e}}const ae=n=>new re(n);window.openStationCreateAiAssistant=ae})();
170