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

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