@marketrix.ai/widget 4.0.111 → 4.0.113

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.
@@ -16,6 +16,12 @@
16
16
  * carrying every tenant token as an inline style, which is why it, not the shadow root, is the portal container —
17
17
  * a portal landing outside it falls back to `index.css`'s hardcoded palette. `onRetry` is spread in only when
18
18
  * `StreamClient.canReconnect()`, so a terminal failure offers no Retry button rather than one that does nothing.
19
+ *
20
+ * `useScrollLock` (below) hides `overflow` on html and body while `state.isOpen`, but only under
21
+ * MOBILE_MAX_WIDTH, where the open panel covers the page; on desktop the host page keeps scrolling. It
22
+ * restores the exact previous values on release. Hand-rolled on purpose, alongside `MessengerShell`'s
23
+ * `useFocusTrap`: both serve a non-modal panel that is not a Dialog, and Base UI exposes no standalone
24
+ * scroll-lock — reaching one by making the panel a Dialog would inert the customer's page.
19
25
  */
20
26
  import React from 'react';
21
27
  import type { ValidWidgetConfig } from '../types';
@@ -5,7 +5,7 @@
5
5
  import type { ComponentPropsWithRef } from 'react';
6
6
  import { type RadiusToken, type ShadowToken } from '../../design-system/component-tokens';
7
7
  type AvatarSize = 'sm' | 'md' | 'lg';
8
- export interface AvatarProps extends Omit<ComponentPropsWithRef<'img'>, 'size'> {
8
+ interface AvatarProps extends Omit<ComponentPropsWithRef<'img'>, 'size'> {
9
9
  src: string;
10
10
  alt: string;
11
11
  elevation?: ShadowToken;
@@ -3,7 +3,7 @@ import { type ShadowToken } from '../../design-system/component-tokens';
3
3
  type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'bare' | 'chip' | 'tab';
4
4
  type ButtonSize = 'sm' | 'md';
5
5
  type ButtonShape = 'default' | 'pill';
6
- export interface ButtonProps extends ComponentPropsWithRef<'button'> {
6
+ interface ButtonProps extends ComponentPropsWithRef<'button'> {
7
7
  elevation?: ShadowToken;
8
8
  size?: ButtonSize;
9
9
  shape?: ButtonShape;
@@ -12,10 +12,11 @@
12
12
  */
13
13
  import { type ReactNode } from 'react';
14
14
  import { type SurfaceProps } from './Surface';
15
- export interface FlexProps extends SurfaceProps {
15
+ interface FlexProps extends SurfaceProps {
16
16
  direction?: 'row' | 'column';
17
17
  children?: ReactNode;
18
18
  }
19
19
  export type StackProps = Omit<FlexProps, 'direction'>;
20
20
  export declare const Flex: import("react").ForwardRefExoticComponent<FlexProps & import("react").RefAttributes<HTMLElement>>;
21
21
  export declare const Stack: import("react").ForwardRefExoticComponent<StackProps & import("react").RefAttributes<HTMLElement>>;
22
+ export {};
@@ -12,9 +12,10 @@
12
12
  */
13
13
  import type { ComponentPropsWithRef } from 'react';
14
14
  import { type IconName } from './icons';
15
- export interface IconProps extends ComponentPropsWithRef<'svg'> {
15
+ interface IconProps extends ComponentPropsWithRef<'svg'> {
16
16
  name: IconName;
17
17
  size?: number;
18
18
  className?: string;
19
19
  }
20
20
  export declare function Icon({ name, size, className, ref, ...props }: IconProps): import("react").JSX.Element | null;
21
+ export {};
@@ -6,7 +6,7 @@ import type { ComponentPropsWithRef } from 'react';
6
6
  import { type TextTone } from '../../design-system/component-tokens';
7
7
  type IconButtonVariant = 'primary' | 'secondary' | 'ghost';
8
8
  type IconButtonSize = 'xs' | 'sm';
9
- export interface IconButtonProps extends ComponentPropsWithRef<'button'> {
9
+ interface IconButtonProps extends ComponentPropsWithRef<'button'> {
10
10
  variant?: IconButtonVariant;
11
11
  size?: IconButtonSize;
12
12
  tone?: TextTone;
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import type { CSSProperties, Ref } from 'react';
6
6
  type SpinnerSize = 'sm' | 'md' | 'lg';
7
- export interface SpinnerProps {
7
+ interface SpinnerProps {
8
8
  size?: SpinnerSize;
9
9
  style?: CSSProperties;
10
10
  ref?: Ref<HTMLDivElement>;
@@ -21,7 +21,7 @@ type TextVariant = 'default' | 'muted' | 'faint';
21
21
  type TextSize = 'xxs' | 'xs' | 'sm' | 'lg';
22
22
  type TextWeight = 'normal' | 'medium' | 'semibold';
23
23
  type TextAlign = 'center' | 'right';
24
- export interface TextProps extends React.HTMLAttributes<HTMLElement> {
24
+ interface TextProps extends React.HTMLAttributes<HTMLElement> {
25
25
  as?: ElementType;
26
26
  block?: boolean;
27
27
  inheritColor?: boolean;
@@ -15,7 +15,7 @@ export interface ChatInputMode {
15
15
  icon: IconName;
16
16
  label: string;
17
17
  }
18
- export interface ChatInputProps {
18
+ interface ChatInputProps {
19
19
  value: string;
20
20
  onChange: (value: string) => void;
21
21
  onSubmit: () => void;
@@ -28,3 +28,4 @@ export interface ChatInputProps {
28
28
  ref?: React.Ref<HTMLTextAreaElement>;
29
29
  }
30
30
  export declare function ChatInput({ value, onChange, onSubmit, modes, activeMode, onModeChange, disabled, taskRunning, onStop, ref, }: ChatInputProps): React.JSX.Element;
31
+ export {};
@@ -1,11 +1,11 @@
1
1
  import React from 'react';
2
- export interface NotificationProviderProps {
2
+ interface NotificationProviderProps {
3
3
  children?: React.ReactNode;
4
4
  container?: HTMLElement | null;
5
5
  offsetBottom?: number;
6
6
  }
7
7
  export declare const NotificationProvider: React.FC<NotificationProviderProps>;
8
- export interface WidgetNotificationsProps {
8
+ interface WidgetNotificationsProps {
9
9
  error?: string | undefined;
10
10
  onClearError: () => void;
11
11
  onRetry?: (() => void) | undefined;
@@ -14,3 +14,4 @@ export interface WidgetNotificationsProps {
14
14
  onGreetingDismiss: () => void;
15
15
  }
16
16
  export declare const WidgetNotifications: React.FC<WidgetNotificationsProps>;
17
+ export {};
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- export interface WidgetDialogProps {
2
+ interface WidgetDialogProps {
3
3
  open: boolean;
4
4
  onClose: () => void;
5
5
  title: string;
@@ -10,3 +10,4 @@ export interface WidgetDialogProps {
10
10
  finalFocusRef?: React.RefObject<HTMLElement | null>;
11
11
  }
12
12
  export declare const WidgetDialog: React.FC<WidgetDialogProps>;
13
+ export {};
@@ -7,9 +7,43 @@
7
7
  * Glow and activity ring are ONE class each, red or green keyed on the `data-tone` the error state
8
8
  * picks — the same data-attribute variant convention every other component here uses. The two icon
9
9
  * layers carry only their own transform and opacity; the transition they share is `.mtx-fab-icon-layer`.
10
+ *
11
+ * `useDragSnap` (below) drags this launcher and snaps it to the nearest corner over ONE Pointer Events
12
+ * path (`onPointerDown/Move/Up/Cancel` — no separate mouse/touch handlers, since Pointer Events already
13
+ * unify both). Pointer state is tracked in a ref; movement under DRAG_THRESHOLD_PX stays a click, beyond
14
+ * it the wrapper is translated on a rAF loop with velocity sampled into `velocityHistoryRef` so a flick
15
+ * lands where it was heading — `projectFlickVelocity` (module-level, pure) turns that sample history into
16
+ * a projected pixel delta. On release
17
+ * `getNearestCornerByTranslation` picks the corner, the wrapper animates there for SNAP_DURATION_MS via
18
+ * `left`/`top` transitions, and `commitPositionAfterAnimation` calls `onPositionCommit` on
19
+ * `transitionend` (with a timeout fallback, since a hidden tab fires no transition events) — the
20
+ * committed corner is the one being animated TO, so two snaps in flight cannot commit the abandoned one
21
+ * (`abandonSnapRef`). `suppressUntilRef` stamps a time after which a click may open the widget again,
22
+ * so the pointer-up that ends a drag is not read as a tap. The wrapper is measured with a
23
+ * ResizeObserver in a layout effect so the pixel position is right on the first paint; preview mode
24
+ * disables everything. Exported so `WidgetFab.test.tsx`'s `renderHook` case can drive it directly.
10
25
  */
11
26
  import React from 'react';
12
27
  import type { WidgetPosition } from '../../types';
28
+ interface UseDragSnapOptions {
29
+ position: WidgetPosition;
30
+ onPositionCommit: (position: WidgetPosition) => void;
31
+ isPreviewMode?: boolean;
32
+ wrapperRef: React.RefObject<HTMLDivElement | null>;
33
+ }
34
+ interface UseDragSnapResult {
35
+ isDragging: boolean;
36
+ pixelPositionStyle: {
37
+ left: number;
38
+ top: number;
39
+ } | undefined;
40
+ onPointerDown: (event: React.PointerEvent<HTMLButtonElement>) => void;
41
+ onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;
42
+ onPointerUp: (event: React.PointerEvent<HTMLButtonElement>) => void;
43
+ onPointerCancel: (event: React.PointerEvent<HTMLButtonElement>) => void;
44
+ suppressUntilRef: React.RefObject<number>;
45
+ }
46
+ export declare function useDragSnap({ position, onPositionCommit, isPreviewMode, wrapperRef, }: UseDragSnapOptions): UseDragSnapResult;
13
47
  interface WidgetFabProps {
14
48
  onPositionCommit: (position: WidgetPosition) => void;
15
49
  }
@@ -1,2 +1,20 @@
1
1
  import React from 'react';
2
+ import type { MarketrixConfig, WidgetPosition } from '../../types';
3
+ export declare function useFocusTrap(containerRef: React.RefObject<HTMLElement | null>, isActive: boolean, options?: {
4
+ onEscape?: () => void;
5
+ focusTargetRef?: React.RefObject<HTMLElement | null> | undefined;
6
+ }): void;
7
+ export declare function useResize(settingsWidth: string | undefined, settingsHeight: string | undefined, position: WidgetPosition, config: MarketrixConfig, isPreviewMode: boolean): {
8
+ widthPx: string;
9
+ heightPx: string;
10
+ grip: {
11
+ vertical: "top" | "bottom";
12
+ horizontal: "left" | "right";
13
+ growX: number;
14
+ growY: number;
15
+ cursor: string;
16
+ };
17
+ onResizeStart: (e: React.MouseEvent) => void;
18
+ containerRef: React.RefObject<HTMLDivElement | null>;
19
+ };
2
20
  export declare const MessengerShell: React.FC;
@@ -17,12 +17,50 @@
17
17
  * injected nodes that outlive the task otherwise. `WidgetDialog` gets an explicit `finalFocusRef`
18
18
  * since Base UI's focus restore resolves to the host page inside a closed shadow root otherwise. The
19
19
  * transcript sits under its own `ErrorBoundary` so one unrenderable message can't take the composer down.
20
+ *
21
+ * `useScreenShare` (this file's only other consumer) owns the screen-share lifecycle: the in-transcript
22
+ * permission card, the browser picker, the live share message, and ending a share. `useLatest` keeps a
23
+ * value readable from a callback that must not be re-created (the polling interval below, mounted once).
24
+ * The hook returns `requestScreenAccess` — posting a request card carrying the queued turn, no-oping if
25
+ * one is already open — plus that card's Allow/Deny handlers, the toolbar dialog's Allow/Dismiss
26
+ * handlers, and `toggleScreenShareRef`, a toggle stopping a live share or opening that dialog.
27
+ * `beginScreenShare` opens the stream and posts the started/live messages; `stopScreenSharing`/
28
+ * `announceStopped` tear it down (video message → a system line); `resolveAccessRequest` stamps
29
+ * allowed/denied; `flushPendingMessage` sends the hold. The user can end the share from the browser's
30
+ * own UI, which fires no subscribable event, so a 1s interval reconciles `isScreenSharingActive()`
31
+ * against local state and announces the stop. `openRequest` is transcript-derived, not component state,
32
+ * since the request card survives an unmount/remount because it is persisted — the resolving state must
33
+ * be too, or the buttons stay live on a request neither Allow nor Deny can reach. Every outcome flushes
34
+ * the pending content (a cancel resolves `denied` like a real failure), leaving no queued turn stranded.
35
+ * `useScreenShare` is exported so `ChatView.test.tsx`'s `renderHook` cases can drive it directly.
20
36
  */
21
37
  import React from 'react';
38
+ import type { InstructionType } from '../../sdk';
39
+ import type { ChatMessage } from '../../types';
22
40
  interface ChatViewProps {
23
41
  onScreenSharingChange: (isSharing: boolean) => void;
24
42
  toggleScreenShareRef: React.MutableRefObject<(() => void) | null>;
25
43
  messageInputRef: React.RefObject<HTMLTextAreaElement | null>;
26
44
  }
45
+ export interface UseScreenShareOptions {
46
+ onScreenSharingChange?: (isSharing: boolean) => void;
47
+ toggleScreenShareRef?: React.MutableRefObject<(() => void) | null>;
48
+ onAddMessage: (message: ChatMessage) => void;
49
+ onUpdateMessage: (messageId: string, updates: Partial<ChatMessage>) => void;
50
+ onRemoveMessage?: (messageId: string) => void;
51
+ onSendMessage: (message: string, mode?: InstructionType, skipUserMessage?: boolean) => void;
52
+ messages: ChatMessage[];
53
+ }
54
+ interface UseScreenShareReturn {
55
+ isScreenSharing: boolean;
56
+ isAwaitingScreenAccess: boolean;
57
+ showScreenAccessDialog: boolean;
58
+ handleScreenAccessDialogAllow: () => Promise<void>;
59
+ handleScreenAccessDialogDismiss: () => void;
60
+ handleScreenAccessRequestAllow: () => Promise<void>;
61
+ handleScreenAccessRequestDeny: () => void;
62
+ requestScreenAccess: (mode: InstructionType, content: string) => void;
63
+ }
64
+ export declare function useScreenShare({ onScreenSharingChange, toggleScreenShareRef, onAddMessage, onUpdateMessage, onRemoveMessage, onSendMessage, messages, }: UseScreenShareOptions): UseScreenShareReturn;
27
65
  export declare const ChatView: React.FC<ChatViewProps>;
28
66
  export {};
@@ -1,3 +1,32 @@
1
+ /**
2
+ * Cross-domain wire primitives shared by every audience — this file is mirrored WHOLE into the widget
3
+ * closure, so any shape it exports republishes the widget SDK regardless of which audience actually
4
+ * reads it.
5
+ * - `unionOfRecord` builds a plain (non-discriminated) union of every variant in a
6
+ * `{ <discriminant value>: ZodType }` map — the shape `TriggerSourceConfigSchemas`/
7
+ * `WorkflowActionTargetConfigSchemas` are declared in, and the registry (`models/columnSchemas.ts`)
8
+ * keys by the same discriminant separately. Typed off the map's own value type rather than a bare
9
+ * `z.ZodType`, whose inferred output is `unknown` and would erase every variant's real shape from the
10
+ * union.
11
+ * - `ToolCallRecordSchema.params`/`.result` stay `z.record(z.string(), z.unknown())` ON PURPOSE —
12
+ * `models/columnSchemas.ts`'s header lists a tool call's own arguments and result as one of the few
13
+ * open boundaries kept opaque deliberately, since a tool's shape varies per tool name with no closed
14
+ * vocabulary this file (or the widget/app readers of `simulation_step.tool_calls`) can type against.
15
+ * - `SessionStateSchema` is `simulation.session_state` (Browserbase cookies + localStorage snapshot).
16
+ * Lives here rather than `models/columnSchemas.ts`, which imports FROM
17
+ * `contracts/foundationEntities.ts` — a leaf-shaped schema this file already is one, so
18
+ * `contracts/foundationEntities.ts` can type `SimulationEntitySchema`'s own `session_state` field
19
+ * with it without cycling back through `columnSchemas.ts`. Its `cookies` field is the other
20
+ * deliberately-open boundary from that same registry header: a browser cookie as the browser itself
21
+ * reports it, no closed shape to narrow to.
22
+ * - `GraphNodeSummarySchema` is the whole-graph tier — `applicationGraphGet`/`simulationGraphGet` load
23
+ * nodes with `readGraph`, which always resolves sections to `[]` for speed; a node's real sections
24
+ * are a lazy drill-in fetched one at a time by `graphNodeSectionsGet` (its own
25
+ * `GraphSectionSchema`-shaped output), so this tier never carries them. `sequence_ids` is DROPPED
26
+ * (not just unselected) — the stored `graph.graph_nodes` column stays for the agent's own write-side
27
+ * dedupe, but no app/widget graph or heatmap component ever read the wire field, and this file's
28
+ * widget-closure membership means dropping it republishes the widget.
29
+ */
1
30
  import { z } from 'zod';
2
31
  export declare const EntityStatusSchema: z.ZodEnum<{
3
32
  created: "created";
@@ -19,24 +19,9 @@
19
19
  * protocol, an unparseable string being exactly a value that is not a URL.
20
20
  */
21
21
  import type { InstructionType } from '../types';
22
- export interface TextData {
22
+ interface TextData {
23
23
  text: string;
24
24
  }
25
- export interface ExtractData {
26
- title: string;
27
- url: string;
28
- text: string;
29
- links: Array<{
30
- text: string;
31
- href: string | null;
32
- }>;
33
- }
34
- export interface DropdownOptionsData {
35
- options: Array<{
36
- value: string;
37
- text: string;
38
- }>;
39
- }
40
25
  type ToolFailure = {
41
26
  success: false;
42
27
  error: string;
package/dist/widget.mjs CHANGED
@@ -18,7 +18,7 @@ return v(ys,{toast:e,className:"mtx-toast",render:/* @__PURE__ */b(rc,{align:"ce
18
18
  /* @__PURE__ */v(oc,{grow:!0,minWidth:"0",children:[/* @__PURE__ */b(Is,{render:/* @__PURE__ */b(pc,{as:"span",block:!0,inheritColor:!0,truncate:!0,weight:"medium",style:{fontSize:"13px",color:t.titleColor,...e.actionProps&&{whiteSpace:"normal"}}})}),null!=e.description&&/* @__PURE__ */b(Es,{render:/* @__PURE__ */b(pc,{as:"span",block:!0,inheritColor:!0,truncate:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8}})})]}),e.actionProps&&/* @__PURE__ */b(Ds,{render:/* @__PURE__ */b(Ja,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
19
19
  /* @__PURE__ */b(_s,{onMouseDown:e=>e.preventDefault(),render:/* @__PURE__ */b(cc,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b(ac,{name:"closeSmall",size:12})})]},e.id)})},fc=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(Ai,{children:[e,/* @__PURE__ */b(qs,{container:t??void 0,children:/* @__PURE__ */b(ts,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(hc,{})})})]}),mc=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Oa();return a(()=>{null!=e?s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}):c("error")},[e,n,s,c,t]),a(()=>{r?s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}):c("greeting")},[r,o,s,c,i]),null},gc=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function yc(e){return Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!function(e){for(let t=e;t;t=t.parentElement)if("true"===t.getAttribute("aria-hidden"))return!0;return!1}(e))}function*bc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function vc(e){if(!(e instanceof Element))return!1;try{const t=e.tagName.toLowerCase();if(!("button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||gc.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0))return!1;const n=window.getComputedStyle(e);if("none"===n.display||"none"===n.pointerEvents)return!1;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;for(const o of bc(e))if(o!==e){const e=window.getComputedStyle(o).overflow;if("hidden"===e||"clip"===e){const e=o.getBoundingClientRect();if(r.right<e.left||r.left>e.right||r.bottom<e.top||r.top>e.bottom)return!1}if(o===document.body)break}for(let o=e.getRootNode();o instanceof ShadowRoot;o=o.host.getRootNode()){const e=o.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(t){return console.error("[isIndexable] Unexpected error:",t),!1}}var wc=["id","type","role","aria-label","name","href"],xc=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateAnchoredSelector(e){const t=[];let n=e;for(;n!==document.body;){const e=n.id?`#${CSS.escape(n.id)}`:"";if(e&&1===document.querySelectorAll(e).length)return t.unshift(e),t.join(" > ");const r=n.parentElement;if(!r)break;const o=n.tagName,i=Array.from(r.children).filter(e=>e.tagName===o),s=i.length>1?`:nth-of-type(${i.indexOf(n)+1})`:"";t.unshift(o.toLowerCase()+s),n=r}return["body",...t].join(" > ")}indexElements(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap;const e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{if(e instanceof HTMLElement&&null===e.offsetParent&&"BODY"!==e.tagName){const t=window.getComputedStyle(e),n="fixed"===t.position||"sticky"===t.position;if("none"===t.display)return NodeFilter.FILTER_REJECT;if(!n){let t=e.parentElement,n=!1;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if("fixed"===e.position||"sticky"===e.position){n=!0;break}t=t.parentElement}if(!n)return NodeFilter.FILTER_REJECT}}return NodeFilter.FILTER_ACCEPT}});let t=e.nextNode(),n=0;for(;t;){const r=t instanceof HTMLElement?t:null;if(r){const e=r.matches('a[href], button, input, textarea, select, [role="button"]'),t=r.classList.contains("cursor-pointer")||r.classList.contains("clickable"),o="function"==typeof r.onclick;(e||t||o||vc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:wc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{e.querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){console.warn(`[DomService] Failed to tag index ${n}:`,t)}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}notInteractableReason(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=function(e){if(!0===e.disabled)return"is a disabled control";if("true"===e.getAttribute("aria-disabled"))return"is aria-disabled";for(const t of bc(e))if(t.hasAttribute("inert"))return"is inside an inert subtree";return null}(e);if(n)return`ELEMENT_NOT_INTERACTABLE: Element ${t} ${n}`;const r=window.getComputedStyle(e);if("none"===r.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===r.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(r.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const o=e.getBoundingClientRect();if(0===o.width||0===o.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;const i=o.left+o.width/2,s=o.top+o.height/2,a=document.elementFromPoint(i,s);if(a&&a!==e&&!e.contains(a)&&!a.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=a.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${a.className?`${e}.${a.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}getValidatedElement(e){const t=this.index.get(e);if(!t)return{element:null,error:`Element ${e} not found`};const n=!document.contains(t.element),r=wc.some((e,n)=>t.element.getAttribute(e)!==t.identity[n]);if(n||r)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n?"no longer exists":"has changed"}. Call get_html to get updated indices.`};const o=this.notInteractableReason(t.element,e);return o?{element:null,error:o}:{element:t.element}}},Sc=e=>e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement,kc=e=>e instanceof HTMLButtonElement||"button"===e.getAttribute("role");function Cc(e,t){const n=1===t?"ArrowDown":"ArrowUp",r=e.selectedIndex+t;return r<0||r>=e.options.length?`${n}: already at ${1===t?"last":"first"} option`:(e.selectedIndex=r,e.dispatchEvent(new Event("change",{bubbles:!0})),`${n}: selected "${e.options[r]?.text??""}"`)}function Ec(e,t){const n=e.value,r=e.selectionStart??n.length,o=e.selectionEnd??n.length;let i,s;if(r!==o)i=n.slice(0,r)+n.slice(o),s=r;else if("Backspace"===t&&r>0)i=n.slice(0,r-1)+n.slice(o),s=r-1;else{if(!("Delete"===t&&r<n.length))return`${t}: ${"Backspace"===t?"cursor at start":"cursor at end"}, nothing to delete`;i=n.slice(0,r)+n.slice(r+1),s=r}return function(e,t,n){Ic(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}(e,i,s),`${t}: deleted character, value is now "${i}"`}function Ic(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}var Mc=["scroll","resize","touchmove","wheel"],Tc=new class{currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;visibilityCheckInterval=null;async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:o}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===o&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),this.createHighlight(),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.(/* @__PURE__ */new Error("Cancelled by cleanup")),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of Mc)window.removeEventListener(e,this.scrollHandler,{capture:!0});this.scrollHandler=null}this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.currentPopup?.remove(),this.currentHighlight?.remove(),document.getElementById("marketrix-show-popup")?.remove(),document.getElementById("marketrix-show-highlight")?.remove(),this.currentPopup=null,this.currentHighlight=null,this.currentElement=null,this.currentOptions=null,this.currentPromise=null}settle(e){const{resolve:t,reject:n}=this.takeSettlers();e?n?.(new Error(e)):t?.(),this.cleanup()}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}createHighlight(){const e=document.createElement("div");e.id="marketrix-show-highlight",e.style.cssText="position:fixed;border:3px solid #3b82f6;border-radius:4px;box-shadow:0 0 0 4px rgba(59,130,246,0.2),0 0 20px rgba(59,130,246,0.4);z-index:2147483645;pointer-events:none;transition:none;",document.body.appendChild(e),this.currentHighlight=e,this.trackElement()}trackElement(){if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();Object.assign(this.currentHighlight.style,{top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`}),this.updatePopupPosition()}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom:12px;font-weight:500;color:#1f2937;font-size:12px;">${this.escapeHtml(e)}</div><div style="display:flex;gap:8px;justify-content:flex-end;"><button id="marketrix-show-continue" style="background:#3b82f6;color:white;border:none;border-radius:6px;padding:8px 16px;font-size:12px;font-weight:500;cursor:pointer;">Continue</button></div>`,n.style.cssText="position: fixed; width: 320px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;",document.body.appendChild(n),this.currentPopup=n,t||window.requestAnimationFrame(()=>{n.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.settle()})}),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>this.trackElement();for(const e of Mc)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=10,n=e.left+e.width/2,r=e.top+e.height/2,o=[{left:e.right+20,top:r-60},{left:e.left-320-20,top:r-60},{left:n-160,top:e.top-120-20},{left:n-160,top:e.bottom+20}];let i=o[0];for(const s of o)if(s.left>=t&&s.left+320<=window.innerWidth-t&&s.top>=t&&s.top+120<=window.innerHeight-t){i=s;break}this.currentPopup.style.left=`${Math.max(t,Math.min(i.left,window.innerWidth-320-t))}px`,this.currentPopup.style.top=`${Math.max(t,Math.min(i.top,window.innerHeight-120-t))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.settle())},document.addEventListener("click",this.clickHandler,{capture:!0})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{const e=this.currentElement;if(!e)return;const t=e.getBoundingClientRect();if(t.bottom<0||t.top>window.innerHeight||t.right<0||t.left>window.innerWidth)return void this.settle("ELEMENT_OFF_SCREEN: The highlighted element scrolled out of view");const n=xc.getSequenceForElement(e)??-1,r=xc.notInteractableReason(e,n);r&&this.settle(r)},200)}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},Rc=e=>({success:!0,data:{text:e}}),Oc=e=>({success:!0,data:e}),Ac=e=>({success:!1,error:e}),_c=(e,t)=>({success:!0,data:{text:e},afterResponseAttempt:t}),Dc="finish",Pc=new class{tools={navigate:{label:"Navigating",run:e=>this.navigate(e)},search_web:{label:"Searching",run:e=>this.search(e)},click_element:{label:"Clicking element",waitForUser:!0,run:e=>this.clickElement(e)},type_text:{label:"Typing text",waitForUser:!0,run:e=>this.typeText(e)},scroll:{label:"Scrolling",run:e=>this.scroll(e)},scroll_to_text:{label:"Scrolling to text",run:e=>this.scrollToText(e)},extract:{label:"Extracting content",run:e=>this.extract(e)},go_back:{label:"Going back",run:()=>this.goBack()},wait_seconds:{label:"Waiting",run:e=>this.wait(e)},select_dropdown:{label:"Selecting option",waitForUser:!0,run:e=>this.selectDropdownOption(e)},get_dropdown_options:{label:"Reading dropdown options",run:e=>this.getDropdownOptions(e)},send_keys:{label:"Pressing key",waitForUser:!0,run:e=>this.sendKeys(e)},close_tab:{label:"Closing tab",run:()=>this.closeTab()},[Dc]:{label:"Done",run:e=>this.done(e)},get_html:{label:"Reading the page",run:()=>this.getHtml()},get_screenshot:{label:"Taking screenshot",run:()=>this.getScreenshot()}};element(e){if(void 0===e)throw new Error("Index required");const{element:t,error:n}=xc.getValidatedElement(e);if(!t)throw new Error(n||`Element ${e} not found`);return t}selectElement(e){const t=this.element(e);if(!(t instanceof HTMLSelectElement))throw new Error(`Element ${e} is not a select element`);return t}getFriendlyToolName(e){return this.tools[e]?.label??e}isWaitForUserTool(e){return!!this.tools[e]?.waitForUser}async executeTool(e,t,n,r=""){const o=t,i=this.tools[e];try{return"show"===n&&i?.waitForUser&&void 0!==o.index&&await Tc.showToolAction({element:this.element(o.index),explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e}),i?await i.run(o):Ac(`Unknown tool: ${e}`)}catch(s){return Ac(lr(s))}}navigate(e){const t=(e=>{if(!e)return null;try{const t=new URL(e,window.location.href);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}})(e.url);return t?e.new_tab?window.open(t,"_blank")?Rc(`Opened ${t} in new tab`):Ac("The browser blocked opening a new tab"):_c(`Navigating to ${t}`,()=>{window.location.href=t}):Ac("An http(s) URL is required")}search(e){if(!e.query)return Ac("Query is required");const t=e.engine||"duckduckgo",n=encodeURIComponent(e.query);let r=`https://duckduckgo.com/?q=${n}`;return"google"===t&&(r=`https://www.google.com/search?q=${n}`),"bing"===t&&(r=`https://www.bing.com/search?q=${n}`),_c(`Searching for "${e.query}" on ${t}`,()=>{window.location.href=r})}async clickElement(e){const t=this.element(e.index);return t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),_c(`Clicking element ${e.index}`,()=>t.click())}typeText(e){if(void 0===e.text)return Ac("Text required");const t=!1!==e.clear,n=this.element(e.index);if(Sc(n))n.focus(),Ic(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return Ac(`Could not insert text into element ${e.index}`)}else"value"in n?(n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))):(n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})));return Rc(`Typed text into element ${e.index}`)}scroll(e){const t=.8*window.innerHeight;switch(e.direction){case"down":window.scrollBy({top:t,behavior:"smooth"});break;case"up":window.scrollBy({top:-t,behavior:"smooth"});break;case"left":window.scrollBy({left:-t,behavior:"smooth"});break;case"right":window.scrollBy({left:t,behavior:"smooth"});break;default:return Ac("Invalid direction")}return Rc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return Ac("Text required");const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text)&&n.parentElement)return n.parentElement.scrollIntoView({behavior:"smooth",block:"center"}),Rc(`Scrolled to "${e.text}"`);return Ac(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return Oc(n)}goBack(){return window.history.length<=1?Ac("No history"):_c("Going back",()=>window.history.back())}async wait({seconds:e}){return void 0===e?Ac("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),Rc(`Waited ${e}s`))}selectDropdownOption(e){if(!e.option)return Ac("Option required");const t=this.selectElement(e.index),n=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return n?(t.value=n.value,t.dispatchEvent(new Event("change",{bubbles:!0})),Rc(`Selected ${e.option}`)):Ac(`Option ${e.option} not found`)}getDropdownOptions(e){const t=Array.from(this.selectElement(e.index).options).map(e=>({value:e.value,text:e.text}));return Oc({options:t})}sendKeys(e){if(!e.keys)return Ac("Keys required");const t=this.element(e.index);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const n=function(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=yc(document),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(kc(e))return e.click(),"Enter: clicked button";if(Sc(e)){const t=e.closest("form");if(t){const e=t.querySelector('button[type="submit"], input[type="submit"]');return e?(e.click(),"Enter: clicked form submit button"):(t.requestSubmit(),"Enter: submitted form")}}return e instanceof HTMLAnchorElement?(e.click(),"Enter: clicked link"):"Enter: dispatched event";case"Escape":return e.blur(),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),"Escape: blurred element and dispatched to document";case" ":case"Space":return e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?(e.click(),`Space: toggled ${e.type}`):kc(e)?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":return e instanceof HTMLSelectElement?Cc(e,1):"ArrowDown: dispatched event";case"ArrowUp":return e instanceof HTMLSelectElement?Cc(e,-1):"ArrowUp: dispatched event";case"Home":return Sc(e)?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(Sc(e)){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":return Sc(e)?Ec(e,"Backspace"):"Backspace: dispatched event";case"Delete":return Sc(e)?Ec(e,"Delete"):"Delete: dispatched event";default:return null}}(t,e.keys);return Rc(n||`Sent keys ${e.keys}`)}closeTab(){return window.close(),window.closed?Rc("Tab closed"):Ac("The browser refused to close a tab this script did not open")}done(e){return Rc(e.message||"Task ended")}getHtml(){return Rc(xc.reindexAndSnapshot())}async getScreenshot(){const e=mr();if(!e)return Ac("The visitor is not sharing their screen.");const t=document.createElement("video");try{t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),await new Promise((e,n)=>{const r=setTimeout(()=>n(/* @__PURE__ */new Error("Screen capture produced no frame")),5e3);t.onloadeddata=()=>{clearTimeout(r),e()},t.onerror=()=>{clearTimeout(r),n(/* @__PURE__ */new Error("Screen capture failed"))}});const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;const r=n.getContext("2d");return r?(r.drawImage(t,0,0),Rc(n.toDataURL("image/jpeg",.75))):Ac("Could not read the shared screen: the browser refused a 2d canvas context.")}finally{t.remove()}}},Nc={show:"Show",tell:"Tell",do:"Do"},Lc=e=>Nc[e];function Fc(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(void 0!==r&&t(r))return n}return-1}function zc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest&&!e.taskStatus,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);const s=Fc(e,e=>"agent"===e.sender&&!!e.taskStatus)+1,a=e.slice(s);for(const c of i){const e=Fc(a,c),t=e>=0?a[e]:void 0;if(t)return{index:s+e,message:t}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var Bc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function $c(e,t,n){const r=t>=0?e.parts[t]:void 0;if(!r)return e;const o=[...e.parts];return o[t]={...r,...n},{...e,parts:o}}var Wc=(e,t)=>e.parts.findIndex(e=>"progress"===e.type&&"in_progress"===e.status&&e.browserToolName===t);function Uc(e,t,n,r={}){return{id:`${e}-${globalThis.crypto.randomUUID()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Hc=(e,t,n="user-message")=>Uc(n,"user",e.trim(),{mode:t}),jc=e=>Uc("agent-message","agent",e.trim()),qc=(e,t)=>Uc(t,"agent",e,{isSystemMessage:!0}),Vc=e=>e.filter(e=>"text"===e.type).map(e=>e.content).join("\n"),Yc=e=>({state:e,effects:[]});function Kc(e,t,n,r,o,i,s){const a=zc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=Wc(e,t),o=r>=0?e.parts[r]:void 0;if(!o)return e;const i=Bc(o.content),s=Bc(n);return $c(e,r,{status:"failed",content:s?`${i} (${s})`:i})}(c,r,s||""):"finish"!==r&&(c="in_progress"===i?function(e,t,n){const r=Bc(n),o=Wc(e,t);return o>=0?$c(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||Pc.getFriendlyToolName(r)):((e,t)=>$c(e,Wc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&Pc.isWaitForUserTool(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Xc=(e,t)=>"running"===e.task.phase?e.task.mode??t:t,Gc=e=>({...e,isPlaceholder:!1}),Jc=e=>"stopped"===e.phase?e:{phase:"idle"};function Zc(e,t,n){const r=zc({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:Xc(e,t)}),o=[...e.messages];return r&&(o[r.index]=Gc(n(r.message))),{messages:o,task:Jc(e.task)}}var Qc={completed:"done",failed:"failed",stopped:"stopped"};function el(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming,a={type:"text",content:r&&s?i.content+n:n,...r&&{streaming:!0}};return s?o[o.length-1]=a:o.push(a),{...e,content:Vc(o),isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var tl=(e,t)=>{const n=[...e.parts,{type:"text",content:t}];return{...e,content:Vc(n),parts:n}},nl=(e,t)=>({...Gc(tl(e,t)),placeholderState:void 0,taskStatus:"failed"});function rl(e,t,n){const r=e.messages.map(e=>e.id===t?nl(e,n):e);return{...e,messages:r}}var ol=n(void 0),il=({children:e})=>{const[t,n]=p({isOpen:!1,activeView:"home",currentMode:"tell"}),r=u(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
20
20
  return b(ol.Provider,{value:{uiState:t,uiActions:r},children:e})},sl=()=>{const e=s(ol);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},al=n(void 0),cl=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=sl(),[o,s]=p(()=>({messages:[],task:{phase:"idle"}})),c=d(o),l=d(n.currentMode);l.current=n.currentMode;const h=d(/* @__PURE__ */new Set),f=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),m=i(e=>{f(t=>({...t,messages:[...t.messages,e]}))},[f]),g=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),y=i(e=>{f(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[f]),v=i(e=>{f(t=>({...t,messages:e}))},[f]),w=i(()=>{f(e=>({...e,messages:[]}))},[f]),x=i(()=>{f(e=>({...e,task:{phase:"idle"}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>`${e.id}:${e.parts.length}`).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>e.split(":")[0]).filter(e=>void 0!==e).map(e=>setTimeout(()=>f(t=>function(e,t){const n=e.messages.find(e=>e.id===t);return n?.isPlaceholder&&"waiting-for-user"!==n.placeholderState?rl(e,t,"This is taking longer than expected. Please try again."):e}(t,e)),12e4));return()=>e.forEach(clearTimeout)},[S,f]);const k=i(async(e,n,r)=>{const o=n??l.current;if(t)return r||m(Hc(e,o)),void m(jc("This is a preview. In production, I'll respond to your messages here."));if(!Fe.getCredentialedConfig())return console.error("Config not loaded or incomplete"),void m(jc("Configuration error: Missing API credentials. Please check your widget settings."));r||m(Hc(e,o));const i=(e=>Uc("temp","agent","",{mode:e,isPlaceholder:!0,placeholderState:"thinking"}))(o);f(e=>function(e,t){return{messages:[...e.messages,t],task:{phase:"idle"}}}(e,i));try{await async function(e,t,n){const r=await ze.getOrCreateChatId(),o={type:`chat/${t}`,request_id:n,content:e};await pr.ready(r),await pr.send(o)}(e,o,i.id)}catch(s){console.error("Failed to send message:",s),f(e=>rl(e,i.id,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=async e=>{const{toolCallId:t,tool:n,args:o,mode:i,explanation:s}=e,a=await Pc.executeTool(n,o,i,s),c=a.success?void 0:a.error;f(e=>function(e,t,n,r,o,i){return{...e,messages:Kc(e.messages,"running"===e.task.phase,Xc(e,o),t,n,r,i)}}(e,n,s,c?"failed":"completed",l.current,c)),c||"finish"!==n||f(e=>function(e,t){return Zc(e,t,e=>({...e,taskStatus:"done",parts:e.parts.filter(e=>"progress"!==e.type)}))}(e,l.current)),await pr.send({type:"tool/response",tool_call_id:t,success:a.success,...a.success&&{data:JSON.stringify(a.data)},error:c}).catch(e=>{console.error("Failed to send tool response:",e),r.setError("Could not report that step back to the assistant — it may stop responding.")}),a.success&&a.afterResponseAttempt?.()},n={onMessage:t=>{if("tool/call"===t.type){const e=t.tool_call_id;if(h.current.has(e))return;h.current.add(e),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500)))}else"task/status"===t.type&&t.status in Qc&&h.current.clear();let n=[];f(e=>{const r=function(e,t,n){switch(t.type){case"tool/call":{if("stopped"===e.task.phase)return Yc(e);const r="running"===e.task.phase?e.task:{phase:"running",mode:t.mode||n},o=t.explanation||"";return{state:{messages:Kc(e.messages,!0,r.mode??n,t.browser_tool,o,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:t.mode||n,explanation:o}]}}case"task/status":{if("running"===t.status)return Yc(e);const r=t.status,o=e=>t.message?tl(e,t.message):e;return{state:Zc(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:Qc[r]})),effects:[]}}case"chat/delta":return{state:el(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:el(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:rl(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return Yc(e)}}(e,t,l.current);return n=r.effects,r.state});for(const o of n)e(o).catch(e=>{console.error("[Widget] Tool call failed:",e),r.setError("Something went wrong running that step. Please try again.")})},onError:e=>{r.setError(e.message),e instanceof dr&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?nl(e,t):e),task:Jc(e.task)}}(t,e.message))}};return pr.addCallbacks(n),()=>{pr.removeCallbacks(n)}},[t,f,r]);const C=i(async()=>{f(e=>function(e,t){return{...Zc(e,t,e=>({...e,taskStatus:"stopped"})),task:{phase:"stopped"}}}(e,l.current)),t||pr.send({type:"chat/stop"}).catch(e=>{console.error("Failed to stop task remotely:",e),r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),E=u(()=>({addMessage:m,updateMessage:g,removeMessage:y,setMessages:v,clearMessages:w,messageDispatch:k}),[m,g,y,v,w,k]),I=u(()=>({resetTask:x,stopTask:C}),[x,C]);/* @__PURE__ */
21
- return b(al.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},ll=()=>{const e=s(al);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},ul=n(null),dl=()=>{const{uiState:e}=sl(),{messages:t}=ll();return a(()=>{const{currentMode:n,isOpen:r}=e;var o;o={messages:t,currentMode:n,isOpen:r},Fe.updateContext({...o,messages:o.messages.map(({videoStream:e,...t})=>{const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screen sharing ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}})})},[t,e]),null},pl=({children:e,previewMode:t})=>{const{uiActions:n}=sl(),{chatActions:r}=ll(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=function(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=Fe.getContext();return{...o,messages:r.map(e=>{const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}})}}();n.applyState(o),r.setMessages(t),i(!0);const s=await ze.getOrCreateChatId();e||pr.connect(s).catch(e=>console.error("Initial stream connection failed:",e))})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[]),/* @__PURE__ */v(y,{children:[e,o&&/* @__PURE__ */b(dl,{})]})},hl=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(il,{children:/* @__PURE__ */b(cl,{previewMode:t,children:/* @__PURE__ */b(pl,{previewMode:t,children:e})})}),fl=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,ml=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function gl(e){const t=fl.exec(e.trim())?.[1];if(t){const[e,n,r]=3===t.length?[t.charAt(0)+t.charAt(0),t.charAt(1)+t.charAt(1),t.charAt(2)+t.charAt(2)]:[t.slice(0,2),t.slice(2,4),t.slice(4,6)];return{r:parseInt(e??"",16),g:parseInt(n??"",16),b:parseInt(r??"",16)}}const n=ml.exec(e.trim());if(!n)return null;const r=Number(n[1]),o=Number(n[2]),i=Number(n[3]);return r>255||o>255||i>255?null:{r:r,g:o,b:i}}function yl(e){const t=gl(e);if(!t)return"#000000";const n=e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4);return.2126*n(t.r/255)+.7152*n(t.g/255)+.0722*n(t.b/255)>.5?"#000000":"#ffffff"}function bl(e,t){const n=gl(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}function vl(e){return e.includes("gradient")?e:`linear-gradient(135deg, ${e} 0%, ${e} 100%)`}var wl={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"},xl=n(null),Sl=()=>{const e=s(xl);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},kl=()=>{const{uiState:e,uiActions:t}=sl(),{messages:n,chatActions:r,taskState:o,taskActions:i}=ll();return{state:u(()=>({...e,messages:n,isTaskRunning:"running"===o.phase,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),actions:u(()=>({...t,...i,...r,clearChatHistory:()=>{r.clearMessages(),i.resetTask(),t.setError(void 0)}}),[t,i,r])}},Cl={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},El=Object.keys(Cl),Il=e=>Cl[e],Ml=e=>{const{vertical:t,horizontal:n}=Il(e);return{[t]:"20px",[n]:"20px"}},Tl={top:"bottom",bottom:"top",left:"right",right:"left"},Rl=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Il(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},Ol=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},Al="cubic-bezier(0.16, 1, 0.3, 1)",_l=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=Sl(),{state:c,actions:u}=kl(),h=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!h&&(c.isAwaitingReply||f),y=!h&&f,w=m?"error":"processing",x=d(null),{isDragging:S,pixelPositionStyle:k,onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,suppressUntilRef:T}=function({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,u]=p({w:56,h:56}),[,h]=p(0),f=d(null),m=d(null),g=d(null),y=d(0),b=d([]),v=d(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>w,[]),t.useEffect(()=>{if(r)return;const e=()=>h(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();u(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,C=Rl(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:C.x,top:C.y}:void 0,I=(e,t=.999)=>e/1e3*t/(1-t),M=()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="",o.current.style.left="",o.current.style.top="")},T=i((e,t)=>{f.current?.();let r=!1;const i=()=>{r=!0,window.clearTimeout(c),t.removeEventListener("transitionend",l),f.current=null},s=()=>{r||(i(),t.style.transition="none",t.style.willChange="",t.style.left="",t.style.top="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))},c=window.setTimeout(s,650),l=e=>{e.target===t&&"left"===e.propertyName&&s()};t.addEventListener("transitionend",l),f.current=i},[n,o]),R=i((t,r,i)=>{if(!o.current||!E)return M(),n(t),void a(!1);w();const s=o.current,l=Rl(e,S,k,c.w,c.h),u=Rl(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${Al}, top 600ms ${Al}`,s.style.left=`${u.x}px`,s.style.top=`${u.y}px`}),T(t,s)},[T,n,E,e,S,k,c.w,c.h,o]),O=e=>{M(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),b.current=[],v.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-v.current>=10&&(v.current=i,b.current=[...b.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=(()=>{const e=b.current;if(e.length<2)return{x:0,y:0};const t=e[0],n=e[e.length-1];if(!t||!n)return{x:0,y:0};const r=n.t-t.t;return r<=0?{x:0,y:0}:{x:(n.x-t.x)/r*1e3,y:(n.y-t.y)/r*1e3}})(),i=I(r.x),s=I(r.y),a={dx:n.lastX+i,dy:n.lastY+s},c=o.current?.getBoundingClientRect(),l=c?((e,t,n,r,o,i)=>{const s=Rl(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,u=1/0;for(const d of El){const e=Rl(d,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<u&&(u=t,l=d)}return l})(a,e,window.innerWidth,window.innerHeight,c.width,c.height):e;return R(l,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}O(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&O(e)},suppressUntilRef:y}}({position:s,onPositionCommit:e,isPreviewMode:n,wrapperRef:x});/* @__PURE__ */
21
+ return b(al.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},ll=()=>{const e=s(al);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},ul=n(null),dl=()=>{const{uiState:e}=sl(),{messages:t}=ll();return a(()=>{const{currentMode:n,isOpen:r}=e;var o;o={messages:t,currentMode:n,isOpen:r},Fe.updateContext({...o,messages:o.messages.map(({videoStream:e,...t})=>{const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screen sharing ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}})})},[t,e]),null},pl=({children:e,previewMode:t})=>{const{uiActions:n}=sl(),{chatActions:r}=ll(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=function(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=Fe.getContext();return{...o,messages:r.map(e=>{const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}})}}();n.applyState(o),r.setMessages(t),i(!0);const s=await ze.getOrCreateChatId();e||pr.connect(s).catch(e=>console.error("Initial stream connection failed:",e))})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[]),/* @__PURE__ */v(y,{children:[e,o&&/* @__PURE__ */b(dl,{})]})},hl=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(il,{children:/* @__PURE__ */b(cl,{previewMode:t,children:/* @__PURE__ */b(pl,{previewMode:t,children:e})})}),fl=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,ml=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function gl(e){const t=fl.exec(e.trim())?.[1];if(t){const[e,n,r]=3===t.length?[t.charAt(0)+t.charAt(0),t.charAt(1)+t.charAt(1),t.charAt(2)+t.charAt(2)]:[t.slice(0,2),t.slice(2,4),t.slice(4,6)];return{r:parseInt(e??"",16),g:parseInt(n??"",16),b:parseInt(r??"",16)}}const n=ml.exec(e.trim());if(!n)return null;const r=Number(n[1]),o=Number(n[2]),i=Number(n[3]);return r>255||o>255||i>255?null:{r:r,g:o,b:i}}function yl(e){const t=gl(e);if(!t)return"#000000";const n=e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4);return.2126*n(t.r/255)+.7152*n(t.g/255)+.0722*n(t.b/255)>.5?"#000000":"#ffffff"}function bl(e,t){const n=gl(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}function vl(e){return e.includes("gradient")?e:`linear-gradient(135deg, ${e} 0%, ${e} 100%)`}var wl={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"},xl=n(null),Sl=()=>{const e=s(xl);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},kl=()=>{const{uiState:e,uiActions:t}=sl(),{messages:n,chatActions:r,taskState:o,taskActions:i}=ll();return{state:u(()=>({...e,messages:n,isTaskRunning:"running"===o.phase,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),actions:u(()=>({...t,...i,...r,clearChatHistory:()=>{r.clearMessages(),i.resetTask(),t.setError(void 0)}}),[t,i,r])}},Cl={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},El=Object.keys(Cl),Il=e=>Cl[e],Ml=e=>{const{vertical:t,horizontal:n}=Il(e);return{[t]:"20px",[n]:"20px"}},Tl={top:"bottom",bottom:"top",left:"right",right:"left"},Rl=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Il(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},Ol=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},Al="cubic-bezier(0.16, 1, 0.3, 1)",_l=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=Sl(),{state:c,actions:u}=kl(),h=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!h&&(c.isAwaitingReply||f),y=!h&&f,w=m?"error":"processing",x=d(null),{isDragging:S,pixelPositionStyle:k,onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,suppressUntilRef:T}=function({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,u]=p({w:56,h:56}),[,h]=p(0),f=d(null),m=d(null),g=d(null),y=d(0),b=d([]),v=d(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>w,[]),t.useEffect(()=>{if(r)return;const e=()=>h(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();u(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,C=Rl(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:C.x,top:C.y}:void 0,I=()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="",o.current.style.left="",o.current.style.top="")},M=i((e,t)=>{f.current?.();let r=!1;const i=()=>{r=!0,window.clearTimeout(c),t.removeEventListener("transitionend",l),f.current=null},s=()=>{r||(i(),t.style.transition="none",t.style.willChange="",t.style.left="",t.style.top="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))},c=window.setTimeout(s,650),l=e=>{e.target===t&&"left"===e.propertyName&&s()};t.addEventListener("transitionend",l),f.current=i},[n,o]),T=i((t,r,i)=>{if(!o.current||!E)return I(),n(t),void a(!1);w();const s=o.current,l=Rl(e,S,k,c.w,c.h),u=Rl(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${Al}, top 600ms ${Al}`,s.style.left=`${u.x}px`,s.style.top=`${u.y}px`}),M(t,s)},[M,n,E,e,S,k,c.w,c.h,o]),R=e=>{I(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),b.current=[],v.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-v.current>=10&&(v.current=i,b.current=[...b.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=function(e,t=.999){if(e.length<2)return{x:0,y:0};const n=e[0],r=e[e.length-1];if(!n||!r)return{x:0,y:0};const o=r.t-n.t;if(o<=0)return{x:0,y:0};const i=e=>e/o*t/(1-t);return{x:i(r.x-n.x),y:i(r.y-n.y)}}(b.current),i={dx:n.lastX+r.x,dy:n.lastY+r.y},s=o.current?.getBoundingClientRect(),a=s?((e,t,n,r,o,i)=>{const s=Rl(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,u=1/0;for(const d of El){const e=Rl(d,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<u&&(u=t,l=d)}return l})(i,e,window.innerWidth,window.innerHeight,s.width,s.height):e;return T(a,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}R(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&R(e)},suppressUntilRef:y}}({position:s,onPositionCommit:e,isPreviewMode:n,wrapperRef:x});/* @__PURE__ */
22
22
  return b(nc,{ref:x,className:"mtx-fab-anchor","data-animated":S?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:h?"none":"auto",...S?k:Ml(s)},children:/* @__PURE__ */v(nc,{className:"mtx-fab","data-open":h?"true":"false",children:[g&&/* @__PURE__ */b(nc,{className:"mtx-fab-glow","data-tone":w,"aria-hidden":!0}),y&&!S&&/* @__PURE__ */b(Ja,{type:"button",variant:"secondary",size:"sm",className:"mtx-fab-stop","data-side":s.includes("left")?"left":"right",onClick:e=>{e.preventDefault(),e.stopPropagation(),u.stopTask()},children:"Stop"}),
23
23
  /* @__PURE__ */b(Ja,{type:"button",variant:"bare",onClick:()=>{Date.now()<T.current||u.toggleWidget()},onDragStart:e=>e.preventDefault(),onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,className:"mtx-fab-trigger",style:{touchAction:"none",cursor:S?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":h?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */b(rc,{className:"mtx-fab-center",children:/* @__PURE__ */v(nc,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:h?o:r,boxShadow:Na.fab},children:[g&&/* @__PURE__ */b("svg",{className:"mtx-fab-ring","data-tone":w,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */b("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:13,ry:13})}),
24
24
  /* @__PURE__ */b(rc,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:h?0:1},"aria-hidden":h,children:/* @__PURE__ */b(Ka,{src:Aa,alt:"",className:"mtx-fab-avatar",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:"12px",border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
@@ -28,37 +28,37 @@ return new Map}function Ll(){/* @__PURE__ */
28
28
  return new Set}function Fl(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function zl(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}var Bl=/*#__PURE__*/e.createContext(void 0);function $l(){const t=e.useContext(Bl);if(void 0===t)throw new Error(Dr(64));return t}var Wl="data-activation-direction",Ul={tabActivationDirection:e=>({[Wl]:e})},Hl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,defaultValue:o=0,onValueChange:i,orientation:s="horizontal",render:a,value:c,style:l,...u}=t,d=void 0!==t.defaultValue,p=e.useRef([]),[h,f]=e.useState(()=>/* @__PURE__ */new Map),[m,g]=function({controlled:t,default:n,name:r,state:o="value"}){const{current:i}=e.useRef(void 0!==t),[s,a]=e.useState(n);return[i&&void 0!==t?t:s,e.useCallback(e=>{i||a(e)},[])]}({controlled:c,default:o,name:"Tabs",state:"value"}),y=void 0!==c,[v,w]=e.useState(()=>/* @__PURE__ */new Map),x=e.useRef(void 0),S=e.useCallback(e=>jl(v,e),[v]),[k,C]=e.useState(()=>({previousValue:m,tabActivationDirection:"none"})),{previousValue:E,tabActivationDirection:I}=k;let M=I,T=!1;E!==m&&(M=ql(E,m,s,v),T=null!=E&&null!=m&&null==S(m));const R=T?E:m,O=E!==R||I!==M;_r(()=>{O&&C({previousValue:R,tabActivationDirection:M})},[R,O,M]);const A=Kr((e,t)=>{t.activationDirection=ql(m,e,s,v),i?.(e,t),t.isCanceled||g(e)}),_=Kr((e,t)=>{i?.(e,Fs(t,void 0,void 0,{activationDirection:"none"}))}),D=Kr((e,t)=>(f(n=>{const r=new Map(n);return r.set(e,t),r}),()=>{f(n=>{if(n.get(e)!==t)return n;const r=new Map(n);return r.delete(e),r})})),P=e.useCallback(e=>h.get(e),[h]),N=e.useCallback(e=>{for(const t of v.values())if(e===t.value)return t.id},[v]),L=e.useMemo(()=>({getTabElementBySelectedValue:S,getTabIdByPanelValue:N,getTabPanelIdByValue:P,onValueChange:A,orientation:s,registerMountedTabPanel:D,setTabMap:w,tabActivationDirection:M,value:m}),[S,N,P,A,s,D,w,M,m]),F=e.useMemo(()=>{for(const e of v.values())if(e.value===m)return e},[v,m]),z=e.useMemo(()=>{for(const e of v.values())if(!e.disabled)return e.value},[v]),B=e.useRef(!d),$=e.useRef(o),W=e.useRef(d),U=e.useRef(!1);_r(()=>{if(y)return;function e(e,t){g(e),C({previousValue:e,tabActivationDirection:"none"}),_(e,t),B.current=!1}if(0===v.size)return void(U.current&&null!==m&&!x.current?.isConnected&&e(null,Ns));U.current=!0,x.current=v.keys().next().value;const t=F?.disabled,n=null==F&&null!==m;if(t||m!==$.current||(W.current=!1),W.current&&t&&m===$.current)return;const r=B.current;if(t||n){const n=z??null;if(m===n)return void(B.current=!1);let o=Ns;return r?o=Ls:t&&(o="disabled"),void e(n,o)}r&&null!=F&&(_(m,Ls),B.current=!1)},[z,y,_,F,g,v,m]);const H=Zi("div",t,{state:{orientation:s,tabActivationDirection:M},ref:n,props:u,stateAttributesMapping:Ul});/*#__PURE__*/
29
29
  return b(Bl.Provider,{value:L,children:/*#__PURE__*/b(Pl,{elementsRef:p,children:H})})});function jl(e,t){for(const[n,r]of e.entries())if(t===r.value)return n;return null}function ql(e,t,n,r){if(null==e||null==t)return"none";const[o,i,s]="horizontal"===n?["left","left","right"]:["top","up","down"],a=jl(r,e),c=jl(r,t);if(null==a||null==c)return a===c||"number"!=typeof e&&"string"!=typeof e||typeof e!=typeof t?"none":t>e?s:i;const l=a.getBoundingClientRect()[o],u=c.getBoundingClientRect()[o];return u<l?i:u>l?s:"none"}function Vl(e){return ws(e,"base-ui")}var Yl="data-composite-item-active";function Kl(t={}){const{guess:n,label:r,metadata:o,textRef:i,index:s}=t,{register:a,unregister:c,subscribeMapChange:l,nextIndexRef:u}=e.useContext(Dl),d=e.useRef(-1),[p,h]=e.useState(null==s&&n?()=>{if(-1===d.current){const e=u.current;u.current+=1,d.current=e}return d.current}:-1),f=s??p,m=e.useRef(null),g=e.useCallback(e=>{const t=m.current;t&&c(t),m.current=e,e&&a(e,{metadata:o??null,index:s??null,label:r,textRef:i})},[s,a,c,o,r,i]);return _r(()=>{if(null==s)return l(e=>{const t=m.current?e.get(m.current)?.index:null;null!=t&&h(t)})},[s,l]),{ref:g,index:f}}var Xl=/*#__PURE__*/e.createContext(void 0),Gl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,disabled:o=!1,render:i,value:s,id:a,nativeButton:c=!0,style:l,...u}=t,{value:d,getTabPanelIdByValue:p,onValueChange:h,orientation:f,tabActivationDirection:m}=$l(),{activateOnFocus:g,registerTabResizeObserverElement:y,tabsListElement:b}=function(){const t=e.useContext(Xl);if(void 0===t)throw new Error(Dr(65));return t}(),{highlightedIndex:v,onHighlightedIndexChange:w}=Ts(),x=Vl(a),S=e.useMemo(()=>({disabled:o,id:x,value:s}),[o,x,s]),{compositeProps:k,compositeRef:C,index:E}=function(t={}){const{highlightItemOnHover:n,highlightedIndex:r,onHighlightedIndexChange:o}=Ts(),{ref:i,index:s}=Kl(t),a=r===s,c=e.useRef(null),l=Ni(i,c);return{compositeProps:{tabIndex:a?0:-1,onFocus(){o(s)},onMouseMove(){const e=c.current;if(!n||!e)return;const t=e.hasAttribute("disabled")||"true"===e.ariaDisabled;a||t||e.focus()}},compositeRef:l,index:s}}({metadata:S}),I=s===d,M=e.useRef(!1),T=e.useRef(null),R=Kr(e=>{T.current?.(),T.current=e?y(e):null});_r(()=>{if(M.current)return void(M.current=!1);if(!(I&&E>-1&&v!==E))return;const e=b;if(null!=e){const t=Do(lo(e));if(t&&Po(e,t))return}o||w(E)},[I,E,v,w,o,b]);const{getButtonProps:O,buttonRef:A}=Os({disabled:o,native:c,focusableWhenDisabled:!0}),_=p(s),D=e.useRef(!1),P=e.useRef(!1);function N(e){h(s,Fs(Ps,e.nativeEvent,void 0,{activationDirection:"none"}))}return Zi("button",t,{state:{disabled:o,active:I,orientation:f,tabActivationDirection:m},ref:[n,A,C,R],props:[k,{role:"tab","aria-controls":_,"aria-selected":I,id:x,onClick:function(e){I||o||N(e)},onFocus:function(e){I||o||!g||D.current&&!P.current||N(e)},onPointerDown:function(e){if(I||o)return;D.current=!0,P.current=0===e.button;const t=lo(e.currentTarget);function n(){D.current=!1,P.current=!1,t.removeEventListener("pointerup",n),t.removeEventListener("pointercancel",n)}t.addEventListener("pointerup",n),t.addEventListener("pointercancel",n)},[Yl]:I?"":void 0,onKeyDownCapture(){M.current=!0}},u,O],stateAttributesMapping:Ul})}),Jl="data-index",Zl={...Ul,...Wo},Ql=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,value:o,render:i,keepMounted:s=!1,style:a,...c}=t,{value:l,getTabIdByPanelValue:u,orientation:d,tabActivationDirection:p,registerMountedTabPanel:h}=$l(),f=Vl(),{ref:m,index:g}=Kl(),y=o===l,{mounted:b,transitionStatus:v,setMounted:w}=va(y),x=!b,S=u(o),k={hidden:x,orientation:d,tabActivationDirection:p,transitionStatus:v},C=e.useRef(null),E=Zi("div",t,{state:k,ref:[n,m,C],props:[{"aria-labelledby":S,hidden:x,id:f,role:"tabpanel",tabIndex:y?0:-1,inert:ns(!y),[Jl]:g},c],stateAttributesMapping:Zl});return as({open:y,ref:C,onComplete(){y||w(!1)}}),_r(()=>{if(null!=f&&(!x||s))return h(o,f)},[x,s,o,f,h]),s||b?E:null}),eu="ArrowUp",tu="ArrowDown",nu="ArrowLeft",ru="ArrowRight",ou=/* @__PURE__ */new Set([eu,tu,nu,ru,"Home","End"]),iu=["Shift","Control","Alt","Meta"];function su(e){return!(!function(e){return ro(e)&&"INPUT"===e.tagName}(e)||null==e.selectionStart)||!(!ro(e)||"TEXTAREA"!==e.tagName)}function au(e,t,n,r){if(!e||!t||!t.scrollTo)return;let o=e.scrollLeft,i=e.scrollTop;const s=e.clientWidth<e.scrollWidth,a=e.clientHeight<e.scrollHeight;if(s&&"vertical"!==r){const r=cu(e,t,"left"),i=lu(e),s=lu(t);"ltr"===n&&(r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight?o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight:r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft&&(o=r-s.scrollMarginLeft-i.scrollPaddingLeft)),"rtl"===n&&(r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft?o=r-s.scrollMarginLeft-i.scrollPaddingLeft:r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight&&(o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight))}if(a&&"horizontal"!==r){const n=cu(e,t,"top"),r=lu(e),o=lu(t);n-o.scrollMarginTop<e.scrollTop+r.scrollPaddingTop?i=n-o.scrollMarginTop-r.scrollPaddingTop:n+t.offsetHeight+o.scrollMarginBottom>e.scrollTop+e.clientHeight-r.scrollPaddingBottom&&(i=n+t.offsetHeight+o.scrollMarginBottom-e.clientHeight+r.scrollPaddingBottom)}e.scrollTo({left:o,top:i,behavior:"auto"})}function cu(e,t,n){const r="left"===n?"offsetLeft":"offsetTop";let o=0;for(;t.offsetParent&&(o+=t[r],t.offsetParent!==e);)t=t.offsetParent;return o}function lu(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}function uu(t){const{render:n,className:r,style:o,refs:i=Mr,props:s=Mr,state:a=Tr,stateAttributesMapping:c,highlightedIndex:l,onHighlightedIndexChange:u,orientation:d,grid:p,loopFocus:h,onLoop:f,enableHomeAndEndKeys:m,onMapChange:g,stopEventPropagation:y=!0,rootRef:v,disabledIndices:w,modifierKeys:x,highlightItemOnHover:S=!1,tag:k="div",...C}=t,E=e.useContext(Ra)?.direction??"ltr",{props:I,highlightedIndex:M,onHighlightedIndexChange:T,elementsRef:R,onMapChange:O,relayKeyboardEvent:A}=function(t){const{loopFocus:n=!0,orientation:r="both",grid:o,onLoop:i,direction:s,highlightedIndex:a,onHighlightedIndexChange:c,rootRef:l,enableHomeAndEndKeys:u=!1,stopEventPropagation:d,disabledIndices:p,modifierKeys:h=Mr}=t,[f,m]=e.useState(0),g=null!=o,y=e.useRef(null),b=Ni(y,l),v=e.useRef([]),w=e.useRef(!1),x=e.useRef(null),S=a??f,k=Kr((e,t=!1)=>{if(x.current=v.current[e]??null,(c??m)(e),t){const t=v.current[e];au(y.current,t,s,r)}}),C=Kr(e=>{if(0===e.size)return;if(w.current){const e=v.current,t=e.indexOf(x.current);if(-1===t){const t=e[S];!t||si(e,S,p)?k(function(e,t){let n=-1;for(let r=0;r<e.length;r+=1){const o=e[r];if(o&&!si(e,r,t)){if(o.hasAttribute("data-composite-item-active"))return r;-1===n&&(n=r)}}return Math.max(n,0)}(e,p)):x.current=t}else t!==S&&k(t);return}w.current=!0;const t=Array.from(e.keys()),n=t.find(e=>e?.hasAttribute("data-composite-item-active"))??null,o=n?e.get(n)?.index??-1:-1;if(-1!==o)k(o);else if(si(t,S,p)){const e=ii(t,{disabledIndices:p});oi(t,e)||k(e)}au(y.current,n,s,r)});_r(()=>{if(null==p||null!=a||!w.current)return;const e=v.current;if(si(e,S,p)){const t=ii(e,{disabledIndices:p});oi(e,t)||k(t)}},[p,a,S,v,k]);const E=Kr((e,t,n)=>i?i(e,t,n,v):n),I=Kr(e=>{const t="Home"===e.key||"End"===e.key;if(!ou.has(e.key)||!u&&t)return;if(function(e,t){for(const n of iu)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}(e,h))return;if(!y.current)return;const a="rtl"===s,c=a?nu:ru,l=a?ru:nu,f="vertical"===r?tu:c,m="vertical"===r?eu:l,b=No(e.nativeEvent);if(null!=b&&su(b)&&null!=(w=b)&&!w.hasAttribute("disabled")&&"true"!==w.getAttribute("aria-disabled")){const t=b.selectionStart,n=b.selectionEnd,r=b.value;if(null==t||e.shiftKey||t!==n)return;if(e.key!==m&&t<r.length)return;if(e.key!==f&&t>0)return}var w;let x=S;const C=function(e,t){return ii(e.current,{disabledIndices:t})}(v,p),I=function(e,t){return ii(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}(v,p);null!=o&&(x=o({disabledIndices:p,elementsRef:v,event:e,highlightedIndex:S,loopFocus:n,maxIndex:I,minIndex:C,onLoop:E,orientation:r,rtl:a}));const M="vertical"!==r&&e.key===c||"horizontal"!==r&&"ArrowDown"===e.key,T="vertical"!==r&&e.key===l||"horizontal"!==r&&"ArrowUp"===e.key;u&&("Home"===e.key?x=C:"End"===e.key&&(x=I)),x===S&&(M||T)&&(n&&x===I&&M?(x=C,i&&(x=i(e,S,x,v))):n&&x===C&&T?(x=I,i&&(x=i(e,S,x,v))):x=ii(v.current,{startingIndex:x,decrement:T,disabledIndices:p})),x===S||oi(v.current,x)||(d&&e.stopPropagation(),(g||t||M||T)&&e.preventDefault(),k(x,!0),queueMicrotask(()=>{v.current[x]?.focus()}))});return{props:{ref:b,onFocus(e){const t=y.current,n=No(e.nativeEvent);t&&null!=n&&su(n)&&n.setSelectionRange(0,n.value.length)},onKeyDown:I},highlightedIndex:S,onHighlightedIndexChange:k,elementsRef:v,onMapChange:C,relayKeyboardEvent:I}}({grid:p,loopFocus:h,onLoop:f,orientation:d,highlightedIndex:l,onHighlightedIndexChange:u,rootRef:v,stopEventPropagation:y,enableHomeAndEndKeys:m,direction:E,disabledIndices:w,modifierKeys:x}),_=Zi(k,t,{state:a,ref:i,props:[I,...s,C],stateAttributesMapping:c}),D=e.useMemo(()=>({highlightedIndex:M,onHighlightedIndexChange:T,highlightItemOnHover:S,relayKeyboardEvent:A}),[M,T,S,A]);/*#__PURE__*/
30
30
  return b(Ms.Provider,{value:D,children:/*#__PURE__*/b(Pl,{elementsRef:R,onMapChange:e=>{g?.(e),O(e)},children:_})})}var du=/*#__PURE__*/e.forwardRef(function(t,n){const{activateOnFocus:r=!1,className:o,loopFocus:i=!0,render:s,style:a,...c}=t,{orientation:l,setTabMap:u,tabActivationDirection:d}=$l(),[p,h]=e.useState(0),[f,m]=e.useState(null),g=e.useRef(/* @__PURE__ */new Set),y=e.useRef(/* @__PURE__ */new Set),v=e.useRef(null);_r(()=>{if("undefined"==typeof ResizeObserver)return;const e=new ResizeObserver(()=>{g.current.forEach(e=>{e()})});return v.current=e,f&&e.observe(f),y.current.forEach(t=>{e.observe(t)}),()=>{e.disconnect(),v.current=null}},[f]);const w=Kr(e=>(g.current.add(e),()=>{g.current.delete(e)})),x=Kr(e=>(y.current.add(e),v.current?.observe(e),()=>{y.current.delete(e),v.current?.unobserve(e)})),S={orientation:l,tabActivationDirection:d},k={"aria-orientation":"vertical"===l?"vertical":void 0,role:"tablist"},C=e.useMemo(()=>({activateOnFocus:r,registerIndicatorUpdateListener:w,registerTabResizeObserverElement:x,tabsListElement:f}),[r,w,x,f]);/*#__PURE__*/
31
- return b(Xl.Provider,{value:C,children:/*#__PURE__*/b(uu,{render:s,className:o,style:a,state:S,refs:[n,m],props:[k,c],stateAttributesMapping:Ul,highlightedIndex:p,enableHomeAndEndKeys:!0,loopFocus:i,orientation:l,onHighlightedIndexChange:h,onMapChange:u,disabledIndices:Mr})})});function pu(e){const t=e.getRootNode();return(t instanceof ShadowRoot?t.activeElement:document.activeElement)??null}function hu({width:e,height:t}){return{width:Math.min(Math.max(e,280),600),height:Math.min(Math.max(t,320),Math.floor(.85*window.innerHeight))}}function fu(e,t){const n=/^\s*(\d+(?:\.\d+)?)px\s*$/.exec(e??"");return n?Number(n[1]):t}function mu({style:e}){/* @__PURE__ */
32
- return v("span",{className:"mtx-live-dot",style:e,children:[/* @__PURE__ */b("span",{className:"mtx-live-dot-ping"}),/* @__PURE__ */b("span",{className:"mtx-live-dot-core"})]})}var gu=({title:e,subtitle:t,onClose:n,controls:r})=>/* @__PURE__ */v(rc,{align:"center",justify:"between",paddingX:"lg",paddingY:"md",border:"bottom",shrink:!1,elevation:"section",children:[/* @__PURE__ */v(rc,{align:"center",gap:"md",minWidth:"0",grow:!0,children:[/* @__PURE__ */b(Ka,{src:Aa,alt:"",size:"md",rounded:"lg",elevation:"card"}),/* @__PURE__ */v(oc,{minWidth:"0",children:[/* @__PURE__ */b(pc,{size:"sm",weight:"semibold",truncate:!0,leading:"tight",children:e}),null!=t&&/* @__PURE__ */b(pc,{as:"p",size:"xs",variant:"muted",truncate:!0,children:t})]})]}),/* @__PURE__ */v(rc,{align:"center",gap:"2xs",shrink:!1,children:[r,/* @__PURE__ */b(cc,{size:"sm",label:"Close",onClick:n,children:/* @__PURE__ */b(ac,{name:"close",size:16})})]})]});function yu(e){const t=d(e);return t.current=e,t}function bu(...e){return t=>{e.forEach(e=>{"function"==typeof e?e(t):e&&(e.current=t)})}}function vu({value:e,onChange:t,onSubmit:n,modes:r=[],activeMode:o,onModeChange:s,disabled:c=!1,taskRunning:l=!1,onStop:u,ref:p}){const h=d(null);a(()=>{const e=h.current;if(!e)return;e.style.height="auto";const{scrollHeight:t}=e;e.style.height=`${Math.min(t,66)}px`,e.style.overflowY=t>66?"auto":"hidden"},[e]);const f=i(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())},[n]),m=Boolean(e.trim())&&!c;/* @__PURE__ */
33
- return v(oc,{background:"card",rounded:"xl",border:!0,overflow:"hidden",className:"mtx-composer",children:[/* @__PURE__ */b("textarea",{ref:bu(h,p),value:e,onChange:e=>t(e.target.value),onKeyDown:f,placeholder:"Ask anything",disabled:c,rows:1,className:"mtx-composer-input",style:{lineHeight:"20px",paddingTop:"4px",paddingBottom:"2px",minHeight:"unset"}}),/* @__PURE__ */v(rc,{align:"center",justify:"between",paddingX:"sm",paddingTop:"xs",paddingBottom:"sm",children:[/* @__PURE__ */b(rc,{align:"center",gap:"xs",children:r.map(e=>{const t=o===e.id;/* @__PURE__ */
34
- return v("button",{type:"button",className:"mtx-mode-chip","data-active":t?"true":"false",onClick:t=>{t.preventDefault(),t.stopPropagation(),s?.(e.id)},children:[/* @__PURE__ */b(ac,{name:e.icon,size:12}),/* @__PURE__ */b(pc,{as:"span",inheritColor:!0,children:e.label})]},e.id)})}),/* @__PURE__ */b(cc,{variant:l?"secondary":"primary",size:"sm",disabled:!l&&!m,label:l?"Stop the assistant":"Send message",onClick:e=>{e.preventDefault(),e.stopPropagation(),l&&u?u():n()},children:/* @__PURE__ */b(ac,l?{name:"stop",size:14}:{name:"send",size:16})})]})]})}var wu=/*#__PURE__*/e.createContext(void 0);function xu(t){const n=e.useContext(wu);if(!t&&void 0===n)throw new Error(Dr(27));return n}var Su=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,forceRender:i=!1,...s}=e,a=xu(),c=a.useState("open"),l=a.useState("nested"),u=a.useState("mounted");return Zi("div",e,{state:{open:c,transitionStatus:a.useState("transitionStatus")},ref:[a.context.backdropRef,t],stateAttributesMapping:Xo,props:[{role:"presentation",hidden:!u,style:{userSelect:"none",WebkitUserSelect:"none"}},s],enabled:i||!l})}),ku=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=xu(),c=Vl(i);return a.useSyncedValueWithCleanup("descriptionElementId",c),Zi("p",e,{ref:t,props:[{id:c},s]})}),Cu=/*#__PURE__*/e.createContext(void 0),Eu="--nested-dialogs",Iu="data-nested-dialog-open",Mu={...Ko,...Wo,nestedDialogOpen:e=>e?{[Iu]:""}:null},Tu=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,finalFocus:s,initialFocus:a,...c}=t,l=xu(),u=l.useState("descriptionElementId"),d=l.useState("disablePointerDismissal"),p=l.useState("floatingRootContext"),h=l.useState("popupProps"),f=l.useState("modal"),m=l.useState("mounted"),g=l.useState("nested"),y=l.useState("nestedOpenDialogCount"),v=l.useState("open"),w=l.useState("openMethod"),x=l.useState("titleElementId"),S=l.useState("transitionStatus"),k=l.useState("role"),C=p.useState("floatingId");!function(){if(void 0===e.useContext(Cu))throw new Error(Dr(26))}(),as({open:v,ref:l.context.popupRef,onComplete(){v&&l.context.onOpenChangeComplete?.(!0)}});const E=void 0===a?(I=l.context.popupRef,e=>"touch"!==e||I.current):a;var I;const M=y>0,T=l.useStateSetter("popupElement"),R=Zi("div",t,{state:{open:v,nested:g,transitionStatus:S,nestedDialogOpen:M},props:[h,{id:C,"aria-labelledby":x,"aria-describedby":u,role:k,...wa,hidden:!m,onKeyDown(e){ou.has(e.key)&&e.stopPropagation()},style:{[Eu]:y}},c],ref:[n,l.context.popupRef,T],stateAttributesMapping:Mu});/*#__PURE__*/
35
- return b(ma,{context:p,openInteractionType:w,disabled:!m,closeOnFocusOut:!d,initialFocus:E,returnFocus:s,modal:!1!==f,restoreFocus:"popup",children:R})}),Ru=/*#__PURE__*/e.forwardRef(function(e,t){const{cutout:n,...r}=e;let o;if(n){const e=n.getBoundingClientRect();o=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${e.left}px ${e.top}px,${e.left}px ${e.bottom}px,${e.right}px ${e.bottom}px,${e.right}px ${e.top}px,${e.left}px ${e.top}px)`}/*#__PURE__*/
36
- return b("div",{ref:t,role:"presentation","data-base-ui-inert":"",...r,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})}),Ou=/*#__PURE__*/e.forwardRef(function(e,t){const{keepMounted:n=!1,...r}=e,o=xu(),i=o.useState("mounted"),s=o.useState("modal"),a=o.useState("open");return i||n?/*#__PURE__*/b(Cu.Provider,{value:n,children:/*#__PURE__*/v(Hs,{ref:t,...r,children:[i&&!0===s&&/*#__PURE__*/b(Ru,{ref:o.context.internalBackdropRef,inert:ns(!a)}),e.children]})}):null}),Au={},_u={},Du="";function Pu(e,t){return function(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=so(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==o&&"contents"!==o}(e)?e:t}function Nu(e,t,n){return/hidden|clip/.test(e.getComputedStyle(Pu(t,n)).overflowY)}var Lu=new class{lockCount=0;restore=null;timeoutLock=go.create();timeoutUnlock=go.create();acquire(e){return this.lockCount+=1,1===this.lockCount&&null===this.restore&&this.timeoutLock.start(0,()=>this.lock(e)),this.release}release=()=>{this.lockCount-=1,0===this.lockCount&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{0===this.lockCount&&this.restore&&(this.restore?.(),this.restore=null)};lock(e){if(0===this.lockCount||null!==this.restore)return;const t=lo(e),n=t.documentElement,r=t.body,o=eo(n);if(Nu(o,n,r)){const t=new o.MutationObserver(()=>{Nu(o,n,r)||(t.disconnect(),this.restore=null,this.lock(e))}),i={attributes:!0};return t.observe(n,i),t.observe(r,i),void(this.restore=()=>t.disconnect())}const i=Eo||!function(e){if("undefined"==typeof document)return!1;const t=lo(e);return eo(t).innerWidth-t.documentElement.clientWidth>0}(e);this.restore=i?function(e){const t=lo(e),n=Pu(t.documentElement,t.body),r={overflowY:n.style.overflowY,overflowX:n.style.overflowX};return Object.assign(n.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(n.style,r)}}(e):function(e){const t=lo(e),n=t.documentElement,r=t.body,o=eo(n);let i=0,s=0,a=!1;const c=fo.create();if(Oo&&1!==(o.visualViewport?.scale??1))return()=>{};function l(){const t=o.getComputedStyle(n),c=o.getComputedStyle(r),l=(t.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";i=n.scrollTop,s=n.scrollLeft,Au={scrollbarGutter:n.style.scrollbarGutter,overflowY:n.style.overflowY,overflowX:n.style.overflowX},Du=n.style.scrollBehavior,_u={position:r.style.position,height:r.style.height,width:r.style.width,boxSizing:r.style.boxSizing,overflowY:r.style.overflowY,overflowX:r.style.overflowX,scrollBehavior:r.style.scrollBehavior};const u=n.scrollHeight>n.clientHeight,d=n.scrollWidth>n.clientWidth,p="scroll"===t.overflowY||"scroll"===c.overflowY,h="scroll"===t.overflowX||"scroll"===c.overflowX,f=Math.max(0,o.innerWidth-r.clientWidth),m=Math.max(0,o.innerHeight-r.clientHeight),g=parseFloat(c.marginTop)+parseFloat(c.marginBottom),y=parseFloat(c.marginLeft)+parseFloat(c.marginRight),b=Pu(n,r);if(a=function(e){if("undefined"==typeof CSS||!CSS.supports||!CSS.supports("scrollbar-gutter","stable")||"undefined"==typeof document)return!1;const t=lo(e),n=t.documentElement,r=Pu(n,t.body),o=r.style.overflowY,i=n.style.scrollbarGutter;n.style.scrollbarGutter="stable",r.style.overflowY="scroll";const s=r.offsetWidth;r.style.overflowY="hidden";const a=r.offsetWidth;return r.style.overflowY=o,n.style.scrollbarGutter=i,s===a}(e),a)return n.style.scrollbarGutter=l,b.style.overflowY="hidden",void(b.style.overflowX="hidden");Object.assign(n.style,{scrollbarGutter:l,overflowY:"hidden",overflowX:"hidden"}),(u||p)&&(n.style.overflowY="scroll"),(d||h)&&(n.style.overflowX="scroll"),Object.assign(r.style,{position:"relative",height:g||m?`calc(100dvh - ${g+m}px)`:"100dvh",width:y||f?`calc(100vw - ${y+f}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),r.scrollTop=i,r.scrollLeft=s,n.setAttribute("data-base-ui-scroll-locked",""),n.style.scrollBehavior="unset"}function u(){Object.assign(n.style,Au),Object.assign(r.style,_u),a||(n.scrollTop=i,n.scrollLeft=s,n.removeAttribute("data-base-ui-scroll-locked"),n.style.scrollBehavior=Du)}l();const d=uo(o,"resize",function(){u(),c.request(l)});return()=>{c.cancel(),u(),"function"==typeof o.removeEventListener&&d()}}(e)}};function Fu({store:t,parentContext:n,isDrawer:r}){const o=t.useState("open"),i=t.useState("disablePointerDismissal"),s=t.useState("modal"),a=t.useState("popupElement"),c=t.useState("floatingRootContext"),[l,u]=e.useState(0),[d,p]=e.useState(0),h=0===l,f=function(t,n={}){const{enabled:r=!0,escapeKey:o=!0,outsidePress:i=!0,outsidePressEvent:s="sloppy",referencePress:a=ga,bubbles:c,externalTree:l}=n,u="rootStore"in t?t.rootStore:t,d=u.useState("open"),p=u.useState("floatingElement"),{dataRef:h,events:f}=u.context,m=la(l),g=Kr("function"==typeof i?i:()=>!1),y="function"==typeof i?g:i,b=!1!==y,v=Kr(()=>s),{escapeKey:w,outsidePress:x}={escapeKey:"boolean"==typeof(S=c)?S:S?.escapeKey??!1,outsidePress:"boolean"==typeof S?S:S?.outsidePress??!0};var S;const k=e.useRef(!1),C=e.useRef(!1),E=e.useRef(!1),I=e.useRef(!1),M=e.useRef(!1),T=e.useRef(""),R=e.useRef(null),O=yo(),A=yo(),_=Kr(()=>{A.clear(),h.current.insideReactTree=!1}),D=Kr(e=>{const t=h.current.floatingContext?.nodeId;return(m?ti(m.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),P=Kr(e=>Go(e,u.select("floatingElement"))||Go(e,u.select("domReferenceElement"))),N=Kr(e=>{a()&&u.setOpen(!1,Fs("trigger-press",e.nativeEvent))}),L=Kr(e=>{if(!d||!r||!o||"Escape"!==e.key)return;if(M.current)return;if(!w&&D("__escapeKeyBubbles"))return;const t=Fs("escape-key",function(e){return"nativeEvent"in e}(e)?e.nativeEvent:e);u.setOpen(!1,t),t.isCanceled||e.preventDefault(),w||t.isPropagationAllowed||e.stopPropagation()}),F=Kr(()=>{h.current.insideReactTree=!0,A.start(0,_)}),z=Kr(e=>{if(!d||!r||0!==e.button)return;const t=No(e.nativeEvent);Po(u.select("floatingElement"),t)&&(k.current||(k.current=!0,C.current=!1))}),B=Kr(e=>{d&&r&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&k.current&&(C.current=!0)});e.useEffect(()=>{function e(e){e.open||(I.current=!1)}return f.on("openchange",e),()=>{f.off("openchange",e)}},[f]),e.useEffect(()=>{if(!d||!r)return d||(I.current=!1),_;h.current.__escapeKeyBubbles=w,h.current.__outsidePressBubbles=x;const e=new go,t=new go,n=lo(p);function i(){E.current=!0,t.start(0,()=>{E.current=!1})}function s(){k.current=!1,C.current=!1}function a(){const e=T.current,t="pen"!==e&&e?e:"mouse",n=v(),r="function"==typeof n?n():n;return"string"==typeof r?r:r[t]}function c(e){const t=h.current.floatingContext?.nodeId,n=m&&ti(m.nodesRef.current,t).some(t=>Go(e,t.context?.elements.floating));return P(e)||n}function l(e){if(function(e){const t=a();return"intentional"===t&&"click"!==e.type||"sloppy"===t&&"click"===e.type}(e))return"click"===e.type||P(e)||(t.clear(),E.current=!1),void _();if(h.current.insideReactTree)return void _();const n=No(e),r=`[${zs("inert")}]`,o=no(n)?n.getRootNode():null,i=Array.from((oo(o)?o:lo(u.select("floatingElement"))).querySelectorAll(r)),s=u.context.triggerElements;if(n&&(s.hasElement(n)||s.hasMatchingElement(e=>Po(e,n))))return;let l=no(n)?n:null;for(;l&&!io(l);){const e=ao(l);if(io(e)||!no(e))break;l=e}if(!i.length||!no(n)||n.matches("html,body")||Po(n,u.select("floatingElement"))||!i.every(e=>!Po(l,e))){if(ro(n)&&!("touches"in e)){const t=io(n),r=so(n),o=/auto|scroll/,i=t||o.test(r.overflowX),s=t||o.test(r.overflowY),a=i&&n.clientWidth>0&&n.scrollWidth>n.clientWidth,c=s&&n.clientHeight>0&&n.scrollHeight>n.clientHeight,l="rtl"===r.direction,u=c&&(l?e.offsetX<=n.offsetWidth-n.clientWidth:e.offsetX>n.clientWidth),d=a&&e.offsetY>n.clientHeight;if(u||d)return}if(!c(e)){if("intentional"===a()){if(0!==e.detail&&!ri(e)&&!I.current)return;if(E.current)return t.clear(),void(E.current=!1)}("function"!=typeof y||y(e))&&(D("__outsidePressBubbles")||(u.setOpen(!1,Fs("outside-press",e)),_()))}}}function f(e){if("sloppy"!==a()||!u.select("open")||!r||P(e))return;const t=e.touches[0];t&&(R.current={startTime:Date.now(),startX:t.clientX,startY:t.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},O.start(1e3,()=>{R.current&&(R.current.dismissOnTouchEnd=!1,R.current.dismissOnMouseDown=!1)}))}function g(e,t){const n=No(e);if(!n)return;const r=uo(n,e.type,()=>{t(e),r()})}function S(e){O.clear(),"pointerdown"===e.type&&(0===e.button&&(I.current=!0),T.current=e.pointerType),"mousedown"===e.type&&R.current&&!R.current.dismissOnMouseDown||g(e,e=>{"pointerdown"===e.type?function(e){"sloppy"===a()&&"touch"!==e.pointerType&&u.select("open")&&r&&!P(e)&&l(e)}(e):l(e)})}function A(e){if("pointercancel"===e.type&&(I.current=!1),!k.current)return;const n=C.current;s(),"intentional"===a()&&("pointercancel"!==e.type?c(e)||(n?i():("function"!=typeof y||y(e))&&(t.clear(),E.current=!0,_())):n&&i())}function N(e){if("sloppy"!==a()||!R.current||P(e))return;const t=e.touches[0];if(!t)return;const n=Math.abs(t.clientX-R.current.startX),r=Math.abs(t.clientY-R.current.startY),o=Math.sqrt(n*n+r*r);o>5&&(R.current.dismissOnTouchEnd=!0),o>10&&(l(e),O.clear(),R.current=null)}function F(e){"sloppy"===a()&&R.current&&!P(e)&&(R.current.dismissOnTouchEnd&&l(e),O.clear(),R.current=null)}const z=co(o&&co(uo(n,"keydown",L),uo(n,"compositionstart",function(){e.clear(),M.current=!0}),uo(n,"compositionend",function(){e.start(Oo?5:0,()=>{M.current=!1})})),b&&co(uo(n,"click",S,!0),uo(n,"pointerdown",S,!0),uo(n,"pointerup",A,!0),uo(n,"pointercancel",A,!0),uo(n,"mousedown",S,!0),uo(n,"mouseup",A,!0),uo(n,"touchstart",function(e){T.current="touch",g(e,f)},{capture:!0,passive:!0}),uo(n,"touchmove",function(e){g(e,N)},{capture:!0,passive:!0}),uo(n,"touchend",function(e){g(e,F)},{capture:!0,passive:!0})));return()=>{z(),e.clear(),t.clear(),s(),E.current=!1,_()}},[h,p,o,b,y,d,r,w,x,L,_,v,D,P,m,u,O]);const $=e.useMemo(()=>({onKeyDown:L,onPointerDown:N,onClick:N}),[L,N]),W=e.useMemo(()=>({onKeyDown:L,onPointerDown:B,onMouseDown:B,onClickCapture:F,onMouseDownCapture(e){F(),z(e)},onPointerDownCapture(e){F(),z(e)},onMouseUpCapture:F,onTouchEndCapture:F,onTouchMoveCapture:F}),[L,F,z,B]);return e.useMemo(()=>r?{reference:$,floating:W,trigger:$}:{},[r,$,W])}(c,{outsidePressEvent:()=>t.context.internalBackdropRef.current||t.context.backdropRef.current?"intentional":{mouse:"trap-focus"===s?"sloppy":"intentional",touch:"sloppy"},outsidePress(e){if(!t.context.outsidePressEnabledRef.current)return!1;if("button"in e&&0!==e.button)return!1;if("touches"in e)if("touchend"===e.type){if(1!==e.changedTouches.length||0!==e.touches.length)return!1}else if(1!==e.touches.length)return!1;const n=No(e);if(h&&!i){if(s){const e=t.context.internalBackdropRef.current,r=t.context.backdropRef.current;return!e&&!r||e===n||r===n||Po(n,a)&&!n?.hasAttribute("data-base-ui-portal")}return!0}return!1},escapeKey:h});return function(e=!0,t=null){_r(()=>{if(e)return Lu.acquire(t)},[e,t])}(o&&!0===s,a),t.useContextCallback("onNestedDialogOpen",(e,t)=>{u(e),p(t)}),_r(()=>(n?.onNestedDialogOpen&&(o?n.onNestedDialogOpen(l+1,d+(r?1:0)):n.onNestedDialogOpen(0,0)),()=>{n?.onNestedDialogOpen&&o&&n.onNestedDialogOpen(0,0)}),[r,o,l,d,n]),function(e,t){e.useSyncedValues(t),_r(()=>()=>{e.update({activeTriggerProps:Tr,inactiveTriggerProps:Tr,popupProps:Tr})},[e])}(t,{activeTriggerProps:f.reference,inactiveTriggerProps:f.trigger,popupProps:f.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:d}),null}var zu={...Ta,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role},Bu=class extends Jr{constructor(t,n,r){const o=new Sa,i=function(e,t,n,r=!1){return{...ka(t,n,r),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}(t,o,n,r);super(i,function(t){return{popupRef:/*#__PURE__*/e.createRef(),backdropRef:/*#__PURE__*/e.createRef(),internalBackdropRef:/*#__PURE__*/e.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:t,onOpenChange:void 0,onOpenChangeComplete:void 0}}(o),zu)}setOpen=(e,t)=>{t.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},e||null!=t.trigger||null==this.state.activeTriggerId||(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled||(this.state.floatingRootContext.dispatchOpenChange(e,t),this.update(function(e,t,n,r=!1){let o=e.preventUnmountingOnClose;t?o=!1:r&&(o=!0);const i=n?.id??null;let s=e.activeTriggerId,a=e.activeTriggerElement;return(i||t)&&(s=i,a=n??null),{open:t,preventUnmountingOnClose:o,activeTriggerId:s,activeTriggerElement:a}}(this.state,e,t.trigger)))}};var $u=function(e){const t=(t,n)=>{const r=Ar($r).current;let o;try{Br=r;for(const e of zr)e.before(r);o=e(t);for(const e of zr)e.after(r);r.didInitialize=!0}finally{Br=void 0}return o};return t.displayName=e.displayName||e.name,t}(function(t){return function(t,n){const{children:r,open:o,defaultOpen:i=!1,onOpenChange:s,onOpenChangeComplete:a,disablePointerDismissal:c=!1,modal:l=!0,actionsRef:u,handle:d,triggerId:p,defaultTriggerId:h=null}=n,f="drawer"===t,m="alert-dialog"===t,g=!!m||l,y=m||c,w=m?"alertdialog":"dialog",x=xu(!0),S={modal:g,disablePointerDismissal:y,nested:null!=x,role:w},k=function(t,n=!1){const r=ws(),o=null!=(e.useContext(aa)?.id||null),i=Ar(()=>t(r,o)).current;return function(t){const{popupStore:n,treatPopupAsFloatingElement:r=!1,floatingRootContext:o,floatingId:i,nested:s,onOpenChange:a}=t,c=n.useState("open"),l=n.useState("activeTriggerElement"),u=n.useState(r?"popupElement":"positionerElement"),d=n.context.triggerElements,p=a,h=e.useRef(null);void 0===o&&null===h.current&&(h.current=new ba({open:c,transitionStatus:void 0,referenceElement:l,floatingElement:u,triggerElements:d,onOpenChange:p,floatingId:i,syncOnly:!0,nested:s}));const f=o??h.current;n.useSyncedValue("floatingId",i),_r(()=>{const e={open:c,floatingId:i,referenceElement:l,floatingElement:u};no(l)&&(e.domReferenceElement=l),f.state.positionReference===f.state.referenceElement&&(e.positionReference=l),f.update(e)},[c,i,l,u,f]),f.context.onOpenChange=p,f.context.nested=s}({popupStore:i,treatPopupAsFloatingElement:n,floatingRootContext:i.state.floatingRootContext,floatingId:r,nested:o,onOpenChange:i.setOpen}),i}((e,t)=>new Bu({open:i,openProp:o,activeTriggerId:h,triggerIdProp:p,...S},e,t),!0);k.useControlledProp("openProp",o),k.useControlledProp("triggerIdProp",p),k.useSyncedValues(S),k.useContextCallback("onOpenChange",s),k.useContextCallback("onOpenChangeComplete",a);const C=k.useState("open"),E=k.useState("mounted"),I=k.useState("payload");!function(e,t){_r(()=>{t||null===e.state.openMethod||e.set("openMethod",null)},[t,e]),_r(()=>()=>{null!==e.state.openMethod&&e.set("openMethod",null)},[e])}(k,C),function(t,n={}){const{closeOnActiveTriggerUnmount:r=!1}=n,o=e.useRef(null),i=t.useState("open"),s=t.useState("triggerCount"),a=t.useState("activeTriggerId"),c=t.useState("activeTriggerElement");_r(()=>{if(!i)return o.current=null,void(0!==t.state.triggerCount&&t.set("triggerCount",0));const e=t.context.triggerElements.size,n={};t.state.triggerCount!==e&&(n.triggerCount=e);const s=t.select("activeTriggerId");let a=null;if(s){const e=t.context.triggerElements.getById(s);if(e)o.current=s,e!==t.state.activeTriggerElement&&(n.activeTriggerElement=e);else{for(const[e,r]of t.context.triggerElements.entries())if(r===t.state.activeTriggerElement){n.activeTriggerId=e,n.activeTriggerElement=r,o.current=e;break}void 0===n.activeTriggerId&&(o.current===s?a=s:o.current=null)}}else o.current=null;if(!a&&!s&&1===e){const e=t.context.triggerElements.entries().next();if(!e.done){const[t,r]=e.value;n.activeTriggerId=t,n.activeTriggerElement=r,o.current=t}}void 0===n.triggerCount&&void 0===n.activeTriggerId&&void 0===n.activeTriggerElement||t.update(n),a&&r&&queueMicrotask(()=>{if(t.select("open")&&t.select("activeTriggerId")===a&&!t.context.triggerElements.getById(a)){const e=Fs(Ps);t.setOpen(!1,e),e.isCanceled||t.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,t,s,a,c,r])}(k);const{forceUnmount:M}=function(e,t){const{mounted:n,setMounted:r,transitionStatus:o}=va(e,!1,!1,void 0),i=t.useState("preventUnmountingOnClose"),s=!e&&i;t.useSyncedValues({mounted:n,transitionStatus:o,preventUnmountingOnClose:s});const a=Kr(()=>{r(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),t.context.onOpenChangeComplete?.(!1)});return as({enabled:n&&!e&&!s,open:e,ref:t.context.popupRef,onComplete(){e||a()}}),{forceUnmount:a,transitionStatus:o}}(C,k);e.useImperativeHandle(u,()=>({unmount:M,close:()=>k.setOpen(!1,Fs("imperative-action"))}),[M,k]);const T=C||E;/*#__PURE__*/
37
- return v(wu.Provider,{value:k,children:[d&&/*#__PURE__*/b(xa,{handle:d,store:k}),T&&/*#__PURE__*/b(Fu,{store:k,parentContext:x?.context,isDrawer:f}),"function"==typeof r?r({payload:I}):r]})}("dialog",t)}),Wu=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=xu(),c=Vl(i);return a.useSyncedValueWithCleanup("titleElementId",c),Zi("h2",e,{ref:t,props:[{id:c},s]})}),Uu=({open:e,onClose:t,title:n,description:r,onConfirm:o,confirmLabel:i="Confirm",cancelLabel:a="Cancel",finalFocusRef:c})=>{const l=s(ul)??document.body;/* @__PURE__ */
38
- return b($u,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/* @__PURE__ */v(Ou,{container:l,children:[/* @__PURE__ */b(Su,{className:"mtx-dialog-backdrop",style:{zIndex:La}}),/* @__PURE__ */v(Tu,{className:"mtx-dialog-popup",finalFocus:c,style:{...za("panel"),zIndex:La},children:[
39
- /* @__PURE__ */b(Wu,{className:"mtx-dialog-title",children:n}),null!=r&&/* @__PURE__ */b(ku,{className:"mtx-dialog-description",children:r}),
40
- /* @__PURE__ */b(rc,{gap:"md",justify:"end",children:[["secondary",a,t],["primary",i,()=>o?.()]].map(([e,t,n])=>/* @__PURE__ */b(Ja,{type:"button",variant:e,size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),n()},children:t},e))})]})]})})},Hu={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function ju({size:e="md",style:t,ref:n}){/* @__PURE__ */
41
- return v("div",{ref:n,"data-size":e,role:"status",style:{display:"inline-flex",alignItems:"center",gap:"6px",...t},children:[/* @__PURE__ */b("div",{"aria-hidden":"true",className:"mtx-spinner-ring",style:Hu[e]}),/* @__PURE__ */b("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var qu="8px 8px 0 0",Vu=({label:e,children:t})=>/* @__PURE__ */b(rc,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:qu,zIndex:10},children:/* @__PURE__ */v(rc,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),Yu=({stream:e})=>{const t=d(null),[n,r]=p(!1),[o,i]=p(!1);return a(()=>{const n=t.current;if(!n)return;r(!1),i(!1),n.srcObject=e;const o=()=>{r(!0)},s=()=>{i(!0),r(!1)};return n.addEventListener("loadedmetadata",o),n.addEventListener("error",s),n.play().catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),i(!0))}),()=>{n.removeEventListener("loadedmetadata",o),n.removeEventListener("error",s),n.srcObject=null}},[e]),/* @__PURE__ */v(nc,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:qu,backgroundColor:"#000000",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)"},children:[!n&&!o&&/* @__PURE__ */b(Vu,{label:"Loading stream...",children:/* @__PURE__ */b(ju,{size:"lg",style:{color:"white"}})}),o&&/* @__PURE__ */b(Vu,{label:"Failed to load stream",children:/* @__PURE__ */b(ac,{name:"alertCircle",size:32,style:{color:"#9ca3af"}})}),
42
- /* @__PURE__ */b("video",{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:qu,transition:"opacity 500ms",opacity:n?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),n&&!o&&/* @__PURE__ */v(rc,{position:"absolute",align:"center",gap:"sm",animate:"fadeIn",style:{top:"8px",right:"8px",padding:"4px 8px",borderRadius:"9999px",backgroundColor:"rgba(55,65,81,0.9)",backdropFilter:"blur(4px)",zIndex:20,boxShadow:"0 2px 8px rgba(31, 41, 55, 0.4)"},children:[/* @__PURE__ */b(mu,{style:{color:"white"}}),/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
43
- /* @__PURE__ */b(rc,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:qu,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(nc,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(pc,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]})},Ku={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},Xu=({isWaitingForUser:e})=>/* @__PURE__ */v(rc,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */b(ju,{size:"sm"}),/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),Gu=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=kl().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return 0===e.parts.length?e.isPlaceholder||o?/* @__PURE__ */b(Xu,{isWaitingForUser:r}):/* @__PURE__ */b(nc,{}):/* @__PURE__ */v(oc,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */b(pc,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e.content},`part-${t}`):null:"progress"===e.type?/* @__PURE__ */b(rc,{align:"start",gap:"md",children:/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap"},children:e.content})},`part-${t}`):null),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||o)&&/* @__PURE__ */b(Xu,{isWaitingForUser:r})]})},Ju=({message:e,isLastMessage:t,onScreenAccessAllow:n,onScreenAccessDeny:r})=>{const o=Sl().widget_accent_color;if(e.isSystemMessage)/* @__PURE__ */return b(rc,{justify:"center",align:"center",children:/* @__PURE__ */b(pc,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})});const i="user"===e.sender,s=i?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0,a=!i&&e.taskStatus?Ku[e.taskStatus]:void 0;/* @__PURE__ */
31
+ return b(Xl.Provider,{value:C,children:/*#__PURE__*/b(uu,{render:s,className:o,style:a,state:S,refs:[n,m],props:[k,c],stateAttributesMapping:Ul,highlightedIndex:p,enableHomeAndEndKeys:!0,loopFocus:i,orientation:l,onHighlightedIndexChange:h,onMapChange:u,disabledIndices:Mr})})});function pu({style:e}){/* @__PURE__ */
32
+ return v("span",{className:"mtx-live-dot",style:e,children:[/* @__PURE__ */b("span",{className:"mtx-live-dot-ping"}),/* @__PURE__ */b("span",{className:"mtx-live-dot-core"})]})}var hu=({title:e,subtitle:t,onClose:n,controls:r})=>/* @__PURE__ */v(rc,{align:"center",justify:"between",paddingX:"lg",paddingY:"md",border:"bottom",shrink:!1,elevation:"section",children:[/* @__PURE__ */v(rc,{align:"center",gap:"md",minWidth:"0",grow:!0,children:[/* @__PURE__ */b(Ka,{src:Aa,alt:"",size:"md",rounded:"lg",elevation:"card"}),/* @__PURE__ */v(oc,{minWidth:"0",children:[/* @__PURE__ */b(pc,{size:"sm",weight:"semibold",truncate:!0,leading:"tight",children:e}),null!=t&&/* @__PURE__ */b(pc,{as:"p",size:"xs",variant:"muted",truncate:!0,children:t})]})]}),/* @__PURE__ */v(rc,{align:"center",gap:"2xs",shrink:!1,children:[r,/* @__PURE__ */b(cc,{size:"sm",label:"Close",onClick:n,children:/* @__PURE__ */b(ac,{name:"close",size:16})})]})]});function fu(...e){return t=>{e.forEach(e=>{"function"==typeof e?e(t):e&&(e.current=t)})}}function mu({value:e,onChange:t,onSubmit:n,modes:r=[],activeMode:o,onModeChange:s,disabled:c=!1,taskRunning:l=!1,onStop:u,ref:p}){const h=d(null);a(()=>{const e=h.current;if(!e)return;e.style.height="auto";const{scrollHeight:t}=e;e.style.height=`${Math.min(t,66)}px`,e.style.overflowY=t>66?"auto":"hidden"},[e]);const f=i(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())},[n]),m=Boolean(e.trim())&&!c;/* @__PURE__ */
33
+ return v(oc,{background:"card",rounded:"xl",border:!0,overflow:"hidden",className:"mtx-composer",children:[/* @__PURE__ */b("textarea",{ref:fu(h,p),value:e,onChange:e=>t(e.target.value),onKeyDown:f,placeholder:"Ask anything",disabled:c,rows:1,className:"mtx-composer-input",style:{lineHeight:"20px",paddingTop:"4px",paddingBottom:"2px",minHeight:"unset"}}),/* @__PURE__ */v(rc,{align:"center",justify:"between",paddingX:"sm",paddingTop:"xs",paddingBottom:"sm",children:[/* @__PURE__ */b(rc,{align:"center",gap:"xs",children:r.map(e=>{const t=o===e.id;/* @__PURE__ */
34
+ return v("button",{type:"button",className:"mtx-mode-chip","data-active":t?"true":"false",onClick:t=>{t.preventDefault(),t.stopPropagation(),s?.(e.id)},children:[/* @__PURE__ */b(ac,{name:e.icon,size:12}),/* @__PURE__ */b(pc,{as:"span",inheritColor:!0,children:e.label})]},e.id)})}),/* @__PURE__ */b(cc,{variant:l?"secondary":"primary",size:"sm",disabled:!l&&!m,label:l?"Stop the assistant":"Send message",onClick:e=>{e.preventDefault(),e.stopPropagation(),l&&u?u():n()},children:/* @__PURE__ */b(ac,l?{name:"stop",size:14}:{name:"send",size:16})})]})]})}var gu=/*#__PURE__*/e.createContext(void 0);function yu(t){const n=e.useContext(gu);if(!t&&void 0===n)throw new Error(Dr(27));return n}var bu=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,forceRender:i=!1,...s}=e,a=yu(),c=a.useState("open"),l=a.useState("nested"),u=a.useState("mounted");return Zi("div",e,{state:{open:c,transitionStatus:a.useState("transitionStatus")},ref:[a.context.backdropRef,t],stateAttributesMapping:Xo,props:[{role:"presentation",hidden:!u,style:{userSelect:"none",WebkitUserSelect:"none"}},s],enabled:i||!l})}),vu=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=yu(),c=Vl(i);return a.useSyncedValueWithCleanup("descriptionElementId",c),Zi("p",e,{ref:t,props:[{id:c},s]})}),wu=/*#__PURE__*/e.createContext(void 0),xu="--nested-dialogs",Su="data-nested-dialog-open",ku={...Ko,...Wo,nestedDialogOpen:e=>e?{[Su]:""}:null},Cu=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,finalFocus:s,initialFocus:a,...c}=t,l=yu(),u=l.useState("descriptionElementId"),d=l.useState("disablePointerDismissal"),p=l.useState("floatingRootContext"),h=l.useState("popupProps"),f=l.useState("modal"),m=l.useState("mounted"),g=l.useState("nested"),y=l.useState("nestedOpenDialogCount"),v=l.useState("open"),w=l.useState("openMethod"),x=l.useState("titleElementId"),S=l.useState("transitionStatus"),k=l.useState("role"),C=p.useState("floatingId");!function(){if(void 0===e.useContext(wu))throw new Error(Dr(26))}(),as({open:v,ref:l.context.popupRef,onComplete(){v&&l.context.onOpenChangeComplete?.(!0)}});const E=void 0===a?(I=l.context.popupRef,e=>"touch"!==e||I.current):a;var I;const M=y>0,T=l.useStateSetter("popupElement"),R=Zi("div",t,{state:{open:v,nested:g,transitionStatus:S,nestedDialogOpen:M},props:[h,{id:C,"aria-labelledby":x,"aria-describedby":u,role:k,...wa,hidden:!m,onKeyDown(e){ou.has(e.key)&&e.stopPropagation()},style:{[xu]:y}},c],ref:[n,l.context.popupRef,T],stateAttributesMapping:ku});/*#__PURE__*/
35
+ return b(ma,{context:p,openInteractionType:w,disabled:!m,closeOnFocusOut:!d,initialFocus:E,returnFocus:s,modal:!1!==f,restoreFocus:"popup",children:R})}),Eu=/*#__PURE__*/e.forwardRef(function(e,t){const{cutout:n,...r}=e;let o;if(n){const e=n.getBoundingClientRect();o=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${e.left}px ${e.top}px,${e.left}px ${e.bottom}px,${e.right}px ${e.bottom}px,${e.right}px ${e.top}px,${e.left}px ${e.top}px)`}/*#__PURE__*/
36
+ return b("div",{ref:t,role:"presentation","data-base-ui-inert":"",...r,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})}),Iu=/*#__PURE__*/e.forwardRef(function(e,t){const{keepMounted:n=!1,...r}=e,o=yu(),i=o.useState("mounted"),s=o.useState("modal"),a=o.useState("open");return i||n?/*#__PURE__*/b(wu.Provider,{value:n,children:/*#__PURE__*/v(Hs,{ref:t,...r,children:[i&&!0===s&&/*#__PURE__*/b(Eu,{ref:o.context.internalBackdropRef,inert:ns(!a)}),e.children]})}):null}),Mu={},Tu={},Ru="";function Ou(e,t){return function(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=so(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==o&&"contents"!==o}(e)?e:t}function Au(e,t,n){return/hidden|clip/.test(e.getComputedStyle(Ou(t,n)).overflowY)}var _u=new class{lockCount=0;restore=null;timeoutLock=go.create();timeoutUnlock=go.create();acquire(e){return this.lockCount+=1,1===this.lockCount&&null===this.restore&&this.timeoutLock.start(0,()=>this.lock(e)),this.release}release=()=>{this.lockCount-=1,0===this.lockCount&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{0===this.lockCount&&this.restore&&(this.restore?.(),this.restore=null)};lock(e){if(0===this.lockCount||null!==this.restore)return;const t=lo(e),n=t.documentElement,r=t.body,o=eo(n);if(Au(o,n,r)){const t=new o.MutationObserver(()=>{Au(o,n,r)||(t.disconnect(),this.restore=null,this.lock(e))}),i={attributes:!0};return t.observe(n,i),t.observe(r,i),void(this.restore=()=>t.disconnect())}const i=Eo||!function(e){if("undefined"==typeof document)return!1;const t=lo(e);return eo(t).innerWidth-t.documentElement.clientWidth>0}(e);this.restore=i?function(e){const t=lo(e),n=Ou(t.documentElement,t.body),r={overflowY:n.style.overflowY,overflowX:n.style.overflowX};return Object.assign(n.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(n.style,r)}}(e):function(e){const t=lo(e),n=t.documentElement,r=t.body,o=eo(n);let i=0,s=0,a=!1;const c=fo.create();if(Oo&&1!==(o.visualViewport?.scale??1))return()=>{};function l(){const t=o.getComputedStyle(n),c=o.getComputedStyle(r),l=(t.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";i=n.scrollTop,s=n.scrollLeft,Mu={scrollbarGutter:n.style.scrollbarGutter,overflowY:n.style.overflowY,overflowX:n.style.overflowX},Ru=n.style.scrollBehavior,Tu={position:r.style.position,height:r.style.height,width:r.style.width,boxSizing:r.style.boxSizing,overflowY:r.style.overflowY,overflowX:r.style.overflowX,scrollBehavior:r.style.scrollBehavior};const u=n.scrollHeight>n.clientHeight,d=n.scrollWidth>n.clientWidth,p="scroll"===t.overflowY||"scroll"===c.overflowY,h="scroll"===t.overflowX||"scroll"===c.overflowX,f=Math.max(0,o.innerWidth-r.clientWidth),m=Math.max(0,o.innerHeight-r.clientHeight),g=parseFloat(c.marginTop)+parseFloat(c.marginBottom),y=parseFloat(c.marginLeft)+parseFloat(c.marginRight),b=Ou(n,r);if(a=function(e){if("undefined"==typeof CSS||!CSS.supports||!CSS.supports("scrollbar-gutter","stable")||"undefined"==typeof document)return!1;const t=lo(e),n=t.documentElement,r=Ou(n,t.body),o=r.style.overflowY,i=n.style.scrollbarGutter;n.style.scrollbarGutter="stable",r.style.overflowY="scroll";const s=r.offsetWidth;r.style.overflowY="hidden";const a=r.offsetWidth;return r.style.overflowY=o,n.style.scrollbarGutter=i,s===a}(e),a)return n.style.scrollbarGutter=l,b.style.overflowY="hidden",void(b.style.overflowX="hidden");Object.assign(n.style,{scrollbarGutter:l,overflowY:"hidden",overflowX:"hidden"}),(u||p)&&(n.style.overflowY="scroll"),(d||h)&&(n.style.overflowX="scroll"),Object.assign(r.style,{position:"relative",height:g||m?`calc(100dvh - ${g+m}px)`:"100dvh",width:y||f?`calc(100vw - ${y+f}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),r.scrollTop=i,r.scrollLeft=s,n.setAttribute("data-base-ui-scroll-locked",""),n.style.scrollBehavior="unset"}function u(){Object.assign(n.style,Mu),Object.assign(r.style,Tu),a||(n.scrollTop=i,n.scrollLeft=s,n.removeAttribute("data-base-ui-scroll-locked"),n.style.scrollBehavior=Ru)}l();const d=uo(o,"resize",function(){u(),c.request(l)});return()=>{c.cancel(),u(),"function"==typeof o.removeEventListener&&d()}}(e)}};function Du({store:t,parentContext:n,isDrawer:r}){const o=t.useState("open"),i=t.useState("disablePointerDismissal"),s=t.useState("modal"),a=t.useState("popupElement"),c=t.useState("floatingRootContext"),[l,u]=e.useState(0),[d,p]=e.useState(0),h=0===l,f=function(t,n={}){const{enabled:r=!0,escapeKey:o=!0,outsidePress:i=!0,outsidePressEvent:s="sloppy",referencePress:a=ga,bubbles:c,externalTree:l}=n,u="rootStore"in t?t.rootStore:t,d=u.useState("open"),p=u.useState("floatingElement"),{dataRef:h,events:f}=u.context,m=la(l),g=Kr("function"==typeof i?i:()=>!1),y="function"==typeof i?g:i,b=!1!==y,v=Kr(()=>s),{escapeKey:w,outsidePress:x}={escapeKey:"boolean"==typeof(S=c)?S:S?.escapeKey??!1,outsidePress:"boolean"==typeof S?S:S?.outsidePress??!0};var S;const k=e.useRef(!1),C=e.useRef(!1),E=e.useRef(!1),I=e.useRef(!1),M=e.useRef(!1),T=e.useRef(""),R=e.useRef(null),O=yo(),A=yo(),_=Kr(()=>{A.clear(),h.current.insideReactTree=!1}),D=Kr(e=>{const t=h.current.floatingContext?.nodeId;return(m?ti(m.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),P=Kr(e=>Go(e,u.select("floatingElement"))||Go(e,u.select("domReferenceElement"))),N=Kr(e=>{a()&&u.setOpen(!1,Fs("trigger-press",e.nativeEvent))}),L=Kr(e=>{if(!d||!r||!o||"Escape"!==e.key)return;if(M.current)return;if(!w&&D("__escapeKeyBubbles"))return;const t=Fs("escape-key",function(e){return"nativeEvent"in e}(e)?e.nativeEvent:e);u.setOpen(!1,t),t.isCanceled||e.preventDefault(),w||t.isPropagationAllowed||e.stopPropagation()}),F=Kr(()=>{h.current.insideReactTree=!0,A.start(0,_)}),z=Kr(e=>{if(!d||!r||0!==e.button)return;const t=No(e.nativeEvent);Po(u.select("floatingElement"),t)&&(k.current||(k.current=!0,C.current=!1))}),B=Kr(e=>{d&&r&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&k.current&&(C.current=!0)});e.useEffect(()=>{function e(e){e.open||(I.current=!1)}return f.on("openchange",e),()=>{f.off("openchange",e)}},[f]),e.useEffect(()=>{if(!d||!r)return d||(I.current=!1),_;h.current.__escapeKeyBubbles=w,h.current.__outsidePressBubbles=x;const e=new go,t=new go,n=lo(p);function i(){E.current=!0,t.start(0,()=>{E.current=!1})}function s(){k.current=!1,C.current=!1}function a(){const e=T.current,t="pen"!==e&&e?e:"mouse",n=v(),r="function"==typeof n?n():n;return"string"==typeof r?r:r[t]}function c(e){const t=h.current.floatingContext?.nodeId,n=m&&ti(m.nodesRef.current,t).some(t=>Go(e,t.context?.elements.floating));return P(e)||n}function l(e){if(function(e){const t=a();return"intentional"===t&&"click"!==e.type||"sloppy"===t&&"click"===e.type}(e))return"click"===e.type||P(e)||(t.clear(),E.current=!1),void _();if(h.current.insideReactTree)return void _();const n=No(e),r=`[${zs("inert")}]`,o=no(n)?n.getRootNode():null,i=Array.from((oo(o)?o:lo(u.select("floatingElement"))).querySelectorAll(r)),s=u.context.triggerElements;if(n&&(s.hasElement(n)||s.hasMatchingElement(e=>Po(e,n))))return;let l=no(n)?n:null;for(;l&&!io(l);){const e=ao(l);if(io(e)||!no(e))break;l=e}if(!i.length||!no(n)||n.matches("html,body")||Po(n,u.select("floatingElement"))||!i.every(e=>!Po(l,e))){if(ro(n)&&!("touches"in e)){const t=io(n),r=so(n),o=/auto|scroll/,i=t||o.test(r.overflowX),s=t||o.test(r.overflowY),a=i&&n.clientWidth>0&&n.scrollWidth>n.clientWidth,c=s&&n.clientHeight>0&&n.scrollHeight>n.clientHeight,l="rtl"===r.direction,u=c&&(l?e.offsetX<=n.offsetWidth-n.clientWidth:e.offsetX>n.clientWidth),d=a&&e.offsetY>n.clientHeight;if(u||d)return}if(!c(e)){if("intentional"===a()){if(0!==e.detail&&!ri(e)&&!I.current)return;if(E.current)return t.clear(),void(E.current=!1)}("function"!=typeof y||y(e))&&(D("__outsidePressBubbles")||(u.setOpen(!1,Fs("outside-press",e)),_()))}}}function f(e){if("sloppy"!==a()||!u.select("open")||!r||P(e))return;const t=e.touches[0];t&&(R.current={startTime:Date.now(),startX:t.clientX,startY:t.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},O.start(1e3,()=>{R.current&&(R.current.dismissOnTouchEnd=!1,R.current.dismissOnMouseDown=!1)}))}function g(e,t){const n=No(e);if(!n)return;const r=uo(n,e.type,()=>{t(e),r()})}function S(e){O.clear(),"pointerdown"===e.type&&(0===e.button&&(I.current=!0),T.current=e.pointerType),"mousedown"===e.type&&R.current&&!R.current.dismissOnMouseDown||g(e,e=>{"pointerdown"===e.type?function(e){"sloppy"===a()&&"touch"!==e.pointerType&&u.select("open")&&r&&!P(e)&&l(e)}(e):l(e)})}function A(e){if("pointercancel"===e.type&&(I.current=!1),!k.current)return;const n=C.current;s(),"intentional"===a()&&("pointercancel"!==e.type?c(e)||(n?i():("function"!=typeof y||y(e))&&(t.clear(),E.current=!0,_())):n&&i())}function N(e){if("sloppy"!==a()||!R.current||P(e))return;const t=e.touches[0];if(!t)return;const n=Math.abs(t.clientX-R.current.startX),r=Math.abs(t.clientY-R.current.startY),o=Math.sqrt(n*n+r*r);o>5&&(R.current.dismissOnTouchEnd=!0),o>10&&(l(e),O.clear(),R.current=null)}function F(e){"sloppy"===a()&&R.current&&!P(e)&&(R.current.dismissOnTouchEnd&&l(e),O.clear(),R.current=null)}const z=co(o&&co(uo(n,"keydown",L),uo(n,"compositionstart",function(){e.clear(),M.current=!0}),uo(n,"compositionend",function(){e.start(Oo?5:0,()=>{M.current=!1})})),b&&co(uo(n,"click",S,!0),uo(n,"pointerdown",S,!0),uo(n,"pointerup",A,!0),uo(n,"pointercancel",A,!0),uo(n,"mousedown",S,!0),uo(n,"mouseup",A,!0),uo(n,"touchstart",function(e){T.current="touch",g(e,f)},{capture:!0,passive:!0}),uo(n,"touchmove",function(e){g(e,N)},{capture:!0,passive:!0}),uo(n,"touchend",function(e){g(e,F)},{capture:!0,passive:!0})));return()=>{z(),e.clear(),t.clear(),s(),E.current=!1,_()}},[h,p,o,b,y,d,r,w,x,L,_,v,D,P,m,u,O]);const $=e.useMemo(()=>({onKeyDown:L,onPointerDown:N,onClick:N}),[L,N]),W=e.useMemo(()=>({onKeyDown:L,onPointerDown:B,onMouseDown:B,onClickCapture:F,onMouseDownCapture(e){F(),z(e)},onPointerDownCapture(e){F(),z(e)},onMouseUpCapture:F,onTouchEndCapture:F,onTouchMoveCapture:F}),[L,F,z,B]);return e.useMemo(()=>r?{reference:$,floating:W,trigger:$}:{},[r,$,W])}(c,{outsidePressEvent:()=>t.context.internalBackdropRef.current||t.context.backdropRef.current?"intentional":{mouse:"trap-focus"===s?"sloppy":"intentional",touch:"sloppy"},outsidePress(e){if(!t.context.outsidePressEnabledRef.current)return!1;if("button"in e&&0!==e.button)return!1;if("touches"in e)if("touchend"===e.type){if(1!==e.changedTouches.length||0!==e.touches.length)return!1}else if(1!==e.touches.length)return!1;const n=No(e);if(h&&!i){if(s){const e=t.context.internalBackdropRef.current,r=t.context.backdropRef.current;return!e&&!r||e===n||r===n||Po(n,a)&&!n?.hasAttribute("data-base-ui-portal")}return!0}return!1},escapeKey:h});return function(e=!0,t=null){_r(()=>{if(e)return _u.acquire(t)},[e,t])}(o&&!0===s,a),t.useContextCallback("onNestedDialogOpen",(e,t)=>{u(e),p(t)}),_r(()=>(n?.onNestedDialogOpen&&(o?n.onNestedDialogOpen(l+1,d+(r?1:0)):n.onNestedDialogOpen(0,0)),()=>{n?.onNestedDialogOpen&&o&&n.onNestedDialogOpen(0,0)}),[r,o,l,d,n]),function(e,t){e.useSyncedValues(t),_r(()=>()=>{e.update({activeTriggerProps:Tr,inactiveTriggerProps:Tr,popupProps:Tr})},[e])}(t,{activeTriggerProps:f.reference,inactiveTriggerProps:f.trigger,popupProps:f.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:d}),null}var Pu={...Ta,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role},Nu=class extends Jr{constructor(t,n,r){const o=new Sa,i=function(e,t,n,r=!1){return{...ka(t,n,r),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}(t,o,n,r);super(i,function(t){return{popupRef:/*#__PURE__*/e.createRef(),backdropRef:/*#__PURE__*/e.createRef(),internalBackdropRef:/*#__PURE__*/e.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:t,onOpenChange:void 0,onOpenChangeComplete:void 0}}(o),Pu)}setOpen=(e,t)=>{t.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},e||null!=t.trigger||null==this.state.activeTriggerId||(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled||(this.state.floatingRootContext.dispatchOpenChange(e,t),this.update(function(e,t,n,r=!1){let o=e.preventUnmountingOnClose;t?o=!1:r&&(o=!0);const i=n?.id??null;let s=e.activeTriggerId,a=e.activeTriggerElement;return(i||t)&&(s=i,a=n??null),{open:t,preventUnmountingOnClose:o,activeTriggerId:s,activeTriggerElement:a}}(this.state,e,t.trigger)))}};var Lu=function(e){const t=(t,n)=>{const r=Ar($r).current;let o;try{Br=r;for(const e of zr)e.before(r);o=e(t);for(const e of zr)e.after(r);r.didInitialize=!0}finally{Br=void 0}return o};return t.displayName=e.displayName||e.name,t}(function(t){return function(t,n){const{children:r,open:o,defaultOpen:i=!1,onOpenChange:s,onOpenChangeComplete:a,disablePointerDismissal:c=!1,modal:l=!0,actionsRef:u,handle:d,triggerId:p,defaultTriggerId:h=null}=n,f="drawer"===t,m="alert-dialog"===t,g=!!m||l,y=m||c,w=m?"alertdialog":"dialog",x=yu(!0),S={modal:g,disablePointerDismissal:y,nested:null!=x,role:w},k=function(t,n=!1){const r=ws(),o=null!=(e.useContext(aa)?.id||null),i=Ar(()=>t(r,o)).current;return function(t){const{popupStore:n,treatPopupAsFloatingElement:r=!1,floatingRootContext:o,floatingId:i,nested:s,onOpenChange:a}=t,c=n.useState("open"),l=n.useState("activeTriggerElement"),u=n.useState(r?"popupElement":"positionerElement"),d=n.context.triggerElements,p=a,h=e.useRef(null);void 0===o&&null===h.current&&(h.current=new ba({open:c,transitionStatus:void 0,referenceElement:l,floatingElement:u,triggerElements:d,onOpenChange:p,floatingId:i,syncOnly:!0,nested:s}));const f=o??h.current;n.useSyncedValue("floatingId",i),_r(()=>{const e={open:c,floatingId:i,referenceElement:l,floatingElement:u};no(l)&&(e.domReferenceElement=l),f.state.positionReference===f.state.referenceElement&&(e.positionReference=l),f.update(e)},[c,i,l,u,f]),f.context.onOpenChange=p,f.context.nested=s}({popupStore:i,treatPopupAsFloatingElement:n,floatingRootContext:i.state.floatingRootContext,floatingId:r,nested:o,onOpenChange:i.setOpen}),i}((e,t)=>new Nu({open:i,openProp:o,activeTriggerId:h,triggerIdProp:p,...S},e,t),!0);k.useControlledProp("openProp",o),k.useControlledProp("triggerIdProp",p),k.useSyncedValues(S),k.useContextCallback("onOpenChange",s),k.useContextCallback("onOpenChangeComplete",a);const C=k.useState("open"),E=k.useState("mounted"),I=k.useState("payload");!function(e,t){_r(()=>{t||null===e.state.openMethod||e.set("openMethod",null)},[t,e]),_r(()=>()=>{null!==e.state.openMethod&&e.set("openMethod",null)},[e])}(k,C),function(t,n={}){const{closeOnActiveTriggerUnmount:r=!1}=n,o=e.useRef(null),i=t.useState("open"),s=t.useState("triggerCount"),a=t.useState("activeTriggerId"),c=t.useState("activeTriggerElement");_r(()=>{if(!i)return o.current=null,void(0!==t.state.triggerCount&&t.set("triggerCount",0));const e=t.context.triggerElements.size,n={};t.state.triggerCount!==e&&(n.triggerCount=e);const s=t.select("activeTriggerId");let a=null;if(s){const e=t.context.triggerElements.getById(s);if(e)o.current=s,e!==t.state.activeTriggerElement&&(n.activeTriggerElement=e);else{for(const[e,r]of t.context.triggerElements.entries())if(r===t.state.activeTriggerElement){n.activeTriggerId=e,n.activeTriggerElement=r,o.current=e;break}void 0===n.activeTriggerId&&(o.current===s?a=s:o.current=null)}}else o.current=null;if(!a&&!s&&1===e){const e=t.context.triggerElements.entries().next();if(!e.done){const[t,r]=e.value;n.activeTriggerId=t,n.activeTriggerElement=r,o.current=t}}void 0===n.triggerCount&&void 0===n.activeTriggerId&&void 0===n.activeTriggerElement||t.update(n),a&&r&&queueMicrotask(()=>{if(t.select("open")&&t.select("activeTriggerId")===a&&!t.context.triggerElements.getById(a)){const e=Fs(Ps);t.setOpen(!1,e),e.isCanceled||t.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,t,s,a,c,r])}(k);const{forceUnmount:M}=function(e,t){const{mounted:n,setMounted:r,transitionStatus:o}=va(e,!1,!1,void 0),i=t.useState("preventUnmountingOnClose"),s=!e&&i;t.useSyncedValues({mounted:n,transitionStatus:o,preventUnmountingOnClose:s});const a=Kr(()=>{r(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),t.context.onOpenChangeComplete?.(!1)});return as({enabled:n&&!e&&!s,open:e,ref:t.context.popupRef,onComplete(){e||a()}}),{forceUnmount:a,transitionStatus:o}}(C,k);e.useImperativeHandle(u,()=>({unmount:M,close:()=>k.setOpen(!1,Fs("imperative-action"))}),[M,k]);const T=C||E;/*#__PURE__*/
37
+ return v(gu.Provider,{value:k,children:[d&&/*#__PURE__*/b(xa,{handle:d,store:k}),T&&/*#__PURE__*/b(Du,{store:k,parentContext:x?.context,isDrawer:f}),"function"==typeof r?r({payload:I}):r]})}("dialog",t)}),Fu=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=yu(),c=Vl(i);return a.useSyncedValueWithCleanup("titleElementId",c),Zi("h2",e,{ref:t,props:[{id:c},s]})}),zu=({open:e,onClose:t,title:n,description:r,onConfirm:o,confirmLabel:i="Confirm",cancelLabel:a="Cancel",finalFocusRef:c})=>{const l=s(ul)??document.body;/* @__PURE__ */
38
+ return b(Lu,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/* @__PURE__ */v(Iu,{container:l,children:[/* @__PURE__ */b(bu,{className:"mtx-dialog-backdrop",style:{zIndex:La}}),/* @__PURE__ */v(Cu,{className:"mtx-dialog-popup",finalFocus:c,style:{...za("panel"),zIndex:La},children:[
39
+ /* @__PURE__ */b(Fu,{className:"mtx-dialog-title",children:n}),null!=r&&/* @__PURE__ */b(vu,{className:"mtx-dialog-description",children:r}),
40
+ /* @__PURE__ */b(rc,{gap:"md",justify:"end",children:[["secondary",a,t],["primary",i,()=>o?.()]].map(([e,t,n])=>/* @__PURE__ */b(Ja,{type:"button",variant:e,size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),n()},children:t},e))})]})]})})},Bu={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function $u({size:e="md",style:t,ref:n}){/* @__PURE__ */
41
+ return v("div",{ref:n,"data-size":e,role:"status",style:{display:"inline-flex",alignItems:"center",gap:"6px",...t},children:[/* @__PURE__ */b("div",{"aria-hidden":"true",className:"mtx-spinner-ring",style:Bu[e]}),/* @__PURE__ */b("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var Wu="8px 8px 0 0",Uu=({label:e,children:t})=>/* @__PURE__ */b(rc,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:Wu,zIndex:10},children:/* @__PURE__ */v(rc,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),Hu=({stream:e})=>{const t=d(null),[n,r]=p(!1),[o,i]=p(!1);return a(()=>{const n=t.current;if(!n)return;r(!1),i(!1),n.srcObject=e;const o=()=>{r(!0)},s=()=>{i(!0),r(!1)};return n.addEventListener("loadedmetadata",o),n.addEventListener("error",s),n.play().catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),i(!0))}),()=>{n.removeEventListener("loadedmetadata",o),n.removeEventListener("error",s),n.srcObject=null}},[e]),/* @__PURE__ */v(nc,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:Wu,backgroundColor:"#000000",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)"},children:[!n&&!o&&/* @__PURE__ */b(Uu,{label:"Loading stream...",children:/* @__PURE__ */b($u,{size:"lg",style:{color:"white"}})}),o&&/* @__PURE__ */b(Uu,{label:"Failed to load stream",children:/* @__PURE__ */b(ac,{name:"alertCircle",size:32,style:{color:"#9ca3af"}})}),
42
+ /* @__PURE__ */b("video",{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:Wu,transition:"opacity 500ms",opacity:n?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),n&&!o&&/* @__PURE__ */v(rc,{position:"absolute",align:"center",gap:"sm",animate:"fadeIn",style:{top:"8px",right:"8px",padding:"4px 8px",borderRadius:"9999px",backgroundColor:"rgba(55,65,81,0.9)",backdropFilter:"blur(4px)",zIndex:20,boxShadow:"0 2px 8px rgba(31, 41, 55, 0.4)"},children:[/* @__PURE__ */b(pu,{style:{color:"white"}}),/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
43
+ /* @__PURE__ */b(rc,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:Wu,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(nc,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(pc,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]})},ju={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},qu=({isWaitingForUser:e})=>/* @__PURE__ */v(rc,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */b($u,{size:"sm"}),/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),Vu=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=kl().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return 0===e.parts.length?e.isPlaceholder||o?/* @__PURE__ */b(qu,{isWaitingForUser:r}):/* @__PURE__ */b(nc,{}):/* @__PURE__ */v(oc,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */b(pc,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e.content},`part-${t}`):null:"progress"===e.type?/* @__PURE__ */b(rc,{align:"start",gap:"md",children:/* @__PURE__ */b(pc,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap"},children:e.content})},`part-${t}`):null),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||o)&&/* @__PURE__ */b(qu,{isWaitingForUser:r})]})},Yu=({message:e,isLastMessage:t,onScreenAccessAllow:n,onScreenAccessDeny:r})=>{const o=Sl().widget_accent_color;if(e.isSystemMessage)/* @__PURE__ */return b(rc,{justify:"center",align:"center",children:/* @__PURE__ */b(pc,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})});const i="user"===e.sender,s=i?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0,a=!i&&e.taskStatus?ju[e.taskStatus]:void 0;/* @__PURE__ */
44
44
  return v(oc,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Assistant says…",animate:t?"fadeIn":void 0,children:[/* @__PURE__ */v(rc,{align:"start",gap:"sm",width:"full",children:[
45
45
  /* @__PURE__ */b(rc,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */b(Ka,{src:"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20viewBox='0%200%20361%20360'%3e%3cdefs%3e%3cstyle%3e%20.st0%20{%20display:%20none;%20fill:%20none;%20stroke:%20%23cdc9c2;%20stroke-width:%201.3px;%20}%20.st1%20{%20fill:%20%23fff;%20}%20.st2,%20.st3%20{%20fill:%20%237cffa6;%20}%20.st3%20{%20stroke:%20%237cffa6;%20stroke-width:%20.38px;%20}%20.st4%20{%20fill:%20%23101828;%20}%20%3c/style%3e%3c/defs%3e%3crect%20class='st4'%20x='.5'%20width='360'%20height='360'/%3e%3cpath%20class='st2'%20d='M83.37,209.58c15.35,0,27.8-12.45,27.8-27.8s-12.44-27.79-27.8-27.79-27.8,12.44-27.8,27.79,12.44,27.8,27.8,27.8Z'/%3e%3cpath%20class='st1'%20d='M85.86,68.28l152.45,223.44h67.29l-70.62-113.77,68.13-109.67h-67.29l-41.12,65.31-41.54-65.31h-67.29Z'/%3e%3cpath%20class='st3'%20d='M176.61,249.83l-35.08-51-57.82,92.71h66.85l26.05-41.7Z'/%3e%3crect%20class='st0'%20x='1.25'%20y='.65'%20width='358.7'%20height='358.7'%20rx='43.35'%20ry='43.35'/%3e%3c/svg%3e",alt:"Marketrix AI",size:20,fit:"cover",rounded:"lg",style:{border:"none",outline:"none",display:"block",backgroundColor:"transparent"}})}),
46
- /* @__PURE__ */v(oc,{grow:!0,position:"relative",rounded:"lg",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:i?"var(--primary)":void 0,color:i?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */b(Yu,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */v(rc,{align:"start",gap:"sm",children:[/* @__PURE__ */b(rc,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */b(ac,{name:s,size:13})}),/* @__PURE__ */b(oc,{grow:!0,children:/* @__PURE__ */b(Gu,{message:e,isLastMessage:t})})]}):/* @__PURE__ */b(Gu,{message:e,isLastMessage:t})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v(rc,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */b(Ja,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>n?.(),children:"Yes"}),/* @__PURE__ */b(Ja,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */b(pc,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"No"}),a&&/* @__PURE__ */b(rc,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */b(ac,{name:a.name,size:14,style:{color:bl(o,a.opacity),flexShrink:0}})})]}),
47
- /* @__PURE__ */b(rc,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */b(pc,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:(c=e.timestamp,(c??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))})]});var c},Zu={boxShadow:Na.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Qu=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=Sl(),{state:o,actions:i}=kl(),{messages:s}=o,{isPreviewMode:c}=r,[l,h]=p(!1),[f,m]=p(!1),g=d(null),y=u(()=>jc(r.widget_body),[r.widget_body]),w=u(()=>[y,...s],[y,s]),x=()=>{if(g.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=g.current;h(e>200);const r=Math.abs(t-e-n)<50;m(!r&&t>n)}};a(()=>{window.requestAnimationFrame(()=>{e.current&&(!c&&e.current.scrollIntoView({behavior:"auto"}),!c&&x())})},[s.length,c]);const S=s[s.length-1]?.content?.length??0;return a(()=>{const t=g.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[S,c,e]),/* @__PURE__ */v(nc,{position:"relative",height:"full",children:[/* @__PURE__ */v(nc,{ref:g,onScroll:x,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:r.widget_background_color.includes("gradient")?"transparent":r.widget_background_color,backgroundImage:vl(r.widget_background_color),scrollbarColor:`${bl(r.widget_border_color,.3)} ${bl(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */b(Ju,{message:e,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */b(rc,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */b(Ja,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */b(pc,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
48
- /* @__PURE__ */b(nc,{ref:e},"scroll-anchor")]},"message-list-container"),[{show:l,edge:{top:"8px"},label:"Scroll to top",icon:"arrowUp",onClick:()=>g.current?.scrollTo({top:0,behavior:"smooth"})},{show:f,edge:{bottom:"8px"},label:"Scroll to bottom",icon:"arrowDown",onClick:()=>!c&&e.current?.scrollIntoView({behavior:"smooth"})}].map(({show:e,edge:t,label:n,icon:o,onClick:i})=>e&&/* @__PURE__ */b(rc,{position:"absolute",justify:"center",style:{...t,left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(cc,{variant:"secondary",size:"sm",label:n,onClick:i,style:Zu,children:/* @__PURE__ */b(ac,{name:o,size:10,style:{color:r.widget_accent_color}})})},n))]})},ed=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],td=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=Sl(),{state:o,actions:i}=kl(),{currentMode:s,isTaskRunning:l,isAwaitingReply:u}=o,[h,f]=p(""),m=d(null),{isScreenSharing:g,isAwaitingScreenAccess:y,showScreenAccessDialog:w,handleScreenAccessDialogAllow:x,handleScreenAccessDialogDismiss:S,handleScreenAccessRequestAllow:k,handleScreenAccessRequestDeny:C,requestScreenAccess:E}=function({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:n,onUpdateMessage:r,onRemoveMessage:o,onSendMessage:i,messages:s}){const[l,u]=p(!1),[d,h]=p(null),[f,m]=p(!1),g=yu(l),y=yu(d),b=yu(e),v=t=>{u(t),e?.(t)},w=e=>{e&&o?.(e),n(qc("Screen sharing stopped","stopped-sharing")),h(null)},x=yu(w);a(()=>{const e=()=>{const e=null!==mr(),t=g.current,n=y.current;e!==t&&(g.current=e,u(e),b.current?.(e)),t&&!e&&n&&x.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[]);const S=s[Fc(s,e=>!!e.isScreenAccessRequest&&!e.screenShareStatus)]??null,k=()=>{S?.pendingContent&&i(S.pendingContent,S.mode,!0)},C=e=>{S&&r(S.id,{screenShareStatus:e})},E=async()=>{try{const e=await async function(){if(!1===Fe.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=mr();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return fr=t,t.getVideoTracks()[0]?.addEventListener("ended",()=>{fr=null}),t}();v(!0),C("allowed"),n(qc("Screen sharing started","started-screenshare"));const t=((e,t="show")=>Uc("screenshare","user","",{mode:t,videoStream:e}))(e,"show");h(t.id),n(t)}catch(e){console.error("Failed to start screen sharing:",e),v(!1),C("denied")}k()},I=E;return c(t,()=>()=>{l?(gr(),v(!1),w(d)):m(!0)}),{isScreenSharing:l,isAwaitingScreenAccess:null!==S,showScreenAccessDialog:f,handleScreenAccessDialogAllow:async()=>{m(!1),await E()},handleScreenAccessDialogDismiss:()=>{m(!1)},handleScreenAccessRequestAllow:I,handleScreenAccessRequestDeny:()=>{C("denied"),k()},requestScreenAccess:(e,t)=>{S||n(((e,t)=>Uc("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0,pendingContent:t}))(e,t))}}}({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:i.addMessage,onUpdateMessage:i.updateMessage,onRemoveMessage:i.removeMessage,onSendMessage:i.messageDispatch,messages:o.messages}),I=y||u;/* @__PURE__ */
49
- return v(oc,{height:"full",children:[w&&/* @__PURE__ */b(Uu,{open:w,onClose:S,title:"Can I take a look at your screen?",description:"By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.",onConfirm:x,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:n}),
50
- /* @__PURE__ */b(oc,{grow:!0,overflow:"hidden",paddingY:"2xs",minHeight:"0",children:/* @__PURE__ */b(Ol,{label:"Chat",fallback:/* @__PURE__ */b(pc,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */b(Qu,{messagesEndRef:m,onScreenAccessAllow:k,onScreenAccessDeny:C})})}),
51
- /* @__PURE__ */b(nc,{variant:"floatingCard",style:{marginTop:"auto"},children:/* @__PURE__ */b(vu,{ref:n,value:h,onChange:f,onSubmit:()=>{if(!h.trim()||I)return;const e=h.trim();f(""),i.addMessage(Hc(e,s)),!1===r.use_screenshare||"show"!==s&&"do"!==s||g?i.messageDispatch(e,s,!0):E(s,e)},modes:ed.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:Lc(e)})),activeMode:s,onModeChange:e=>{e!==s&&(i.addMessage(qc(`Switched to ${Lc(e)} mode`,"mode-change")),i.setMode(e))},disabled:I,taskRunning:l,onStop:()=>{Tc.cleanup(),i.stopTask()}})})]})},nd=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}],rd=({onNavigateToChat:e,onChipClick:t})=>{const n=Sl(),{messages:r}=kl().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:"show"===e.chip_mode?`Show me ${e.chip_text.replace(/^Show me\s+/i,"")}`:"do"===e.chip_mode?`Do ${e.chip_text.replace(/^Do\s+/i,"")}`:e.chip_text,type:e.chip_mode})):nd}(n);/* @__PURE__ */
46
+ /* @__PURE__ */v(oc,{grow:!0,position:"relative",rounded:"lg",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:i?"var(--primary)":void 0,color:i?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */b(Hu,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */v(rc,{align:"start",gap:"sm",children:[/* @__PURE__ */b(rc,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */b(ac,{name:s,size:13})}),/* @__PURE__ */b(oc,{grow:!0,children:/* @__PURE__ */b(Vu,{message:e,isLastMessage:t})})]}):/* @__PURE__ */b(Vu,{message:e,isLastMessage:t})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v(rc,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */b(Ja,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>n?.(),children:"Yes"}),/* @__PURE__ */b(Ja,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */b(pc,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"No"}),a&&/* @__PURE__ */b(rc,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */b(ac,{name:a.name,size:14,style:{color:bl(o,a.opacity),flexShrink:0}})})]}),
47
+ /* @__PURE__ */b(rc,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */b(pc,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:(c=e.timestamp,(c??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))})]});var c},Ku={boxShadow:Na.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Xu=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=Sl(),{state:o,actions:i}=kl(),{messages:s}=o,{isPreviewMode:c}=r,[l,h]=p(!1),[f,m]=p(!1),g=d(null),y=u(()=>jc(r.widget_body),[r.widget_body]),w=u(()=>[y,...s],[y,s]),x=()=>{if(g.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=g.current;h(e>200);const r=Math.abs(t-e-n)<50;m(!r&&t>n)}};a(()=>{window.requestAnimationFrame(()=>{e.current&&(!c&&e.current.scrollIntoView({behavior:"auto"}),!c&&x())})},[s.length,c]);const S=s[s.length-1]?.content?.length??0;return a(()=>{const t=g.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[S,c,e]),/* @__PURE__ */v(nc,{position:"relative",height:"full",children:[/* @__PURE__ */v(nc,{ref:g,onScroll:x,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:r.widget_background_color.includes("gradient")?"transparent":r.widget_background_color,backgroundImage:vl(r.widget_background_color),scrollbarColor:`${bl(r.widget_border_color,.3)} ${bl(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */b(Yu,{message:e,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */b(rc,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */b(Ja,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */b(pc,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
48
+ /* @__PURE__ */b(nc,{ref:e},"scroll-anchor")]},"message-list-container"),[{show:l,edge:{top:"8px"},label:"Scroll to top",icon:"arrowUp",onClick:()=>g.current?.scrollTo({top:0,behavior:"smooth"})},{show:f,edge:{bottom:"8px"},label:"Scroll to bottom",icon:"arrowDown",onClick:()=>!c&&e.current?.scrollIntoView({behavior:"smooth"})}].map(({show:e,edge:t,label:n,icon:o,onClick:i})=>e&&/* @__PURE__ */b(rc,{position:"absolute",justify:"center",style:{...t,left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(cc,{variant:"secondary",size:"sm",label:n,onClick:i,style:Ku,children:/* @__PURE__ */b(ac,{name:o,size:10,style:{color:r.widget_accent_color}})})},n))]})},Gu=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}];function Ju(e){const t=d(e);return t.current=e,t}var Zu=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=Sl(),{state:o,actions:i}=kl(),{currentMode:s,isTaskRunning:l,isAwaitingReply:u}=o,[h,f]=p(""),m=d(null),{isScreenSharing:g,isAwaitingScreenAccess:y,showScreenAccessDialog:w,handleScreenAccessDialogAllow:x,handleScreenAccessDialogDismiss:S,handleScreenAccessRequestAllow:k,handleScreenAccessRequestDeny:C,requestScreenAccess:E}=function({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:n,onUpdateMessage:r,onRemoveMessage:o,onSendMessage:i,messages:s}){const[l,u]=p(!1),[d,h]=p(null),[f,m]=p(!1),g=Ju(l),y=Ju(d),b=Ju(e),v=t=>{u(t),e?.(t)},w=e=>{e&&o?.(e),n(qc("Screen sharing stopped","stopped-sharing")),h(null)},x=Ju(w);a(()=>{const e=()=>{const e=null!==mr(),t=g.current,n=y.current;e!==t&&(g.current=e,u(e),b.current?.(e)),t&&!e&&n&&x.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[]);const S=s[Fc(s,e=>!!e.isScreenAccessRequest&&!e.screenShareStatus)]??null,k=()=>{S?.pendingContent&&i(S.pendingContent,S.mode,!0)},C=e=>{S&&r(S.id,{screenShareStatus:e})},E=async()=>{try{const e=await async function(){if(!1===Fe.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=mr();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return fr=t,t.getVideoTracks()[0]?.addEventListener("ended",()=>{fr=null}),t}();v(!0),C("allowed"),n(qc("Screen sharing started","started-screenshare"));const t=((e,t="show")=>Uc("screenshare","user","",{mode:t,videoStream:e}))(e,"show");h(t.id),n(t)}catch(e){console.error("Failed to start screen sharing:",e),v(!1),C("denied")}k()},I=E;return c(t,()=>()=>{l?(gr(),v(!1),w(d)):m(!0)}),{isScreenSharing:l,isAwaitingScreenAccess:null!==S,showScreenAccessDialog:f,handleScreenAccessDialogAllow:async()=>{m(!1),await E()},handleScreenAccessDialogDismiss:()=>{m(!1)},handleScreenAccessRequestAllow:I,handleScreenAccessRequestDeny:()=>{C("denied"),k()},requestScreenAccess:(e,t)=>{S||n(((e,t)=>Uc("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0,pendingContent:t}))(e,t))}}}({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:i.addMessage,onUpdateMessage:i.updateMessage,onRemoveMessage:i.removeMessage,onSendMessage:i.messageDispatch,messages:o.messages}),I=y||u;/* @__PURE__ */
49
+ return v(oc,{height:"full",children:[w&&/* @__PURE__ */b(zu,{open:w,onClose:S,title:"Can I take a look at your screen?",description:"By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.",onConfirm:x,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:n}),
50
+ /* @__PURE__ */b(oc,{grow:!0,overflow:"hidden",paddingY:"2xs",minHeight:"0",children:/* @__PURE__ */b(Ol,{label:"Chat",fallback:/* @__PURE__ */b(pc,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */b(Xu,{messagesEndRef:m,onScreenAccessAllow:k,onScreenAccessDeny:C})})}),
51
+ /* @__PURE__ */b(nc,{variant:"floatingCard",style:{marginTop:"auto"},children:/* @__PURE__ */b(mu,{ref:n,value:h,onChange:f,onSubmit:()=>{if(!h.trim()||I)return;const e=h.trim();f(""),i.addMessage(Hc(e,s)),!1===r.use_screenshare||"show"!==s&&"do"!==s||g?i.messageDispatch(e,s,!0):E(s,e)},modes:Gu.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:Lc(e)})),activeMode:s,onModeChange:e=>{e!==s&&(i.addMessage(qc(`Switched to ${Lc(e)} mode`,"mode-change")),i.setMode(e))},disabled:I,taskRunning:l,onStop:()=>{Tc.cleanup(),i.stopTask()}})})]})},Qu=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}],ed=({onNavigateToChat:e,onChipClick:t})=>{const n=Sl(),{messages:r}=kl().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:"show"===e.chip_mode?`Show me ${e.chip_text.replace(/^Show me\s+/i,"")}`:"do"===e.chip_mode?`Do ${e.chip_text.replace(/^Do\s+/i,"")}`:e.chip_text,type:e.chip_mode})):Qu}(n);/* @__PURE__ */
52
52
  return v(oc,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(oc,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */v(nc,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */b(pc,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */b(pc,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */v(oc,{gap:"sm",children:[/* @__PURE__ */v(Ja,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */b(ac,{name:"chat",size:16}),"Ask a question"]}),o.map((r,o)=>/* @__PURE__ */b(Ja,{elevation:"card",size:"sm",variant:"chip",full:!0,onClick:n=>(async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)})(r,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */b(pc,{as:"span",weight:"normal",leading:"tight",children:r.text})},`welcome-chip-${r.id}-${o}`))]})]}),r.length>0&&/* @__PURE__ */v(nc,{variant:"floatingCard",children:[
53
53
  /* @__PURE__ */b(pc,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
54
54
  /* @__PURE__ */b(pc,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1]?.content||"Message"}),
55
- /* @__PURE__ */b(pc,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})},od=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],id=()=>/* @__PURE__ */b(du,{render:/* @__PURE__ */b(rc,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:od.map(e=>/* @__PURE__ */v(Gl,{value:e.id,render:/* @__PURE__ */b(Ja,{stacked:!0,variant:"tab"}),children:[
55
+ /* @__PURE__ */b(pc,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})},td=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],nd=()=>/* @__PURE__ */b(du,{render:/* @__PURE__ */b(rc,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:td.map(e=>/* @__PURE__ */v(Gl,{value:e.id,render:/* @__PURE__ */b(Ja,{stacked:!0,variant:"tab"}),children:[
56
56
  /* @__PURE__ */b("span",{className:"mtx-tab-underline"}),
57
57
  /* @__PURE__ */b(pc,{as:"span",inheritColor:!0,"aria-hidden":"true",children:/* @__PURE__ */b(ac,{name:e.icon,size:20})}),
58
- /* @__PURE__ */b(pc,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))}),sd=()=>{const e=Sl(),{state:t,actions:n}=kl(),{isOpen:r,activeView:o}=t,{isPreviewMode:s}=e,{widthPx:c,heightPx:l,grip:h,onResizeStart:f,containerRef:m}=function(e,t,n,r,o){const s=Oe("marketrix_widget_size",r),a=d(null),c=u(()=>(e=>{const t=Il(e),n=Tl[t.vertical],r=Tl[t.horizontal];return{vertical:n,horizontal:r,growX:"left"===r?-1:1,growY:"top"===n?-1:1,cursor:"top"===n==("left"===r)?"nwse-resize":"nesw-resize"}})(n),[n]),[l,h]=p(()=>function(e){try{const t=JSON.parse(_e(e)??"null");return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.width&&"number"==typeof e.height}(t)?hu(t):null}catch(t){return console.warn("[useResize] Ignoring an unparseable stored size:",t),null}}(s)??hu({width:fu(e,360),height:fu(t,450)})),f=d(l);f.current=l;const m=i(e=>{if(e.preventDefault(),e.stopPropagation(),o)return;const t=e.clientX,n=e.clientY,r=f.current.width,i=f.current.height,{growX:l,growY:u,cursor:d}=c;a.current&&(a.current.dataset.resizing="true");const p=e=>{const o=hu({width:r+(e.clientX-t)*l,height:i+(e.clientY-n)*u});f.current=o,a.current&&(a.current.style.width=`${o.width}px`,a.current.style.height=`${o.height}px`)},m=()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",a.current&&delete a.current.dataset.resizing,h({...f.current}),De(s,JSON.stringify(f.current))};document.body.style.cursor=d,document.body.style.userSelect="none",document.addEventListener("mousemove",p),document.addEventListener("mouseup",m)},[o,s,c]);return{widthPx:`${l.width}px`,heightPx:`${l.height}px`,grip:c,onResizeStart:m,containerRef:a}}(e.widget_width,e.widget_height,e.widget_position,e,s),g=d(null),y="chat"===o?"forward":"back";!function(e,t,n){const r=d(!1),o=d(null);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=pu(i)),r.current=!0,(n?.focusTargetRef?.current??yc(i)[0])?.focus({preventScroll:!0});const s=e=>{const t=pu(i);if(!t||!i.contains(t))return;if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const r=yc(i);if(0===r.length)return;const o=r.indexOf(t);-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),r[r.length-1]?.focus()):o===r.length-1&&(e.preventDefault(),r[0]?.focus()))};return document.addEventListener("keydown",s,!0),()=>document.removeEventListener("keydown",s,!0)},[t,e,n?.focusTargetRef,n?.onEscape])}(m,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?g:void 0});const w=Ml(e.widget_position),[x,S]=p(!1),k=d(null);if(!r)return null;const C=vl(e.widget_background_color),{vertical:E,horizontal:I}=Il(e.widget_position),M="chat"===o&&!1!==e.use_screenshare?()=>k.current?.():void 0;/* @__PURE__ */
58
+ /* @__PURE__ */b(pc,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))});function rd(e){const t=e.getRootNode();return(t instanceof ShadowRoot?t.activeElement:document.activeElement)??null}function od({width:e,height:t}){return{width:Math.min(Math.max(e,280),600),height:Math.min(Math.max(t,320),Math.floor(.85*window.innerHeight))}}function id(e,t){const n=/^\s*(\d+(?:\.\d+)?)px\s*$/.exec(e??"");return n?Number(n[1]):t}var sd=()=>{const e=Sl(),{state:t,actions:n}=kl(),{isOpen:r,activeView:o}=t,{isPreviewMode:s}=e,{widthPx:c,heightPx:l,grip:h,onResizeStart:f,containerRef:m}=function(e,t,n,r,o){const s=Oe("marketrix_widget_size",r),a=d(null),c=u(()=>(e=>{const t=Il(e),n=Tl[t.vertical],r=Tl[t.horizontal];return{vertical:n,horizontal:r,growX:"left"===r?-1:1,growY:"top"===n?-1:1,cursor:"top"===n==("left"===r)?"nwse-resize":"nesw-resize"}})(n),[n]),[l,h]=p(()=>function(e){try{const t=JSON.parse(_e(e)??"null");return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.width&&"number"==typeof e.height}(t)?od(t):null}catch(t){return console.warn("[useResize] Ignoring an unparseable stored size:",t),null}}(s)??od({width:id(e,360),height:id(t,450)})),f=d(l);f.current=l;const m=i(e=>{if(e.preventDefault(),e.stopPropagation(),o)return;const t=e.clientX,n=e.clientY,r=f.current.width,i=f.current.height,{growX:l,growY:u,cursor:d}=c;a.current&&(a.current.dataset.resizing="true");const p=e=>{const o=od({width:r+(e.clientX-t)*l,height:i+(e.clientY-n)*u});f.current=o,a.current&&(a.current.style.width=`${o.width}px`,a.current.style.height=`${o.height}px`)},m=()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",a.current&&delete a.current.dataset.resizing,h({...f.current}),De(s,JSON.stringify(f.current))};document.body.style.cursor=d,document.body.style.userSelect="none",document.addEventListener("mousemove",p),document.addEventListener("mouseup",m)},[o,s,c]);return{widthPx:`${l.width}px`,heightPx:`${l.height}px`,grip:c,onResizeStart:m,containerRef:a}}(e.widget_width,e.widget_height,e.widget_position,e,s),g=d(null),y="chat"===o?"forward":"back";!function(e,t,n){const r=d(!1),o=d(null);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=rd(i)),r.current=!0,(n?.focusTargetRef?.current??yc(i)[0])?.focus({preventScroll:!0});const s=e=>{const t=rd(i);if(!t||!i.contains(t))return;if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const r=yc(i);if(0===r.length)return;const o=r.indexOf(t);-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),r[r.length-1]?.focus()):o===r.length-1&&(e.preventDefault(),r[0]?.focus()))};return document.addEventListener("keydown",s,!0),()=>document.removeEventListener("keydown",s,!0)},[t,e,n?.focusTargetRef,n?.onEscape])}(m,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?g:void 0});const w=Ml(e.widget_position),[x,S]=p(!1),k=d(null);if(!r)return null;const C=vl(e.widget_background_color),{vertical:E,horizontal:I}=Il(e.widget_position),M="chat"===o&&!1!==e.use_screenshare?()=>k.current?.():void 0;/* @__PURE__ */
59
59
  return v(oc,{ref:m,position:s?"absolute":"fixed",rounded:"lg",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:C,transformOrigin:`${E} ${I}`,width:c,height:l,fontSize:"14px",...w,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:Na.panel},children:[
60
- /* @__PURE__ */b(gu,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:M&&/* @__PURE__ */v(cc,{variant:"ghost",size:"sm",label:x?"Stop screen sharing":"Start screen sharing",onClick:M,children:[x&&/* @__PURE__ */b(mu,{style:{position:"absolute",top:"2px",right:"2px"}}),/* @__PURE__ */b(ac,{name:"screenShare",size:16})]})}),
61
- /* @__PURE__ */v(Hl,{value:o,onValueChange:e=>n.setActiveView(e),render:/* @__PURE__ */b(oc,{grow:!0,minHeight:"0"}),children:[/* @__PURE__ */v(oc,{grow:!0,overflow:"hidden",minHeight:"0",children:[/* @__PURE__ */b(Ql,{value:"home","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(rd,{onNavigateToChat:()=>n.setActiveView("chat"),onChipClick:e=>{n.addMessage(Hc(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */b(Ql,{value:"chat","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(td,{onScreenSharingChange:S,toggleScreenShareRef:k,messageInputRef:g})})]}),/* @__PURE__ */b(id,{})]}),!s&&/* @__PURE__ */b("div",{role:"separator","aria-label":`Resize widget from ${h.vertical} ${h.horizontal}`,title:"Drag to resize",style:{position:"absolute",[h.vertical]:0,[h.horizontal]:0,width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:"top"===h.vertical?"flex-start":"flex-end",justifyContent:"left"===h.horizontal?"flex-start":"flex-end",cursor:h.cursor},onMouseDown:f})]})},ad=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=kl(),c=e.isPreviewMode??!1;var l;l=i.isOpen,a(()=>{if(!l)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[l]);const[u,d]=p(e.widget_position??"bottom_right"),h=Oe("marketrix_widget_position",e);a(()=>{const t=c?null:_e(h);(e=>El.includes(e))(t)?d(t):d(e.widget_position??"bottom_right")},[c,h,e.widget_position]),a(()=>{if(i.isOpen||c||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,c,e.widget_greeting_toast]);const f=!1===e.show_widget||"hidden"===e.widget_appearance;if(!c&&f)return null;const m=Math.max(e.widget_position_z_index??0,2147483002),g={...e,widget_position:u,widget_position_z_index:m,isPreviewMode:c},y=i.isAwaitingReply||i.isTaskRunning,w=(x=function(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)),n={...wl,...t};return{color:{background:n.widget_background_color,foreground:n.widget_text_color,foregroundMuted:bl(n.widget_text_color,.6),foregroundFaint:bl(n.widget_text_color,.4),border:n.widget_border_color,primary:n.widget_accent_color,primaryForeground:yl(n.widget_accent_color),primaryHover:bl(n.widget_accent_color,.85),secondary:n.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:bl(n.widget_secondary_color,.2),secondaryHover:bl(n.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}(e),{"--background":x.color.background,"--foreground":x.color.foreground,"--card":x.color.background,"--card-foreground":x.color.foreground,"--primary":x.color.primary,"--foreground-muted":x.color.foregroundMuted,"--foreground-faint":x.color.foregroundFaint,"--primary-foreground":x.color.primaryForeground,"--primary-hover":x.color.primaryHover,"--secondary":x.color.secondary,"--secondary-foreground":x.color.secondaryForeground,"--secondary-bg":x.color.secondaryBg,"--secondary-hover":x.color.secondaryHover,"--border":x.color.border,"--ring":x.color.primary,"--radius":x.radius,"--duration-animation":x.motion.durationAnimation,"--duration-fade":x.motion.durationFade});var x;/* @__PURE__ */
60
+ /* @__PURE__ */b(hu,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:M&&/* @__PURE__ */v(cc,{variant:"ghost",size:"sm",label:x?"Stop screen sharing":"Start screen sharing",onClick:M,children:[x&&/* @__PURE__ */b(pu,{style:{position:"absolute",top:"2px",right:"2px"}}),/* @__PURE__ */b(ac,{name:"screenShare",size:16})]})}),
61
+ /* @__PURE__ */v(Hl,{value:o,onValueChange:e=>n.setActiveView(e),render:/* @__PURE__ */b(oc,{grow:!0,minHeight:"0"}),children:[/* @__PURE__ */v(oc,{grow:!0,overflow:"hidden",minHeight:"0",children:[/* @__PURE__ */b(Ql,{value:"home","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(ed,{onNavigateToChat:()=>n.setActiveView("chat"),onChipClick:e=>{n.addMessage(Hc(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */b(Ql,{value:"chat","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(Zu,{onScreenSharingChange:S,toggleScreenShareRef:k,messageInputRef:g})})]}),/* @__PURE__ */b(nd,{})]}),!s&&/* @__PURE__ */b("div",{role:"separator","aria-label":`Resize widget from ${h.vertical} ${h.horizontal}`,title:"Drag to resize",style:{position:"absolute",[h.vertical]:0,[h.horizontal]:0,width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:"top"===h.vertical?"flex-start":"flex-end",justifyContent:"left"===h.horizontal?"flex-start":"flex-end",cursor:h.cursor},onMouseDown:f})]})},ad=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=kl(),c=e.isPreviewMode??!1;var l;l=i.isOpen,a(()=>{if(!l)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[l]);const[u,d]=p(e.widget_position??"bottom_right"),h=Oe("marketrix_widget_position",e);a(()=>{const t=c?null:_e(h);(e=>El.includes(e))(t)?d(t):d(e.widget_position??"bottom_right")},[c,h,e.widget_position]),a(()=>{if(i.isOpen||c||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,c,e.widget_greeting_toast]);const f=!1===e.show_widget||"hidden"===e.widget_appearance;if(!c&&f)return null;const m=Math.max(e.widget_position_z_index??0,2147483002),g={...e,widget_position:u,widget_position_z_index:m,isPreviewMode:c},y=i.isAwaitingReply||i.isTaskRunning,w=(x=function(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)),n={...wl,...t};return{color:{background:n.widget_background_color,foreground:n.widget_text_color,foregroundMuted:bl(n.widget_text_color,.6),foregroundFaint:bl(n.widget_text_color,.4),border:n.widget_border_color,primary:n.widget_accent_color,primaryForeground:yl(n.widget_accent_color),primaryHover:bl(n.widget_accent_color,.85),secondary:n.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:bl(n.widget_secondary_color,.2),secondaryHover:bl(n.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}(e),{"--background":x.color.background,"--foreground":x.color.foreground,"--card":x.color.background,"--card-foreground":x.color.foreground,"--primary":x.color.primary,"--foreground-muted":x.color.foregroundMuted,"--foreground-faint":x.color.foregroundFaint,"--primary-foreground":x.color.primaryForeground,"--primary-hover":x.color.primaryHover,"--secondary":x.color.secondary,"--secondary-foreground":x.color.secondaryForeground,"--secondary-bg":x.color.secondaryBg,"--secondary-hover":x.color.secondaryHover,"--border":x.color.border,"--ring":x.color.primary,"--radius":x.radius,"--duration-animation":x.motion.durationAnimation,"--duration-fade":x.motion.durationFade});var x;/* @__PURE__ */
62
62
  return b(xl,{value:g,children:/* @__PURE__ */b(nc,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...w,...c&&{width:"100%",height:"100%"}},children:/* @__PURE__ */b(ul,{value:r,children:/* @__PURE__ */v(fc,{container:r,offsetBottom:"top"===Il(u).vertical?20:90,children:[y&&/* @__PURE__ */b(nc,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${bl(g.widget_accent_color,.72)}, inset 0 0 46px 10px ${bl(g.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:2147483001}}),
63
63
  /* @__PURE__ */b(Ol,{label:"Widget",children:/* @__PURE__ */b(sd,{})}),
64
64
  /* @__PURE__ */b(_l,{onPositionCommit:e=>{d(e),c||De(h,e)}}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marketrix.ai/widget",
3
- "version": "4.0.111",
3
+ "version": "4.0.113",
4
4
  "type": "module",
5
5
  "packageManager": "bun@1.4.2",
6
6
  "sideEffects": false,
@@ -1,34 +0,0 @@
1
- /**
2
- * `useDragSnap` — drag the launcher (FAB) and snap it to the nearest corner. Pointer events are tracked
3
- * in a ref; movement under DRAG_THRESHOLD_PX stays a click, beyond it the wrapper is translated on a
4
- * rAF loop with velocity sampled so a flick lands where it was heading. On release
5
- * `getNearestCornerByTranslation` picks the corner, the wrapper animates there for SNAP_DURATION_MS via
6
- * `left`/`top` transitions, and `commitPositionAfterAnimation` calls `onPositionCommit` on
7
- * `transitionend` (with a timeout fallback, since a hidden tab fires no transition events) — the
8
- * committed corner is the one being animated TO, so two snaps in flight cannot commit the abandoned
9
- * one (`abandonSnapRef`). `suppressUntilRef` stamps a time after which a click may open the widget
10
- * again, so the pointer-up that ends a drag is not read as a tap. The wrapper is measured with a
11
- * ResizeObserver in a layout effect so the pixel position is right on the first paint; preview mode
12
- * disables everything.
13
- */
14
- import React from 'react';
15
- import type { WidgetPosition } from '../types';
16
- export interface UseDragSnapOptions {
17
- position: WidgetPosition;
18
- onPositionCommit: (position: WidgetPosition) => void;
19
- isPreviewMode?: boolean;
20
- wrapperRef: React.RefObject<HTMLDivElement | null>;
21
- }
22
- export interface UseDragSnapResult {
23
- isDragging: boolean;
24
- pixelPositionStyle: {
25
- left: number;
26
- top: number;
27
- } | undefined;
28
- onPointerDown: (event: React.PointerEvent<HTMLButtonElement>) => void;
29
- onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;
30
- onPointerUp: (event: React.PointerEvent<HTMLButtonElement>) => void;
31
- onPointerCancel: (event: React.PointerEvent<HTMLButtonElement>) => void;
32
- suppressUntilRef: React.RefObject<number>;
33
- }
34
- export declare function useDragSnap({ position, onPositionCommit, isPreviewMode, wrapperRef, }: UseDragSnapOptions): UseDragSnapResult;
@@ -1,22 +0,0 @@
1
- /**
2
- * Focus trap for the messenger panel: while `isActive`, focus starts inside `containerRef`, Tab cycles
3
- * within it, Escape calls `onEscape`, and on deactivation focus returns to whatever held it before.
4
- * `useFocusTrap(containerRef, isActive, {onEscape, focusTargetRef})` focuses `focusTargetRef` (else the
5
- * first focusable), installs one capture-phase `keydown` listener on `document`, and restores focus on
6
- * the active→inactive edge. The tabbable candidates come from `utils/dom`'s shared `focusablesIn`, the
7
- * same filter `keySimulation`'s Tab simulation uses, so the widget's own tab order and the host page's
8
- * can't re-diverge.
9
- *
10
- * Inside the widget's closed shadow root `document.activeElement` retargets to the HOST, never naming
11
- * an element of the widget's own tree; `activeElementIn` reads through `container.getRootNode()`
12
- * instead and is the ONE home for that retargeting — eslint's `no-restricted-properties` bans the bare
13
- * read everywhere else. Hand-rolled on purpose: `MessengerShell` is a NON-modal panel, not a Dialog, and
14
- * Base UI exposes no standalone focus trap; reaching it by making the panel a Dialog would inert the
15
- * customer's page. Both key arms bail unless focus is currently inside the container, since the
16
- * listener sits on `document` ahead of host-page handlers and an unguarded Escape would close the
17
- * widget mid-typing.
18
- */
19
- export declare function useFocusTrap(containerRef: React.RefObject<HTMLElement | null>, isActive: boolean, options?: {
20
- onEscape?: () => void;
21
- focusTargetRef?: React.RefObject<HTMLElement | null> | undefined;
22
- }): void;
@@ -1,14 +0,0 @@
1
- import type { MarketrixConfig, WidgetPosition } from '../types';
2
- export declare function useResize(settingsWidth: string | undefined, settingsHeight: string | undefined, position: WidgetPosition, config: MarketrixConfig, isPreviewMode: boolean): {
3
- widthPx: string;
4
- heightPx: string;
5
- grip: {
6
- vertical: "top" | "bottom";
7
- horizontal: "left" | "right";
8
- growX: number;
9
- growY: number;
10
- cursor: string;
11
- };
12
- onResizeStart: (e: React.MouseEvent) => void;
13
- containerRef: import("react").RefObject<HTMLDivElement | null>;
14
- };
@@ -1,22 +0,0 @@
1
- import type { InstructionType } from '../sdk';
2
- import type { ChatMessage } from '../types';
3
- export interface UseScreenShareOptions {
4
- onScreenSharingChange?: (isSharing: boolean) => void;
5
- toggleScreenShareRef?: React.MutableRefObject<(() => void) | null>;
6
- onAddMessage: (message: ChatMessage) => void;
7
- onUpdateMessage: (messageId: string, updates: Partial<ChatMessage>) => void;
8
- onRemoveMessage?: (messageId: string) => void;
9
- onSendMessage: (message: string, mode?: InstructionType, skipUserMessage?: boolean) => void;
10
- messages: ChatMessage[];
11
- }
12
- export interface UseScreenShareReturn {
13
- isScreenSharing: boolean;
14
- isAwaitingScreenAccess: boolean;
15
- showScreenAccessDialog: boolean;
16
- handleScreenAccessDialogAllow: () => Promise<void>;
17
- handleScreenAccessDialogDismiss: () => void;
18
- handleScreenAccessRequestAllow: () => Promise<void>;
19
- handleScreenAccessRequestDeny: () => void;
20
- requestScreenAccess: (mode: InstructionType, content: string) => void;
21
- }
22
- export declare function useScreenShare({ onScreenSharingChange, toggleScreenShareRef, onAddMessage, onUpdateMessage, onRemoveMessage, onSendMessage, messages, }: UseScreenShareOptions): UseScreenShareReturn;
@@ -1 +0,0 @@
1
- export declare function useScrollLock(enabled: boolean): void;