@livelayer/react 0.2.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +257 -26
- package/dist/index.d.ts +148 -0
- package/dist/index.js +2 -1
- package/dist/index.mjs +1371 -993
- package/dist/styles.css +31 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("react"),lt=require("@livelayer/sdk"),xe=require("livekit-client");class Ue extends t.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,l){var a,s;(s=(a=this.props).onError)==null||s.call(a,r,l)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[e.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),e.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),e.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function $e(n){const[r,l]=t.useState("idle"),[a,s]=t.useState("idle"),[c,d]=t.useState([]),[m,u]=t.useState(null),[x,p]=t.useState(null),[i,o]=t.useState(null),[k,b]=t.useState(!1),[j,N]=t.useState(null),C=t.useRef(null),M=t.useRef(n.onDataMessage);M.current=n.onDataMessage,t.useEffect(()=>{const y={onConnectionStateChange:v=>{l(v),v==="connected"&&N(null)},onAgentStateChange:s,onTranscript:v=>d([...v]),onAgentConfig:u,onAudioTrack:v=>o(v),onVideoTrack:v=>p(v),onVideoTrackRemoved:()=>p(null),onError:v=>N(v),onDataMessage:v=>{var E;(E=M.current)==null||E.call(M,v)},onResumabilityChange:b},_=new lt.LiveKitSession({agentId:n.agentId,baseUrl:n.baseUrl,apiKey:n.apiKey,sessionEndpoint:n.sessionEndpoint,sessionBody:n.sessionBody},y);return C.current=_,l("idle"),s("idle"),d([]),u(null),p(null),o(null),b(!1),N(null),()=>{var v;(v=_.destroy)==null||v.call(_),C.current=null}},[n.agentId,n.baseUrl,n.apiKey,n.sessionEndpoint,JSON.stringify(n.sessionBody??{})]);const L=t.useCallback(async()=>{const y=C.current;if(y)try{await y.connect()}catch(_){throw N(_ instanceof Error?_.message:String(_)),_}},[]),R=t.useCallback(()=>{const y=C.current;y&&y.disconnect()},[]),S=t.useCallback(()=>{var y;return((y=C.current)==null?void 0:y.getRoom())??null},[]);return{connectionState:r,agentState:a,transcript:c,agentConfig:m,videoElement:x,audioElement:i,canResume:k,error:j,connect:L,disconnect:R,getRoom:S,session:C.current}}function Oe(){const n=t.useRef(null),r=t.useRef(null),l=t.useRef(null),a=t.useRef(null),s=t.useRef(new Set),c=t.useRef(null),d=t.useCallback(()=>{const i=r.current;if(!i){a.current=null;return}(!c.current||c.current.length!==i.frequencyBinCount)&&(c.current=new Uint8Array(new ArrayBuffer(i.frequencyBinCount)));const o=c.current;i.getByteFrequencyData(o);let k=0;for(let j=0;j<o.length;j++)k+=o[j];const b=k/o.length/255;for(const j of s.current)try{j(b)}catch(N){console.error("[useAudioLevel] subscriber threw:",N)}a.current=requestAnimationFrame(d)},[]),m=t.useCallback(()=>{if(n.current||typeof window>"u"||typeof AudioContext>"u")return;const i=new AudioContext,o=i.createAnalyser();o.fftSize=64,o.connect(i.destination),n.current=i,r.current=o},[]),u=t.useCallback(i=>{if(m(),!(!n.current||!r.current)){if(l.current){try{l.current.disconnect()}catch{}l.current=null}try{const o=n.current.createMediaElementSource(i);o.connect(r.current),l.current=o}catch(o){console.warn("[useAudioLevel] createMediaElementSource failed:",o);return}a.current===null&&(a.current=requestAnimationFrame(d))}},[m,d]),x=t.useCallback(()=>{if(a.current!==null&&(cancelAnimationFrame(a.current),a.current=null),l.current){try{l.current.disconnect()}catch{}l.current=null}},[]),p=t.useCallback(i=>(s.current.add(i),()=>{s.current.delete(i)}),[]);return t.useEffect(()=>()=>{if(x(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(n.current){try{n.current.close()}catch{}n.current=null}s.current.clear(),c.current=null},[x]),{attach:u,detach:x,subscribe:p}}function Ve(){const[n,r]=t.useState(!1),[l,a]=t.useState(null),s=t.useRef(null),c=t.useRef(null),d=t.useCallback(async p=>{if(s.current&&c.current){try{await c.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}c.current=p,a(null);try{const i=await xe.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await p.localParticipant.publishTrack(i),s.current=i,r(i.isMuted)}catch(i){const o=i instanceof Error&&i.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw a(o),i}},[]),m=t.useCallback(()=>{const p=s.current;p&&(p.isMuted?(p.unmute(),r(!1)):(p.mute(),r(!0)))},[]),u=t.useCallback(()=>{const p=s.current,i=c.current;if(p&&i){try{i.localParticipant.unpublishTrack(p)}catch{}p.stop()}s.current=null,c.current=null,r(!1)},[]),x=t.useCallback(()=>a(null),[]);return{isMuted:n,micError:l,toggleMute:m,setupMic:d,teardownMic:u,clearError:x}}const at={resolution:{width:640,height:480,frameRate:24}};function We(){const[n,r]=t.useState(!1),[l,a]=t.useState(null),[s,c]=t.useState(null),[d,m]=t.useState(""),u=t.useRef(null),x=t.useRef(null),p=t.useCallback(C=>{u.current=C},[]),i=t.useCallback(()=>{const C=u.current,M=x.current;if(M&&C){const L=C.localParticipant.getTrackPublication(xe.Track.Source.Camera);if(L!=null&&L.track){try{C.localParticipant.unpublishTrack(L.track)}catch{}L.track.stop()}else M.stop()}x.current=null,c(null),r(!1)},[]),o=t.useCallback(async C=>{const M=u.current;if(M){a(null);try{const L={...at};C&&(L.deviceId=C);const R=await xe.createLocalVideoTrack(L);await M.localParticipant.publishTrack(R),x.current=R;const S=R.attach();c(S),r(!0),C&&m(C);try{M.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(L){const R=L instanceof Error&&L.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";a(R)}}},[]),k=t.useCallback(async()=>{n?i():await o(d||void 0)},[n,d,i,o]),b=t.useCallback(async C=>{i(),await o(C)},[i,o]),j=t.useCallback(()=>{i(),u.current=null,a(null),m("")},[i]),N=t.useCallback(()=>a(null),[]);return t.useEffect(()=>()=>{x.current&&x.current.stop()},[]),{isEnabled:n,error:l,previewEl:s,activeDeviceId:d,toggle:k,switchDevice:b,attachRoom:p,teardown:j,clearError:N}}function Fe(){const[n,r]=t.useState(!1),[l,a]=t.useState(null),[s,c]=t.useState(null),d=t.useRef(null),m=t.useCallback(o=>{d.current=o},[]),u=t.useCallback(()=>c(null),[]),x=t.useCallback(async()=>{const o=d.current;if(o){if(n){try{await o.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1);return}a(null);try{await o.localParticipant.setScreenShareEnabled(!0);let k=0;const b=()=>{const j=o.localParticipant.getTrackPublication(xe.Track.Source.ScreenShare);if(j!=null&&j.track){const N=j.track.attach();c(N),r(!0);try{o.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}k++<10?setTimeout(b,100):r(!0)};b()}catch(k){const b=k instanceof Error?k.name:"";b!=="NotAllowedError"&&b!=="AbortError"&&a("Screen share unavailable. Try again."),r(!1)}}},[n,u]),p=t.useCallback(()=>{const o=d.current;if(o&&n)try{o.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1),a(null),d.current=null},[n,u]),i=t.useCallback(()=>a(null),[]);return{isEnabled:n,error:l,previewEl:s,toggle:x,attachRoom:m,teardown:p,clearError:i}}function Ke(){const[n,r]=t.useState([]),[l,a]=t.useState([]),s=t.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const c=await navigator.mediaDevices.enumerateDevices();r(c.filter(d=>d.kind==="audioinput")),a(c.filter(d=>d.kind==="videoinput"))}catch{}},[]);return t.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const c=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",c),()=>navigator.mediaDevices.removeEventListener("devicechange",c)},[s]),{mics:n,cameras:l,refresh:s}}function qe(n,r,l=!1){const[a,s]=t.useState(null),[c,d]=t.useState(null),[m,u]=t.useState(!l&&!!n);return t.useEffect(()=>{if(l||!n){u(!1);return}const x=new AbortController,p=r||"https://app.livelayer.studio";return u(!0),d(null),fetch(`${p}/api/widget/agent/${encodeURIComponent(n)}`,{signal:x.signal}).then(async i=>{if(!i.ok){const o=await i.json().catch(()=>({}));throw new Error(o.error||`HTTP ${i.status}`)}return i.json()}).then(i=>{x.signal.aborted||(s(i),u(!1))}).catch(i=>{x.signal.aborted||(d(i instanceof Error?i.message:"Agent lookup failed"),u(!1))}),()=>x.abort()},[n,r,l]),{info:a,error:c,loading:m}}function it(n){if(typeof window>"u")return null;try{return window.localStorage.getItem(n)}catch{return null}}function ot(n,r){if(!(typeof window>"u"))try{window.localStorage.setItem(n,r)}catch{}}function Ge({value:n,defaultValue:r="expanded",onChange:l}={}){const a=n!==void 0,[s,c]=t.useState(r),d=a?n:s,m=t.useCallback(u=>{u!==d&&(a||c(u),l==null||l(u))},[d,a,l]);return[d,m]}const ct=["hidden","minimized","expanded"];function dt(n){return n&&ct.includes(n)?n:null}function Ye({value:n,defaultValue:r="expanded",onChange:l,persistKey:a="ll-widget",disablePersistence:s=!1}={}){const c=`${a}:display-mode`,d=t.useRef(!1),[m,u]=Ge({value:n,defaultValue:r,onChange:x=>{n===void 0&&!s&&ot(c,x),l==null||l(x)}});return t.useEffect(()=>{if(d.current||(d.current=!0,s||n!==void 0))return;const x=dt(it(c));x&&x!==m&&u(x)},[]),[m,u]}const ut=640;function He(n=ut){const[r,l]=t.useState(!1);return t.useEffect(()=>{if(n===!1){l(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const a=`(max-width: ${n-1}px)`,s=window.matchMedia(a),c=()=>l(s.matches);return c(),typeof s.addEventListener=="function"?(s.addEventListener("change",c),()=>s.removeEventListener("change",c)):(s.addListener(c),()=>{s.removeListener(c)})},[n]),r}const Ie=({muted:n=!1,className:r})=>n?e.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):e.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Ae=({className:n})=>e.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),ft=({className:n})=>e.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),ht={left:180,right:0,up:-90,down:90},pt=({direction:n="right",className:r})=>e.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${ht[n]}deg)`},"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function mt(n){return n==="top-left"||n==="bottom-left"?"left":"right"}const Je="ll-hidden-tab-center-y",xt=5,De=16;function gt(){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Je);if(!n)return null;const r=Number.parseFloat(n);return Number.isFinite(r)?r:null}catch{return null}}function Te(n){if(!(typeof window>"u"))try{window.localStorage.setItem(Je,String(n))}catch{}}const vt=({position:n,isMobile:r,isSpeaking:l,onExpand:a,label:s="Open widget"})=>{const c=mt(n),d=c==="right"?"left":"right",m=r?80:72,[u,x]=t.useState(null),[p,i]=t.useState(!1),o=t.useRef(null),k=t.useRef(!1),b=t.useCallback(y=>{if(typeof window>"u")return y;const _=m/2,v=De+_,E=window.innerHeight-De-_;return E<v?Math.max(v,y):Math.max(v,Math.min(E,y))},[m]);t.useEffect(()=>{const y=gt();x(b(y??window.innerHeight/2));const _=()=>{x(v=>v===null?null:b(v))};return window.addEventListener("resize",_),()=>window.removeEventListener("resize",_)},[b]);const j=t.useCallback(y=>{if(!(y.pointerType==="mouse"&&y.button!==0)&&u!==null){try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}o.current={startClientY:y.clientY,startCenterY:u,moved:!1}}},[u]),N=t.useCallback(y=>{const _=o.current;if(!_)return;const v=y.clientY-_.startClientY;!_.moved&&Math.abs(v)>xt&&(_.moved=!0,i(!0)),_.moved&&x(b(_.startCenterY+v))},[b]),C=t.useCallback(y=>{const _=o.current;if(_){try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}o.current=null,_.moved&&(i(!1),k.current=!0,x(v=>(v!==null&&Te(v),v)))}},[]),M=t.useCallback(()=>{if(k.current){k.current=!1;return}a()},[a]),L=t.useCallback(y=>{if(y.key==="ArrowUp"||y.key==="ArrowDown"){y.preventDefault();const _=y.key==="ArrowUp"?-8:8;x(v=>{if(v===null)return v;const E=b(v+_);return Te(E),E})}},[b]),R=["ll-hidden",`ll-hidden--${c}`,r?"ll-hidden--mobile":"ll-hidden--desktop",l?"ll-hidden--speaking":null,p?"is-dragging":null].filter(Boolean).join(" "),S=u===null?void 0:{top:`${u-m/2}px`,transform:"none"};return e.jsx("button",{type:"button",className:R,onPointerDown:j,onPointerMove:N,onPointerUp:C,onPointerCancel:C,onClick:M,onKeyDown:L,"aria-label":s,"data-position":n,style:S,children:e.jsx(pt,{direction:d,className:"ll-hidden__chevron"})})},bt=({audioLevel:n,bars:r=20,maxHeight:l=20,minHeight:a=4,className:s,barClassName:c})=>{const d=t.useRef(null),m=t.useRef([]),u=t.useMemo(()=>{const p=(Math.sqrt(5)-1)/2;return Array.from({length:r},(i,o)=>.5+o*p%1*.5)},[r]);t.useEffect(()=>n.subscribe(i=>{for(let o=0;o<r;o++){const k=m.current[o];if(!k)continue;const b=Math.max(a,i*l*u[o]);k.style.height=`${b}px`}}),[n,r,l,a,u]);const x=["ll-waveform",s].filter(Boolean).join(" ");return e.jsx("div",{ref:d,className:x,"aria-hidden":"true",children:Array.from({length:r},(p,i)=>e.jsx("div",{ref:o=>{m.current[i]=o},className:["ll-waveform__bar",c].filter(Boolean).join(" "),style:{height:`${a}px`}},i))})},yt=({position:n,isMobile:r,agentName:l,avatarImageUrl:a,agentState:s,isMuted:c,audioLevel:d,onExpand:m,onToggleMute:u,onClose:x})=>r?e.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${l} widget`,children:e.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:m,"aria-label":`Expand ${l} widget`,children:[a?e.jsx("img",{src:a,alt:l,className:"ll-minimized__avatar"}):e.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),e.jsx(bt,{audioLevel:d,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),e.jsx("span",{className:"ll-minimized__name",children:l}),e.jsxs("div",{className:"ll-minimized__controls",children:[e.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:p=>{p.stopPropagation(),u()},onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.stopPropagation(),p.preventDefault(),u())},"aria-label":c?"Unmute microphone":"Mute microphone",children:e.jsx(Ie,{muted:c,className:"ll-minimized__icon"})}),e.jsx(Ae,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):e.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":n,role:"region","aria-label":`${l} widget`,children:e.jsxs("div",{className:"ll-minimized__surface",children:[a?e.jsx("img",{src:a,alt:l,className:"ll-minimized__avatar"}):e.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),e.jsxs("div",{className:"ll-minimized__meta",children:[e.jsx("span",{className:"ll-minimized__name",children:l}),e.jsx("span",{className:"ll-minimized__state",children:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),e.jsxs("div",{className:"ll-minimized__controls",children:[e.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":c?"Unmute microphone":"Mute microphone",children:e.jsx(Ie,{muted:c,className:"ll-minimized__icon"})}),e.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:m,"aria-label":`Expand ${l} widget`,children:e.jsx(Ae,{className:"ll-minimized__icon"})}),e.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:x,"aria-label":"Close widget",children:e.jsx(ft,{className:"ll-minimized__icon"})})]})]})}),_t=({src:n,alt:r,preCannedPlaying:l=!1,className:a,style:s})=>{const[c,d]=t.useState(!1),m=t.useRef(n);if(t.useEffect(()=>{m.current!==n&&(m.current=n,d(!1))},[n]),!n)return null;const u={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:l?"scale(1.02)":"scale(1)",opacity:c?1:0,...s};return e.jsx("img",{src:n,alt:r,className:a,style:u,loading:"eager",fetchpriority:"high",onLoad:()=>d(!0)})},kt=({position:n,isMobile:r,agentName:l,avatarImageUrl:a,idleLoopUrl:s,greeting:c,branding:d,teamMembers:m,currentTeamMemberId:u,isSwitchingTeamMember:x,teamSwitcherOpen:p,onToggleTeamSwitcher:i,onSelectTeamMember:o,languageMenuOpen:k,onToggleLanguageMenu:b,connectionState:j,agentState:N,transcript:C,canResume:M,needsUserGesture:L,error:R,isMuted:S,micError:y,micDevices:_,isCameraEnabled:v,cameraPreviewEl:E,cameraDevices:G,activeCameraId:Q,isScreenShareEnabled:T,screenPreviewEl:z,isSpeakerMuted:$,allowCamera:Z,allowScreenShare:I,allowTyping:ge,avatarVideoContainerRef:ve,onConnect:fe,onDisconnect:ie,onRetry:be,onResumeAudio:ye,onToggleMute:Y,onToggleCamera:D,onSwitchCameraDevice:he,onToggleScreenShare:H,onToggleSpeaker:O,onSendMessage:J,onMinimize:ee,onClose:P,onClearMicError:V})=>{var pe;const B=C.length>0?C[C.length-1]:null,W=((m==null?void 0:m.length)??0)>1,te=j==="connecting"||j==="connected",F=j==="connected",oe=j==="idle"||j==="disconnected"||j==="error",ce=t.useRef(null),ne=t.useRef(null);t.useEffect(()=>{const h=ce.current;h&&(h.innerHTML="",E&&(E.style.width="100%",E.style.height="100%",E.style.objectFit="cover",E.style.transform="scaleX(-1)",h.appendChild(E)))},[E]),t.useEffect(()=>{const h=ne.current;h&&(h.innerHTML="",z&&(z.style.width="100%",z.style.height="100%",z.style.objectFit="contain",h.appendChild(z)))},[z]);const[K,re]=t.useState(!1),[se,q]=t.useState(!1);t.useEffect(()=>{if(!K&&!se&&!k&&!p)return;const h=()=>{re(!1),q(!1),k&&b(),p&&i()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[K,se,k,p,b,i]);const[le,ae]=t.useState(""),A=t.useCallback(h=>{h.preventDefault();const U=le.trim();U&&(J(U),ae(""))},[le,J]),f=d.productName||"Live Layer",de=F&&(B!=null&&B.text)?B.text:c||"",_e=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return e.jsxs("div",{className:_e,"data-position":n,"data-state":F?"connected":te?"connecting":"idle",role:"dialog","aria-label":`${l} widget`,children:[e.jsxs("div",{className:"ll-expanded__bg",children:[a?e.jsx(_t,{src:a,alt:l,className:"ll-expanded__bg-img"}):e.jsx("div",{className:"ll-expanded__bg-fallback",children:e.jsx("span",{className:"ll-expanded__bg-initial",children:((pe=l==null?void 0:l.charAt(0))==null?void 0:pe.toUpperCase())||"A"})}),s&&!F&&e.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),e.jsx("div",{ref:ve,className:"ll-expanded__video"}),j==="connecting"&&e.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[e.jsx("div",{className:"ll-expanded__spinner"}),e.jsx("p",{className:"ll-expanded__overlay-text",children:x?"Switching...":"Connecting..."})]}),L&&F&&e.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:ye,children:[e.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:e.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),e.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),te?e.jsxs("div",{className:"ll-expanded__topbar",children:[e.jsxs("div",{className:"ll-expanded__topbar-left",children:[e.jsxs("div",{className:"ll-expanded__pill-wrap",children:[e.jsxs("button",{type:"button",className:"ll-hpill",onClick:h=>{W&&(h.stopPropagation(),i())},"aria-haspopup":W?"listbox":void 0,"aria-expanded":W?p:void 0,children:[e.jsx("span",{className:"ll-hpill__label",children:l}),W&&e.jsx(me,{})]}),W&&p&&e.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:m==null?void 0:m.map(h=>e.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===u?"is-active":""}`,onClick:()=>o(h.id),role:"option","aria-selected":h.id===u,children:[h.avatarImageUrl&&e.jsx("img",{src:h.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),e.jsx("span",{className:"ll-hmenu__name",children:h.name}),h.role&&e.jsx("span",{className:"ll-hmenu__role",children:h.role})]},h.id))})]}),e.jsxs("div",{className:"ll-expanded__pill-wrap",children:[e.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:h=>{h.stopPropagation(),b()},"aria-haspopup":"listbox","aria-expanded":k,"aria-label":"Language: English",title:"Language: English",children:[e.jsx("span",{className:"ll-hpill__label",children:"EN"}),e.jsx(me,{})]}),k&&e.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:e.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:e.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),e.jsx("span",{className:`ll-expanded__state ll-expanded__state--${N}`,children:N})]}),e.jsxs("div",{className:"ll-expanded__header-actions",children:[e.jsx("button",{type:"button",className:"ll-hbtn",onClick:ee,"aria-label":"Minimize widget",title:"Minimize",children:e.jsx(Pe,{})}),e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:P,"aria-label":"End conversation",title:"End conversation",children:e.jsx(ze,{})})]})]}):e.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[e.jsx("span",{className:"ll-expanded__brand",children:f}),e.jsxs("div",{className:"ll-expanded__header-actions",children:[e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:ee,"aria-label":"Minimize widget",children:e.jsx(Pe,{})}),e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:P,"aria-label":"Close widget",children:e.jsx(ze,{})})]})]}),oe&&e.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:fe,"aria-label":M?"Resume session":"Start video call",children:[e.jsx("div",{className:"ll-expanded__play-circle",children:e.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:e.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),e.jsx("span",{className:"ll-expanded__play-label",children:M?"Restart session":"Start video call"}),M&&e.jsx("span",{className:"ll-expanded__play-sublabel",children:"Pick up where you left off"})]}),e.jsxs("div",{className:`ll-expanded__pip ${te&&(v||T)?"is-visible":""}`,children:[e.jsx("div",{ref:ne,className:T?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),e.jsx("div",{ref:ce,className:!T&&v?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),te?e.jsxs("div",{className:"ll-expanded__bottom",children:[de&&e.jsx("div",{className:"ll-expanded__transcript",children:e.jsx("p",{className:"ll-expanded__transcript-text",children:de})}),e.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[I&&e.jsx("button",{type:"button",className:`ll-tool ${T?"is-on":""}`,onClick:H,"aria-label":T?"Stop sharing screen":"Share screen",title:T?"Stop sharing":"Share screen",children:e.jsx(jt,{})}),Z&&e.jsxs("div",{className:"ll-tool-split",children:[e.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${v?"is-on":""}`,onClick:D,"aria-label":v?"Turn off camera":"Turn on camera",title:v?"Stop camera":"Start camera",children:e.jsx(Ct,{})}),e.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${v?"is-on":""}`,onClick:h=>{h.stopPropagation(),q(U=>!U),re(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":se,children:e.jsx(me,{})}),se&&G.length>0&&e.jsx(Be,{label:"Camera",devices:G,activeId:Q,onPick:h=>{q(!1),he(h)}})]}),e.jsxs("div",{className:"ll-tool-split",children:[e.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${S?"is-muted":""}`,onClick:Y,"aria-label":S?"Unmute microphone":"Mute microphone",title:S?"Unmute":"Mute",children:e.jsx(wt,{muted:S})}),e.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${S?"is-muted":""}`,onClick:h=>{h.stopPropagation(),re(U=>!U),q(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":K,children:e.jsx(me,{})}),K&&_.length>0&&e.jsx(Be,{label:"Microphone",devices:_,activeId:"",onPick:()=>re(!1)})]}),e.jsx("button",{type:"button",className:`ll-tool ${$?"is-muted":""}`,onClick:O,"aria-label":$?"Unmute speaker":"Mute speaker",title:$?"Unmute speaker":"Mute speaker",children:e.jsx(St,{muted:$})})]}),ge&&e.jsxs("form",{className:"ll-message-input",onSubmit:A,children:[e.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:le,onChange:h=>ae(h.target.value),"aria-label":"Message the agent"}),le.trim()&&e.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:e.jsx(Et,{})})]}),e.jsx("button",{type:"button",className:"ll-expanded__end",onClick:ie,children:"End conversation"})]}):c&&e.jsx("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:e.jsx("div",{className:"ll-expanded__transcript",children:e.jsx("p",{className:"ll-expanded__transcript-text",children:c})})}),(()=>{if(y&&j!=="error")return e.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[e.jsx("span",{children:y}),e.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:V,"aria-label":"Dismiss",children:"×"})]});if(!R||j!=="error")return null;let h="Failed to connect",U="Try again";return R==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":R==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":R==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":R==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":R==="CONNECT_FAILED"?h="Connection failed. Check your network.":R.length<80&&(h=R),e.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:be,children:U})]})})()]})};function me(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})}function ze(){return e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Pe(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function jt(){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ct(){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),e.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function wt({muted:n}){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),e.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),e.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n&&e.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function St({muted:n}){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),n?e.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),e.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function Et(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),e.jsx("polyline",{points:"12 5 19 12 12 19"})]})}const Be=({label:n,devices:r,activeId:l,onPick:a})=>e.jsxs("div",{className:"ll-device-menu",onClick:s=>s.stopPropagation(),role:"listbox",children:[e.jsx("p",{className:"ll-device-menu__label",children:n}),r.map((s,c)=>{const d=l===s.deviceId;return e.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>a(s.deviceId),role:"option","aria-selected":d,children:[d&&e.jsx("span",{className:"ll-device-menu__dot",children:"●"}),e.jsx("span",{className:"ll-device-menu__name",children:s.label||`${n} ${c+1}`})]},s.deviceId||c)})]}),Nt=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout"]);function Mt(n){var Se,Ee,Ne,Me,Le,Re;const{agentId:r,apiKey:l,baseUrl:a="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:c,autoConnect:d=!1,displayMode:m,defaultDisplayMode:u="expanded",onDisplayModeChange:x,position:p="bottom-right",mobileBreakpoint:i=640,persistKey:o="ll-widget",disablePersistence:k=!1,teamMembers:b,currentTeamMemberId:j,onTeamMemberChange:N,idleLoopUrl:C,greeting:M,avatarImageUrl:L,agentName:R,branding:S={},allowCamera:y=!0,allowScreenShare:_=!0,allowTyping:v=!0,onConnect:E,onDisconnect:G,onTranscript:Q,onAgentState:T,onConnectionStateChange:z,onAgentEvent:$,onAgentCommand:Z,controlledSession:I,className:ge,style:ve,zIndex:fe=2147483647}=n,ie=j!==void 0,[be,ye]=t.useState(()=>{var g;return j??((g=b==null?void 0:b[0])==null?void 0:g.id)}),Y=ie?j:be,D=t.useMemo(()=>(b==null?void 0:b.find(g=>g.id===Y))??null,[b,Y]),he=(D==null?void 0:D.agentId)??r,[H,O]=Ye({value:m,defaultValue:u,onChange:x,persistKey:o,disablePersistence:k}),J=He(i),ee=Oe(),P=Ve(),V=We(),B=Fe(),W=Ke(),[te,F]=t.useState(!1),[oe,ce]=t.useState(!1),[ne,K]=t.useState(!1),[re,se]=t.useState(!1),[q,le]=t.useState(!1),ae=t.useCallback(g=>{const w=g;!w.type||typeof w.type!="string"||($==null||$({eventName:w.type,data:g}),Nt.has(w.type)||Z==null||Z(w))},[Z,$]),A=$e({agentId:I?"__controlled__":he,baseUrl:a,apiKey:l,sessionEndpoint:s,sessionBody:c,onDataMessage:I?void 0:ae});t.useEffect(()=>{if(I!=null&&I.subscribeToDataMessages)return I.subscribeToDataMessages(ae)},[I,ae]);const f=t.useMemo(()=>I?{connectionState:I.connectionState,agentState:I.agentState,transcript:I.transcript,videoElement:I.videoElement,audioElement:I.audioElement,canResume:I.canResume,error:I.error,agentConfig:null,connect:async()=>{await I.onConnect()},disconnect:()=>I.onDisconnect(),getRoom:A.getRoom,isControlled:!0}:{connectionState:A.connectionState,agentState:A.agentState,transcript:A.transcript,videoElement:A.videoElement,audioElement:A.audioElement,canResume:A.canResume,error:A.error,agentConfig:A.agentConfig,connect:A.connect,disconnect:A.disconnect,getRoom:A.getRoom,isControlled:!1},[I,A]),de=t.useRef(null);t.useEffect(()=>{const g=f.videoElement,w=de.current;if(!(!g||!w))return w.appendChild(g),()=>{g.parentNode===w&&w.removeChild(g)}},[f.videoElement]),t.useEffect(()=>{const g=f.audioElement;if(!g)return;ee.attach(g);const w=g.play();return w&&typeof w.catch=="function"&&w.catch(X=>{(X==null?void 0:X.name)==="NotAllowedError"&&F(!0)}),()=>{ee.detach()}},[f.audioElement]),t.useEffect(()=>{if(f.isControlled||f.connectionState!=="connected")return;const g=f.getRoom();if(g)return P.setupMic(g).catch(()=>{}),V.attachRoom(g),B.attachRoom(g),W.refresh(),()=>{P.teardownMic(),V.teardown(),B.teardown()}},[f.isControlled,f.connectionState]),t.useEffect(()=>{const g=f.audioElement;g&&(g.muted=q)},[f.audioElement,q]);const _e=t.useCallback(g=>{const w=f.getRoom();if(w)try{const X=new TextEncoder().encode(JSON.stringify({type:"user_message",text:g}));w.localParticipant.publishData(X,{reliable:!0})}catch{}},[f]),pe=t.useCallback(()=>{le(g=>!g)},[]);t.useEffect(()=>{z==null||z(f.connectionState),f.connectionState==="connected"?E==null||E():f.connectionState==="disconnected"&&(G==null||G())},[f.connectionState,E,G,z]),t.useEffect(()=>{Q==null||Q(f.transcript)},[f.transcript,Q]),t.useEffect(()=>{T==null||T(f.agentState)},[f.agentState,T]);const h=t.useRef(!1);t.useEffect(()=>{f.isControlled||!d||h.current||f.connectionState==="idle"&&(h.current=!0,f.connect())},[d,f.connectionState,f]);const U=t.useCallback(g=>{const w=b==null?void 0:b.find(X=>X.id===g);w&&(K(!1),g!==Y&&(ce(!0),f.disconnect(),ie||ye(g),N==null||N(w)))},[b,Y,f,ie,N]);t.useEffect(()=>{oe&&f.connectionState==="connected"&&ce(!1)},[f.connectionState,oe]),t.useEffect(()=>{if(!ne)return;const g=w=>{w.key==="Escape"&&K(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[ne]);const Xe=!!L||!!(D!=null&&D.avatarImageUrl)||f.isControlled,ke=qe(he,a,Xe),je=(D==null?void 0:D.name)??R??((Se=f.agentConfig)==null?void 0:Se.name)??((Ee=ke.info)==null?void 0:Ee.name)??"Live Layer",Ce=(D==null?void 0:D.avatarImageUrl)??L??((Ne=f.agentConfig)==null?void 0:Ne.avatarImageUrl)??((Me=ke.info)==null?void 0:Me.avatarImageUrl)??null,Qe=C??((Le=f.agentConfig)==null?void 0:Le.idleLoopUrl)??((Re=ke.info)==null?void 0:Re.idleLoopUrl)??null,Ze=M??null,et=t.useCallback(()=>O("expanded"),[O]),tt=t.useCallback(()=>O("minimized"),[O]),we=t.useCallback(()=>{f.disconnect(),O("hidden")},[f,O]),nt=t.useCallback(()=>{const g=f.audioElement;g&&g.play().then(()=>F(!1)).catch(()=>{})},[f.audioElement]),rt=t.useCallback(()=>{F(!1),f.connect()},[f]),ue={...ve,zIndex:fe};S.primaryColor&&(ue["--ll-color-primary"]=S.primaryColor),S.accentColor&&(ue["--ll-color-accent"]=S.accentColor),S.backgroundColor&&(ue["--ll-color-bg"]=S.backgroundColor),S.textColor&&(ue["--ll-color-fg"]=S.textColor);const st=["ll-widget",`ll-widget--${H}`,`ll-widget--${J?"mobile":"desktop"}`,ge].filter(Boolean).join(" ");return e.jsxs("div",{className:st,style:ue,"data-display-mode":H,"data-position":p,children:[H==="hidden"&&e.jsx(vt,{position:p,isMobile:J,isSpeaking:f.agentState==="speaking",onExpand:()=>O("expanded"),label:`Open ${je} widget`}),H==="minimized"&&e.jsx(yt,{position:p,isMobile:J,agentName:je,avatarImageUrl:Ce,agentState:f.agentState,isMuted:P.isMuted,audioLevel:ee,onExpand:et,onToggleMute:P.toggleMute,onClose:we}),H==="expanded"&&e.jsx(kt,{position:p,isMobile:J,agentName:je,avatarImageUrl:Ce,idleLoopUrl:Qe,greeting:Ze,branding:S,teamMembers:b,currentTeamMemberId:Y,isSwitchingTeamMember:oe,teamSwitcherOpen:ne,onToggleTeamSwitcher:()=>K(g=>!g),onSelectTeamMember:U,connectionState:f.connectionState,agentState:f.agentState,transcript:f.transcript,isMuted:P.isMuted,micDevices:W.mics,isCameraEnabled:V.isEnabled,cameraPreviewEl:V.previewEl,cameraDevices:W.cameras,activeCameraId:V.activeDeviceId,isScreenShareEnabled:B.isEnabled,screenPreviewEl:B.previewEl,isSpeakerMuted:q,allowCamera:y,allowScreenShare:_,allowTyping:v,languageMenuOpen:re,onToggleLanguageMenu:()=>se(g=>!g),needsUserGesture:te,canResume:f.canResume,micError:P.micError,error:f.error,avatarVideoContainerRef:de,onConnect:()=>void f.connect(),onDisconnect:()=>f.disconnect(),onRetry:rt,onResumeAudio:nt,onToggleMute:P.toggleMute,onToggleCamera:()=>void V.toggle(),onSwitchCameraDevice:g=>void V.switchDevice(g),onToggleScreenShare:()=>void B.toggle(),onToggleSpeaker:pe,onSendMessage:_e,onMinimize:tt,onClose:we,onClearMicError:P.clearError})]})}function Lt(n){return e.jsx(Ue,{children:e.jsx(Mt,{...n})})}const Rt=({agentId:n,baseUrl:r,apiKey:l,mode:a,onAgentEvent:s,className:c,style:d})=>{const m=t.useRef(null),u=t.useRef(null),x=t.useRef(s);x.current=s;const p=t.useCallback(i=>{var k;const o=i.detail;(k=x.current)==null||k.call(x,o)},[]);return t.useEffect(()=>{const i=m.current;if(!i)return;const o=document.createElement("livelayer-widget");return o.setAttribute("agent-id",n),r&&o.setAttribute("base-url",r),l&&o.setAttribute("api-key",l),a&&o.setAttribute("mode",a),o.addEventListener("agent-event",p),i.appendChild(o),u.current=o,()=>{o.removeEventListener("agent-event",p),i.removeChild(o),u.current=null}},[n]),t.useEffect(()=>{u.current&&(a?u.current.setAttribute("mode",a):u.current.removeAttribute("mode"))},[a]),e.jsx("div",{ref:m,className:c,style:d})};function It(){const[n,r]=t.useState([]),l=t.useCallback(s=>{r(c=>{const d=c.findIndex(m=>m.id===s.id);if(d>=0){const m=c.slice();return m[d]=s,m}return[...c,s]})},[]),a=t.useCallback(()=>r([]),[]);return{entries:n,pushSegment:l,clear:a,latest:n.length>0?n[n.length-1]:null}}exports.AvatarWidget=Lt;exports.ErrorBoundary=Ue;exports.LiveLayerWidget=Rt;exports.useAgentInfo=qe;exports.useAudioLevel=Oe;exports.useCameraState=We;exports.useDisplayMode=Ge;exports.useDisplayModePersistence=Ye;exports.useIsMobile=He;exports.useLiveKitSession=$e;exports.useMediaDevices=Ke;exports.useMicrophoneState=Ve;exports.useScreenShareState=Fe;exports.useTranscript=It;
|
|
1
|
+
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),n=require("react"),qt=require("@livelayer/sdk"),Ae=require("livekit-client");class xt extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,i){var s,o;(o=(s=this.props).onError)==null||o.call(s,r,i)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[e.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),e.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),e.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function vt(t){const[r,i]=n.useState("idle"),[s,o]=n.useState("idle"),[l,d]=n.useState([]),[f,u]=n.useState(null),[x,p]=n.useState(null),[a,c]=n.useState(null),[j,_]=n.useState(!1),[k,R]=n.useState(null),y=n.useRef(null),L=n.useRef(t.onDataMessage);L.current=t.onDataMessage,n.useEffect(()=>{const w={onConnectionStateChange:b=>{i(b),b==="connected"&&R(null)},onAgentStateChange:o,onTranscript:b=>d([...b]),onAgentConfig:u,onAudioTrack:b=>c(b),onVideoTrack:b=>p(b),onVideoTrackRemoved:()=>p(null),onError:b=>R(b),onDataMessage:b=>{var M;(M=L.current)==null||M.call(L,b)},onResumabilityChange:_},S=new qt.LiveKitSession({agentId:t.agentId,baseUrl:t.baseUrl,apiKey:t.apiKey,sessionEndpoint:t.sessionEndpoint,sessionBody:t.sessionBody},w);return y.current=S,i("idle"),o("idle"),d([]),u(null),p(null),c(null),_(!1),R(null),()=>{var b;(b=S.destroy)==null||b.call(S),y.current=null}},[t.agentId,t.baseUrl,t.apiKey,t.sessionEndpoint,JSON.stringify(t.sessionBody??{})]);const m=n.useCallback(async()=>{const w=y.current;if(w)try{await w.connect()}catch(S){throw R(S instanceof Error?S.message:String(S)),S}},[]),C=n.useCallback(()=>{const w=y.current;w&&w.disconnect()},[]),N=n.useCallback(()=>{var w;return((w=y.current)==null?void 0:w.getRoom())??null},[]);return{connectionState:r,agentState:s,transcript:l,agentConfig:f,videoElement:x,audioElement:a,canResume:j,error:k,connect:m,disconnect:C,getRoom:N,session:y.current}}function yt(){const t=n.useRef(null),r=n.useRef(null),i=n.useRef(null),s=n.useRef(null),o=n.useRef(new Set),l=n.useRef(null),d=n.useCallback(()=>{const a=r.current;if(!a){s.current=null;return}(!l.current||l.current.length!==a.frequencyBinCount)&&(l.current=new Uint8Array(new ArrayBuffer(a.frequencyBinCount)));const c=l.current;a.getByteFrequencyData(c);let j=0;for(let k=0;k<c.length;k++)j+=c[k];const _=j/c.length/255;for(const k of o.current)try{k(_)}catch(R){console.error("[useAudioLevel] subscriber threw:",R)}s.current=requestAnimationFrame(d)},[]),f=n.useCallback(()=>{if(t.current||typeof window>"u"||typeof AudioContext>"u")return;const a=new AudioContext,c=a.createAnalyser();c.fftSize=64,c.connect(a.destination),t.current=a,r.current=c},[]),u=n.useCallback(a=>{if(f(),!(!t.current||!r.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=t.current.createMediaElementSource(a);c.connect(r.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}s.current===null&&(s.current=requestAnimationFrame(d))}},[f,d]),x=n.useCallback(()=>{if(s.current!==null&&(cancelAnimationFrame(s.current),s.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),p=n.useCallback(a=>(o.current.add(a),()=>{o.current.delete(a)}),[]);return n.useEffect(()=>()=>{if(x(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(t.current){try{t.current.close()}catch{}t.current=null}o.current.clear(),l.current=null},[x]),{attach:u,detach:x,subscribe:p}}function bt(){const[t,r]=n.useState(!1),[i,s]=n.useState(null),o=n.useRef(null),l=n.useRef(null),d=n.useCallback(async p=>{if(o.current&&l.current){try{await l.current.localParticipant.unpublishTrack(o.current)}catch{}o.current.stop(),o.current=null}l.current=p,s(null);try{const a=await Ae.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await p.localParticipant.publishTrack(a),o.current=a,r(a.isMuted)}catch(a){const c=a instanceof Error&&a.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw s(c),a}},[]),f=n.useCallback(()=>{const p=o.current;p&&(p.isMuted?(p.unmute(),r(!1)):(p.mute(),r(!0)))},[]),u=n.useCallback(()=>{const p=o.current,a=l.current;if(p&&a){try{a.localParticipant.unpublishTrack(p)}catch{}p.stop()}o.current=null,l.current=null,r(!1)},[]),x=n.useCallback(()=>s(null),[]);return{isMuted:t,micError:i,toggleMute:f,setupMic:d,teardownMic:u,clearError:x}}const Gt={resolution:{width:640,height:480,frameRate:24}};function _t(){const[t,r]=n.useState(!1),[i,s]=n.useState(null),[o,l]=n.useState(null),[d,f]=n.useState(""),u=n.useRef(null),x=n.useRef(null),p=n.useCallback(y=>{u.current=y},[]),a=n.useCallback(()=>{const y=u.current,L=x.current;if(L&&y){const m=y.localParticipant.getTrackPublication(Ae.Track.Source.Camera);if(m!=null&&m.track){try{y.localParticipant.unpublishTrack(m.track)}catch{}m.track.stop()}else L.stop()}x.current=null,l(null),r(!1)},[]),c=n.useCallback(async y=>{const L=u.current;if(L){s(null);try{const m={...Gt};y&&(m.deviceId=y);const C=await Ae.createLocalVideoTrack(m);await L.localParticipant.publishTrack(C),x.current=C;const N=C.attach();l(N),r(!0),y&&f(y);try{L.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(m){const C=m instanceof Error&&m.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";s(C)}}},[]),j=n.useCallback(async()=>{t?a():await c(d||void 0)},[t,d,a,c]),_=n.useCallback(async y=>{a(),await c(y)},[a,c]),k=n.useCallback(()=>{a(),u.current=null,s(null),f("")},[a]),R=n.useCallback(()=>s(null),[]);return n.useEffect(()=>()=>{x.current&&x.current.stop()},[]),{isEnabled:t,error:i,previewEl:o,activeDeviceId:d,toggle:j,switchDevice:_,attachRoom:p,teardown:k,clearError:R}}function wt(){const[t,r]=n.useState(!1),[i,s]=n.useState(null),[o,l]=n.useState(null),d=n.useRef(null),f=n.useCallback(c=>{d.current=c},[]),u=n.useCallback(()=>l(null),[]),x=n.useCallback(async()=>{const c=d.current;if(c){if(t){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1);return}s(null);try{await c.localParticipant.setScreenShareEnabled(!0);let j=0;const _=()=>{const k=c.localParticipant.getTrackPublication(Ae.Track.Source.ScreenShare);if(k!=null&&k.track){const R=k.track.attach();l(R),r(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}j++<10?setTimeout(_,100):r(!0)};_()}catch(j){const _=j instanceof Error?j.name:"";_!=="NotAllowedError"&&_!=="AbortError"&&s("Screen share unavailable. Try again."),r(!1)}}},[t,u]),p=n.useCallback(()=>{const c=d.current;if(c&&t)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1),s(null),d.current=null},[t,u]),a=n.useCallback(()=>s(null),[]);return{isEnabled:t,error:i,previewEl:o,toggle:x,attachRoom:f,teardown:p,clearError:a}}function kt(){const[t,r]=n.useState([]),[i,s]=n.useState([]),o=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const l=await navigator.mediaDevices.enumerateDevices();r(l.filter(d=>d.kind==="audioinput")),s(l.filter(d=>d.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(o(),typeof navigator>"u"||!navigator.mediaDevices)return;const l=()=>void o();return navigator.mediaDevices.addEventListener("devicechange",l),()=>navigator.mediaDevices.removeEventListener("devicechange",l)},[o]),{mics:t,cameras:i,refresh:o}}function Ct(t,r,i=!1){const[s,o]=n.useState(null),[l,d]=n.useState(null),[f,u]=n.useState(!i&&!!t);return n.useEffect(()=>{if(i||!t){u(!1);return}const x=new AbortController,p=r||"https://app.livelayer.studio";return u(!0),d(null),fetch(`${p}/api/widget/agent/${encodeURIComponent(t)}`,{signal:x.signal}).then(async a=>{if(!a.ok){const c=await a.json().catch(()=>({}));throw new Error(c.error||`HTTP ${a.status}`)}return a.json()}).then(a=>{x.signal.aborted||(o(a),u(!1))}).catch(a=>{x.signal.aborted||(d(a instanceof Error?a.message:"Agent lookup failed"),u(!1))}),()=>x.abort()},[t,r,i]),{info:s,error:l,loading:f}}function Kt(t){if(typeof window>"u")return null;try{return window.localStorage.getItem(t)}catch{return null}}function Yt(t,r){if(!(typeof window>"u"))try{window.localStorage.setItem(t,r)}catch{}}function jt({value:t,defaultValue:r="expanded",onChange:i}={}){const s=t!==void 0,[o,l]=n.useState(r),d=s?t:o,f=n.useCallback(u=>{u!==d&&(s||l(u),i==null||i(u))},[d,s,i]);return[d,f]}const Xt=["hidden","minimized","expanded"];function Jt(t){return t&&Xt.includes(t)?t:null}function St({value:t,defaultValue:r="expanded",onChange:i,persistKey:s="ll-widget",disablePersistence:o=!1}={}){const l=`${s}:display-mode`,d=n.useRef(!1),[f,u]=jt({value:t,defaultValue:r,onChange:x=>{t===void 0&&!o&&Yt(l,x),i==null||i(x)}});return n.useEffect(()=>{if(d.current||(d.current=!0,o||t!==void 0))return;const x=Jt(Kt(l));x&&x!==f&&u(x)},[]),[f,u]}const Qt=640;function Et(t=Qt){const[r,i]=n.useState(!1);return n.useEffect(()=>{if(t===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const s=`(max-width: ${t-1}px)`,o=window.matchMedia(s),l=()=>i(o.matches);return l(),typeof o.addEventListener=="function"?(o.addEventListener("change",l),()=>o.removeEventListener("change",l)):(o.addListener(l),()=>{o.removeListener(l)})},[t]),r}const st="__llHistoryPatched",Me="ll:pathname";function Zt(){if(typeof window>"u"||window.history[st])return;const t=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...i){const s=t.apply(this,i);return window.dispatchEvent(new Event(Me)),s},window.history.replaceState=function(...i){const s=r.apply(this,i);return window.dispatchEvent(new Event(Me)),s},window.history[st]=!0}function ot(){return typeof window>"u"?"/":window.location.pathname||"/"}function Nt(t){const[r,i]=n.useState(()=>t??ot());return n.useEffect(()=>{if(t!==void 0)return;Zt();const s=()=>i(ot());return s(),window.addEventListener("popstate",s),window.addEventListener(Me,s),()=>{window.removeEventListener("popstate",s),window.removeEventListener(Me,s)}},[t]),t??r}const lt=new Map,en=/[\\^$+?.()|{}[\]]/g;function tn(t){return t.replace(en,"\\$&")}function nn(t){const r=lt.get(t);if(r)return r;const i=t.length>1&&t.endsWith("/")?t.slice(0,-1):t,s="",o="",l=i.replace(/\*\*/g,s).replace(/\*/g,o),f=tn(l).replace(new RegExp(`\\/${s}`,"g"),"(?:\\/.*)?").replace(new RegExp(s,"g"),".*").replace(new RegExp(o,"g"),"[^/]+"),u=new RegExp(`^${f}\\/?$`);return lt.set(t,u),u}function rn(t,r){const i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return nn(t).test(i)}function Lt(t,r){return typeof t=="function"?t(r):t instanceof RegExp?t.test(r):rn(t,r)}function at(t,r){if(!t||t.length===0)return!1;for(const i of t)if(Lt(i,r))return!0;return!1}function Rt(t,r,i){return t===void 0?!0:at(i,t)?!1:r&&r.length>0?at(r,t):!0}function At(t,r,i){return n.useMemo(()=>Rt(t,r,i),[t,r,i])}const ct=({muted:t=!1,className:r})=>t?e.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):e.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),ut=({className:t})=>e.jsx("svg",{className:t,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),sn=({className:t})=>e.jsx("svg",{className:t,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),on={left:180,right:0,up:-90,down:90},ln=({direction:t="right",className:r})=>e.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${on[t]}deg)`},"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function an(t){return t==="top-left"||t==="bottom-left"?"left":"right"}const Mt="ll-hidden-tab-center-y",cn=5,dt=16;function un(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Mt);if(!t)return null;const r=Number.parseFloat(t);return Number.isFinite(r)?r:null}catch{return null}}function ft(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Mt,String(t))}catch{}}const dn=({position:t,isMobile:r,isSpeaking:i,onExpand:s,label:o="Open widget"})=>{const l=an(t),d=l==="right"?"left":"right",f=r?80:72,[u,x]=n.useState(null),[p,a]=n.useState(!1),c=n.useRef(null),j=n.useRef(!1),_=n.useCallback(w=>{if(typeof window>"u")return w;const S=f/2,b=dt+S,M=window.innerHeight-dt-S;return M<b?Math.max(b,w):Math.max(b,Math.min(M,w))},[f]);n.useEffect(()=>{const w=un();x(_(w??window.innerHeight/2));const S=()=>{x(b=>b===null?null:_(b))};return window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[_]);const k=n.useCallback(w=>{if(!(w.pointerType==="mouse"&&w.button!==0)&&u!==null){try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}c.current={startClientY:w.clientY,startCenterY:u,moved:!1}}},[u]),R=n.useCallback(w=>{const S=c.current;if(!S)return;const b=w.clientY-S.startClientY;!S.moved&&Math.abs(b)>cn&&(S.moved=!0,a(!0)),S.moved&&x(_(S.startCenterY+b))},[_]),y=n.useCallback(w=>{const S=c.current;if(S){try{w.currentTarget.releasePointerCapture(w.pointerId)}catch{}c.current=null,S.moved&&(a(!1),j.current=!0,x(b=>(b!==null&&ft(b),b)))}},[]),L=n.useCallback(()=>{if(j.current){j.current=!1;return}s()},[s]),m=n.useCallback(w=>{if(w.key==="ArrowUp"||w.key==="ArrowDown"){w.preventDefault();const S=w.key==="ArrowUp"?-8:8;x(b=>{if(b===null)return b;const M=_(b+S);return ft(M),M})}},[_]),C=["ll-hidden",`ll-hidden--${l}`,r?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,p?"is-dragging":null].filter(Boolean).join(" "),N=u===null?void 0:{top:`${u-f/2}px`,transform:"none"};return e.jsx("button",{type:"button",className:C,onPointerDown:k,onPointerMove:R,onPointerUp:y,onPointerCancel:y,onClick:L,onKeyDown:m,"aria-label":o,"data-position":t,style:N,children:e.jsx(ln,{direction:d,className:"ll-hidden__chevron"})})},fn=({audioLevel:t,bars:r=20,maxHeight:i=20,minHeight:s=4,className:o,barClassName:l})=>{const d=n.useRef(null),f=n.useRef([]),u=n.useMemo(()=>{const p=(Math.sqrt(5)-1)/2;return Array.from({length:r},(a,c)=>.5+c*p%1*.5)},[r]);n.useEffect(()=>t.subscribe(a=>{for(let c=0;c<r;c++){const j=f.current[c];if(!j)continue;const _=Math.max(s,a*i*u[c]);j.style.height=`${_}px`}}),[t,r,i,s,u]);const x=["ll-waveform",o].filter(Boolean).join(" ");return e.jsx("div",{ref:d,className:x,"aria-hidden":"true",children:Array.from({length:r},(p,a)=>e.jsx("div",{ref:c=>{f.current[a]=c},className:["ll-waveform__bar",l].filter(Boolean).join(" "),style:{height:`${s}px`}},a))})},hn=({position:t,isMobile:r,agentName:i,avatarImageUrl:s,agentState:o,isMuted:l,audioLevel:d,onExpand:f,onToggleMute:u,onClose:x})=>r?e.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:e.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:f,"aria-label":`Expand ${i} widget`,children:[s?e.jsx("img",{src:s,alt:i,className:"ll-minimized__avatar"}):e.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),e.jsx(fn,{audioLevel:d,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),e.jsx("span",{className:"ll-minimized__name",children:i}),e.jsxs("div",{className:"ll-minimized__controls",children:[e.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:p=>{p.stopPropagation(),u()},onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.stopPropagation(),p.preventDefault(),u())},"aria-label":l?"Unmute microphone":"Mute microphone",children:e.jsx(ct,{muted:l,className:"ll-minimized__icon"})}),e.jsx(ut,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):e.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":t,role:"region","aria-label":`${i} widget`,children:e.jsxs("div",{className:"ll-minimized__surface",children:[s?e.jsx("img",{src:s,alt:i,className:"ll-minimized__avatar"}):e.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),e.jsxs("div",{className:"ll-minimized__meta",children:[e.jsx("span",{className:"ll-minimized__name",children:i}),e.jsx("span",{className:"ll-minimized__state",children:o==="speaking"?"Speaking":o==="thinking"?"Thinking":"Listening"})]}),e.jsxs("div",{className:"ll-minimized__controls",children:[e.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":l?"Unmute microphone":"Mute microphone",children:e.jsx(ct,{muted:l,className:"ll-minimized__icon"})}),e.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":`Expand ${i} widget`,children:e.jsx(ut,{className:"ll-minimized__icon"})}),e.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:x,"aria-label":"Close widget",children:e.jsx(sn,{className:"ll-minimized__icon"})})]})]})}),pn=({src:t,alt:r,preCannedPlaying:i=!1,className:s,style:o})=>{const[l,d]=n.useState(!1),f=n.useRef(t);if(n.useEffect(()=>{f.current!==t&&(f.current=t,d(!1))},[t]),!t)return null;const u={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:l?1:0,...o};return e.jsx("img",{src:t,alt:r,className:s,style:u,loading:"eager",fetchpriority:"high",onLoad:()=>d(!0)})},mn=({position:t,isMobile:r,agentName:i,avatarImageUrl:s,idleLoopUrl:o,greeting:l,branding:d,teamMembers:f,currentTeamMemberId:u,isSwitchingTeamMember:x,teamSwitcherOpen:p,onToggleTeamSwitcher:a,onSelectTeamMember:c,languageMenuOpen:j,onToggleLanguageMenu:_,connectionState:k,agentState:R,transcript:y,canResume:L,needsUserGesture:m,error:C,isMuted:N,micError:w,micDevices:S,isCameraEnabled:b,cameraPreviewEl:M,cameraDevices:_e,activeCameraId:Te,isScreenShareEnabled:V,screenPreviewEl:q,isSpeakerMuted:Y,allowCamera:we,allowScreenShare:te,allowTyping:ne,avatarVideoContainerRef:re,onConnect:X,onDisconnect:ie,onRetry:se,onResumeAudio:oe,onToggleMute:A,onToggleCamera:Ie,onSwitchCameraDevice:Pe,onToggleScreenShare:De,onToggleSpeaker:ke,onSendMessage:le,onMinimize:ae,onClose:Ce,onClearMicError:ze})=>{var Se;const U=y.length>0?y[y.length-1]:null,T=((f==null?void 0:f.length)??0)>1,J=k==="connecting"||k==="connected",O=k==="connected",G=k==="idle"||k==="disconnected"||k==="error",Q=n.useRef(null),ce=n.useRef(null);n.useEffect(()=>{const h=Q.current;h&&(h.innerHTML="",M&&(M.style.width="100%",M.style.height="100%",M.style.objectFit="cover",M.style.transform="scaleX(-1)",h.appendChild(M)))},[M]),n.useEffect(()=>{const h=ce.current;h&&(h.innerHTML="",q&&(q.style.width="100%",q.style.height="100%",q.style.objectFit="contain",h.appendChild(q)))},[q]);const[$,B]=n.useState(!1),[H,K]=n.useState(!1);n.useEffect(()=>{if(!$&&!H&&!j&&!p)return;const h=()=>{B(!1),K(!1),j&&_(),p&&a()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[$,H,j,p,_,a]);const[ue,de]=n.useState(""),ge=n.useCallback(h=>{h.preventDefault();const D=ue.trim();D&&(le(D),de(""))},[ue,le]),je=d.productName||"Live Layer",fe=O&&(U!=null&&U.text)?U.text:l||"",xe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return e.jsxs("div",{className:xe,"data-position":t,"data-state":O?"connected":J?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[e.jsxs("div",{className:"ll-expanded__bg",children:[s?e.jsx(pn,{src:s,alt:i,className:"ll-expanded__bg-img"}):e.jsx("div",{className:"ll-expanded__bg-fallback",children:e.jsx("span",{className:"ll-expanded__bg-initial",children:((Se=i==null?void 0:i.charAt(0))==null?void 0:Se.toUpperCase())||"A"})}),o&&!O&&e.jsx("video",{className:"ll-expanded__bg-idle",src:o,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),e.jsx("div",{ref:re,className:"ll-expanded__video"}),k==="connecting"&&e.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[e.jsx("div",{className:"ll-expanded__spinner"}),e.jsx("p",{className:"ll-expanded__overlay-text",children:x?"Switching...":"Connecting..."})]}),m&&O&&e.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:oe,children:[e.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:e.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),e.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),J?e.jsxs("div",{className:"ll-expanded__topbar",children:[e.jsxs("div",{className:"ll-expanded__topbar-left",children:[e.jsxs("div",{className:"ll-expanded__pill-wrap",children:[e.jsxs("button",{type:"button",className:"ll-hpill",onClick:h=>{T&&(h.stopPropagation(),a())},"aria-haspopup":T?"listbox":void 0,"aria-expanded":T?p:void 0,children:[e.jsx("span",{className:"ll-hpill__label",children:i}),T&&e.jsx(Le,{})]}),T&&p&&e.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:f==null?void 0:f.map(h=>e.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===u?"is-active":""}`,onClick:()=>c(h.id),role:"option","aria-selected":h.id===u,children:[h.avatarImageUrl&&e.jsx("img",{src:h.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),e.jsx("span",{className:"ll-hmenu__name",children:h.name}),h.role&&e.jsx("span",{className:"ll-hmenu__role",children:h.role})]},h.id))})]}),e.jsxs("div",{className:"ll-expanded__pill-wrap",children:[e.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:h=>{h.stopPropagation(),_()},"aria-haspopup":"listbox","aria-expanded":j,"aria-label":"Language: English",title:"Language: English",children:[e.jsx("span",{className:"ll-hpill__label",children:"EN"}),e.jsx(Le,{})]}),j&&e.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:e.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:e.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),e.jsx("span",{className:`ll-expanded__state ll-expanded__state--${R}`,children:R})]}),e.jsxs("div",{className:"ll-expanded__header-actions",children:[e.jsx("button",{type:"button",className:"ll-hbtn",onClick:ae,"aria-label":"Minimize widget",title:"Minimize",children:e.jsx(pt,{})}),e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ce,"aria-label":"End call",title:"End call",children:e.jsx(ht,{})})]})]}):e.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[e.jsx("span",{className:"ll-expanded__brand",children:je}),e.jsxs("div",{className:"ll-expanded__header-actions",children:[e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:ae,"aria-label":"Minimize widget",children:e.jsx(pt,{})}),e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ce,"aria-label":"Close widget",children:e.jsx(ht,{})})]})]}),G&&(()=>{const h=L?"Restart paused session":k==="disconnected"?"Reconnect to agent":"Start video call",D=L?"Pick up where you left off":null,$e=k==="idle"&&!L&&!C;return e.jsxs(e.Fragment,{children:[$e&&e.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:X,"aria-label":h,children:[e.jsx("div",{className:"ll-expanded__play-circle",children:e.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:e.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),e.jsx("span",{className:"ll-expanded__play-label",children:h})]}),e.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[l&&e.jsx("div",{className:"ll-expanded__transcript",children:e.jsx("p",{className:"ll-expanded__transcript-text",children:l})}),D&&e.jsx("p",{className:"ll-expanded__cta-sublabel",children:D}),e.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:X,"aria-label":h,children:h})]})]})})(),e.jsxs("div",{className:`ll-expanded__pip ${J&&(b||V)?"is-visible":""}`,children:[e.jsx("div",{ref:ce,className:V?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),e.jsx("div",{ref:Q,className:!V&&b?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),J?e.jsxs("div",{className:"ll-expanded__bottom",children:[fe&&e.jsx("div",{className:"ll-expanded__transcript",children:e.jsx("p",{className:"ll-expanded__transcript-text",children:fe})}),e.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[te&&e.jsx("button",{type:"button",className:`ll-tool ${V?"is-on":""}`,onClick:De,"aria-label":V?"Stop sharing screen":"Share screen",title:V?"Stop sharing":"Share screen",children:e.jsx(gn,{})}),we&&e.jsxs("div",{className:"ll-tool-split",children:[e.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${b?"is-on":""}`,onClick:Ie,"aria-label":b?"Turn off camera":"Turn on camera",title:b?"Stop camera":"Start camera",children:e.jsx(xn,{})}),e.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${b?"is-on":""}`,onClick:h=>{h.stopPropagation(),K(D=>!D),B(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":H,children:e.jsx(Le,{})}),H&&_e.length>0&&e.jsx(mt,{label:"Camera",devices:_e,activeId:Te,onPick:h=>{K(!1),Pe(h)}})]}),e.jsxs("div",{className:"ll-tool-split",children:[e.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${N?"is-muted":""}`,onClick:A,"aria-label":N?"Unmute microphone":"Mute microphone",title:N?"Unmute":"Mute",children:e.jsx(vn,{muted:N})}),e.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${N?"is-muted":""}`,onClick:h=>{h.stopPropagation(),B(D=>!D),K(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":$,children:e.jsx(Le,{})}),$&&S.length>0&&e.jsx(mt,{label:"Microphone",devices:S,activeId:"",onPick:()=>B(!1)})]}),e.jsx("button",{type:"button",className:`ll-tool ${Y?"is-muted":""}`,onClick:ke,"aria-label":Y?"Unmute speaker":"Mute speaker",title:Y?"Unmute speaker":"Mute speaker",children:e.jsx(yn,{muted:Y})})]}),ne&&e.jsxs("form",{className:"ll-message-input",onSubmit:ge,children:[e.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:ue,onChange:h=>de(h.target.value),"aria-label":"Message the agent"}),ue.trim()&&e.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:e.jsx(bn,{})})]}),e.jsx("button",{type:"button",className:"ll-expanded__end",onClick:ie,children:"End conversation"})]}):null,(()=>{if(w&&k!=="error")return e.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[e.jsx("span",{children:w}),e.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:ze,"aria-label":"Dismiss",children:"×"})]});if(!C||k!=="error")return null;let h="Failed to connect",D="Try again";return C==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":C==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":C==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":C==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":C==="CONNECT_FAILED"?h="Connection failed. Check your network.":C.length<80&&(h=C),e.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:se,children:D})]})})()]})};function Le(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})}function ht(){return e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function pt(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function gn(){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function xn(){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),e.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function vn({muted:t}){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),e.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),e.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),t&&e.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function yn({muted:t}){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t?e.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),e.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function bn(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),e.jsx("polyline",{points:"12 5 19 12 12 19"})]})}const mt=({label:t,devices:r,activeId:i,onPick:s})=>e.jsxs("div",{className:"ll-device-menu",onClick:o=>o.stopPropagation(),role:"listbox",children:[e.jsx("p",{className:"ll-device-menu__label",children:t}),r.map((o,l)=>{const d=i===o.deviceId;return e.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>s(o.deviceId),role:"option","aria-selected":d,children:[d&&e.jsx("span",{className:"ll-device-menu__dot",children:"●"}),e.jsx("span",{className:"ll-device-menu__name",children:o.label||`${t} ${l+1}`})]},o.deviceId||l)})]}),Re=4096,_n=20,wn=20,kn=10,gt=500,Cn=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function ye(t){if(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))return!0;let r=t;for(;r;){for(const i of Cn)if(r.matches(i))return!0;r=r.parentElement}return!1}function be(t){if(typeof window>"u")return!0;const r=t.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<i&&r.left<s}function jn(t){if(t.type==="password")return!0;const r=(t.getAttribute("autocomplete")||"").toLowerCase();return!!(r==="off"||r.startsWith("cc-"))}function Sn(t){const r=t.getAttribute("id");if(r){const l=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(l!=null&&l.textContent)return l.textContent.trim()}const i=t.getAttribute("aria-label");if(i)return i.trim();const s=t.getAttribute("placeholder");if(s)return s.trim();const o=t.closest("label");return o!=null&&o.textContent?o.textContent.trim():""}function he(t,r){return t.length<=r?t:t.slice(0,r-1)+"…"}function pe(t){return t.length}function Tt(t,r={}){const i=r.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],extras:t};const s=typeof window<"u"&&window.location.href||"",o=typeof window<"u"&&window.location.pathname||"/",l=i.title||"",d=Array.from(i.querySelectorAll("[data-ll-region]")),f=[];for(const m of d){if(f.length>=kn)break;if(ye(m)||!be(m))continue;const C=m.getAttribute("data-ll-region")??"",N=m.getAttribute("data-ll-intent")??void 0,w=he((m.innerText||m.textContent||"").trim(),gt*2);!C||!w||f.push({id:C,intent:N,text:w})}const u=[],x=["H1","H2","H3","H4","H5","H6"],p=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const m of p){if(ye(m)||!be(m))continue;const C=(m.textContent||"").trim();C&&u.push(`${m.tagName}: ${he(C,200)}`)}const a=Array.from(i.querySelectorAll("p, li"));for(const m of a){if(ye(m)||!be(m)||x.includes(m.tagName))continue;const C=(m.textContent||"").trim();C.length>10&&u.push(he(C,gt))}const c=u.join(`
|
|
2
|
+
`),j=[],_=Array.from(i.querySelectorAll("a[href]"));for(const m of _){if(j.length>=_n)break;if(ye(m)||!be(m))continue;const C=m.getAttribute("href")||"",N=(m.textContent||"").trim();!C||!N||j.push({href:C,text:he(N,100)})}const k=[],R=Array.from(i.querySelectorAll("input, textarea, select"));for(const m of R){if(k.length>=wn)break;if(ye(m)||m instanceof HTMLInputElement&&jn(m)||!be(m))continue;const C=Sn(m),N=m instanceof HTMLInputElement?m.type:m.tagName.toLowerCase();C&&k.push({label:he(C,100),type:N})}const y={url:s,title:l,pathname:o,regions:f,visibleText:c,visibleLinks:j,visibleFields:k,extras:t};let L=pe(JSON.stringify(y.regions))+pe(y.visibleText)+pe(JSON.stringify(y.visibleLinks))+pe(JSON.stringify(y.visibleFields));for(;L>Re&&y.visibleFields.length>0;)y.visibleFields.pop(),L=pe(JSON.stringify(y.visibleFields));for(;L>Re&&y.visibleLinks.length>0;)y.visibleLinks.pop(),L-=80;return pe(y.visibleText)>Re&&(y.visibleText=he(y.visibleText,Re-100)),y}let me=null;function Ve(t,r={}){const i=Date.now(),o=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(me&&me.key===o&&i-me.at<1e3)return me.ctx;const l=Tt(t,r);return me={key:o,at:i,ctx:l},l}function It(){me=null}const En=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context"]);function Nn(t){var Qe,Ze,et,tt,nt,rt;const{agentId:r,apiKey:i,baseUrl:s="https://app.livelayer.studio",sessionEndpoint:o,sessionBody:l,autoConnect:d=!1,displayMode:f,defaultDisplayMode:u="expanded",onDisplayModeChange:x,position:p="bottom-right",mobileBreakpoint:a=640,persistKey:c="ll-widget",disablePersistence:j=!1,teamMembers:_,currentTeamMemberId:k,onTeamMemberChange:R,idleLoopUrl:y,greeting:L,avatarImageUrl:m,agentName:C,branding:N={},allowCamera:w=!0,allowScreenShare:S=!0,allowTyping:b=!0,showOn:M,hideOn:_e,pathname:Te,onNavigate:V,onScrollToSelector:q,getPageContext:Y,pageContextExtras:we,onConnect:te,onDisconnect:ne,onTranscript:re,onAgentState:X,onConnectionStateChange:ie,onAgentEvent:se,onAgentCommand:oe,controlledSession:A,className:Ie,style:Pe,zIndex:De=2147483647}=t,ke=Nt(Te),le=At(ke,M,_e);n.useEffect(()=>{It()},[ke]);const ae=k!==void 0,[Ce,ze]=n.useState(()=>{var v;return k??((v=_==null?void 0:_[0])==null?void 0:v.id)}),U=ae?k:Ce,T=n.useMemo(()=>(_==null?void 0:_.find(v=>v.id===U))??null,[_,U]),J=(T==null?void 0:T.agentId)??r,[O,G]=St({value:f,defaultValue:u,onChange:x,persistKey:c,disablePersistence:j}),Q=Et(a),ce=yt(),$=bt(),B=_t(),H=wt(),K=kt(),[ue,de]=n.useState(!1),[ge,je]=n.useState(!1),[fe,xe]=n.useState(!1),[Se,h]=n.useState(!1),[D,$e]=n.useState(!1),Be=n.useRef(V),Ue=n.useRef(q),qe=n.useRef(Y),Ge=n.useRef(we),Ee=n.useRef(null);Be.current=V,Ue.current=q,qe.current=Y,Ge.current=we;const Oe=n.useCallback(v=>{var F;const E=v;if(!(!E.type||typeof E.type!="string")){if(se==null||se({eventName:E.type,data:v}),E.type==="navigate"){const z=typeof E.href=="string"?E.href:null;if(!z){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(Be.current){try{Be.current(z)}catch(P){console.warn(`[LiveLayer] onNavigate threw for "${z}". Falling back. Error:`,P)}return}if(typeof document<"u"){const P=document.querySelector(`a[href="${z.replace(/"/g,'\\"')}"]`);if(P){P.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",z),window.dispatchEvent(new PopStateEvent("popstate"))}catch(P){console.warn(`[LiveLayer] history.pushState fallback failed for "${z}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,P)}return}if(E.type==="scroll_to"){const z=typeof E.selector=="string"?E.selector:null;if(!z)return;const P=E.behavior==="instant"?"instant":"smooth";if(Ue.current){try{Ue.current(z,P)}catch(W){console.warn("[LiveLayer] onScrollToSelector threw.",W)}return}if(typeof document<"u"){let W=null;try{W=document.querySelector(z)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${z}".`);return}if(!W){console.warn(`[LiveLayer] scroll_to: no element matched "${z}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}W.scrollIntoView({behavior:P,block:"start"})}return}if(E.type==="request_page_context"){const z=(F=Ee.current)==null?void 0:F.call(Ee),P=Z=>{const ee=z,Ne=ee==null?void 0:ee.localParticipant;if(Ne!=null&&Ne.publishData)try{const We=new TextEncoder().encode(JSON.stringify(Z));Ne.publishData(We,{reliable:!0})}catch(We){console.warn("[LiveLayer] publishData failed.",We)}},W=Ge.current,it=qe.current;try{if(it){const Z=it(W);if(Z instanceof Promise){P({type:"page_context_pending"}),Z.then(ee=>P({type:"page_context",context:ee})).catch(ee=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",ee),P({type:"page_context",context:Ve(W)})});return}P({type:"page_context",context:Z});return}P({type:"page_context",context:Ve(W)})}catch(Z){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",Z),P({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],extras:W}})}return}En.has(E.type)||oe==null||oe(E)}},[oe,se]),I=vt({agentId:A?"__controlled__":J,baseUrl:s,apiKey:i,sessionEndpoint:o,sessionBody:l,onDataMessage:A?void 0:Oe});n.useEffect(()=>{if(A!=null&&A.subscribeToDataMessages)return A.subscribeToDataMessages(Oe)},[A,Oe]),Ee.current=()=>{var v;return(v=I.getRoom)==null?void 0:v.call(I)};const g=n.useMemo(()=>A?{connectionState:A.connectionState,agentState:A.agentState,transcript:A.transcript,videoElement:A.videoElement,audioElement:A.audioElement,canResume:A.canResume,error:A.error,agentConfig:null,connect:async()=>{await A.onConnect()},disconnect:()=>A.onDisconnect(),getRoom:I.getRoom,isControlled:!0}:{connectionState:I.connectionState,agentState:I.agentState,transcript:I.transcript,videoElement:I.videoElement,audioElement:I.audioElement,canResume:I.canResume,error:I.error,agentConfig:I.agentConfig,connect:I.connect,disconnect:I.disconnect,getRoom:I.getRoom,isControlled:!1},[A,I]),Ke=n.useRef(null);n.useEffect(()=>{const v=g.videoElement,E=Ke.current;if(!(!v||!E))return E.appendChild(v),()=>{v.parentNode===E&&E.removeChild(v)}},[g.videoElement]),n.useEffect(()=>{const v=g.audioElement;if(!v)return;ce.attach(v);const E=v.play();return E&&typeof E.catch=="function"&&E.catch(F=>{(F==null?void 0:F.name)==="NotAllowedError"&&de(!0)}),()=>{ce.detach()}},[g.audioElement]),n.useEffect(()=>{if(g.isControlled||g.connectionState!=="connected")return;const v=g.getRoom();if(v)return $.setupMic(v).catch(()=>{}),B.attachRoom(v),H.attachRoom(v),K.refresh(),()=>{$.teardownMic(),B.teardown(),H.teardown()}},[g.isControlled,g.connectionState]),n.useEffect(()=>{const v=g.audioElement;v&&(v.muted=D)},[g.audioElement,D]);const Pt=n.useCallback(v=>{const E=g.getRoom();if(E)try{const F=new TextEncoder().encode(JSON.stringify({type:"user_message",text:v}));E.localParticipant.publishData(F,{reliable:!0})}catch{}},[g]),Dt=n.useCallback(()=>{$e(v=>!v)},[]);n.useEffect(()=>{ie==null||ie(g.connectionState),g.connectionState==="connected"?te==null||te():g.connectionState==="disconnected"&&(ne==null||ne())},[g.connectionState,te,ne,ie]),n.useEffect(()=>{re==null||re(g.transcript)},[g.transcript,re]),n.useEffect(()=>{X==null||X(g.agentState)},[g.agentState,X]);const Ye=n.useRef(!1);n.useEffect(()=>{g.isControlled||!d||Ye.current||le&&g.connectionState==="idle"&&(Ye.current=!0,g.connect())},[d,g.connectionState,g,le]);const zt=n.useCallback(v=>{const E=_==null?void 0:_.find(F=>F.id===v);E&&(xe(!1),v!==U&&(je(!0),g.disconnect(),ae||ze(v),R==null||R(E)))},[_,U,g,ae,R]);n.useEffect(()=>{ge&&g.connectionState==="connected"&&je(!1)},[g.connectionState,ge]),n.useEffect(()=>{if(!fe)return;const v=E=>{E.key==="Escape"&&xe(!1)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[fe]);const $t=!!m||!!(T!=null&&T.avatarImageUrl)||g.isControlled,He=Ct(J,s,$t),Fe=(T==null?void 0:T.name)??C??((Qe=g.agentConfig)==null?void 0:Qe.name)??((Ze=He.info)==null?void 0:Ze.name)??"Live Layer",Xe=(T==null?void 0:T.avatarImageUrl)??m??((et=g.agentConfig)==null?void 0:et.avatarImageUrl)??((tt=He.info)==null?void 0:tt.avatarImageUrl)??null,Bt=y??((nt=g.agentConfig)==null?void 0:nt.idleLoopUrl)??((rt=He.info)==null?void 0:rt.idleLoopUrl)??null,Ut=L??null,Ot=n.useCallback(()=>G("expanded"),[G]),Ht=n.useCallback(()=>G("minimized"),[G]),Je=n.useCallback(()=>{g.disconnect(),G("hidden")},[g,G]),Ft=n.useCallback(()=>{const v=g.audioElement;v&&v.play().then(()=>de(!1)).catch(()=>{})},[g.audioElement]),Wt=n.useCallback(()=>{de(!1),g.connect()},[g]),ve={...Pe,zIndex:De};N.primaryColor&&(ve["--ll-color-primary"]=N.primaryColor),N.accentColor&&(ve["--ll-color-accent"]=N.accentColor),N.backgroundColor&&(ve["--ll-color-bg"]=N.backgroundColor),N.textColor&&(ve["--ll-color-fg"]=N.textColor);const Vt=["ll-widget",`ll-widget--${O}`,`ll-widget--${Q?"mobile":"desktop"}`,Ie].filter(Boolean).join(" ");return le?e.jsxs("div",{className:Vt,style:ve,"data-display-mode":O,"data-position":p,children:[O==="hidden"&&e.jsx(dn,{position:p,isMobile:Q,isSpeaking:g.agentState==="speaking",onExpand:()=>G("expanded"),label:`Open ${Fe} widget`}),O==="minimized"&&e.jsx(hn,{position:p,isMobile:Q,agentName:Fe,avatarImageUrl:Xe,agentState:g.agentState,isMuted:$.isMuted,audioLevel:ce,onExpand:Ot,onToggleMute:$.toggleMute,onClose:Je}),O==="expanded"&&e.jsx(mn,{position:p,isMobile:Q,agentName:Fe,avatarImageUrl:Xe,idleLoopUrl:Bt,greeting:Ut,branding:N,teamMembers:_,currentTeamMemberId:U,isSwitchingTeamMember:ge,teamSwitcherOpen:fe,onToggleTeamSwitcher:()=>xe(v=>!v),onSelectTeamMember:zt,connectionState:g.connectionState,agentState:g.agentState,transcript:g.transcript,isMuted:$.isMuted,micDevices:K.mics,isCameraEnabled:B.isEnabled,cameraPreviewEl:B.previewEl,cameraDevices:K.cameras,activeCameraId:B.activeDeviceId,isScreenShareEnabled:H.isEnabled,screenPreviewEl:H.previewEl,isSpeakerMuted:D,allowCamera:w,allowScreenShare:S,allowTyping:b,languageMenuOpen:Se,onToggleLanguageMenu:()=>h(v=>!v),needsUserGesture:ue,canResume:g.canResume,micError:$.micError,error:g.error,avatarVideoContainerRef:Ke,onConnect:()=>void g.connect(),onDisconnect:()=>g.disconnect(),onRetry:Wt,onResumeAudio:Ft,onToggleMute:$.toggleMute,onToggleCamera:()=>void B.toggle(),onSwitchCameraDevice:v=>void B.switchDevice(v),onToggleScreenShare:()=>void H.toggle(),onToggleSpeaker:Dt,onSendMessage:Pt,onMinimize:Ht,onClose:Je,onClearMicError:$.clearError})]}):null}function Ln(t){return e.jsx(xt,{children:e.jsx(Nn,{...t})})}const Rn=({agentId:t,baseUrl:r,apiKey:i,mode:s,onAgentEvent:o,className:l,style:d})=>{const f=n.useRef(null),u=n.useRef(null),x=n.useRef(o);x.current=o;const p=n.useCallback(a=>{var j;const c=a.detail;(j=x.current)==null||j.call(x,c)},[]);return n.useEffect(()=>{const a=f.current;if(!a)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",t),r&&c.setAttribute("base-url",r),i&&c.setAttribute("api-key",i),s&&c.setAttribute("mode",s),c.addEventListener("agent-event",p),a.appendChild(c),u.current=c,()=>{c.removeEventListener("agent-event",p),a.removeChild(c),u.current=null}},[t]),n.useEffect(()=>{u.current&&(s?u.current.setAttribute("mode",s):u.current.removeAttribute("mode"))},[s]),e.jsx("div",{ref:f,className:l,style:d})},An=n.forwardRef(function({id:r,intent:i,as:s="div",className:o,style:l,children:d},f){return n.createElement(s,{ref:f,"data-ll-region":r,"data-ll-intent":i,className:o,style:l},d)});function Mn(){const[t,r]=n.useState([]),i=n.useCallback(o=>{r(l=>{const d=l.findIndex(f=>f.id===o.id);if(d>=0){const f=l.slice();return f[d]=o,f}return[...l,o]})},[]),s=n.useCallback(()=>r([]),[]);return{entries:t,pushSegment:i,clear:s,latest:t.length>0?t[t.length-1]:null}}exports.AvatarWidget=Ln;exports.ErrorBoundary=xt;exports.LiveLayerRegion=An;exports.LiveLayerWidget=Rn;exports.clearPageContextCache=It;exports.extractPageContext=Tt;exports.getCachedPageContext=Ve;exports.matchesPattern=Lt;exports.shouldRenderAtPath=Rt;exports.useAgentInfo=Ct;exports.useAudioLevel=yt;exports.useCameraState=_t;exports.useDisplayMode=jt;exports.useDisplayModePersistence=St;exports.useIsMobile=Et;exports.useLiveKitSession=vt;exports.useMediaDevices=kt;exports.useMicrophoneState=bt;exports.usePathname=Nt;exports.useRouteMatch=At;exports.useScreenShareState=wt;exports.useTranscript=Mn;
|