@runtypelabs/persona 4.8.0 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-BsZtXPKK.d.cts → types-4ROVJ1gA.d.cts} +42 -0
- package/dist/animations/{types-BsZtXPKK.d.ts → types-4ROVJ1gA.d.ts} +42 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-IO5VVUKP.js +3 -0
- package/dist/chunk-IPVK3KOM.js +1 -0
- package/dist/chunk-UPO4GUFC.js +1 -0
- package/dist/codegen.cjs +6 -6
- package/dist/codegen.js +8 -8
- package/dist/context-mentions-7S5KVUTG.js +169 -0
- package/dist/context-mentions-inline-TTCN7ZM2.js +4 -0
- package/dist/context-mentions-inline.cjs +4 -0
- package/dist/context-mentions-inline.d.cts +203 -0
- package/dist/context-mentions-inline.d.ts +203 -0
- package/dist/context-mentions-inline.js +4 -0
- package/dist/context-mentions.cjs +295 -0
- package/dist/context-mentions.d.cts +7025 -0
- package/dist/context-mentions.d.ts +7025 -0
- package/dist/context-mentions.js +295 -0
- package/dist/index.cjs +72 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +634 -3
- package/dist/index.d.ts +634 -3
- package/dist/index.global.js +59 -51
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +64 -56
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.d.cts +17 -0
- package/dist/plugin-kit.d.ts +17 -0
- package/dist/plugin-kit.js +1 -1
- package/dist/smart-dom-reader.cjs +17 -16
- package/dist/smart-dom-reader.d.cts +507 -1
- package/dist/smart-dom-reader.d.ts +507 -1
- package/dist/smart-dom-reader.js +17 -16
- package/dist/theme-editor-preview.cjs +236 -57
- package/dist/theme-editor-preview.d.cts +485 -1
- package/dist/theme-editor-preview.d.ts +485 -1
- package/dist/theme-editor-preview.js +53 -47
- package/dist/theme-editor.cjs +7 -7
- package/dist/theme-editor.d.cts +473 -0
- package/dist/theme-editor.d.ts +473 -0
- package/dist/theme-editor.js +5 -5
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +2 -0
- package/dist/theme-reference.d.ts +2 -0
- package/dist/widget.css +1 -1
- package/package.json +15 -3
- package/src/client.test.ts +69 -0
- package/src/client.ts +65 -51
- package/src/components/artifact-pane.test.ts +47 -0
- package/src/components/artifact-pane.ts +25 -2
- package/src/components/composer-parts.ts +3 -12
- package/src/components/context-mention-button.test.ts +70 -0
- package/src/components/context-mention-button.ts +82 -0
- package/src/components/context-mention-chip.ts +134 -0
- package/src/components/context-mention-menu.test.ts +508 -0
- package/src/components/context-mention-menu.ts +0 -0
- package/src/components/message-bubble.test.ts +175 -0
- package/src/components/message-bubble.ts +177 -19
- package/src/components/panel.ts +7 -10
- package/src/context-mentions-bundle.test.ts +163 -0
- package/src/context-mentions-entry.ts +185 -0
- package/src/context-mentions-inline-entry.test.ts +136 -0
- package/src/context-mentions-inline-entry.ts +226 -0
- package/src/context-mentions-inline-loader.test.ts +30 -0
- package/src/context-mentions-inline-loader.ts +36 -0
- package/src/context-mentions-inline.ts +15 -0
- package/src/context-mentions-loader.ts +32 -0
- package/src/context-mentions.ts +16 -0
- package/src/index-core.ts +27 -0
- package/src/index-global.ts +51 -0
- package/src/markdown-parsers-loader.ts +35 -44
- package/src/plugin-kit.test.ts +40 -0
- package/src/plugin-kit.ts +39 -5
- package/src/runtime/init-update-reset.test.ts +81 -0
- package/src/runtime/init.test.ts +62 -0
- package/src/runtime/init.ts +7 -14
- package/src/session.mentions.test.ts +175 -0
- package/src/session.test.ts +52 -4
- package/src/session.ts +121 -5
- package/src/smart-dom-reader.test.ts +129 -2
- package/src/smart-dom-reader.ts +127 -1
- package/src/styles/context-mention-menu-css.ts +176 -0
- package/src/styles/widget.css +243 -126
- package/src/theme-editor/sections.ts +3 -3
- package/src/types/theme.ts +2 -0
- package/src/types.ts +542 -0
- package/src/ui.artifact-pane-gating.test.ts +11 -1
- package/src/ui.attachments-drop.test.ts +90 -0
- package/src/ui.header-update-stability.test.ts +149 -0
- package/src/ui.launcher-update-merge.test.ts +83 -0
- package/src/ui.mention-submit.test.ts +235 -0
- package/src/ui.send-button-stream-update.test.ts +69 -0
- package/src/ui.ts +379 -84
- package/src/utils/chunk-loader.test.ts +97 -0
- package/src/utils/chunk-loader.ts +88 -0
- package/src/utils/composer-contenteditable.test.ts +507 -0
- package/src/utils/composer-contenteditable.ts +626 -0
- package/src/utils/composer-document.test.ts +280 -0
- package/src/utils/composer-document.ts +293 -0
- package/src/utils/composer-history.test.ts +35 -7
- package/src/utils/composer-history.ts +30 -20
- package/src/utils/composer-input.ts +159 -0
- package/src/utils/config-merge.test.ts +131 -0
- package/src/utils/config-merge.ts +61 -0
- package/src/utils/context-mention-controller.test.ts +1215 -0
- package/src/utils/context-mention-controller.ts +1186 -0
- package/src/utils/context-mention-manager.test.ts +422 -0
- package/src/utils/context-mention-manager.ts +410 -0
- package/src/utils/context-mention-orchestrator.test.ts +538 -0
- package/src/utils/context-mention-orchestrator.ts +348 -0
- package/src/utils/live-region.test.ts +108 -0
- package/src/utils/live-region.ts +94 -0
- package/src/utils/mention-channels.ts +63 -0
- package/src/utils/mention-llm-format.test.ts +91 -0
- package/src/utils/mention-llm-format.ts +79 -0
- package/src/utils/mention-matcher.test.ts +86 -0
- package/src/utils/mention-matcher.ts +221 -0
- package/src/utils/mention-token.ts +72 -0
- package/src/utils/mention-trigger.test.ts +155 -0
- package/src/utils/mention-trigger.ts +156 -0
- package/src/utils/theme.test.ts +54 -4
- package/src/utils/theme.ts +6 -3
- package/src/utils/tokens.ts +27 -11
package/dist/codegen.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var w="4.
|
|
1
|
+
var w="4.10.0";var c=w;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function P(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var x=`({ text, message }: any) => {
|
|
2
2
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
3
3
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
4
4
|
let cleanJson = jsonSource
|
|
@@ -11,7 +11,7 @@ var w="4.8.0";var c=w;function u(e){if(e!==void 0)return typeof e=="string"?e:Ar
|
|
|
11
11
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
12
12
|
} catch (e) { return null; }
|
|
13
13
|
return null;
|
|
14
|
-
}`,
|
|
14
|
+
}`,S=`function(ctx) {
|
|
15
15
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
16
16
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
17
17
|
var cleanJson = jsonSource
|
|
@@ -70,11 +70,11 @@ var w="4.8.0";var c=w;function u(e){if(e!==void 0)return typeof e=="string"?e:Ar
|
|
|
70
70
|
if (parsed.action === 'message') return parsed.text || '';
|
|
71
71
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
72
72
|
return parsed.text || null;
|
|
73
|
-
}`;function _(e){if(!e)return null;let i=e.toString();return i.includes("createJsonStreamParser")||i.includes("partial-json")?"json":i.includes("createRegexJsonParser")||i.includes("regex")?"regex-json":i.includes("createXmlParser")||i.includes("<text>")?"xml":null}function g(e){return e.parserType??_(e.streamParser)??"plain"}function m(e,i){let n=[];return e.toolCall&&(n.push(`${i}toolCall: {`),Object.entries(e.toolCall).forEach(([s,
|
|
74
|
-
`)}function R(e,i){let n=i?.hooks,s=g(e),
|
|
75
|
-
`)}function W(e,i){let n=i?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${h(i)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n?.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${v}),`)),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${S}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${S}`),s.push(" ],")),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${A}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${A}`),s.push(" ],")),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
76
|
-
`)}function E(e){let i=g(e),n=i!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=i),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let
|
|
73
|
+
}`;function _(e){if(!e)return null;let i=e.toString();return i.includes("createJsonStreamParser")||i.includes("partial-json")?"json":i.includes("createRegexJsonParser")||i.includes("regex")?"regex-json":i.includes("createXmlParser")||i.includes("<text>")?"xml":null}function g(e){return e.parserType??_(e.streamParser)??"plain"}function m(e,i){let n=[];return e.toolCall&&(n.push(`${i}toolCall: {`),Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&n.push(`${i} ${s}: "${a}",`)}),n.push(`${i}},`)),n}function f(e,i,n){let s=[],a=e.messageActions&&Object.entries(e.messageActions).some(([r,o])=>r!=="onFeedback"&&r!=="onCopy"&&o!==void 0),t=n?.onFeedback||n?.onCopy;return(a||t)&&(s.push(`${i}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([r,o])=>{r==="onFeedback"||r==="onCopy"||(typeof o=="string"?s.push(`${i} ${r}: "${o}",`):typeof o=="boolean"&&s.push(`${i} ${r}: ${o},`))}),n?.onFeedback&&s.push(`${i} onFeedback: ${n.onFeedback},`),n?.onCopy&&s.push(`${i} onCopy: ${n.onCopy},`),s.push(`${i}},`)),s}function y(e,i){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(s||a)&&(n.push(`${i}markdown: {`),s&&(n.push(`${i} options: {`),Object.entries(e.markdown.options).forEach(([t,r])=>{typeof r=="string"?n.push(`${i} ${t}: "${r}",`):typeof r=="boolean"&&n.push(`${i} ${t}: ${r},`)}),n.push(`${i} },`)),a&&n.push(`${i} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${i}},`))}return n}function C(e,i){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),a=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||a)&&(n.push(`${i}layout: {`),s&&(n.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,r])=>{t!=="render"&&(typeof r=="string"?n.push(`${i} ${t}: "${r}",`):typeof r=="boolean"&&n.push(`${i} ${t}: ${r},`))}),n.push(`${i} },`)),a&&(n.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,r])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof r=="object"&&r!==null?(n.push(`${i} avatar: {`),Object.entries(r).forEach(([o,p])=>{typeof p=="string"?n.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&n.push(`${i} ${o}: ${p},`)}),n.push(`${i} },`)):t==="timestamp"&&typeof r=="object"&&r!==null?Object.entries(r).some(([p])=>p!=="format")&&(n.push(`${i} timestamp: {`),Object.entries(r).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?n.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&n.push(`${i} ${p}: ${l},`))}),n.push(`${i} },`)):typeof r=="string"?n.push(`${i} ${t}: "${r}",`):typeof r=="boolean"&&n.push(`${i} ${t}: ${r},`))}),n.push(`${i} },`)),n.push(`${i}},`))}return n}function $(e,i){let n=[];return e&&(e.getHeaders&&n.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${i}streamParser: ${e.streamParser},`)),n}function O(e,i,n){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${n}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${n}${s}: {`),O(e,a,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,n,s){n&&(e.push(`${s}${i}: {`),O(e,n,`${s} `),e.push(`${s}},`))}function h(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function T(e,i="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=n?{...n,hooks:P(n.hooks)}:void 0;return i==="esm"?M(s,a):i==="script-installer"?H(s,a):i==="script-advanced"?D(s,a):i==="react-component"?R(s,a):i==="react-advanced"?W(s,a):N(s,a)}function M(e,i){let n=i?.hooks,s=g(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${h(i)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
74
|
+
`)}function R(e,i){let n=i?.hooks,s=g(e),a=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${h(i)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
|
|
75
|
+
`)}function W(e,i){let n=i?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${h(i)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n?.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${v}),`)),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${A}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${A}`),s.push(" ],")),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
76
|
+
`)}function E(e){let i=g(e),n=i!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=i),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let a={};Object.entries(e.toolCall).forEach(([t,r])=>{typeof r=="string"&&(a[t]=r)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,r])=>{t!=="onFeedback"&&t!=="onCopy"&&r!==void 0&&(typeof r=="string"||typeof r=="boolean")&&(a[t]=r)}),Object.keys(a).length>0&&(s.messageActions=a)}if(e.markdown){let a={};e.markdown.options&&(a.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(a.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(a).length>0&&(s.markdown=a)}if(e.layout){let a={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([r,o])=>{r!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[r]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([r,o])=>{if(r!=="renderUserMessage"&&r!=="renderAssistantMessage")if(r==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(r==="timestamp"&&typeof o=="object"&&o!==null){let p={};Object.entries(o).forEach(([l,b])=>{l!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(p[l]=b)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof o=="string"||typeof o=="boolean")&&(t[r]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function H(e,i){let n=E(e),a=!!(i?.windowKey||i?.target)?{config:n,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:n,t=JSON.stringify(a,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function N(e,i){let n=i?.hooks,s=g(e),a=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${h(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([r,o])=>{t.push(` ${r}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"?t.push(` ${r}: ${o},`):typeof o=="number"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,o])=>{typeof o=="string"?t.push(` ${r}: "${o}",`):typeof o=="boolean"&&t.push(` ${r}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([r,o])=>{t.push(` ${r}: ${o},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
|
|
77
77
|
`)}function D(e,i){let n=i?.hooks,s=E(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
|
|
78
|
-
`).map((r,
|
|
79
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${n.getHeaders};`),t.push("")),n?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${n.contextProviders};`),t.push("")),n?.streamParser?t.push(` widgetConfig.streamParser = ${n.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${I});`),t.push(" };")),t.push(""),n?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${n.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${
|
|
78
|
+
`).map((r,o)=>o===0?r:" "+r).join(`
|
|
79
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${n.getHeaders};`),t.push("")),n?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${n.contextProviders};`),t.push("")),n?.streamParser?t.push(` widgetConfig.streamParser = ${n.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${I});`),t.push(" };")),t.push(""),n?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${n.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${S}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${S}`),t.push(" ];")),t.push(""),n?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${n.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${j}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${j}`),t.push(" ];")),t.push(""),n?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${n.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),n?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(n?.onFeedback||n?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${h(i)}',`," useShadowDom: false,",...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
|
|
80
80
|
`)}export{T as generateCodeSnippet};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import{a as S,d as C,f as N,g as X,h as J,i as Z}from"./chunk-IPVK3KOM.js";import{b as ee}from"./chunk-UPO4GUFC.js";import{a as _,c as Y}from"./chunk-IO5VVUKP.js";function te(s){let{ref:e,config:t,onRemove:n}=s;if(t.renderMentionChip){let u="resolving",A,T=t.renderMentionChip({ref:e,status:u,payload:A,remove:n});return{get el(){return T},setStatus:(z,E)=>{if(z===u&&E===A)return;u=z,A=E;let B=t.renderMentionChip({ref:e,status:u,payload:A,remove:n});T.replaceWith(B),T=B}}}let i=e.iconName??t.chipIconName??"at-sign",o=C("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),r=S("span","persona-mention-chip-icon"),d=u=>{r.replaceChildren();let A=N(u,13,"currentColor",2);A&&r.appendChild(A)};d(i);let a=S("span","persona-mention-chip-spinner"),l=C("span",{className:"persona-mention-chip-label",text:e.label}),x=C("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),p=N("x",11,"currentColor",2.5);return p?x.appendChild(p):x.textContent="\xD7",x.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),o.appendChild(a),o.appendChild(l),o.appendChild(x),{el:o,setStatus:u=>{o.setAttribute("data-status",u),u==="resolving"?(a.parentNode!==o&&o.insertBefore(a,l),r.parentNode===o&&r.remove(),o.setAttribute("title",e.label)):(a.parentNode===o&&a.remove(),r.parentNode!==o&&o.insertBefore(r,l),u==="error"?(d("triangle-alert"),o.setAttribute("title",`Couldn't add ${e.label} to context`)):(d(i),o.setAttribute("title",e.label)))}}}function ce(s){let e=0;for(let t of s.split(`
|
|
2
|
+
`)){let n=/^ {0,3}(`+)/.exec(t);n&&n[1].length>e&&(e=n[1].length)}return e}function Q(s,e){let t="`".repeat(Math.max(3,ce(e)+1));return`${t}${s}
|
|
3
|
+
${e}
|
|
4
|
+
${t}`}function de(s,e,t){return e.includes("</document_content>")?Q(s,e):`<document index="${t+1}">
|
|
5
|
+
<source>${s}</source>
|
|
6
|
+
<document_content>
|
|
7
|
+
${e}
|
|
8
|
+
</document_content>
|
|
9
|
+
</document>`}function ne(s,e,t="fenced"){if(typeof t=="function")try{return t(s,e)}catch(n){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",n),Q(s.label,s.text)}return t==="document"?de(s.label,s.text,e):Q(s.label,s.text)}function G(s,e){return{sourceId:s.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var ie=(s,e)=>`${s}\0${e}`,D=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,t,n=""){let i=ie(e.id,t.id);if(this.mentions.some(d=>d.key===i))return this.reject(e,t,"duplicate");if(this.atLimit())return this.reject(e,t,"limit");let o=G(e,t),r={key:i,source:e,item:t,ref:o,status:"resolving",args:n};return r.chip=te({ref:o,config:this.opts.mentionConfig,onRemove:()=>this.remove(i)}),this.opts.contextRow.appendChild(r.chip.el),this.startPending(r),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,t){return this.atLimit()?this.reject(e,t,"limit"):!0}track(e,t,n,i="",o){let r={key:e,source:t,item:n,ref:G(t,n),status:"resolving",args:i,reportStatus:o};this.startPending(r)}reject(e,t,n){return this.opts.mentionConfig.onMentionRejected?.(t,n),this.opts.emit?.("rejected",{sourceId:e.id,itemId:t.id,reason:n}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,t,n=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:t,signal:e}}async resolvePending(e){let t=new AbortController;e.abort=t;try{let n=await e.source.resolve(e.item,this.buildResolveContext(t.signal,e.args));if(t.signal.aborted)return;e.payload=n,e.status="ready",e.chip?.setStatus("ready",n),e.reportStatus?.("resolved")}catch(n){if(t.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,n),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let t=this.mentions.findIndex(i=>i.key===e);if(t===-1)return;let[n]=this.mentions.splice(t,1);n.abort?.abort(),n.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${n.ref.label} from context`)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],t=e.map(o=>o.ref),n=this.opts.getComposerText();for(let o of e)o.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:t,finalize:async()=>{var x;let o=await Promise.all(e.map(async p=>{try{return p.source.resolveOn==="submit"?await p.source.resolve(p.item,this.buildResolveContext(new AbortController().signal,p.args,n)):(p.resolvePromise&&await p.resolvePromise,p.payload??null)}catch(M){try{this.opts.mentionConfig.onMentionResolveError?.(p.item,M)}catch(u){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",u)}return this.opts.emit?.("resolve-error",{sourceId:p.source.id,itemId:p.item.id}),null}})),r=[],d=[],a={},l=new Set;for(let p=0;p<e.length;p++){let M=e[p],u=o[p];if(!u)continue;let A=ie(M.source.id,M.item.id);if(!l.has(A)){if(l.add(A),u.llmAppend&&u.llmAppend.trim())try{r.push(ne({label:M.ref.label,text:u.llmAppend,ref:M.ref,item:M.item},r.length,this.opts.mentionConfig.llmFormat))}catch(T){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",T)}u.contentParts?.length&&d.push(...u.contentParts),u.context&&((a[x=M.source.id]??(a[x]={}))[M.item.id]=u.context)}}return{blocks:r,contentParts:d,context:a}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}};var oe=`
|
|
10
|
+
.persona-mention-menu {
|
|
11
|
+
box-sizing: border-box;
|
|
12
|
+
display: flex;
|
|
13
|
+
flex-direction: column;
|
|
14
|
+
max-height: var(--persona-mention-menu-max-height, 280px);
|
|
15
|
+
overflow: hidden;
|
|
16
|
+
background: var(--persona-mention-menu-bg, var(--persona-surface, #ffffff));
|
|
17
|
+
border: 1px solid var(--persona-mention-menu-border, var(--persona-border, #e5e7eb));
|
|
18
|
+
border-radius: var(--persona-mention-menu-radius, 10px);
|
|
19
|
+
box-shadow: var(--persona-mention-menu-shadow, 0 8px 28px rgba(0, 0, 0, 0.12));
|
|
20
|
+
font-family: var(--persona-font-family, inherit);
|
|
21
|
+
}
|
|
22
|
+
.persona-mention-list {
|
|
23
|
+
min-height: 0;
|
|
24
|
+
overflow-y: auto;
|
|
25
|
+
padding: 4px;
|
|
26
|
+
}
|
|
27
|
+
.persona-mention-search {
|
|
28
|
+
display: flex;
|
|
29
|
+
align-items: center;
|
|
30
|
+
gap: 6px;
|
|
31
|
+
padding: 8px 10px;
|
|
32
|
+
border-bottom: 1px solid var(--persona-mention-menu-border, var(--persona-border, #e5e7eb));
|
|
33
|
+
}
|
|
34
|
+
.persona-mention-search-icon {
|
|
35
|
+
display: inline-flex;
|
|
36
|
+
align-items: center;
|
|
37
|
+
flex: 0 0 auto;
|
|
38
|
+
color: var(--persona-mention-group-fg, var(--persona-muted, #6b7280));
|
|
39
|
+
}
|
|
40
|
+
.persona-mention-search-input {
|
|
41
|
+
flex: 1 1 auto;
|
|
42
|
+
min-width: 0;
|
|
43
|
+
padding: 0;
|
|
44
|
+
border: none;
|
|
45
|
+
outline: none;
|
|
46
|
+
background: transparent;
|
|
47
|
+
font-family: inherit;
|
|
48
|
+
/* 16px, not 14px: iOS Safari zooms the page when focusing an input under 16px. */
|
|
49
|
+
font-size: 16px;
|
|
50
|
+
line-height: 1.4;
|
|
51
|
+
color: var(--persona-text, #111827);
|
|
52
|
+
}
|
|
53
|
+
.persona-mention-search-input::placeholder {
|
|
54
|
+
color: var(--persona-mention-group-fg, var(--persona-muted, #6b7280));
|
|
55
|
+
}
|
|
56
|
+
.persona-mention-group + .persona-mention-group {
|
|
57
|
+
margin-top: 2px;
|
|
58
|
+
border-top: 1px solid var(--persona-mention-menu-border, var(--persona-border, #f1f1f1));
|
|
59
|
+
padding-top: 2px;
|
|
60
|
+
}
|
|
61
|
+
.persona-mention-group-header {
|
|
62
|
+
padding: 6px 8px 4px;
|
|
63
|
+
font-size: 11px;
|
|
64
|
+
font-weight: 600;
|
|
65
|
+
text-transform: uppercase;
|
|
66
|
+
letter-spacing: 0.04em;
|
|
67
|
+
color: var(--persona-mention-group-fg, var(--persona-muted, #6b7280));
|
|
68
|
+
}
|
|
69
|
+
.persona-mention-option {
|
|
70
|
+
display: flex;
|
|
71
|
+
align-items: center;
|
|
72
|
+
gap: 8px;
|
|
73
|
+
padding: 7px 8px;
|
|
74
|
+
border-radius: 6px;
|
|
75
|
+
cursor: pointer;
|
|
76
|
+
color: var(--persona-text, #111827);
|
|
77
|
+
}
|
|
78
|
+
.persona-mention-option[data-active="true"] {
|
|
79
|
+
background: var(--persona-mention-option-active-bg, var(--persona-container, #f1f5f9));
|
|
80
|
+
}
|
|
81
|
+
.persona-mention-option-icon {
|
|
82
|
+
display: inline-flex;
|
|
83
|
+
align-items: center;
|
|
84
|
+
flex: 0 0 auto;
|
|
85
|
+
opacity: 0.7;
|
|
86
|
+
}
|
|
87
|
+
.persona-mention-option-text {
|
|
88
|
+
display: flex;
|
|
89
|
+
flex-direction: column;
|
|
90
|
+
min-width: 0;
|
|
91
|
+
}
|
|
92
|
+
.persona-mention-option-labelline {
|
|
93
|
+
display: flex;
|
|
94
|
+
align-items: baseline;
|
|
95
|
+
gap: 6px;
|
|
96
|
+
min-width: 0;
|
|
97
|
+
}
|
|
98
|
+
.persona-mention-option-label {
|
|
99
|
+
font-size: 13px;
|
|
100
|
+
line-height: 1.3;
|
|
101
|
+
overflow: hidden;
|
|
102
|
+
text-overflow: ellipsis;
|
|
103
|
+
white-space: nowrap;
|
|
104
|
+
}
|
|
105
|
+
.persona-mention-option-arghint {
|
|
106
|
+
flex: 0 0 auto;
|
|
107
|
+
font-size: 12px;
|
|
108
|
+
line-height: 1.3;
|
|
109
|
+
color: var(--persona-muted, #6b7280);
|
|
110
|
+
opacity: 0.85;
|
|
111
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
112
|
+
}
|
|
113
|
+
.persona-mention-option-desc {
|
|
114
|
+
font-size: 11px;
|
|
115
|
+
line-height: 1.3;
|
|
116
|
+
color: var(--persona-muted, #6b7280);
|
|
117
|
+
overflow: hidden;
|
|
118
|
+
text-overflow: ellipsis;
|
|
119
|
+
white-space: nowrap;
|
|
120
|
+
}
|
|
121
|
+
.persona-mention-status,
|
|
122
|
+
.persona-mention-empty,
|
|
123
|
+
.persona-mention-hint {
|
|
124
|
+
padding: 7px 8px;
|
|
125
|
+
font-size: 12px;
|
|
126
|
+
color: var(--persona-muted, #6b7280);
|
|
127
|
+
}
|
|
128
|
+
.persona-mention-error {
|
|
129
|
+
display: flex;
|
|
130
|
+
align-items: center;
|
|
131
|
+
justify-content: space-between;
|
|
132
|
+
gap: 8px;
|
|
133
|
+
color: var(--persona-mention-error, #dc2626);
|
|
134
|
+
}
|
|
135
|
+
.persona-mention-error-text {
|
|
136
|
+
min-width: 0;
|
|
137
|
+
overflow: hidden;
|
|
138
|
+
text-overflow: ellipsis;
|
|
139
|
+
white-space: nowrap;
|
|
140
|
+
}
|
|
141
|
+
.persona-mention-retry {
|
|
142
|
+
flex: 0 0 auto;
|
|
143
|
+
padding: 4px 8px;
|
|
144
|
+
border: 1px solid var(--persona-mention-error, #dc2626);
|
|
145
|
+
border-radius: 6px;
|
|
146
|
+
background: transparent;
|
|
147
|
+
color: var(--persona-mention-error, #dc2626);
|
|
148
|
+
font: inherit;
|
|
149
|
+
font-size: 12px;
|
|
150
|
+
cursor: pointer;
|
|
151
|
+
}
|
|
152
|
+
.persona-mention-retry:hover {
|
|
153
|
+
background: var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.06));
|
|
154
|
+
}
|
|
155
|
+
.persona-mention-hint {
|
|
156
|
+
font-style: italic;
|
|
157
|
+
opacity: 0.8;
|
|
158
|
+
}
|
|
159
|
+
@media (pointer: coarse) {
|
|
160
|
+
.persona-mention-option {
|
|
161
|
+
min-height: 44px;
|
|
162
|
+
}
|
|
163
|
+
.persona-mention-retry {
|
|
164
|
+
min-height: 36px;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
`;function q(s){let e=s.replace(/^\s+/,""),t=e.search(/\s/);return t===-1?{name:e,args:""}:{name:e.slice(0,t),args:e.slice(t+1).trim()}}var re=new Map,pe=(s,e,t)=>{let n=`${s}|${e}|${t}`,i=re.get(n);return i===void 0&&(i=N(s,e,"currentColor",t),re.set(n,i)),i?i.cloneNode(!0):null};function se(s){let{config:e,listboxId:t}=s,n=C("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),i=C("div",{className:"persona-mention-search",style:{display:"none"}}),o=S("span","persona-mention-search-icon"),r=N("search",15,"currentColor",2);r&&o.appendChild(r);let d=C("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":t,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});i.append(o,d),d.addEventListener("input",()=>s.onSearchInput?.(d.value)),d.addEventListener("keydown",c=>s.onSearchKeydown?.(c));let a=C("div",{className:"persona-mention-list",attrs:{role:"listbox",id:t,"aria-label":"Context mentions"}});n.append(i,a);let l=[],x=[],p=-1,M=new Map,u=(c,h)=>`${c}\0${h}`,A=c=>`${t}-opt-${c}`,T=c=>`${t}-grp-${c}`,V=(c,h)=>{let m=l[c];m&&(h?m.setAttribute("data-active","true"):m.removeAttribute("data-active"),m.setAttribute("aria-selected",h?"true":"false"),x[c]?.(h))},z=(c,h=!0)=>{p>=0&&p!==c&&V(p,!1),p=c;let m=l[c];m?(V(c,!0),h&&m.scrollIntoView?.({block:"nearest"}),a.setAttribute("aria-activedescendant",m.id),d.setAttribute("aria-activedescendant",m.id)):(a.removeAttribute("aria-activedescendant"),d.removeAttribute("aria-activedescendant"))},E=(c,h)=>{let m=T(h),v=C("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":m}});return v.appendChild(C("div",{className:"persona-mention-group-header",attrs:{id:m},text:c})),v},B=()=>{let c=C("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),h=S("span","persona-mention-option-icon");c.appendChild(h);let m="",v=S("span","persona-mention-option-text"),w=S("span","persona-mention-option-labelline"),I=S("span","persona-mention-option-label");w.appendChild(I),v.appendChild(w),c.appendChild(v);let y=null,b=null,f={el:c,index:0,update:(g,O,P)=>{f.index=O,c.id=A(O),c.setAttribute("aria-setsize",String(P)),c.setAttribute("aria-posinset",String(O+1)),c.removeAttribute("data-active"),c.setAttribute("aria-selected","false");let W=g.iconName??e.chipIconName??"at-sign";if(W!==m){m=W;let L=pe(W,15,2);h.replaceChildren(...L?[L]:[])}I.textContent!==g.label&&(I.textContent=g.label);let R=g.commandArgsPlaceholder?`\u2039${g.commandArgsPlaceholder}\u203A`:null;R?(y||(y=S("span","persona-mention-option-arghint"),w.appendChild(y)),y.textContent!==R&&(y.textContent=R)):y&&(y.remove(),y=null),g.description?(b||(b=S("span","persona-mention-option-desc"),v.appendChild(b)),b.textContent!==g.description&&(b.textContent=g.description)):b&&(b.remove(),b=null)}};return c.addEventListener("mousedown",g=>{g.button===0&&(g.preventDefault(),s.onSelectIndex(f.index))}),c.addEventListener("mouseenter",()=>s.onHoverIndex(f.index)),f},ae=(c,h,m,v,w)=>{let I=C("div",{className:"persona-mention-option",attrs:{role:"option",id:A(v),"aria-selected":"false","aria-setsize":String(w),"aria-posinset":String(v+1)}}),y=b=>{I.replaceChildren(e.renderMentionItem({item:c,source:h,query:m,active:b,index:v}))};return y(!1),I.addEventListener("mousedown",b=>{b.button===0&&(b.preventDefault(),s.onSelectIndex(v))}),I.addEventListener("mouseenter",()=>s.onHoverIndex(v)),{el:I,paint:y}},le=c=>{let h=C("div",{className:"persona-mention-status persona-mention-error"});if(h.appendChild(C("span",{className:"persona-mention-error-text",text:`Couldn't load ${c.label}`})),s.onRetry){let m=C("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});m.addEventListener("mousedown",v=>v.preventDefault()),m.addEventListener("click",v=>{v.preventDefault(),s.onRetry(c.id)}),h.appendChild(m)}return h};return{el:n,render:c=>{a.replaceChildren(),l=[],x=[],p=-1;let h=new Set,m=0,v=0,w=0,I=0,y=0,b=c.groups.reduce((f,g)=>g.status==="ready"?f+g.items.length:f,0);for(let f of c.groups)if(f.status==="loading"){w++;let g=E(f.source.label,y++);g.appendChild(C("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),a.appendChild(g)}else if(f.status==="error"){I++;let g=E(f.source.label,y++);g.appendChild(le(f.source)),a.appendChild(g)}else if(f.status==="ready"&&f.items.length>0){let g=new Map;for(let P of f.items){let W=P.group??f.source.label,R=g.get(W);R?R.push(P):g.set(W,[P])}let O=Array.from(g.entries());O.forEach(([P,W],R)=>{let L=E(P,y++);for(let K of W){let U=m++,$;if(e.renderMentionItem){let k=ae(K,f.source,c.query,U,b);$=k.el,x.push(k.paint)}else{let k=u(f.source.id,K.id),H=h.has(k)?void 0:M.get(k);H||(H=B(),h.has(k)||M.set(k,H)),h.add(k),H.update(K,U,b),$=H.el,x.push(null)}l.push($),L.appendChild($),v++}f.truncated&&R===O.length-1&&L.appendChild(C("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),a.appendChild(L)})}for(let f of M.keys())h.has(f)||M.delete(f);v===0&&w===0&&I===0&&a.appendChild(C("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),l.length>0?z(Math.min(Math.max(0,c.activeIndex),l.length-1)):(a.removeAttribute("aria-activedescendant"),d.removeAttribute("aria-activedescendant"))},setActiveIndex:z,destroy:()=>{a.replaceChildren(),l=[],M.clear(),n.remove()},showSearch:(c,h)=>{d.value=c,h&&(d.placeholder=h),i.style.display="",d.setAttribute("aria-expanded","true"),d.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{i.style.display!=="none"&&d.focus()})},hideSearch:()=>{i.style.display="none",d.value="",d.setAttribute("aria-expanded","false"),d.removeAttribute("aria-activedescendant")}}}var ue=s=>!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function",he=0,F=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let t=e.mentionConfig,n=X(t),i=n.filter(r=>r.sources.length>0);this.channels=i.length>0?i:[n[0]],this.activeChannel=this.channels[0],this.maxPerGroup=t.maxItemsPerGroup??6,this.debounceMs=t.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++he}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():se({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:r=>this.selectIndex(r),onHoverIndex:r=>this.setActiveIndex(r,!1),onRetry:r=>this.retrySource(r),onSearchInput:r=>this.setQuery(r),onSearchKeydown:r=>{this.handleKeydown(r)}});let o=e.composerInput.element;o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let t=()=>{let n=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(i=>({source:i.source,items:i.items})),status:Object.fromEntries(this.groups.map(i=>[i.source.id,i.status])),activeIndex:this.activeIndex,select:i=>{let o=this.groups.find(r=>r.items.includes(i));o&&this.commit(o.source,i)},close:()=>this.close()});e.replaceChildren(n)};return{el:e,render:t,setActiveIndex:t,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let t=e&&this.channels.find(r=>r.trigger===e)||this.channels[0],n=this.input.getSelection().start,i=_(this.input.getLogicalText(),n,[t]);if(i){this.pickerMode=!1,this.triggerMatch=i.match,this.isOpenState?(this.switchChannel(t),this.setQuery(i.match.query)):this.open(i.match.query,t),this.input.focus();return}let o=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=t.trigger,this.triggerMatch=null,this.isOpenState?(o&&o!==t.trigger&&this.opts.onPickerOpenChange?.(!1,o,this.listboxId),this.switchChannel(t),this.setQuery("")):this.open("",t),this.menu.showSearch?this.menu.showSearch("",t.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,t.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,t=_(this.input.getLogicalText(),e,this.channels);if(!t){this.isOpenState&&this.close();return}if(this.isInlineArgTail(t.channel,t.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=t.match,this.isOpenState?(this.switchChannel(t.channel),this.measuredTriggerIndex!==t.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(t.match.query)):this.open(t.match.query,t.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,t){if(this.isOpenState=!0,this.activeChannel=t,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let n=this.canAnchorMenu();if(this.popover=Z({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!n,offset:6,container:this.opts.popoverContainer,horizontalOffset:n?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:n?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),n){let i=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,i)}px`}}this.updateTriggerAnchor(),this.popover.open(),J(this.menu.el,"persona-mention-menu",oe),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:t.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,t=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!t)return;let n=t(e.triggerIndex,e.triggerIndex+1);if(!n)return;let i=this.opts.anchor.getBoundingClientRect(),o=n.top-i.top,r=this.input.element,d=typeof getComputedStyle=="function"&&getComputedStyle(r).direction==="rtl";this.triggerAnchorOffset={x:d?null:n.left-i.left,y:o}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let t=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let n of this.activeChannel.sources)this.knownAsync.has(n.id)?this.setGroupStatus(n.id,"loading"):(this.invokedForToken.add(n.id),this.invokeSource(n,t));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(t===this.searchToken)for(let n of this.activeChannel.sources)this.knownAsync.has(n.id)&&!this.invokedForToken.has(n.id)&&this.invokeSource(n,t)},this.debounceMs)}invokeSource(e,t){let n={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},i;try{i=e.search(this.query,n)}catch{this.setGroupStatus(e.id,"error"),this.render();return}ue(i)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),i.then(o=>{t===this.searchToken&&(this.setGroupItems(e.id,o),this.render())}).catch(()=>{t===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,i)}getOrCreateGroup(e){let t=this.groups.find(n=>n.source.id===e.id);if(!t){t={source:e,items:[],status:"loading",truncated:!1};let n=this.activeChannel.sources;this.groups.push(t),this.groups.sort((i,o)=>n.findIndex(r=>r.id===i.source.id)-n.findIndex(r=>r.id===o.source.id))}return t}setGroupStatus(e,t){let n=this.activeChannel.sources.find(i=>i.id===e);n&&(this.getOrCreateGroup(n).status=t)}setGroupItems(e,t){let n=this.activeChannel.sources.find(o=>o.id===e);if(!n)return;let i=this.getOrCreateGroup(n);i.truncated=t.length>this.maxPerGroup,i.items=t.slice(0,this.maxPerGroup),i.status=i.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let t of e.items)this.flat.push({source:e.source,item:t});if(this.activeKey){let e=this.flat.findIndex(t=>this.keyOf(t)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(t=>t.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,t=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,t),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let t=this.activeChannel.sources.find(n=>n.id===e);!t||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(t,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let t=this.flat[e];t&&this.commit(t.source,t.item)}deriveArgs(e){return q(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,t){let n=t.command;if(this.isInlineCommand(t)){this.completeCommandInline(e,t);return}if(n==="action"){let o=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(t,o),this.opts.emit?.("command",{sourceId:e.id,itemId:t.id,kind:"action",args:o}),this.input.focus();return}if(n==="prompt"){let o=this.deriveArgs(this.query),r=this.captureStripTarget();this.close(),this.runPromptMacro(e,t,o,r),this.opts.emit?.("command",{sourceId:e.id,itemId:t.id,kind:"prompt",args:o});return}if(this.isInlineDisplay()){this.commitInlineMention(e,t);return}this.opts.onSelect(e,t,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:t.id,label:t.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,t){if(this.opts.admitMention&&!this.opts.admitMention(e,t)){this.close(),this.input.focus();return}let n=G(e,t),i=this.triggerMatch?this.input.insertMentionAtTrigger(n,this.triggerMatch):this.input.insertMentionAtSelection?.(n)??null;i?(this.opts.onInsertMention(i,e,t,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:t.id,label:t.label})):(this.opts.mentionConfig.onMentionRejected?.(t,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:t.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,t){let n=`${this.activeChannel.trigger}${t.label} `,i=this.input.getSelection().start,o=this.triggerMatch?this.triggerMatch.triggerIndex:i;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(o,i,n);else{let r=this.input.getValue();this.input.setValueWithCaret(r.slice(0,o)+n+r.slice(i),o+n.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:t.id,kind:t.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,t){let{name:n}=q(t);return!n||t.length<=n.length?!1:e.sources.some(i=>{let o=i.matchCommand?.(n);return!!o&&this.isInlineCommand(o)})}matchInlineCommand(e){for(let t of this.channels){if(!t.trigger)continue;let n=t.position==="anywhere"?[e]:t.position==="line-start"?e.split(`
|
|
168
|
+
`):[e.split(`
|
|
169
|
+
`)[0]];for(let i of n){if(!i.startsWith(t.trigger))continue;let{name:o,args:r}=q(i.slice(t.trigger.length));if(o)for(let d of t.sources){let a=d.matchCommand?.(o);if(a&&this.isInlineCommand(a))return{source:d,item:a,args:r}}}}return null}async dispatchInlineCommand(e){let t=this.matchInlineCommand(e);if(!t)return null;let{source:n,item:i,args:o}=t,r=i.command??"prompt";if(this.opts.emit?.("command",{sourceId:n.id,itemId:i.id,kind:r,args:o}),r==="action")return this.runAction(i,o),{kind:"action"};if(r==="prompt"){let a;try{a=await n.resolve(i,this.resolveContext(o,e))}catch(l){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",l),null}return{kind:"prompt",sendText:a.insertText??a.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let a=await n.resolve(i,this.resolveContext(o,e)),l={};return a.context&&(l[n.id]={[i.id]:a.context}),{blocks:[],contentParts:a.contentParts??[],context:l}}}}}resolveContext(e,t){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:t,args:e,signal:new AbortController().signal}}runAction(e,t){if(e.action)try{Promise.resolve(e.action({args:t,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(n=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",n)})}catch(n){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",n)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,t,n,i){let o=this.input,r;try{r=await e.resolve(t,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o.getValue(),args:n,signal:new AbortController().signal})}catch(a){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",a);return}let d=r.insertText??r.llmAppend??"";t.insertMode==="insert-at-caret"&&i?o.replaceLogicalRange?(o.replaceLogicalRange(i.start,i.end,d),o.dispatchInput()):o.setValue(i.value.slice(0,i.start)+d+i.value.slice(i.end)):o.setValue(d),t.submitOnSelect&&o.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let t=Y(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(t.value,t.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}};var ge={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"};function j(s,e){let t=document.createElement("div");t.className="persona-sr-only",t.setAttribute("aria-live",s),t.setAttribute("aria-atomic","true"),t.setAttribute("role",s==="assertive"?"alert":"status"),t.setAttribute("data-persona-mention-live-region","");let n=e.getRootNode();typeof ShadowRoot<"u"&&n instanceof ShadowRoot?(Object.assign(t.style,ge),document.body.appendChild(t)):e.appendChild(t);let o;return{announce:r=>{o!==void 0&&clearTimeout(o),t.textContent="",o=setTimeout(()=>{o=void 0,t.textContent=r},0)},destroy:()=>{o!==void 0&&clearTimeout(o),t.remove()}}}function me(s){let e=s.composerInput??ee(s.textarea),t=j("polite",s.liveRegionHost),n=j("assertive",s.liveRegionHost),i=l=>t.announce(l),o=l=>n.announce(l),r=new D({mentionConfig:s.mentionConfig,contextRow:s.contextRow,getMessages:s.getMessages,getConfig:s.getConfig,getComposerText:()=>e.getValue(),announce:i,announceError:o,emit:s.emit}),d=()=>new F({mentionConfig:s.mentionConfig,composerInput:e,anchor:s.anchor,getMessages:s.getMessages,getConfig:s.getConfig,onSelect:(l,x,p)=>r.add(l,x,p),onInsertMention:(l,x,p,M)=>r.track(l,x,p,M,u=>e.setMentionStatus?.(l,u)),admitMention:(l,x)=>r.admit(l,x),announce:i,popoverContainer:s.popoverContainer,onPickerOpenChange:s.onPickerOpenChange,emit:s.emit}),a=d();return{openMenu:l=>a.openFromButton(l),isMenuOpen:()=>a.isOpen(),handleInput:()=>a.onInput(),handleKeydown:l=>a.handleKeydown(l),hasMentions:()=>r.hasMentions(),removeLastChip:()=>r.removeLast(),dispatchInlineCommand:l=>a.dispatchInlineCommand(l),collectForSubmit:()=>r.hasMentions()?r.collectForSubmit():null,untrackMention:l=>r.remove(l),rebindComposer:l=>{l!==e&&(a.destroy(),e=l,a=d())},clear:()=>r.clear(),destroy:()=>{a.destroy(),r.clear(),t.destroy(),n.destroy()}}}export{me as mountContextMentions};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as X}from"./chunk-UPO4GUFC.js";import"./chunk-IO5VVUKP.js";var ce="@";function O(t){return t.kind==="text"?t.value.length:1}function W(t){let n=[],o=r=>{let c=n[n.length-1];c&&c.kind==="text"?c.value+=r:n.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&n.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){o(r.value);continue}let c=n[n.length-1];(!c||c.kind!=="text")&&n.push({kind:"text",value:""}),n.push({kind:"mention",id:r.id,ref:r.ref}),n.push({kind:"text",value:""})}let e=n[n.length-1];return(!e||e.kind!=="text")&&n.push({kind:"text",value:""}),n}function Y(){return{blocks:[{kind:"text",value:""}]}}function B(t){return{blocks:[{kind:"text",value:t}]}}function H(t){return t.blocks.map(n=>n.kind==="text"?n.value:`${ce}${n.ref.label}`).join("")}function R(t){return t.blocks.map(n=>n.kind==="text"?n.value:"\uFFFC").join("")}function L(t){return t.blocks.reduce((n,o)=>n+O(o),0)}function le(t){let n=[];for(let o of t.blocks)o.kind==="mention"&&n.push({id:o.id,ref:o.ref});return n}function I(t,n){let o=[],e=[],r=0;for(let c of t){let a=O(c),p=r+a;if(p<=n)o.push(c);else if(r>=n)e.push(c);else if(c.kind==="text"){let b=n-r;b>0&&o.push({kind:"text",value:c.value.slice(0,b)}),b<a&&e.push({kind:"text",value:c.value.slice(b)})}else e.push(c);r=p}return{left:o,right:e}}function P(t,n,o,e){let r=I(t.blocks,n.start).left,c=I(t.blocks,n.end).right,a=c[0],p=a?.kind==="text"?a.value.charAt(0):"",b=p!==" "&&p!==" "&&p!==`
|
|
2
|
+
`,g=W([...r,{kind:"mention",id:e,ref:o},...b?[{kind:"text",value:" "}]:[],...c]),C=n.start+1+(p===`
|
|
3
|
+
`?0:1);return{doc:{blocks:g},caret:C}}function G(t,n){let o=0,e=0,r=!1;for(let a of t.blocks)a.kind==="mention"&&a.id===n&&(o=e,r=!0),e+=O(a);return r?{doc:{blocks:W(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===n)))},caret:o}:{doc:t,caret:e}}function D(t,n,o,e){let r=L(t),c=Math.max(0,Math.min(n,o,r)),a=Math.min(r,Math.max(n,o,0)),p=I(t.blocks,c).left,b=I(t.blocks,a).right;return{doc:{blocks:W([...p,{kind:"text",value:e},...b])},caret:c+e.length}}function J(t){let n=[];for(let o of t.blocks)o.kind==="text"?o.value.length>0&&n.push({kind:"text",text:o.value}):n.push({kind:"mention",ref:o.ref});return{content:H(t),contextMentions:le(t).map(o=>o.ref),contentSegments:n}}var ae="persona-mention-token-error",y="data-mention-id",A="data-mention-prev-label",_="data-mention-prev-title",U=`
|
|
4
|
+
`;function T(t){return t.nodeType===1&&t.hasAttribute(y)}function Z(t){return t.nodeType===1&&t.tagName==="BR"}function N(t){return t.nodeType===3?t.data.length:T(t)||Z(t)?1:t.textContent?.length??0}function Q(t,n,o){let e=0;for(let r of Array.from(t.childNodes)){if(r===n)return r.nodeType===3?e+o:e+(o>0?N(r):0);if(r.contains(n))return T(r)?e+1:e+ue(r,n,o);e+=N(r)}if(n===t){let r=0,c=Array.from(t.childNodes);for(let a=0;a<Math.min(o,c.length);a++)r+=N(c[a]);return r}return e}function ue(t,n,o){let e=0,r=c=>{if(c===n)return e+=c.nodeType===3?o:0,!0;if(c.nodeType===3)return e+=c.data.length,!1;for(let a of Array.from(c.childNodes))if(r(a))return!0;return!1};return r(t),e}function v(t,n){let o=0,e=Array.from(t.childNodes);for(let r=0;r<e.length;r++){let c=e[r],a=N(c);if(n<=o+a)return c.nodeType===3?{node:c,offset:n-o}:{node:t,offset:n<=o?r:r+1};o+=a}return{node:t,offset:e.length}}function de(t,n){let o=[];for(let e of Array.from(t.childNodes))if(T(e)){let r=e.getAttribute(y),c=n.get(r);c&&o.push({kind:"mention",id:r,ref:c})}else if(Z(e))o.push({kind:"text",value:U});else if(e.nodeType===3)o.push({kind:"text",value:e.data});else{let r=e.textContent??"";r&&o.push({kind:"text",value:r})}return o.length===0&&o.push({kind:"text",value:""}),{blocks:o}}function ee(t){let n=t.renderToken,o=new Map,e=t.element??document.createElement("div");e.setAttribute("contenteditable","true"),e.setAttribute("data-persona-composer-input",""),e.setAttribute("role","textbox"),e.setAttribute("aria-multiline","true"),e.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&e.setAttribute("data-placeholder",t.placeholder);let r=!1,c=0,a=()=>de(e,o),p=l=>{e.replaceChildren();for(let s of l.blocks)if(s.kind==="text")s.value.length>0&&e.appendChild(document.createTextNode(s.value));else{o.set(s.id,s.ref);let i=n(s.ref);i.setAttribute("contenteditable","false"),i.setAttribute(y,s.id),e.appendChild(i)}},b=()=>{let s=e.getRootNode().activeElement;return s===e||s!=null&&e.contains(s)},g=(l,s)=>{if(c=l,!s?.focus&&!b())return;let i=typeof window<"u"?window.getSelection():null;if(!i)return;let d=v(e,l);try{let u=document.createRange();u.setStart(d.node,d.offset),u.collapse(!0),i.removeAllRanges(),i.addRange(u)}catch{}},C=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))},k=()=>{let l={start:c,end:c},s=typeof window<"u"?window.getSelection():null;if(!s||s.rangeCount===0)return l;let i=s.getRangeAt(0);if(!e.contains(i.startContainer))return l;let d=Q(e,i.startContainer,i.startOffset),u=i.collapsed?d:Q(e,i.endContainer,i.endOffset);return{start:Math.min(d,u),end:Math.max(d,u)}},M=()=>{let l=new Set;for(let s of Array.from(e.childNodes))T(s)&&l.add(s.getAttribute(y));for(let s of Array.from(o.keys()))l.has(s)||(o.delete(s),t.onMentionRemoved?.(s))},F=()=>{r||o.size!==0&&M()},V=()=>{r=!0},j=()=>{r=!1,M()},$=l=>{l.preventDefault();let s=l.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,s);else{let{start:i,end:d}=k(),u=D(a(),i,d,s);p(u.doc),g(u.caret,{focus:!0}),M()}C()},q=l=>{if(r)return;let s=l.inputType;if(s==="insertParagraph"){l.preventDefault();let{start:x,end:E}=k(),K=D(a(),x,E,U);p(K.doc),g(K.caret,{focus:!0}),o.size>0&&M(),C();return}if(s!=="deleteContentBackward"&&s!=="deleteContentForward"||o.size===0)return;let{start:i,end:d}=k();if(i!==d)return;let u=a(),m=R(u),f=s==="deleteContentBackward"?i-1:i;if(f<0||f>=m.length||m[f]!=="\uFFFC")return;let h=0,S=null;for(let x of u.blocks){let E=x.kind==="text"?x.value.length:1;if(x.kind==="mention"&&f>=h&&f<h+E){S=x.id;break}h+=E}if(!S)return;l.preventDefault();let z=G(u,S);p(z.doc),g(z.caret,{focus:!0}),M(),C()},te=(l,s)=>{p(B(l)),g(s)},ne=(l,s)=>{if(!Number.isFinite(l)||!Number.isFinite(s)||s<=l)return null;try{let i=v(e,l),d=v(e,s),u=document.createRange();u.setStart(i.node,i.offset),u.setEnd(d.node,d.offset);let m=u.getBoundingClientRect();return m.width===0&&m.height===0?null:m}catch{return null}},oe=(l,s,i)=>{let d=D(a(),l,s,i);p(d.doc),g(d.caret,{focus:!0})},re=(l,s)=>{let i=a(),d=R(i),u=s.triggerIndex,m=s.triggerIndex+1+s.query.length;if(u<0||m>d.length||d.slice(u+1,m)!==s.query)return null;let f=t.generateId(),h=P(i,{start:u,end:m},l,f);return p(h.doc),g(h.caret,{focus:!0}),t.onMentionInserted?.(f,l),C(),f},ie=l=>{let s=a(),i=k(),u=typeof window<"u"&&!!window.getSelection()?.rangeCount&&e.contains(window.getSelection().getRangeAt(0).startContainer)?{start:i.start,end:i.end}:{start:L(s),end:L(s)},m=t.generateId(),f=P(s,u,l,m);return p(f.doc),g(f.caret,{focus:!0}),t.onMentionInserted?.(m,l),C(),m},se=(l,s)=>{for(let i of Array.from(e.childNodes))if(T(i)&&i.getAttribute(y)===l){let d=s==="error";if(i.classList.toggle(ae,d),d){i.hasAttribute(A)||(i.setAttribute(A,i.getAttribute("aria-label")??""),i.setAttribute(_,i.getAttribute("title")??""));let u=o.get(l)?.label??"";i.setAttribute("title",`${u}: failed to attach context`),i.setAttribute("aria-label",`${u}, failed to attach context`)}else if(i.hasAttribute(A)){let u=i.getAttribute(A),m=i.getAttribute(_);u?i.setAttribute("aria-label",u):i.removeAttribute("aria-label"),m?i.setAttribute("title",m):i.removeAttribute("title"),i.removeAttribute(A),i.removeAttribute(_)}return}};return e.addEventListener("input",F),e.addEventListener("compositionstart",V),e.addEventListener("compositionend",j),e.addEventListener("paste",$),e.addEventListener("beforeinput",q),p(Y()),{element:e,getValue:()=>H(a()),getLogicalText:()=>R(a()),getDocument:a,getSelection:k,setSelection:(l,s=l)=>{let i=typeof window<"u"?window.getSelection():null;if(i)try{let d=v(e,l),u=v(e,s),m=document.createRange();m.setStart(d.node,d.offset),m.setEnd(u.node,u.offset),i.removeAllRanges(),i.addRange(m)}catch{}},setValueWithCaret:te,getLogicalRangeRect:ne,setValue:l=>{p(B(l)),e.focus(),g(l.length,{focus:!0}),C()},replaceLogicalRange:oe,insertMentionAtTrigger:re,insertMentionAtSelection:ie,setMentionStatus:se,submit:()=>X(e.closest("form")),dispatchInput:C,focus:()=>e.focus(),destroy:()=>{e.removeEventListener("input",F),e.removeEventListener("compositionstart",V),e.removeEventListener("compositionend",j),e.removeEventListener("paste",$),e.removeEventListener("beforeinput",q)}}}var me=0,pe=()=>`pmention-${++me}`;function fe(t,n){n.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let c=t.style.item(r);c!=="height"&&n.style.setProperty(c,t.style.getPropertyValue(c),t.style.getPropertyPriority(c))}let o=t.getAttribute("placeholder");o&&(n.setAttribute("data-placeholder",o),n.setAttribute("aria-placeholder",o));let e=t.getAttribute("aria-label")??o;e&&n.setAttribute("aria-label",e)}function ge(t,n,o){Object.defineProperty(t,"value",{configurable:!0,get:()=>n.getValue(),set:e=>{n.setValueWithCaret(e,e.length),n.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:e=>{e?(t.setAttribute("data-placeholder",e),t.setAttribute("aria-placeholder",e),o||t.setAttribute("aria-label",e)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),o||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>n.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>n.getSelection().end}),t.setSelectionRange=(e,r)=>n.setSelection(e??0,r??e??0)}function be(t){let{textarea:n}=t,o={generateId:pe,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:n.getAttribute("placeholder")??void 0},e=ee(o),r=e.element,c=n.getAttribute("aria-label")!=null;fe(n,r),ge(r,e,c),r.getInlineMessageFields=()=>J(e.getDocument?.()??{blocks:[]});let a=n.selectionStart??n.value.length;return e.setValueWithCaret(n.value,a),{input:e,element:r,destroy:e.destroy}}export{be as mountInlineComposer};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";var w=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var me=(e,n)=>{for(var o in n)w(e,o,{get:n[o],enumerable:!0})},pe=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of ae(n))!de.call(e,r)&&r!==o&&w(e,r,{get:()=>n[r],enumerable:!(t=ue(n,r))||t.enumerable});return e};var fe=e=>pe(w({},"__esModule",{value:!0}),e);var ke={};me(ke,{mountInlineComposer:()=>ne});module.exports=fe(ke);var ge="@";function O(e){return e.kind==="text"?e.value.length:1}function H(e){let n=[],o=r=>{let l=n[n.length-1];l&&l.kind==="text"?l.value+=r:n.push({kind:"text",value:r})};(e.length===0||e[0].kind!=="text")&&n.push({kind:"text",value:""});for(let r of e){if(r.kind==="text"){o(r.value);continue}let l=n[n.length-1];(!l||l.kind!=="text")&&n.push({kind:"text",value:""}),n.push({kind:"mention",id:r.id,ref:r.ref}),n.push({kind:"text",value:""})}let t=n[n.length-1];return(!t||t.kind!=="text")&&n.push({kind:"text",value:""}),n}function X(){return{blocks:[{kind:"text",value:""}]}}function P(e){return{blocks:[{kind:"text",value:e}]}}function B(e){return e.blocks.map(n=>n.kind==="text"?n.value:`${ge}${n.ref.label}`).join("")}function R(e){return e.blocks.map(n=>n.kind==="text"?n.value:"\uFFFC").join("")}function L(e){return e.blocks.reduce((n,o)=>n+O(o),0)}function be(e){let n=[];for(let o of e.blocks)o.kind==="mention"&&n.push({id:o.id,ref:o.ref});return n}function I(e,n){let o=[],t=[],r=0;for(let l of e){let u=O(l),p=r+u;if(p<=n)o.push(l);else if(r>=n)t.push(l);else if(l.kind==="text"){let b=n-r;b>0&&o.push({kind:"text",value:l.value.slice(0,b)}),b<u&&t.push({kind:"text",value:l.value.slice(b)})}else t.push(l);r=p}return{left:o,right:t}}function _(e,n,o,t){let r=I(e.blocks,n.start).left,l=I(e.blocks,n.end).right,u=l[0],p=u?.kind==="text"?u.value.charAt(0):"",b=p!==" "&&p!==" "&&p!==`
|
|
2
|
+
`,g=H([...r,{kind:"mention",id:t,ref:o},...b?[{kind:"text",value:" "}]:[],...l]),C=n.start+1+(p===`
|
|
3
|
+
`?0:1);return{doc:{blocks:g},caret:C}}function Y(e,n){let o=0,t=0,r=!1;for(let u of e.blocks)u.kind==="mention"&&u.id===n&&(o=t,r=!0),t+=O(u);return r?{doc:{blocks:H(e.blocks.filter(u=>!(u.kind==="mention"&&u.id===n)))},caret:o}:{doc:e,caret:t}}function S(e,n,o,t){let r=L(e),l=Math.max(0,Math.min(n,o,r)),u=Math.min(r,Math.max(n,o,0)),p=I(e.blocks,l).left,b=I(e.blocks,u).right;return{doc:{blocks:H([...p,{kind:"text",value:t},...b])},caret:l+t.length}}function G(e){let n=[];for(let o of e.blocks)o.kind==="text"?o.value.length>0&&n.push({kind:"text",text:o.value}):n.push({kind:"mention",ref:o.ref});return{content:B(e),contextMentions:be(e).map(o=>o.ref),contentSegments:n}}function J(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}var Ce="persona-mention-token-error",k="data-mention-id",v="data-mention-prev-label",F="data-mention-prev-title",Z=`
|
|
4
|
+
`;function y(e){return e.nodeType===1&&e.hasAttribute(k)}function ee(e){return e.nodeType===1&&e.tagName==="BR"}function D(e){return e.nodeType===3?e.data.length:y(e)||ee(e)?1:e.textContent?.length??0}function U(e,n,o){let t=0;for(let r of Array.from(e.childNodes)){if(r===n)return r.nodeType===3?t+o:t+(o>0?D(r):0);if(r.contains(n))return y(r)?t+1:t+he(r,n,o);t+=D(r)}if(n===e){let r=0,l=Array.from(e.childNodes);for(let u=0;u<Math.min(o,l.length);u++)r+=D(l[u]);return r}return t}function he(e,n,o){let t=0,r=l=>{if(l===n)return t+=l.nodeType===3?o:0,!0;if(l.nodeType===3)return t+=l.data.length,!1;for(let u of Array.from(l.childNodes))if(r(u))return!0;return!1};return r(e),t}function T(e,n){let o=0,t=Array.from(e.childNodes);for(let r=0;r<t.length;r++){let l=t[r],u=D(l);if(n<=o+u)return l.nodeType===3?{node:l,offset:n-o}:{node:e,offset:n<=o?r:r+1};o+=u}return{node:e,offset:t.length}}function Me(e,n){let o=[];for(let t of Array.from(e.childNodes))if(y(t)){let r=t.getAttribute(k),l=n.get(r);l&&o.push({kind:"mention",id:r,ref:l})}else if(ee(t))o.push({kind:"text",value:Z});else if(t.nodeType===3)o.push({kind:"text",value:t.data});else{let r=t.textContent??"";r&&o.push({kind:"text",value:r})}return o.length===0&&o.push({kind:"text",value:""}),{blocks:o}}function te(e){let n=e.renderToken,o=new Map,t=e.element??document.createElement("div");t.setAttribute("contenteditable","true"),t.setAttribute("data-persona-composer-input",""),t.setAttribute("role","textbox"),t.setAttribute("aria-multiline","true"),t.classList.add("persona-composer-contenteditable"),e.placeholder!=null&&t.setAttribute("data-placeholder",e.placeholder);let r=!1,l=0,u=()=>Me(t,o),p=c=>{t.replaceChildren();for(let s of c.blocks)if(s.kind==="text")s.value.length>0&&t.appendChild(document.createTextNode(s.value));else{o.set(s.id,s.ref);let i=n(s.ref);i.setAttribute("contenteditable","false"),i.setAttribute(k,s.id),t.appendChild(i)}},b=()=>{let s=t.getRootNode().activeElement;return s===t||s!=null&&t.contains(s)},g=(c,s)=>{if(l=c,!s?.focus&&!b())return;let i=typeof window<"u"?window.getSelection():null;if(!i)return;let d=T(t,c);try{let a=document.createRange();a.setStart(d.node,d.offset),a.collapse(!0),i.removeAllRanges(),i.addRange(a)}catch{}},C=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))},x=()=>{let c={start:l,end:l},s=typeof window<"u"?window.getSelection():null;if(!s||s.rangeCount===0)return c;let i=s.getRangeAt(0);if(!t.contains(i.startContainer))return c;let d=U(t,i.startContainer,i.startOffset),a=i.collapsed?d:U(t,i.endContainer,i.endOffset);return{start:Math.min(d,a),end:Math.max(d,a)}},A=()=>{let c=new Set;for(let s of Array.from(t.childNodes))y(s)&&c.add(s.getAttribute(k));for(let s of Array.from(o.keys()))c.has(s)||(o.delete(s),e.onMentionRemoved?.(s))},V=()=>{r||o.size!==0&&A()},q=()=>{r=!0},j=()=>{r=!1,A()},$=c=>{c.preventDefault();let s=c.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,s);else{let{start:i,end:d}=x(),a=S(u(),i,d,s);p(a.doc),g(a.caret,{focus:!0}),A()}C()},z=c=>{if(r)return;let s=c.inputType;if(s==="insertParagraph"){c.preventDefault();let{start:M,end:E}=x(),Q=S(u(),M,E,Z);p(Q.doc),g(Q.caret,{focus:!0}),o.size>0&&A(),C();return}if(s!=="deleteContentBackward"&&s!=="deleteContentForward"||o.size===0)return;let{start:i,end:d}=x();if(i!==d)return;let a=u(),m=R(a),f=s==="deleteContentBackward"?i-1:i;if(f<0||f>=m.length||m[f]!=="\uFFFC")return;let h=0,N=null;for(let M of a.blocks){let E=M.kind==="text"?M.value.length:1;if(M.kind==="mention"&&f>=h&&f<h+E){N=M.id;break}h+=E}if(!N)return;c.preventDefault();let K=Y(a,N);p(K.doc),g(K.caret,{focus:!0}),A(),C()},oe=(c,s)=>{p(P(c)),g(s)},re=(c,s)=>{if(!Number.isFinite(c)||!Number.isFinite(s)||s<=c)return null;try{let i=T(t,c),d=T(t,s),a=document.createRange();a.setStart(i.node,i.offset),a.setEnd(d.node,d.offset);let m=a.getBoundingClientRect();return m.width===0&&m.height===0?null:m}catch{return null}},ie=(c,s,i)=>{let d=S(u(),c,s,i);p(d.doc),g(d.caret,{focus:!0})},se=(c,s)=>{let i=u(),d=R(i),a=s.triggerIndex,m=s.triggerIndex+1+s.query.length;if(a<0||m>d.length||d.slice(a+1,m)!==s.query)return null;let f=e.generateId(),h=_(i,{start:a,end:m},c,f);return p(h.doc),g(h.caret,{focus:!0}),e.onMentionInserted?.(f,c),C(),f},le=c=>{let s=u(),i=x(),a=typeof window<"u"&&!!window.getSelection()?.rangeCount&&t.contains(window.getSelection().getRangeAt(0).startContainer)?{start:i.start,end:i.end}:{start:L(s),end:L(s)},m=e.generateId(),f=_(s,a,c,m);return p(f.doc),g(f.caret,{focus:!0}),e.onMentionInserted?.(m,c),C(),m},ce=(c,s)=>{for(let i of Array.from(t.childNodes))if(y(i)&&i.getAttribute(k)===c){let d=s==="error";if(i.classList.toggle(Ce,d),d){i.hasAttribute(v)||(i.setAttribute(v,i.getAttribute("aria-label")??""),i.setAttribute(F,i.getAttribute("title")??""));let a=o.get(c)?.label??"";i.setAttribute("title",`${a}: failed to attach context`),i.setAttribute("aria-label",`${a}, failed to attach context`)}else if(i.hasAttribute(v)){let a=i.getAttribute(v),m=i.getAttribute(F);a?i.setAttribute("aria-label",a):i.removeAttribute("aria-label"),m?i.setAttribute("title",m):i.removeAttribute("title"),i.removeAttribute(v),i.removeAttribute(F)}return}};return t.addEventListener("input",V),t.addEventListener("compositionstart",q),t.addEventListener("compositionend",j),t.addEventListener("paste",$),t.addEventListener("beforeinput",z),p(X()),{element:t,getValue:()=>B(u()),getLogicalText:()=>R(u()),getDocument:u,getSelection:x,setSelection:(c,s=c)=>{let i=typeof window<"u"?window.getSelection():null;if(i)try{let d=T(t,c),a=T(t,s),m=document.createRange();m.setStart(d.node,d.offset),m.setEnd(a.node,a.offset),i.removeAllRanges(),i.addRange(m)}catch{}},setValueWithCaret:oe,getLogicalRangeRect:re,setValue:c=>{p(P(c)),t.focus(),g(c.length,{focus:!0}),C()},replaceLogicalRange:ie,insertMentionAtTrigger:se,insertMentionAtSelection:le,setMentionStatus:ce,submit:()=>J(t.closest("form")),dispatchInput:C,focus:()=>t.focus(),destroy:()=>{t.removeEventListener("input",V),t.removeEventListener("compositionstart",q),t.removeEventListener("compositionend",j),t.removeEventListener("paste",$),t.removeEventListener("beforeinput",z)}}}var xe=0,Ae=()=>`pmention-${++xe}`;function ve(e,n){n.className=`${e.className} persona-composer-contenteditable`.trim();for(let r=0;r<e.style.length;r++){let l=e.style.item(r);l!=="height"&&n.style.setProperty(l,e.style.getPropertyValue(l),e.style.getPropertyPriority(l))}let o=e.getAttribute("placeholder");o&&(n.setAttribute("data-placeholder",o),n.setAttribute("aria-placeholder",o));let t=e.getAttribute("aria-label")??o;t&&n.setAttribute("aria-label",t)}function Te(e,n,o){Object.defineProperty(e,"value",{configurable:!0,get:()=>n.getValue(),set:t=>{n.setValueWithCaret(t,t.length),n.dispatchInput()}}),Object.defineProperty(e,"placeholder",{configurable:!0,get:()=>e.getAttribute("data-placeholder")??"",set:t=>{t?(e.setAttribute("data-placeholder",t),e.setAttribute("aria-placeholder",t),o||e.setAttribute("aria-label",t)):(e.removeAttribute("data-placeholder"),e.removeAttribute("aria-placeholder"),o||e.removeAttribute("aria-label"))}}),Object.defineProperty(e,"selectionStart",{configurable:!0,get:()=>n.getSelection().start}),Object.defineProperty(e,"selectionEnd",{configurable:!0,get:()=>n.getSelection().end}),e.setSelectionRange=(t,r)=>n.setSelection(t??0,r??t??0)}function ne(e){let{textarea:n}=e,o={generateId:Ae,renderToken:e.renderToken,onMentionRemoved:e.onMentionRemoved,placeholder:n.getAttribute("placeholder")??void 0},t=te(o),r=t.element,l=n.getAttribute("aria-label")!=null;ve(n,r),Te(r,t,l),r.getInlineMessageFields=()=>G(t.getDocument?.()??{blocks:[]});let u=n.selectionStart??n.value.length;return t.setValueWithCaret(n.value,u),{input:t,element:r,destroy:t.destroy}}0&&(module.exports={mountInlineComposer});
|