@webority/mobile-chat 0.141.0 → 0.143.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.
Files changed (99) hide show
  1. package/lib/commonjs/AgentByline.js +1 -1
  2. package/lib/commonjs/ChatComposer.js +1 -1
  3. package/lib/commonjs/ChatConversationActions.js +1 -1
  4. package/lib/commonjs/ChatLauncher.js +1 -1
  5. package/lib/commonjs/ChatMessageActions.js +1 -1
  6. package/lib/commonjs/ChatOpenTickets.js +1 -1
  7. package/lib/commonjs/ChatPastChats.js +1 -1
  8. package/lib/commonjs/ChatSheet.js +1 -1
  9. package/lib/commonjs/ChatStarters.js +1 -1
  10. package/lib/commonjs/ChatThread.js +1 -1
  11. package/lib/commonjs/chatShared.js +1 -1
  12. package/lib/commonjs/expoModules.js +1 -0
  13. package/lib/commonjs/iconName.js +1 -0
  14. package/lib/commonjs/loaders/ChatLoader.js +1 -1
  15. package/lib/commonjs/renderers/ActionPart.js +1 -1
  16. package/lib/commonjs/renderers/ChartPart.js +1 -1
  17. package/lib/commonjs/renderers/FigureText.js +1 -1
  18. package/lib/commonjs/renderers/FilePart.js +1 -1
  19. package/lib/commonjs/renderers/HandoffPart.js +1 -1
  20. package/lib/commonjs/renderers/InputRequestPart.js +1 -1
  21. package/lib/commonjs/renderers/NoticePart.js +1 -1
  22. package/lib/commonjs/renderers/QuickRepliesPart.js +1 -1
  23. package/lib/commonjs/renderers/SourcesPart.js +1 -1
  24. package/lib/commonjs/renderers/TextPart.js +1 -1
  25. package/lib/commonjs/renderers/VoiceClipPart.js +1 -1
  26. package/lib/commonjs/speech/azureSpeech.js +1 -1
  27. package/lib/commonjs/speech/expoAudio.js +1 -1
  28. package/lib/commonjs/speech/phoneSpeech.js +1 -1
  29. package/lib/commonjs/useChat.js +1 -1
  30. package/lib/commonjs/useChatSound.js +1 -1
  31. package/lib/commonjs/useTranscriptActions.js +1 -1
  32. package/lib/module/AgentByline.js +1 -1
  33. package/lib/module/ChatComposer.js +1 -1
  34. package/lib/module/ChatConversationActions.js +1 -1
  35. package/lib/module/ChatLauncher.js +1 -1
  36. package/lib/module/ChatMessageActions.js +1 -1
  37. package/lib/module/ChatOpenTickets.js +1 -1
  38. package/lib/module/ChatPastChats.js +1 -1
  39. package/lib/module/ChatSheet.js +1 -1
  40. package/lib/module/ChatStarters.js +1 -1
  41. package/lib/module/ChatThread.js +1 -1
  42. package/lib/module/chatShared.js +1 -1
  43. package/lib/module/expoModules.js +1 -0
  44. package/lib/module/iconName.js +1 -0
  45. package/lib/module/loaders/ChatLoader.js +1 -1
  46. package/lib/module/renderers/ActionPart.js +1 -1
  47. package/lib/module/renderers/ChartPart.js +1 -1
  48. package/lib/module/renderers/FigureText.js +1 -1
  49. package/lib/module/renderers/FilePart.js +1 -1
  50. package/lib/module/renderers/HandoffPart.js +1 -1
  51. package/lib/module/renderers/InputRequestPart.js +1 -1
  52. package/lib/module/renderers/NoticePart.js +1 -1
  53. package/lib/module/renderers/QuickRepliesPart.js +1 -1
  54. package/lib/module/renderers/SourcesPart.js +1 -1
  55. package/lib/module/renderers/TextPart.js +1 -1
  56. package/lib/module/renderers/VoiceClipPart.js +1 -1
  57. package/lib/module/speech/azureSpeech.js +1 -1
  58. package/lib/module/speech/expoAudio.js +1 -1
  59. package/lib/module/speech/phoneSpeech.js +1 -1
  60. package/lib/module/useChat.js +1 -1
  61. package/lib/module/useChatSound.js +1 -1
  62. package/lib/module/useTranscriptActions.js +1 -1
  63. package/lib/typescript/commonjs/ChatAppearanceScope.d.ts +1 -1
  64. package/lib/typescript/commonjs/ChatComposer.d.ts +6 -6
  65. package/lib/typescript/commonjs/ChatFrame.d.ts +17 -17
  66. package/lib/typescript/commonjs/ChatOpenTickets.d.ts +1 -1
  67. package/lib/typescript/commonjs/ChatSheet.d.ts +3 -3
  68. package/lib/typescript/commonjs/ChatStarters.d.ts +1 -1
  69. package/lib/typescript/commonjs/ChatThread.d.ts +13 -13
  70. package/lib/typescript/commonjs/chatShared.d.ts +2 -1
  71. package/lib/typescript/commonjs/expoModules.d.ts +58 -0
  72. package/lib/typescript/commonjs/iconName.d.ts +3 -0
  73. package/lib/typescript/commonjs/renderers/ActionPart.d.ts +6 -1
  74. package/lib/typescript/commonjs/renderers/FilePart.d.ts +4 -1
  75. package/lib/typescript/commonjs/renderers/InputRequestPart.d.ts +6 -1
  76. package/lib/typescript/commonjs/renderers/NoticePart.d.ts +1 -1
  77. package/lib/typescript/commonjs/renderers/index.d.ts +40 -2
  78. package/lib/typescript/commonjs/types.d.ts +1 -1
  79. package/lib/typescript/commonjs/useChat.d.ts +2 -2
  80. package/lib/typescript/commonjs/useChatSound.d.ts +1 -1
  81. package/lib/typescript/module/ChatAppearanceScope.d.ts +1 -1
  82. package/lib/typescript/module/ChatComposer.d.ts +6 -6
  83. package/lib/typescript/module/ChatFrame.d.ts +17 -17
  84. package/lib/typescript/module/ChatOpenTickets.d.ts +1 -1
  85. package/lib/typescript/module/ChatSheet.d.ts +3 -3
  86. package/lib/typescript/module/ChatStarters.d.ts +1 -1
  87. package/lib/typescript/module/ChatThread.d.ts +13 -13
  88. package/lib/typescript/module/chatShared.d.ts +2 -1
  89. package/lib/typescript/module/expoModules.d.ts +58 -0
  90. package/lib/typescript/module/iconName.d.ts +3 -0
  91. package/lib/typescript/module/renderers/ActionPart.d.ts +6 -1
  92. package/lib/typescript/module/renderers/FilePart.d.ts +4 -1
  93. package/lib/typescript/module/renderers/InputRequestPart.d.ts +6 -1
  94. package/lib/typescript/module/renderers/NoticePart.d.ts +1 -1
  95. package/lib/typescript/module/renderers/index.d.ts +40 -2
  96. package/lib/typescript/module/types.d.ts +1 -1
  97. package/lib/typescript/module/useChat.d.ts +2 -2
  98. package/lib/typescript/module/useChatSound.d.ts +1 -1
  99. package/package.json +11 -11
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useChat=useChat;var _chatCore=require("@webority/chat-core"),_mobileUi=require("@webority/mobile-ui"),_react=require("react"),_reactNative=require("react-native");const requestFrame=e=>{const t=requestAnimationFrame(e);return()=>cancelAnimationFrame(t)},NO_SUBSCRIPTION=()=>()=>{},IDLE_STATE=Object.freeze({profile:null,profileError:null,features:Object.freeze((0,_chatCore.emptyFeatures)()),conversationId:null,conversationState:"Open",title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:!1,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:"Off",handoffPending:!1,handoffContactRequestId:null,handoffPause:!1,openTickets:[],draft:null}),IDLE_SESSION=new Proxy({},{get:(e,t)=>{if("symbol"!=typeof t&&"client"!==t&&"toJSON"!==t&&!t.startsWith("$$")){if("getState"===t)return()=>IDLE_STATE;if("subscribe"===t)return NO_SUBSCRIPTION;if("then"!==t)return()=>Promise.resolve()}}});function useChat(e){const{client:t,screen:r,layout:n,narrow:a,conversationId:c,pageContext:o,behaviour:s,attribution:u,prefs:i,getCaptchaToken:l,onEvent:f,onError:_,onNavigate:d}=e,p=JSON.stringify(a??{}),v=(0,_react.useRef)(d);v.current=d;const m=(0,_react.useCallback)(e=>v.current?.(e),[]),h=(0,_react.useRef)(c);h.current=c;const E=(0,_react.useRef)(o);E.current=o;const g=(0,_react.useRef)(s);g.current=s;const S=(0,_react.useRef)(u);S.current=u;const C=(0,_react.useRef)(l);C.current=l;const y=(0,_react.useRef)(f);y.current=f;const b=(0,_react.useRef)(_);b.current=_;const I=(0,_react.useRef)(i);I.current=i;const R=(0,_mobileUi.useReducedMotion)(),A=(0,_react.useRef)(R);A.current=R;const[N,L]=(0,_react.useState)(null),[O,T]=(0,_react.useState)(null);(0,_react.useEffect)(()=>{const e=(0,_chatCore.createChatSession)(t,{screen:r,layout:n,pathname:()=>r||"/",narrow:JSON.parse(p),conversationId:h.current??void 0,pageContext:()=>E.current,behaviour:()=>g.current?.()??null,attribution:()=>S.current?.()??null,prefs:I.current,getCaptchaToken:e=>C.current?.(e)??Promise.reject(new Error("No captcha handler.")),onEvent:(e,t)=>y.current?.(e,t),onError:e=>b.current?.(e),schedule:requestFrame,reducedMotion:()=>A.current});return L({client:t,screen:r,layout:n,narrowKey:p,session:e}),()=>e.dispose()},[t,r,n,p]);const w=null!==N&&N.client===t&&N.screen===r&&N.layout===n&&N.narrowKey===p?N.session:IDLE_SESSION,k=(0,_react.useSyncExternalStore)(w.subscribe,w.getState),q=(0,_react.useMemo)(()=>({load:()=>w.load(),submit:e=>w.submit(e),chooseQuickReply:e=>w.chooseQuickReply(e),answerInput:(e,t)=>w.answerInput(e,t),confirmAction:e=>w.confirmAction(e),rejectAction:(e,t)=>w.rejectAction(e,t),stop:()=>w.stop(),retry:()=>w.retry(),regenerate:()=>w.regenerate(),startEdit:e=>w.startEdit(e),cancelEdit:()=>w.cancelEdit(),attach:e=>w.attach(e),removeAttachment:e=>w.removeAttachment(e),openConversation:e=>w.openConversation(e),resumeLast:()=>w.resumeLast(),newConversation:()=>w.newConversation(),rate:(e,t,r)=>w.rate(e,t,r),reset:()=>w.reset(),requestHandoff:async e=>{T(null);try{await w.requestHandoff(e)}catch(e){const t=e instanceof Error&&""!==e.message?e.message:_chatCore.DEFAULT_CHAT_LABELS.errorGeneric;throw T(t),e}},notifyTyping:()=>w.notifyTyping(),resumeLive:()=>w.resumeLive()}),[w]),P=(0,_react.useRef)(c);(0,_react.useEffect)(()=>{w!==IDLE_SESSION&&c&&c!==P.current&&(P.current=c,w.openConversation(c))},[c,w]);const j=(0,_react.useRef)("active"===_reactNative.AppState.currentState),x=(0,_react.useRef)(!0),D=(0,_react.useCallback)(()=>w.setLiveActive(j.current&&x.current),[w]),F=(0,_react.useCallback)(e=>{x.current=e,D()},[D]);(0,_react.useEffect)(()=>{D();const e=_reactNative.AppState.addEventListener("change",e=>{"active"===e?(j.current=!0,w.endHandoffPause()):j.current=!1,D()});return()=>e.remove()},[D,w]);const U=(0,_react.useCallback)((e,t)=>{y.current?.(e,t)},[]);return{...k,...q,session:w,client:t,emit:U,setChatVisible:F,handoffError:O,onNavigate:d?m:void 0}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useChat=useChat;var _chatCore=require("@webority/chat-core"),_mobileUi=require("@webority/mobile-ui"),_react=require("react"),_reactNative=require("react-native");const requestFrame=e=>{const t=requestAnimationFrame(e);return()=>cancelAnimationFrame(t)};function parseNarrow(e){const t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("The chat narrowing must be an object of feature switches.");const r={};for(const e of _chatCore.CHAT_FEATURES){const n=Reflect.get(t,e);if(void 0!==n){if("boolean"!=typeof n)throw new TypeError(`The chat narrowing for "${e}" must be true or false.`);r[e]=n}}const n=new Set(_chatCore.CHAT_FEATURES);for(const e of Object.keys(t))if(!n.has(e))throw new TypeError(`"${e}" is not a chat feature.`);return r}function useChat(e){const{client:t,screen:r,layout:n,narrow:c,conversationId:a,pageContext:o,behaviour:s,attribution:u,prefs:i,getCaptchaToken:f,onEvent:l,onError:_,onNavigate:h}=e,p=JSON.stringify(c??{}),v=(0,_react.useRef)(h);v.current=h;const d=(0,_react.useCallback)(e=>v.current?.(e),[]),m=(0,_react.useRef)(a);m.current=a;const C=(0,_react.useRef)(o);C.current=o;const y=(0,_react.useRef)(s);y.current=s;const E=(0,_react.useRef)(u);E.current=u;const b=(0,_react.useRef)(f);b.current=f;const w=(0,_react.useRef)(l);w.current=l;const A=(0,_react.useRef)(_);A.current=_;const S=(0,_react.useRef)(i);S.current=i;const R=(0,_mobileUi.useReducedMotion)(),g=(0,_react.useRef)(R);g.current=R;const[T,N]=(0,_react.useState)(null),[L,k]=(0,_react.useState)(null);(0,_react.useEffect)(()=>{const e=m.current??void 0,c=(0,_chatCore.createChatSession)(t,{...void 0===r?{}:{screen:r},...void 0===n?{}:{layout:n},pathname:()=>r||"/",narrow:parseNarrow(p),...void 0===e?{}:{conversationId:e},pageContext:()=>C.current,behaviour:()=>y.current?.()??null,attribution:()=>E.current?.()??null,prefs:S.current,getCaptchaToken:e=>b.current?.(e)??Promise.reject(new Error("No captcha handler.")),onEvent:(e,t)=>w.current?.(e,t),onError:e=>A.current?.(e),schedule:requestFrame,reducedMotion:()=>g.current});return N({client:t,screen:r,layout:n,narrowKey:p,session:c}),()=>c.dispose()},[t,r,n,p]);const q=null!==T&&T.client===t&&T.screen===r&&T.layout===n&&T.narrowKey===p?T.session:_chatCore.IDLE_CHAT_SESSION,H=(0,_react.useSyncExternalStore)(q.subscribe,q.getState),I=(0,_react.useMemo)(()=>({load:()=>q.load(),submit:e=>q.submit(e),chooseQuickReply:e=>q.chooseQuickReply(e),answerInput:(e,t)=>q.answerInput(e,t),confirmAction:e=>q.confirmAction(e),rejectAction:(e,t)=>q.rejectAction(e,t),stop:()=>q.stop(),retry:()=>q.retry(),regenerate:()=>q.regenerate(),startEdit:e=>q.startEdit(e),cancelEdit:()=>q.cancelEdit(),attach:e=>q.attach(e),removeAttachment:e=>q.removeAttachment(e),openConversation:e=>q.openConversation(e),resumeLast:()=>q.resumeLast(),newConversation:()=>q.newConversation(),rate:(e,t,r)=>q.rate(e,t,r),reset:()=>q.reset(),requestHandoff:async e=>{k(null);try{await q.requestHandoff(e)}catch(e){const t=e instanceof Error&&""!==e.message?e.message:_chatCore.DEFAULT_CHAT_LABELS.errorGeneric;throw k(t),e}},notifyTyping:()=>q.notifyTyping(),resumeLive:()=>q.resumeLive()}),[q]),j=(0,_react.useRef)(a);(0,_react.useEffect)(()=>{q!==_chatCore.IDLE_CHAT_SESSION&&a&&a!==j.current&&(j.current=a,q.openConversation(a))},[a,q]);const F=(0,_react.useRef)("active"===_reactNative.AppState.currentState),O=(0,_react.useRef)(!0),x=(0,_react.useCallback)(()=>q.setLiveActive(F.current&&O.current),[q]),U=(0,_react.useCallback)(e=>{O.current=e,x()},[x]);(0,_react.useEffect)(()=>{x();const e=_reactNative.AppState.addEventListener("change",e=>{"active"===e?(F.current=!0,q.endHandoffPause()):F.current=!1,x()});return()=>e.remove()},[x,q]);const M=(0,_react.useCallback)((e,t)=>{w.current?.(e,t)},[]);return{...H,...I,session:q,client:t,emit:M,setChatVisible:U,handoffError:L,onNavigate:h?d:void 0}}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CUES=void 0,exports.playCue=playCue,exports.useChatSound=useChatSound;var _mobileCore=require("@webority/mobile-core"),_react=require("react");const CUES=exports.CUES={open:{from:420,to:920,seconds:.16,peak:.16},reply:{from:680,to:540,seconds:.11,peak:.06},sent:{from:540,to:760,seconds:.09,peak:.05}},SAMPLE_RATE=22050,ATTACK_SECONDS=.01,written=new Map;function cueBytes(e){const t=Math.round(22050*e.seconds),n=2*t,s=new Uint8Array(44+n),o=new DataView(s.buffer),text=(e,t)=>{for(let n=0;n<t.length;n+=1)o.setUint8(e+n,t.charCodeAt(n))};text(0,"RIFF"),o.setUint32(4,36+n,!0),text(8,"WAVE"),text(12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,1,!0),o.setUint32(24,22050,!0),o.setUint32(28,44100,!0),o.setUint16(32,2,!0),o.setUint16(34,16,!0),text(36,"data"),o.setUint32(40,n,!0);const r=Math.min(.01,e.seconds/2);let a=0;for(let n=0;n<t;n+=1){const t=n/22050,s=e.from+(e.to-e.from)*t/e.seconds;a+=2*Math.PI*s/22050;const i=t<r?t/r:(e.seconds-t)/(e.seconds-r);o.setInt16(44+2*n,Math.round(32767*e.peak*i*Math.sin(a)),!0)}return s}function playCue(e,t=1){(async()=>{let n=written.get(e);if(void 0===n){const{File:t,Paths:s}=require("expo-file-system"),o=new t(s.cache,`wchat-cue-${e}.wav`);o.create({overwrite:!0}),o.write(cueBytes(CUES[e])),n=o.uri,written.set(e,n)}const{createAudioPlayer:s}=require("expo-audio"),o=s({uri:n});o.volume=t,o.addListener("playbackStatusUpdate",e=>{e.didJustFinish&&o.remove()}),o.play()})().catch(e=>{_mobileCore.Logger.warn("[chat] sound cue failed",e)})}function takeUnseen(e,t,n){if(t){e.wasLoading=!0;for(const t of n)e.seen.add(t.id);return[]}if(e.wasLoading||!e.seeded){e.wasLoading=!1,e.seeded=!0;for(const t of n)e.seen.add(t.id);return[]}const s=[];for(const t of n)e.seen.has(t.id)||(e.seen.add(t.id),s.push(t));return s}function useChatSound(e){const t=e.features.Sounds?e.profile?.experience.sound??null:null,n=(0,_react.useRef)(e);n.current=e;const s=(0,_react.useRef)(e.open),o=(0,_react.useRef)({seen:new Set,seeded:!1,wasLoading:!1}),{open:r,loading:a,messages:i}=e;(0,_react.useEffect)(()=>{const e=s.current;s.current=r;const u=takeUnseen(o.current,a,i);if(null!==t&&!n.current.muted&&t.volume>0){r&&!e&&t.open&&playCue("open",t.volume);for(const e of u){if(e.restored||e.parts.some(e=>"Notice"===e.kind))continue;const n=e.author.kind;"Visitor"===n?!e.stored&&t.sent&&playCue("sent",t.volume):"Assistant"!==n&&"Script"!==n&&"Agent"!==n||!t.reply||playCue("reply",t.volume)}}},[r,a,i,t])}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CUES=void 0,exports.playCue=playCue,exports.useChatSound=useChatSound;var _mobileCore=require("@webority/mobile-core"),_react=require("react"),_expoModules=require("./expoModules.js");const CUES=exports.CUES={open:{from:420,to:920,seconds:.16,peak:.16},reply:{from:680,to:540,seconds:.11,peak:.06},sent:{from:540,to:760,seconds:.09,peak:.05}},SAMPLE_RATE=22050,ATTACK_SECONDS=.01,written=new Map;function cueBytes(e){const t=Math.round(22050*e.seconds),o=2*t,n=new Uint8Array(44+o),s=new DataView(n.buffer),text=(e,t)=>{for(let o=0;o<t.length;o+=1)s.setUint8(e+o,t.charCodeAt(o))};text(0,"RIFF"),s.setUint32(4,36+o,!0),text(8,"WAVE"),text(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,1,!0),s.setUint32(24,22050,!0),s.setUint32(28,44100,!0),s.setUint16(32,2,!0),s.setUint16(34,16,!0),text(36,"data"),s.setUint32(40,o,!0);const r=Math.min(.01,e.seconds/2);let a=0;for(let o=0;o<t;o+=1){const t=o/22050,n=e.from+(e.to-e.from)*t/e.seconds;a+=2*Math.PI*n/22050;const i=t<r?t/r:(e.seconds-t)/(e.seconds-r);s.setInt16(44+2*o,Math.round(32767*e.peak*i*Math.sin(a)),!0)}return n}function playCue(e,t=1){(async()=>{let o=written.get(e);if(void 0===o){const{File:t,Paths:n}=(0,_expoModules.loadExpoFileSystem)(),s=new t(n.cache,`wchat-cue-${e}.wav`);s.create({overwrite:!0}),s.write(cueBytes(CUES[e])),o=s.uri,written.set(e,o)}const{createAudioPlayer:n}=(0,_expoModules.loadExpoAudio)(),s=n({uri:o});s.volume=t,s.addListener("playbackStatusUpdate",e=>{e.didJustFinish&&s.remove()}),s.play()})().catch(e=>{_mobileCore.Logger.warn("[chat] sound cue failed",e)})}function takeUnseen(e,t,o){if(t){e.wasLoading=!0;for(const t of o)e.seen.add(t.id);return[]}if(e.wasLoading||!e.seeded){e.wasLoading=!1,e.seeded=!0;for(const t of o)e.seen.add(t.id);return[]}const n=[];for(const t of o)e.seen.has(t.id)||(e.seen.add(t.id),n.push(t));return n}function useChatSound(e){const t=e.features.Sounds?e.profile?.experience.sound??null:null,o=(0,_react.useRef)(e);o.current=e;const n=(0,_react.useRef)(e.open),s=(0,_react.useRef)({seen:new Set,seeded:!1,wasLoading:!1}),{open:r,loading:a,messages:i}=e;(0,_react.useEffect)(()=>{const e=n.current;n.current=r;const u=takeUnseen(s.current,a,i);if(null!==t&&!o.current.muted&&t.volume>0){r&&!e&&t.open&&playCue("open",t.volume);for(const e of u){if(e.restored||e.parts.some(e=>"Notice"===e.kind))continue;const o=e.author.kind;"Visitor"===o?!e.stored&&t.sent&&playCue("sent",t.volume):"Assistant"!==o&&"Script"!==o&&"Agent"!==o||!t.reply||playCue("reply",t.volume)}}},[r,a,i,t])}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=useTranscriptActions;var _chatCore=require("@webority/chat-core"),_mobileCore=require("@webority/mobile-core"),_react=require("react"),_reactNative=require("react-native");const NOTICE_MS=3e3;async function shareMessages(e,r,t,a){const s=(0,_chatCore.buildTranscript)(e,r);if(0===s.entries.length)return;const c=(0,_chatCore.transcriptToText)(s,{heading:t,speakers:t});try{await _reactNative.Share.share({message:c,title:s.title})}catch(e){_mobileCore.Logger.error("[chat] share failed",e),a()}}function useTranscriptActions(e,r){const[t,a]=(0,_react.useState)(null),s=(0,_react.useRef)(null),c=(0,_react.useRef)(!1);(0,_react.useEffect)(()=>(c.current=!0,()=>{c.current=!1,null!==s.current&&clearTimeout(s.current)}),[]);const i=(0,_react.useCallback)(e=>{c.current&&(null!==s.current&&clearTimeout(s.current),a(e),s.current=setTimeout(()=>a(null),NOTICE_MS))},[]),{messages:n,title:u}=e,l=e.features.FigureText,o=e.profile?.assistant.name,h=(0,_react.useCallback)(e=>shareMessages([e],{labels:r,title:u,figureText:l,assistantName:o},!1,()=>i(r.shareFailed)),[r,u,l,o,i]),_=(0,_react.useCallback)(()=>shareMessages(n,{labels:r,title:u,figureText:l,assistantName:o},!0,()=>i(r.shareFailed)),[n,r,u,l,o,i]);return{canShare:e.features.Share,notice:t,shareReply:h,shareConversation:_}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=useTranscriptActions;var _chatCore=require("@webority/chat-core"),_mobileCore=require("@webority/mobile-core"),_react=require("react"),_reactNative=require("react-native");const NOTICE_MS=3e3;async function shareMessages(e,r,t,a){const s=(0,_chatCore.buildTranscript)(e,r);if(0===s.entries.length)return;const c=(0,_chatCore.transcriptToText)(s,{heading:t,speakers:t});try{await _reactNative.Share.share({message:c,title:s.title})}catch(e){_mobileCore.Logger.error("[chat] share failed",e),a()}}function useTranscriptActions(e,r){const[t,a]=(0,_react.useState)(null),s=(0,_react.useRef)(null),c=(0,_react.useRef)(!1);(0,_react.useEffect)(()=>(c.current=!0,()=>{c.current=!1,null!==s.current&&clearTimeout(s.current)}),[]);const i=(0,_react.useCallback)(e=>{c.current&&(null!==s.current&&clearTimeout(s.current),a(e),s.current=setTimeout(()=>a(null),NOTICE_MS))},[]),{messages:n,title:u}=e,l=e.features.FigureText,o=e.profile?.assistant.name,h=(0,_react.useCallback)(e=>shareMessages([e],{labels:r,title:u,figureText:l,...void 0===o?{}:{assistantName:o}},!1,()=>i(r.shareFailed)),[r,u,l,o,i]),_=(0,_react.useCallback)(()=>shareMessages(n,{labels:r,title:u,figureText:l,...void 0===o?{}:{assistantName:o}},!0,()=>i(r.shareFailed)),[n,r,u,l,o,i]);return{canShare:e.features.Share,notice:t,shareReply:h,shareConversation:_}}
@@ -1 +1 @@
1
- "use strict";import{Avatar,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export function AgentByline({author:e,labels:t,showAvatar:r=!0}){const a=useTheme(),i=e.displayName||t.agent,s=e.avatarUrl?{uri:e.avatarUrl}:void 0;return _jsxs(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{flexDirection:"row",alignItems:"center",gap:a.space.xs},children:[r?_jsx(Avatar,{size:"xs",name:i,source:s}):null,_jsx(Text,{variant:"caption",color:"secondary",children:i}),_jsx(Text,{variant:"caption",color:"tertiary",children:t.agent})]})}
1
+ "use strict";import{Avatar,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export function AgentByline({author:e,labels:t,showAvatar:r=!0}){const a=useTheme(),i=e.displayName||t.agent,s=e.avatarUrl?{uri:e.avatarUrl}:void 0;return _jsxs(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{flexDirection:"row",alignItems:"center",gap:a.space.xs},children:[r?_jsx(Avatar,{size:"xs",name:i,...void 0===s?{}:{source:s}}):null,_jsx(Text,{variant:"caption",color:"secondary",children:i}),_jsx(Text,{variant:"caption",color:"tertiary",children:t.agent})]})}
@@ -1 +1 @@
1
- "use strict";import{defaultChatLook}from"@webority/chat-core";import{Permissions}from"@webority/mobile-core/permissions";import{Banner,Chip,Composer,IconButton,ProgressBar,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{ChatDictationButton}from"./ChatDictationButton.js";import{ChatFooter}from"./ChatFooter.js";import{joinDictation}from"./speech/speechText.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const ALLOWANCE_SHOWN_AT=10,COUNTER_AT=.9,DEFAULT_MAX_LENGTH=4e3,openQuestion=e=>{for(let t=e.length-1;t>=0;t-=1){const s=e[t];for(const e of[...s?.parts??[]].reverse())if("InputRequest"===e.kind&&"Open"===e.state)return e.fields[0]?.label||e.title||null}return null};export function ChatComposer({chat:e,labels:t,pickAttachments:s,keyboardOffset:o,keyboardAware:a,safeArea:n,testID:i="chat-composer",focusRef:r,look:l=defaultChatLook,sendIcon:c}){const u=useTheme(),m=useMemo(()=>buildStyles(u),[u]),[p,d]=useState(""),[h,f]=useState(null),g=e.editing,x=useRef(null),b=useRef(null);useEffect(()=>{if(r)return r.current=()=>b.current?.focus(),()=>{r.current=null}},[r]),useEffect(()=>{g&&x.current?.(),d(g?g.text:"")},[g]);const y=e.attachments,v=y.some(e=>"Uploading"===e.status),j=y.some(e=>"Ready"===e.status),_=e.messagesLeftToday,S=e.profile?.limits.maxMessageLength??4e3,w=void 0!==s&&e.features.Attachments&&(e.profile?.limits.maxAttachments??0)>0,A=e.features.HumanHandoff&&("WaitingForAgent"===e.conversationState||"WithAgent"===e.conversationState),C=w&&!e.handoffPause?_jsx(IconButton,{icon:"paperclip",accessibilityLabel:t.attach,variant:"ghost",tone:"neutral",onPress:()=>{s&&s().then(t=>e.attach(t))},testID:`${i}-attach`}):void 0,T=g?_jsx(Banner,{message:t.editing,accessibilityRole:"summary",actions:[{label:t.cancel,onPress:()=>e.cancelEdit()}],testID:`${i}-editing`}):null,D=y.length>0?_jsx(View,{style:m.tray,testID:`${i}-attachments`,children:_jsx(View,{style:m.row,children:y.map(s=>_jsxs(View,{style:m.item,children:[_jsx(Chip,{label:s.fileName,variant:"soft",onRemove:()=>{e.removeAttachment(s.key)},labels:{remove:t.removeAttachment},removeTestID:`${i}-remove-${s.key}`,testID:`${i}-chip-${s.key}`}),"Uploading"===s.status?_jsx(ProgressBar,{progress:s.progress??void 0,label:t.attachmentUploading,height:4,containerStyle:m.progress}):null,"Failed"===s.status?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:s.error??t.attachmentFailed}):null]},s.key))})}):null,I=null!==_&&_<=10?_jsx(Text,{variant:"caption",color:0===_?"danger":"secondary",accessibilityLiveRegion:"polite",testID:`${i}-allowance`,children:t.allowance(_)}):null,L=h?_jsx(Banner,{message:h.message,tone:h.tone,dismissible:!0,onClose:()=>f(null),actions:h.openSettings?[{label:t.dictateOpenSettings,onPress:()=>{Permissions.openSettings()}}]:void 0,testID:`${i}-voice-notice`}):null,R=p.length>0,k=p.length>.9*S?_jsx(Text,{variant:"caption",color:"secondary",testID:`${i}-counter`,children:t.counter(p.length,S)}):null,P=T||D||I||k||L?_jsxs(_Fragment,{children:[T,D,I,k,L]}):void 0,B=!v&&(!!j||void 0);return _jsx(Composer,{ref:b,onSend:t=>{x.current?.(),e.submit(t)},value:p,onChangeText:t=>{x.current?.(),d(t),A&&t.length>0&&e.notifyTyping()},loading:e.streaming&&e.features.Stop,ring:l.input.ring&&(R||e.streaming),sendReveal:"Always"===l.input.sendReveal?"always":"onText",sendIcon:c||void 0,onStop:e.features.Stop?()=>e.stop():void 0,stopLabel:t.stop,disabled:0===_||e.handoffPause,maxLength:S,canSend:B,placeholder:e.handoffPause?t.handoffMoment:openQuestion(e.messages)??t.placeholder,accessibilityLabel:t.composer,labels:{send:t.send},leading:C,trailing:_jsx(ChatDictationButton,{chat:e,labels:t,disabled:0===_||e.handoffPause,onText:e=>d(t=>joinDictation(t,e,S)),onNotice:f,stopRef:x}),above:P,below:_jsx(ChatFooter,{chat:e,labels:t}),keyboardAware:a,keyboardOffset:o,safeArea:n,testID:i})}const buildStyles=e=>StyleSheet.create({tray:{gap:e.space.xs},row:{flexDirection:"row",flexWrap:"wrap",gap:e.space.xs},item:{gap:e.space.xxs,maxWidth:"100%"},progress:{minWidth:120}});
1
+ "use strict";import{defaultChatLook}from"@webority/chat-core";import{Permissions}from"@webority/mobile-core/permissions";import{Banner,Chip,Composer,IconButton,ProgressBar,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{ChatDictationButton}from"./ChatDictationButton.js";import{ChatFooter}from"./ChatFooter.js";import{iconNameOf}from"./iconName.js";import{joinDictation}from"./speech/speechText.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const ALLOWANCE_SHOWN_AT=10,COUNTER_AT=.9,DEFAULT_MAX_LENGTH=4e3,openQuestion=e=>{for(let t=e.length-1;t>=0;t-=1){const s=e[t];for(const e of[...s?.parts??[]].reverse())if("InputRequest"===e.kind&&"Open"===e.state)return e.fields[0]?.label||e.title||null}return null};export function ChatComposer({chat:e,labels:t,pickAttachments:s,keyboardOffset:o,keyboardAware:a,safeArea:n,testID:i="chat-composer",focusRef:r,look:l=defaultChatLook,sendIcon:c}){const m=useTheme(),u=useMemo(()=>buildStyles(m),[m]),[p,d]=useState(""),[f,h]=useState(null),g=e.editing,x=useRef(null),b=useRef(null);useEffect(()=>{if(r)return r.current=()=>b.current?.focus(),()=>{r.current=null}},[r]),useEffect(()=>{g&&x.current?.(),d(g?g.text:"")},[g]);const y=e.attachments,v=y.some(e=>"Uploading"===e.status),j=y.some(e=>"Ready"===e.status),_=e.messagesLeftToday,S=e.profile?.limits.maxMessageLength??4e3,w=void 0!==s&&e.features.Attachments&&(e.profile?.limits.maxAttachments??0)>0,A=e.features.HumanHandoff&&("WaitingForAgent"===e.conversationState||"WithAgent"===e.conversationState),C=w&&!e.handoffPause?_jsx(IconButton,{icon:"paperclip",accessibilityLabel:t.attach,variant:"ghost",tone:"neutral",onPress:()=>{s&&s().then(t=>e.attach(t))},testID:`${i}-attach`}):void 0,T=g?_jsx(Banner,{message:t.editing,accessibilityRole:"summary",actions:[{label:t.cancel,onPress:()=>e.cancelEdit()}],testID:`${i}-editing`}):null,D=y.length>0?_jsx(View,{style:u.tray,testID:`${i}-attachments`,children:_jsx(View,{style:u.row,children:y.map(s=>_jsxs(View,{style:u.item,children:[_jsx(Chip,{label:s.fileName,variant:"soft",onRemove:()=>{e.removeAttachment(s.key)},labels:{remove:t.removeAttachment},removeTestID:`${i}-remove-${s.key}`,testID:`${i}-chip-${s.key}`}),"Uploading"===s.status?_jsx(ProgressBar,{...null===s.progress||void 0===s.progress?{}:{progress:s.progress},label:t.attachmentUploading,height:4,containerStyle:u.progress}):null,"Failed"===s.status?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:s.error??t.attachmentFailed}):null]},s.key))})}):null,I=null!==_&&_<=10?_jsx(Text,{variant:"caption",color:0===_?"danger":"secondary",accessibilityLiveRegion:"polite",testID:`${i}-allowance`,children:t.allowance(_)}):null,L=f?_jsx(Banner,{message:f.message,tone:f.tone,dismissible:!0,onClose:()=>h(null),...f.openSettings?{actions:[{label:t.dictateOpenSettings,onPress:()=>{Permissions.openSettings()}}]}:{},testID:`${i}-voice-notice`}):null,R=p.length>0,k=p.length>.9*S?_jsx(Text,{variant:"caption",color:"secondary",testID:`${i}-counter`,children:t.counter(p.length,S)}):null,P=T||D||I||k||L?_jsxs(_Fragment,{children:[T,D,I,k,L]}):void 0,B=!v&&(!!j||void 0),F=iconNameOf(c);return _jsx(Composer,{ref:b,onSend:t=>{x.current?.(),e.submit(t)},value:p,onChangeText:t=>{x.current?.(),d(t),A&&t.length>0&&e.notifyTyping()},loading:e.streaming&&e.features.Stop,ring:l.input.ring&&(R||e.streaming),sendReveal:"Always"===l.input.sendReveal?"always":"onText",...F?{sendIcon:F}:{},...e.features.Stop?{onStop:()=>e.stop()}:{},stopLabel:t.stop,disabled:0===_||e.handoffPause,maxLength:S,...void 0===B?{}:{canSend:B},placeholder:e.handoffPause?t.handoffMoment:openQuestion(e.messages)??t.placeholder,accessibilityLabel:t.composer,labels:{send:t.send},leading:C,trailing:_jsx(ChatDictationButton,{chat:e,labels:t,disabled:0===_||e.handoffPause,onText:e=>d(t=>joinDictation(t,e,S)),onNotice:h,stopRef:x}),above:P,below:_jsx(ChatFooter,{chat:e,labels:t}),...void 0===a?{}:{keyboardAware:a},...void 0===o?{}:{keyboardOffset:o},...void 0===n?{}:{safeArea:n},testID:i})}const buildStyles=e=>StyleSheet.create({tray:{gap:e.space.xs},row:{flexDirection:"row",flexWrap:"wrap",gap:e.space.xs},item:{gap:e.space.xxs,maxWidth:"100%"},progress:{minWidth:120}});
@@ -1 +1 @@
1
- "use strict";import{messagePlainText}from"@webority/chat-core";import{IconButton,Text}from"@webority/mobile-ui";import useTranscriptActions from"./useTranscriptActions.js";import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";const REPLY_AUTHORS=new Set(["Assistant","Agent","Script"]);export function ChatConversationActions({chat:s,labels:t,testID:e}){const n=useTranscriptActions(s,t),i=s.messages.some(s=>s.stored&&REPLY_AUTHORS.has(s.author.kind)&&""!==messagePlainText(s.parts));return s.streaming||s.thinking||s.loading||null===s.conversationId||!i||!n.canShare?null:_jsxs(_Fragment,{children:[_jsx(IconButton,{icon:"share",variant:"ghost",size:"sm",accessibilityLabel:t.shareConversation,onPress:()=>{n.shareConversation()},testID:e}),null!==n.notice?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:n.notice}):null]})}
1
+ "use strict";import{messagePlainText}from"@webority/chat-core";import{IconButton,Text}from"@webority/mobile-ui";import useTranscriptActions from"./useTranscriptActions.js";import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";const REPLY_AUTHORS=new Set(["Assistant","Agent","Script"]);export function ChatConversationActions({chat:s,labels:t,testID:e}){const n=useTranscriptActions(s,t),i=s.messages.some(s=>s.stored&&REPLY_AUTHORS.has(s.author.kind)&&""!==messagePlainText(s.parts));return s.streaming||s.thinking||s.loading||null===s.conversationId||!i||!n.canShare?null:_jsxs(_Fragment,{children:[_jsx(IconButton,{icon:"share",variant:"ghost",size:"sm",accessibilityLabel:t.shareConversation,onPress:()=>{n.shareConversation()},...void 0===e?{}:{testID:e}}),null!==n.notice?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:n.notice}):null]})}
@@ -1 +1 @@
1
- "use strict";import{Avatar,FloatingActionButton,useTheme}from"@webority/mobile-ui";import{useEffect,useState}from"react";import{Animated,Easing,StyleSheet}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx as _jsx}from"react/jsx-runtime";const RISE_MS=900,RISE_DELAY_MS=400,ENTRANCE_MS=800,ENTRANCE_DELAY_MS=1e3,FLOAT_HALF_MS=1600,FLOAT_PX=4,RISE_FROM_PX=116,SHRINK_MS=320,SHRINK_EASING=Easing.bezier(.4,0,.2,1);function entranceStyle(e,t){const range=(e,a)=>t.interpolate({inputRange:e,outputRange:a,extrapolate:"clamp"});switch(e){case"Rise":return{opacity:range([0,.4,1],[0,1,1]),transform:[{translateY:t.interpolate({inputRange:[0,1],outputRange:[116,0]})}]};case"SlideUp":return{opacity:range([0,1],[0,1]),transform:[{translateY:t.interpolate({inputRange:[0,1],outputRange:[100,0]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[.8,1]})}]};case"BounceIn":return{transform:[{scale:range([0,.5,.7,1],[.3,1.05,.9,1])}]};case"FadeInPulse":return{opacity:range([0,.5,1],[0,1,1]),transform:[{scale:range([0,.5,1],[1,1.1,1])}]};case"SpinScale":return{transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:["-180deg","0deg"]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[0,1]})}]};case"WiggleIn":return{transform:[{translateY:range([0,.4,1],[100,0,0])},{rotate:range([0,.4,.6,.8,1],["-10deg","5deg","-3deg","1deg","0deg"])}]};case"ElasticIn":return{transform:[{scale:range([0,.55,.75,1],[0,1.1,.95,1])}]};default:return{transform:[]}}}const OVERSHOOT=new Set(["Rise","SlideUp","SpinScale"]);export function ChatLauncher({look:e,hidden:t,label:a,side:n,offsetX:i,offsetY:r,enter:s,reduced:o,mark:u="Icon",avatar:l=null,buttonRef:c,onPress:m,testID:p}){const d=useTheme(),f=useSafeAreaInsets(),g=e.launcher.entrance,S="Avatar"===u&&l?l:null,A=d.components["floating-action-button"].md.diameter,[R]=useState(()=>s&&!o&&"None"!==g),E=t&&e.expressive&&!o,v=!o&&!t&&"FloatAndPulse"===e.launcher.idle,[_]=useState(()=>new Animated.Value(R?0:1)),[h]=useState(()=>new Animated.Value(0)),[I]=useState(()=>new Animated.Value(1)),[b,y]=useState(!1);if(useEffect(()=>{if(!t)return I.setValue(1),void y(!1);if(!E)return;const e=Animated.timing(I,{toValue:0,duration:320,easing:SHRINK_EASING,useNativeDriver:!0});return e.start(({finished:e})=>{e&&y(!0)}),()=>e.stop()},[t,E,I]),useEffect(()=>{if(!R)return void _.setValue(1);const e="Rise"===g,t=Animated.timing(_,{toValue:1,duration:e?900:800,delay:e?400:1e3,easing:OVERSHOOT.has(g)?Easing.bezier(.34,e?1.4:1.56,.64,1):Easing.linear,useNativeDriver:!0});return t.start(),()=>t.stop()},[R,g,_]),useEffect(()=>{if(!v)return void h.setValue(0);const e=Animated.loop(Animated.sequence([Animated.timing(h,{toValue:1,duration:1600,easing:Easing.inOut(Easing.ease),useNativeDriver:!0}),Animated.timing(h,{toValue:0,duration:1600,easing:Easing.inOut(Easing.ease),useNativeDriver:!0})]));return e.start(),()=>e.stop()},[v,h]),t&&(!E||b))return null;const N="Pill"===e.launcher.style&&!e.launcher.compact,V=d.space[d.components["floating-action-button"]["edge-offset"]]+i,x={position:"absolute",bottom:r+f.bottom,..."start"===n?{left:V}:{right:V}},O=entranceStyle(g,_);return _jsx(Animated.View,{pointerEvents:"box-none",style:StyleSheet.absoluteFill,children:_jsx(Animated.View,{style:[x,{opacity:Animated.multiply(O.opacity??1,I),transform:[...O.transform,{scale:I},{translateY:h.interpolate({inputRange:[0,1],outputRange:[0,-4]})}]}],children:_jsx(FloatingActionButton,{ref:c,icon:S?_jsx(Avatar,{dimension:A,name:a,source:{uri:S}}):"messages",label:N?a:void 0,collapsed:!N,accessibilityLabel:a,onPress:m,testID:p})})})}
1
+ "use strict";import{Avatar,FloatingActionButton,useTheme}from"@webority/mobile-ui";import{useEffect,useState}from"react";import{Animated,Easing,StyleSheet}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx as _jsx}from"react/jsx-runtime";const RISE_MS=900,RISE_DELAY_MS=400,ENTRANCE_MS=800,ENTRANCE_DELAY_MS=1e3,FLOAT_HALF_MS=1600,FLOAT_PX=4,RISE_FROM_PX=116,SHRINK_MS=320,SHRINK_EASING=Easing.bezier(.4,0,.2,1);function entranceStyle(e,t){const rangeNumber=(e,a)=>t.interpolate({inputRange:e,outputRange:a,extrapolate:"clamp"});switch(e){case"Rise":return{opacity:rangeNumber([0,.4,1],[0,1,1]),transform:[{translateY:t.interpolate({inputRange:[0,1],outputRange:[116,0]})}]};case"SlideUp":return{opacity:rangeNumber([0,1],[0,1]),transform:[{translateY:t.interpolate({inputRange:[0,1],outputRange:[100,0]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[.8,1]})}]};case"BounceIn":return{transform:[{scale:rangeNumber([0,.5,.7,1],[.3,1.05,.9,1])}]};case"FadeInPulse":return{opacity:rangeNumber([0,.5,1],[0,1,1]),transform:[{scale:rangeNumber([0,.5,1],[1,1.1,1])}]};case"SpinScale":return{transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:["-180deg","0deg"]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[0,1]})}]};case"WiggleIn":return{transform:[{translateY:rangeNumber([0,.4,1],[100,0,0])},{rotate:(a=[0,.4,.6,.8,1],n=["-10deg","5deg","-3deg","1deg","0deg"],t.interpolate({inputRange:a,outputRange:n,extrapolate:"clamp"}))}]};case"ElasticIn":return{transform:[{scale:rangeNumber([0,.55,.75,1],[0,1.1,.95,1])}]};default:return{transform:[]}}var a,n}const OVERSHOOT=new Set(["Rise","SlideUp","SpinScale"]);export function ChatLauncher({look:e,hidden:t,label:a,side:n,offsetX:r,offsetY:i,enter:s,reduced:o,mark:u="Icon",avatar:l=null,buttonRef:c,onPress:p,testID:m}){const g=useTheme(),d=useSafeAreaInsets(),f=e.launcher.entrance,S="Avatar"===u&&l?l:null,R=g.components["floating-action-button"].md.diameter,[A]=useState(()=>s&&!o&&"None"!==f),E=t&&e.expressive&&!o,v=!o&&!t&&"FloatAndPulse"===e.launcher.idle,[_]=useState(()=>new Animated.Value(A?0:1)),[h]=useState(()=>new Animated.Value(0)),[I]=useState(()=>new Animated.Value(1)),[b,y]=useState(!1);if(useEffect(()=>{if(!t)return I.setValue(1),void y(!1);if(!E)return;const e=Animated.timing(I,{toValue:0,duration:320,easing:SHRINK_EASING,useNativeDriver:!0});return e.start(({finished:e})=>{e&&y(!0)}),()=>e.stop()},[t,E,I]),useEffect(()=>{if(!A)return void _.setValue(1);const e="Rise"===f,t=Animated.timing(_,{toValue:1,duration:e?900:800,delay:e?400:1e3,easing:OVERSHOOT.has(f)?Easing.bezier(.34,e?1.4:1.56,.64,1):Easing.linear,useNativeDriver:!0});return t.start(),()=>t.stop()},[A,f,_]),useEffect(()=>{if(!v)return void h.setValue(0);const e=Animated.loop(Animated.sequence([Animated.timing(h,{toValue:1,duration:1600,easing:Easing.inOut(Easing.ease),useNativeDriver:!0}),Animated.timing(h,{toValue:0,duration:1600,easing:Easing.inOut(Easing.ease),useNativeDriver:!0})]));return e.start(),()=>e.stop()},[v,h]),t&&(!E||b))return null;const N="Pill"===e.launcher.style&&!e.launcher.compact,V=g.space[g.components["floating-action-button"]["edge-offset"]]+r,x={position:"absolute",bottom:i+d.bottom,..."start"===n?{left:V}:{right:V}},O=entranceStyle(f,_);return _jsx(Animated.View,{pointerEvents:"box-none",style:StyleSheet.absoluteFill,children:_jsx(Animated.View,{style:[x,{opacity:Animated.multiply(O.opacity??1,I),transform:[...O.transform,{scale:I},{translateY:h.interpolate({inputRange:[0,1],outputRange:[0,-4]})}]}],children:_jsx(FloatingActionButton,{ref:c,icon:S?_jsx(Avatar,{dimension:R,name:a,source:{uri:S}}):"messages",...N?{label:a}:{},collapsed:!N,accessibilityLabel:a,onPress:p,testID:m})})})}
@@ -1 +1 @@
1
- "use strict";import{buildTranscript,messagePlainText}from"@webority/chat-core";import{copyText}from"@webority/mobile-core/clipboard";import{Button,IconButton,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{View}from"react-native";import{ReadAloudButton}from"./ReadAloudButton.js";import useTranscriptActions from"./useTranscriptActions.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const TEXT_AUTHORS=new Set(["Assistant","Agent","Script"]),RATED_AUTHORS=new Set(["Assistant","Agent"]);export function ChatMessageActions({chat:e,message:t,labels:s,isLast:i,isLastVisitor:a,testID:n}){const r=useTheme(),[o,l]=useState(!1),[c,u]=useState("idle"),m=useRef(null),d=useTranscriptActions(e,s),p=useMemo(()=>TEXT_AUTHORS.has(t.author.kind)&&buildTranscript([t],{labels:s,title:null,figureText:!1,assistantName:e.profile?.assistant.name}).entries.length>0,[t,s,e.profile]);if(useEffect(()=>()=>{null!==m.current&&clearTimeout(m.current)},[]),t.streaming)return null;const g=messagePlainText(t.parts),h=TEXT_AUTHORS.has(t.author.kind)&&""!==g,f=t.stored&&RATED_AUTHORS.has(t.author.kind),x=("Assistant"===t.author.kind||"Agent"===t.author.kind||"Script"===t.author.kind)&&""!==messagePlainText(t.parts).trim(),T=i&&"Assistant"===t.author.kind&&!e.streaming&&!e.thinking&&e.features.Regenerate&&e.messages.some(e=>e.stored&&"Visitor"===e.author.kind),b=a&&t.stored&&e.features.Edit&&!e.streaming&&!e.thinking,save=async s=>{try{await e.rate(t.id,s),u("saved")}catch{u("failed")}};return h&&e.features.Copy||p&&e.features.Share&&d.canShare||x||T||b||f&&e.features.Rating?_jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.space.xs},testID:n,children:[h&&e.features.Copy?_jsx(Button,{label:o?s.copied:s.copy,variant:"link",size:"sm",onPress:()=>{(async()=>{await copyText(g)&&(l(!0),null!==m.current&&clearTimeout(m.current),m.current=setTimeout(()=>l(!1),2e3))})()},testID:`${n}-copy`}):null,p&&e.features.Share&&d.canShare?_jsx(Button,{label:s.share,variant:"link",size:"sm",leftIcon:"share",disabled:e.streaming||e.thinking,onPress:()=>{d.shareReply(t)},testID:`${n}-share`}):null,x?_jsx(ReadAloudButton,{chat:e,message:t,labels:s}):null,T?_jsx(Button,{label:s.regenerate,variant:"link",size:"sm",onPress:()=>{e.regenerate()},testID:`${n}-regenerate`}):null,b?_jsx(Button,{label:s.edit,variant:"link",size:"sm",onPress:()=>e.startEdit(t.id),testID:`${n}-edit`}):null,f&&e.features.Rating?_jsxs(_Fragment,{children:[_jsxs(View,{accessibilityRole:"summary",accessibilityLabel:s.rating,style:{flexDirection:"row",alignItems:"center",gap:r.space.xs},children:[_jsx(IconButton,{icon:"like",accessibilityLabel:s.rateUp,tone:"neutral",size:"sm",variant:"Up"===t.rating?"soft":"ghost",accessibilityState:{checked:"Up"===t.rating},onPress:()=>{save("Up")},testID:`${n}-rate-up`}),_jsx(IconButton,{icon:"dislike",accessibilityLabel:s.rateDown,tone:"neutral",size:"sm",variant:"Down"===t.rating?"soft":"ghost",accessibilityState:{checked:"Down"===t.rating},onPress:()=>{save("Down")},testID:`${n}-rate-down`})]}),"failed"===c?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:s.ratingFailed}):null,"saved"===c?_jsx(Text,{variant:"caption",color:"secondary",accessibilityLiveRegion:"polite",children:s.rated}):null]}):null,null!==d.notice?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:d.notice}):null]}):null}
1
+ "use strict";import{buildTranscript,messagePlainText}from"@webority/chat-core";import{copyText}from"@webority/mobile-core/clipboard";import{Button,IconButton,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{View}from"react-native";import{ReadAloudButton}from"./ReadAloudButton.js";import useTranscriptActions from"./useTranscriptActions.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const TEXT_AUTHORS=new Set(["Assistant","Agent","Script"]),RATED_AUTHORS=new Set(["Assistant","Agent"]);export function ChatMessageActions({chat:e,message:t,labels:s,isLast:i,isLastVisitor:a,testID:n}){const r=useTheme(),[o,l]=useState(!1),[c,u]=useState("idle"),m=useRef(null),d=useTranscriptActions(e,s),p=useMemo(()=>TEXT_AUTHORS.has(t.author.kind)&&buildTranscript([t],{labels:s,title:null,figureText:!1,...void 0===e.profile?.assistant.name?{}:{assistantName:e.profile.assistant.name}}).entries.length>0,[t,s,e.profile]);if(useEffect(()=>()=>{null!==m.current&&clearTimeout(m.current)},[]),t.streaming)return null;const g=messagePlainText(t.parts),h=TEXT_AUTHORS.has(t.author.kind)&&""!==g,f=t.stored&&RATED_AUTHORS.has(t.author.kind),x=("Assistant"===t.author.kind||"Agent"===t.author.kind||"Script"===t.author.kind)&&""!==messagePlainText(t.parts).trim(),T=i&&"Assistant"===t.author.kind&&!e.streaming&&!e.thinking&&e.features.Regenerate&&e.messages.some(e=>e.stored&&"Visitor"===e.author.kind),b=a&&t.stored&&e.features.Edit&&!e.streaming&&!e.thinking,save=async s=>{try{await e.rate(t.id,s),u("saved")}catch{u("failed")}};return h&&e.features.Copy||p&&e.features.Share&&d.canShare||x||T||b||f&&e.features.Rating?_jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:r.space.xs},testID:n,children:[h&&e.features.Copy?_jsx(Button,{label:o?s.copied:s.copy,variant:"link",size:"sm",onPress:()=>{(async()=>{await copyText(g)&&(l(!0),null!==m.current&&clearTimeout(m.current),m.current=setTimeout(()=>l(!1),2e3))})()},testID:`${n}-copy`}):null,p&&e.features.Share&&d.canShare?_jsx(Button,{label:s.share,variant:"link",size:"sm",leftIcon:"share",disabled:e.streaming||e.thinking,onPress:()=>{d.shareReply(t)},testID:`${n}-share`}):null,x?_jsx(ReadAloudButton,{chat:e,message:t,labels:s}):null,T?_jsx(Button,{label:s.regenerate,variant:"link",size:"sm",onPress:()=>{e.regenerate()},testID:`${n}-regenerate`}):null,b?_jsx(Button,{label:s.edit,variant:"link",size:"sm",onPress:()=>e.startEdit(t.id),testID:`${n}-edit`}):null,f&&e.features.Rating?_jsxs(_Fragment,{children:[_jsxs(View,{accessibilityRole:"summary",accessibilityLabel:s.rating,style:{flexDirection:"row",alignItems:"center",gap:r.space.xs},children:[_jsx(IconButton,{icon:"like",accessibilityLabel:s.rateUp,tone:"neutral",size:"sm",variant:"Up"===t.rating?"soft":"ghost",accessibilityState:{checked:"Up"===t.rating},onPress:()=>{save("Up")},testID:`${n}-rate-up`}),_jsx(IconButton,{icon:"dislike",accessibilityLabel:s.rateDown,tone:"neutral",size:"sm",variant:"Down"===t.rating?"soft":"ghost",accessibilityState:{checked:"Down"===t.rating},onPress:()=>{save("Down")},testID:`${n}-rate-down`})]}),"failed"===c?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:s.ratingFailed}):null,"saved"===c?_jsx(Text,{variant:"caption",color:"secondary",accessibilityLiveRegion:"polite",children:s.rated}):null]}):null,null!==d.notice?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:d.notice}):null]}):null}
@@ -1 +1 @@
1
- "use strict";import{Card,Chip,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const SHOWN_AT_MOST=3;export function ChatOpenTickets({chat:e,labels:t,onOpenTicket:s,testID:i="chat-open-tickets"}){const n=useTheme();return e.features.OpenTickets&&0!==e.openTickets.length?_jsx(View,{accessibilityLabel:t.openTickets,style:{gap:n.space.xs},testID:i,children:e.openTickets.slice(0,3).map(e=>{const n=s?()=>s({ticketId:e.ticketId,number:e.number}):void 0;return _jsxs(Card,{variant:"outline",padding:"sm",interactive:void 0!==n,onPress:n,testID:`${i}-${e.ticketId}`,children:[_jsx(Text,{variant:"label",children:t.ticketAria(e.number)}),_jsx(Text,{variant:"bodySmall",numberOfLines:1,children:e.subject}),_jsx(Chip,{size:"sm",variant:"soft",label:t.ticketStatus(e.status)||e.status})]},e.ticketId)})}):null}
1
+ "use strict";import{Card,Chip,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const SHOWN_AT_MOST=3;export function ChatOpenTickets({chat:e,labels:t,onOpenTicket:s,testID:i="chat-open-tickets"}){const n=useTheme();return e.features.OpenTickets&&0!==e.openTickets.length?_jsx(View,{accessibilityLabel:t.openTickets,style:{gap:n.space.xs},testID:i,children:e.openTickets.slice(0,3).map(e=>{const n=s?()=>s({ticketId:e.ticketId,number:e.number}):void 0;return _jsxs(Card,{variant:"outline",padding:"sm",interactive:void 0!==n,...void 0===n?{}:{onPress:n},testID:`${i}-${e.ticketId}`,children:[_jsx(Text,{variant:"label",children:t.ticketAria(e.number)}),_jsx(Text,{variant:"bodySmall",numberOfLines:1,children:e.subject}),_jsx(Chip,{size:"sm",variant:"soft",label:t.ticketStatus(e.status)||e.status})]},e.ticketId)})}):null}
@@ -1 +1 @@
1
- "use strict";import{createConversationList,formatChatDate}from"@webority/chat-core";import{Button,Card,IconButton,Input,Text,useTheme}from"@webority/mobile-ui";import{useCallback,useEffect,useState,useSyncExternalStore}from"react";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const PAGE_SIZE=20,EMPTY_LIST_STATE=Object.freeze({items:[],totalCount:null,loading:!1,error:null,hasMore:!1}),NO_SUBSCRIPTION=()=>()=>{};export function ChatPastChats({chat:e,labels:t,testID:n="chat-past-chats"}){const s=useTheme(),a=!0===e.features.History,[i,l]=useState(null),r=a&&null!==i&&i.client===e.client?i.list:null,o=useCallback(e=>r?r.subscribe(e):NO_SUBSCRIPTION(),[r]),c=useCallback(()=>r?r.getState():EMPTY_LIST_STATE,[r]),d=useSyncExternalStore(o,c);if(useEffect(()=>{if(!a)return;const t=createConversationList({client:e.client});return l({client:e.client,list:t}),t.load(),()=>t.dispose()},[e.client,a]),!a||0===d.items.length)return null;const open=t=>{e.openConversation(t.publicId)};return _jsx(View,{style:{gap:s.space.sm},testID:n,children:d.items.slice(0,20).map(s=>_jsx(ConversationRow,{conversation:s,list:r,chat:e,labels:t,testID:n,onOpen:open},s.publicId))})}export function ConversationRow({conversation:e,list:t,chat:n,labels:s,testID:a,onOpen:i,untitledTitle:l}){const r=useTheme(),[o,c]=useState("idle"),[d,u]=useState(""),[m,x]=useState(""),[h,p]=useState(!1),b=e.publicId,f=e.title||l||s.earlierChat,g=formatChatDate(e.lastActivityDateTimeUtc),cancel=()=>{x(""),c("idle")},saveRename=async()=>{const e=d.trim();if(!h&&t&&""!==e){p(!0),x("");try{await t.rename(b,e),c("idle")}catch{x(s.renameFailed)}finally{p(!1)}}};return _jsxs(Card,{variant:"outline",padding:"sm",onPress:"idle"===o?()=>i(e):void 0,accessibilityLabel:`${f}, ${g}`,testID:`${a}-item-${b}`,children:["idle"===o?_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:r.space.sm},children:[_jsxs(View,{style:{flex:1,minWidth:0},children:[_jsx(Text,{variant:"label",numberOfLines:1,children:f}),_jsx(Text,{variant:"caption",color:"secondary",children:g})]}),n.features.Rename?_jsx(IconButton,{icon:"edit",variant:"ghost",accessibilityLabel:s.rename,onPress:()=>{x(""),u(e.title??""),c("renaming")},testID:`${a}-rename-${b}`}):null,n.features.Delete?_jsx(IconButton,{icon:"trash",tone:"danger",variant:"ghost",accessibilityLabel:s.deleteChat,onPress:()=>{x(""),c("deleting")},testID:`${a}-delete-${b}`}):null]}):null,"renaming"===o?_jsxs(View,{style:{gap:r.space.sm},children:[_jsx(Input,{label:s.conversationTitle,value:d,onChangeText:u,maxLength:120,returnKeyType:"done",onSubmitEditing:()=>{saveRename()},testID:`${a}-rename-input-${b}`}),""!==m?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",testID:`${a}-rename-error-${b}`,children:m}):null,_jsxs(View,{style:{flexDirection:"row",justifyContent:"flex-end",gap:r.space.sm},children:[_jsx(Button,{label:s.cancel,variant:"ghost",disabled:h,onPress:cancel,testID:`${a}-rename-cancel-${b}`}),_jsx(Button,{label:s.renameSave,disabled:""===d.trim()||h,loading:h,onPress:()=>{saveRename()},testID:`${a}-rename-save-${b}`})]})]}):null,"deleting"===o?_jsxs(View,{style:{gap:r.space.sm},children:[_jsx(Text,{variant:"bodySmall",color:""!==m?"danger":"secondary",accessibilityLiveRegion:""!==m?"polite":void 0,testID:`${a}-delete-message-${b}`,children:""!==m?m:s.deleteConfirmMessage}),_jsxs(View,{style:{flexDirection:"row",justifyContent:"flex-end",gap:r.space.sm},children:[_jsx(Button,{label:s.cancel,variant:"ghost",disabled:h,onPress:cancel,testID:`${a}-delete-cancel-${b}`}),_jsx(Button,{label:s.deleteConfirm,tone:"danger",loading:h,onPress:()=>{(async()=>{if(!h&&t){p(!0),x("");try{await t.remove(b),b===n.conversationId&&n.newConversation(),c("idle")}catch{x(s.deleteFailed)}finally{p(!1)}}})()},testID:`${a}-delete-confirm-${b}`})]})]}):null]})}
1
+ "use strict";import{createConversationList,formatChatDate}from"@webority/chat-core";import{Logger}from"@webority/mobile-core";import{Button,Card,IconButton,Input,Text,useTheme}from"@webority/mobile-ui";import{useCallback,useEffect,useState,useSyncExternalStore}from"react";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const PAGE_SIZE=20,EMPTY_LIST_STATE=Object.freeze({items:[],totalCount:null,loading:!1,error:null,hasMore:!1}),NO_SUBSCRIPTION=()=>()=>{};export function ChatPastChats({chat:e,labels:t,testID:n="chat-past-chats"}){const s=useTheme(),a=!0===e.features.History,[i,l]=useState(null),r=a&&null!==i&&i.client===e.client?i.list:null,o=useCallback(e=>r?r.subscribe(e):NO_SUBSCRIPTION(),[r]),c=useCallback(()=>r?r.getState():EMPTY_LIST_STATE,[r]),d=useSyncExternalStore(o,c);if(useEffect(()=>{if(!a)return;const t=createConversationList({client:e.client});return l({client:e.client,list:t}),t.load(),()=>t.dispose()},[e.client,a]),!a||0===d.items.length)return null;const open=t=>{e.openConversation(t.publicId)};return _jsx(View,{style:{gap:s.space.sm},testID:n,children:d.items.slice(0,20).map(s=>_jsx(ConversationRow,{conversation:s,list:r,chat:e,labels:t,testID:n,onOpen:open},s.publicId))})}export function ConversationRow({conversation:e,list:t,chat:n,labels:s,testID:a,onOpen:i,untitledTitle:l}){const r=useTheme(),[o,c]=useState("idle"),[d,u]=useState(""),[m,x]=useState(""),[h,f]=useState(!1),g=e.publicId,p=e.title||l||s.earlierChat,b=formatChatDate(e.lastActivityDateTimeUtc),cancel=()=>{x(""),c("idle")},saveRename=async()=>{const e=d.trim();if(!h&&t&&""!==e){f(!0),x("");try{await t.rename(g,e),c("idle")}catch(e){Logger.error("[chat] rename failed",e),x(s.renameFailed)}finally{f(!1)}}};return _jsxs(Card,{variant:"outline",padding:"sm",..."idle"===o?{onPress:()=>i(e)}:{},accessibilityLabel:`${p}, ${b}`,testID:`${a}-item-${g}`,children:["idle"===o?_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:r.space.sm},children:[_jsxs(View,{style:{flex:1,minWidth:0},children:[_jsx(Text,{variant:"label",numberOfLines:1,children:p}),_jsx(Text,{variant:"caption",color:"secondary",children:b})]}),n.features.Rename?_jsx(IconButton,{icon:"edit",variant:"ghost",accessibilityLabel:s.rename,onPress:()=>{x(""),u(e.title??""),c("renaming")},testID:`${a}-rename-${g}`}):null,n.features.Delete?_jsx(IconButton,{icon:"trash",tone:"danger",variant:"ghost",accessibilityLabel:s.deleteChat,onPress:()=>{x(""),c("deleting")},testID:`${a}-delete-${g}`}):null]}):null,"renaming"===o?_jsxs(View,{style:{gap:r.space.sm},children:[_jsx(Input,{label:s.conversationTitle,value:d,onChangeText:u,maxLength:120,returnKeyType:"done",onSubmitEditing:()=>{saveRename()},testID:`${a}-rename-input-${g}`}),""!==m?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",testID:`${a}-rename-error-${g}`,children:m}):null,_jsxs(View,{style:{flexDirection:"row",justifyContent:"flex-end",gap:r.space.sm},children:[_jsx(Button,{label:s.cancel,variant:"ghost",disabled:h,onPress:cancel,testID:`${a}-rename-cancel-${g}`}),_jsx(Button,{label:s.renameSave,disabled:""===d.trim()||h,loading:h,onPress:()=>{saveRename()},testID:`${a}-rename-save-${g}`})]})]}):null,"deleting"===o?_jsxs(View,{style:{gap:r.space.sm},children:[_jsx(Text,{variant:"bodySmall",color:""!==m?"danger":"secondary",accessibilityLiveRegion:""!==m?"polite":void 0,testID:`${a}-delete-message-${g}`,children:""!==m?m:s.deleteConfirmMessage}),_jsxs(View,{style:{flexDirection:"row",justifyContent:"flex-end",gap:r.space.sm},children:[_jsx(Button,{label:s.cancel,variant:"ghost",disabled:h,onPress:cancel,testID:`${a}-delete-cancel-${g}`}),_jsx(Button,{label:s.deleteConfirm,tone:"danger",loading:h,onPress:()=>{(async()=>{if(!h&&t){f(!0),x("");try{await t.remove(g),g===n.conversationId&&n.newConversation(),c("idle")}catch(e){Logger.error("[chat] delete failed",e),x(s.deleteFailed)}finally{f(!1)}}})()},testID:`${a}-delete-confirm-${g}`})]})]}):null]})}
@@ -1 +1 @@
1
- "use strict";import{mergeLabels,mergeLook}from"@webority/chat-core";import{BottomSheet,useReducedMotion,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{ChatAppearanceScope}from"./ChatAppearanceScope.js";import{ChatFrame}from"./ChatFrame.js";import{ChatLauncher}from"./ChatLauncher.js";import{ChatNudge}from"./ChatNudge.js";import{focusForAccessibility}from"./chatShared.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const DEFAULT_SNAP_POINTS=["92%"],DEFAULT_BOTTOM_OFFSET=16;export function ChatSheet({chat:e,labels:t,renderers:o,layoutParts:s,loader:r="Steps",look:n,appearance:a,pickAttachments:i,onOpenAttachment:c,onOpenTarget:l,onNavigate:u,keyboardOffset:f,open:p,defaultOpen:h=!1,onOpenChange:m,snapPoints:d=DEFAULT_SNAP_POINTS,openTicket:b,handoffHosts:g,resolveLink:C,conversationId:S,onClose:k,testID:j="chat-sheet"}){const y=useTheme(),x=mergeLabels(t),T=useMemo(()=>mergeLook(n),[n]),A=useReducedMotion(),_="Reduced"===T.motion||A,L=a?.position??"end",O=void 0!==p,v=O?p:e.open,E=useRef(null),F=useRef(!1),P=useRef(S??null),R=e.setChatVisible,N=useRef(!1),D=!N.current,[I,w]=useState(0),M=useRef(v);useEffect(()=>{v&&(N.current=!0)},[v]),useEffect(()=>{v&&!M.current&&w(e=>e+1),M.current=v},[v]),useEffect(()=>{F.current||(F.current=!0,O||!h||null===e.profile||e.open||e.session.open({trigger:"manual"}))},[O,h,e.profile,e.open,e.session]),useEffect(()=>{O&&(p&&!e.open&&e.session.open({trigger:"manual"}),!p&&e.open&&e.session.close("button"))},[O,p,e.open,e.session]);const V=useRef(v);if(useEffect(()=>{V.current&&!v&&focusForAccessibility(E.current),V.current=v},[v]),useEffect(()=>{R(v)},[R,v]),useEffect(()=>{!O&&S&&S!==P.current&&null!==e.profile&&(P.current=S,e.open||(e.session.open({trigger:"manual"}),m?.(!0)))},[O,S,e.profile,e.open,e.session,m]),null===e.profile||!e.features.VisitorChat)return null;const setOpen=t=>{t?e.session.open({trigger:"manual"}):e.session.close("button"),m?.(t)},closeSheet=()=>{setOpen(!1),k?.()},B=a?.offsetY??16;return _jsx(View,{testID:j,style:StyleSheet.absoluteFill,pointerEvents:"box-none",children:_jsxs(ChatAppearanceScope,{appearance:a,children:[_jsx(ChatLauncher,{look:T,hidden:v,label:e.profile?.experience.launcher?.hoverLabel||x.launcher,side:L,offsetX:a?.offsetX??0,offsetY:B,enter:D,reduced:_,mark:T.launcher.mark,avatar:T.avatar,buttonRef:E,onPress:()=>setOpen(!0),testID:`${j}-launcher`}),_jsx(ChatNudge,{chat:e,labels:x,enabled:!v&&e.features.Nudges,onActivate:()=>setOpen(!0),bottomOffset:B,position:L,testID:`${j}-nudge`}),_jsx(BottomSheet,{open:v,onClose:closeSheet,snapPoints:d,keyboardBehavior:"shift",scrollable:!1,enablePanDownToClose:!0,enableBackdropPress:!0,accessibilityViewIsModal:!0,accessibilityLabel:x.panelTitle,children:_jsx(View,{style:{flex:1,backgroundColor:y.colors.bg},children:_jsx(ChatFrame,{chat:e,labels:x,renderers:o,layoutParts:s,loader:r,look:n,pickAttachments:i,onOpenAttachment:c,onOpenTarget:l,onNavigate:u,openTicket:b,handoffHosts:g,resolveLink:C,keyboardOffset:f,onClose:closeSheet,layout:"sheet",enterKey:I,testID:`${j}-frame`})})})]})})}
1
+ "use strict";import{mergeLabels,mergeLook}from"@webority/chat-core";import{BottomSheet,useReducedMotion,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{ChatAppearanceScope}from"./ChatAppearanceScope.js";import{ChatFrame}from"./ChatFrame.js";import{ChatLauncher}from"./ChatLauncher.js";import{ChatNudge}from"./ChatNudge.js";import{focusForAccessibility}from"./chatShared.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const DEFAULT_SNAP_POINTS=["92%"],DEFAULT_BOTTOM_OFFSET=16;export function ChatSheet({chat:e,labels:t,renderers:o,layoutParts:s,loader:r="Steps",look:n,appearance:a,pickAttachments:i,onOpenAttachment:c,onOpenTarget:l,onNavigate:u,keyboardOffset:f,open:p,defaultOpen:h=!1,onOpenChange:m,snapPoints:d=DEFAULT_SNAP_POINTS,openTicket:b,handoffHosts:g,resolveLink:C,conversationId:S,onClose:k,testID:j="chat-sheet"}){const y=useTheme(),x=mergeLabels(t),T=useMemo(()=>mergeLook(n),[n]),A=useReducedMotion(),_="Reduced"===T.motion||A,v=a?.position??"end",L=void 0!==p,O=L?p:e.open,E=useRef(null),F=useRef(!1),P=useRef(S??null),R=e.setChatVisible,N=useRef(!1),D=!N.current,[I,w]=useState(0),M=useRef(O);useEffect(()=>{O&&(N.current=!0)},[O]),useEffect(()=>{O&&!M.current&&w(e=>e+1),M.current=O},[O]),useEffect(()=>{F.current||(F.current=!0,L||!h||null===e.profile||e.open||e.session.open({trigger:"manual"}))},[L,h,e.profile,e.open,e.session]),useEffect(()=>{L&&(p&&!e.open&&e.session.open({trigger:"manual"}),!p&&e.open&&e.session.close("button"))},[L,p,e.open,e.session]);const V=useRef(O);if(useEffect(()=>{V.current&&!O&&focusForAccessibility(E.current),V.current=O},[O]),useEffect(()=>{R(O)},[R,O]),useEffect(()=>{!L&&S&&S!==P.current&&null!==e.profile&&(P.current=S,e.open||(e.session.open({trigger:"manual"}),m?.(!0)))},[L,S,e.profile,e.open,e.session,m]),null===e.profile||!e.features.VisitorChat)return null;const setOpen=t=>{t?e.session.open({trigger:"manual"}):e.session.close("button"),m?.(t)},closeSheet=()=>{setOpen(!1),k?.()},B=a?.offsetY??16;return _jsx(View,{testID:j,style:StyleSheet.absoluteFill,pointerEvents:"box-none",children:_jsxs(ChatAppearanceScope,{appearance:a,children:[_jsx(ChatLauncher,{look:T,hidden:O,label:e.profile?.experience.launcher?.hoverLabel||x.launcher,side:v,offsetX:a?.offsetX??0,offsetY:B,enter:D,reduced:_,mark:T.launcher.mark,avatar:T.avatar,buttonRef:E,onPress:()=>setOpen(!0),testID:`${j}-launcher`}),_jsx(ChatNudge,{chat:e,labels:x,enabled:!O&&e.features.Nudges,onActivate:()=>setOpen(!0),bottomOffset:B,position:v,testID:`${j}-nudge`}),_jsx(BottomSheet,{open:O,onClose:closeSheet,...void 0===d?{}:{snapPoints:d},keyboardBehavior:"shift",scrollable:!1,enablePanDownToClose:!0,enableBackdropPress:!0,accessibilityViewIsModal:!0,accessibilityLabel:x.panelTitle,children:_jsx(View,{style:{flex:1,backgroundColor:y.colors.bg},children:_jsx(ChatFrame,{chat:e,labels:x,renderers:o,layoutParts:s,loader:r,look:n,pickAttachments:i,onOpenAttachment:c,onOpenTarget:l,onNavigate:u,openTicket:b,handoffHosts:g,resolveLink:C,keyboardOffset:f,onClose:closeSheet,layout:"sheet",enterKey:I,testID:`${j}-frame`})})})]})})}
@@ -1 +1 @@
1
- "use strict";import{formatDate}from"@webority/mobile-core";import{Avatar,Card,Chip,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useState}from"react";import{View}from"react-native";import{ChatEntrance}from"./ChatEntrance.js";import{ChatOpenTickets}from"./ChatOpenTickets.js";import{ChatPastChats}from"./ChatPastChats.js";import{TypingPill}from"./loaders/TypingPill.js";import{chipLook}from"./renderers/chipLook.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";export function ChatStarters({chat:e,labels:t,openTicket:s,avatar:a,motion:r="On",greetingLoaderMs:i=0,testID:n="chat-starters"}){const l=useTheme(),[o,c]=useState(!(i>0));useEffect(()=>{if(o)return;const e=setTimeout(()=>c(!0),i);return()=>clearTimeout(e)},[o,i]);const m=e.profile,p=e.greeting??"";if(!m)return null;const u=m.assistant.intro,h=e.features.Starters&&e.starters.length>0,d=e.lastConversation,x=e.features.ResumeLast&&!e.features.History&&null!==d;return _jsx(View,{accessibilityLabel:t.emptyTitle,style:{flex:1,justifyContent:"center",alignItems:"center",gap:l.space.md,padding:l.space.md},testID:n,children:o?_jsxs(_Fragment,{children:[a?_jsx(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",children:_jsx(Avatar,{size:"lg",name:e.profile?.assistant.name??t.panelTitle,source:{uri:a}})}):null,_jsx(Text,{variant:"h2",align:"center",children:p}),u?_jsx(Text,{variant:"body",color:"secondary",align:"center",children:u}):null,h?_jsx(View,{accessibilityRole:"none",accessibilityLabel:t.starters,style:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:l.space.xs},children:e.starters.map((t,s)=>_jsx(ChatEntrance,{index:s,children:_jsx(Chip,{...t.variant?chipLook(t.variant):null,label:t.label,leftIcon:t.icon?t.icon:void 0,onPress:()=>{e.submit(t.message)},testID:`${n}-${t.id}`})},t.id))}):null,x&&d?_jsxs(Card,{variant:"outline",padding:"sm",onPress:()=>{e.resumeLast()},testID:`${n}-resume`,children:[_jsx(Text,{variant:"caption",color:"secondary",children:t.resumeLast}),_jsx(Text,{variant:"label",numberOfLines:1,children:d.title||t.untitled}),_jsx(Text,{variant:"caption",color:"secondary",children:formatDate(d.lastActivityDateTimeUtc)})]}):null,e.features.History?_jsx(ChatPastChats,{chat:e,labels:t,testID:`${n}-past-chats`}):null,_jsx(ChatOpenTickets,{chat:e,labels:t,onOpenTicket:s})]}):_jsx(View,{children:_jsx(TypingPill,{motion:r,mark:a?_jsx(Avatar,{size:"xs",name:e.profile?.assistant.name??t.panelTitle,source:{uri:a}}):null})})})}
1
+ "use strict";import{formatDate}from"@webority/mobile-core";import{Avatar,Card,Chip,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useState}from"react";import{View}from"react-native";import{ChatEntrance}from"./ChatEntrance.js";import{ChatOpenTickets}from"./ChatOpenTickets.js";import{ChatPastChats}from"./ChatPastChats.js";import{iconNameOf}from"./iconName.js";import{TypingPill}from"./loaders/TypingPill.js";import{chipLook}from"./renderers/chipLook.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";export function ChatStarters({chat:e,labels:t,openTicket:s,avatar:a,motion:r="On",greetingLoaderMs:i=0,testID:n="chat-starters"}){const o=useTheme(),[l,c]=useState(!(i>0));useEffect(()=>{if(l)return;const e=setTimeout(()=>c(!0),i);return()=>clearTimeout(e)},[l,i]);const m=e.profile,p=e.greeting??"";if(!m)return null;const u=m.assistant.intro,h=e.features.Starters&&e.starters.length>0,d=e.lastConversation,f=e.features.ResumeLast&&!e.features.History&&null!==d;return _jsx(View,{accessibilityLabel:t.emptyTitle,style:{flex:1,justifyContent:"center",alignItems:"center",gap:o.space.md,padding:o.space.md},testID:n,children:l?_jsxs(_Fragment,{children:[a?_jsx(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",children:_jsx(Avatar,{size:"lg",name:e.profile?.assistant.name??t.panelTitle,source:{uri:a}})}):null,_jsx(Text,{variant:"h2",align:"center",children:p}),u?_jsx(Text,{variant:"body",color:"secondary",align:"center",children:u}):null,h?_jsx(View,{accessibilityRole:"none",accessibilityLabel:t.starters,style:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:o.space.xs},children:e.starters.map((t,s)=>{const a=iconNameOf(t.icon);return _jsx(ChatEntrance,{index:s,children:_jsx(Chip,{...t.variant?chipLook(t.variant):null,label:t.label,...null===a?{}:{leftIcon:a},onPress:()=>{e.submit(t.message)},testID:`${n}-${t.id}`})},t.id)})}):null,f&&d?_jsxs(Card,{variant:"outline",padding:"sm",onPress:()=>{e.resumeLast()},testID:`${n}-resume`,children:[_jsx(Text,{variant:"caption",color:"secondary",children:t.resumeLast}),_jsx(Text,{variant:"label",numberOfLines:1,children:d.title||t.untitled}),_jsx(Text,{variant:"caption",color:"secondary",children:formatDate(d.lastActivityDateTimeUtc)})]}):null,e.features.History?_jsx(ChatPastChats,{chat:e,labels:t,testID:`${n}-past-chats`}):null,_jsx(ChatOpenTickets,{chat:e,labels:t,onOpenTicket:s})]}):_jsx(View,{children:_jsx(TypingPill,{motion:r,mark:a?_jsx(Avatar,{size:"xs",name:e.profile?.assistant.name??t.panelTitle,source:{uri:a}}):null})})})}
@@ -1 +1 @@
1
- "use strict";import{createTurnApi,formatChatDateTime,handoffSettledIds,messagePlainText}from"@webority/chat-core";import{Avatar,Button,MessageBubble,MessageList,Text,useReducedMotion,useTheme}from"@webority/mobile-ui";import{createElement,memo,useEffect,useMemo,useRef}from"react";import{AccessibilityInfo,Platform,View}from"react-native";import{AgentByline}from"./AgentByline.js";import{ChatEntrance}from"./ChatEntrance.js";import{ChatMessageActions}from"./ChatMessageActions.js";import{defaultOpenTarget,focusForAccessibility,messageSignature}from"./chatShared.js";import{ChatLoader}from"./loaders/ChatLoader.js";import{ReplyRing}from"./loaders/ReplyRing.js";import{TypingPill}from"./loaders/TypingPill.js";import{defaultRenderers}from"./renderers/index.js";import{NoticePart}from"./renderers/NoticePart.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const MINE=new Set(["Visitor","Customer"]),visuallyHidden={position:"absolute",left:-1e4,width:1,height:1,overflow:"hidden"},joinedText=e=>e.filter(e=>"Text"===e.kind).map(e=>e.text).join("\n\n"),renderPart=(e,t,s,a,i,r)=>{const n=e[t.kind];if(n)return createElement(n,{key:r,part:t,message:s,turn:a,pickAttachments:i});const o={kind:"Notice",code:"NeedsNewerApp",text:a.labels.needsNewerApp};return createElement(NoticePart,{key:r,part:o,message:s,turn:a})},sameMessage=(e,t)=>e.signature===t.signature&&e.message.id===t.message.id&&e.message.rating===t.message.rating&&e.message.stored===t.message.stored&&e.groupPosition===t.groupPosition&&e.isLast===t.isLast&&e.handoffSettled===t.handoffSettled&&e.isLastVisitor===t.isLastVisitor&&e.thinking===t.thinking&&e.streaming===t.streaming&&e.pickAttachments===t.pickAttachments&&e.labels===t.labels&&e.all===t.all&&e.layoutParts===t.layoutParts&&e.chat.session===t.chat.session&&e.chat.features===t.chat.features&&e.chat.onNavigate===t.chat.onNavigate&&e.onNavigate===t.onNavigate&&e.onOpenAttachment===t.onOpenAttachment&&e.onOpenTarget===t.onOpenTarget&&e.openTicket===t.openTicket&&e.resolveLink===t.resolveLink&&e.focusComposer===t.focusComposer&&e.byline===t.byline&&e.avatar===t.avatar&&e.replyAvatars===t.replyAvatars&&e.avatarStart===t.avatarStart&&e.expressive===t.expressive&&e.reduced===t.reduced&&e.handoffHosts===t.handoffHosts;function ThreadMessageView({chat:e,message:t,labels:s,all:a,layoutParts:i,groupPosition:r,isLast:n,isLastVisitor:o,pickAttachments:l,onOpenAttachment:d,onOpenTarget:c,onNavigate:g,openTicket:m,handoffHosts:p,resolveLink:u,focusComposer:h,byline:f,avatar:y,replyAvatars:x,avatarStart:v,expressive:T,reduced:k,sourceRows:A,testID:b}){const j=useTheme(),w=Object.assign(createTurnApi(e.session,{messageId:t.id,labels:s,openAttachment:d,openTarget:c??defaultOpenTarget,onNavigate:g??e.onNavigate,openTicket:m,handoffHosts:p,openCitation:e=>{return t=String(e),void focusForAccessibility(A.current.get(t));var t}}),{resolveLink:u,focusComposer:h,registerSourceRow:(e,t)=>{t?A.current.set(e,t):A.current.delete(e)}});let _=0;const nextSlot=()=>(_+=1,_),M=_jsx(ChatMessageActions,{chat:e,message:t,labels:s,isLast:n,isLastVisitor:o,testID:`${b}-actions`});if(MINE.has(t.author.kind)){const e=t.parts.filter(e=>"File"===e.kind),s=_jsxs(View,{style:{gap:j.space.xs},children:[e.map(e=>renderPart(a,e,t,w,l,`${t.id}-file-${nextSlot()}`)),M]});return _jsx(MessageBubble,{side:"mine",text:joinedText(t.parts),labels:{you:""},groupPosition:r,footer:s,testID:b})}const N="Agent"===t.author.kind,P=t.author.displayName||s.agent,R=(i?i(t):t.parts).map(e=>Array.isArray(e)?_jsx(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:j.space.xs},children:e.map(e=>renderPart(a,e,t,w,l,`${t.id}-part-${nextSlot()}`))},`${t.id}-group-${nextSlot()}`):renderPart(a,e,t,w,l,`${t.id}-item-${nextSlot()}`)),S=N&&f?_jsx(AgentByline,{author:t.author,labels:s,showAvatar:x},`${t.id}-byline`):null,I=S?[S,...R]:R,L=messagePlainText(t.parts),V=_jsx(MessageBubble,{side:"theirs",author:N?void 0:t.author.displayName||(e.profile?.assistant.name??s.assistant),text:N?`${s.agentSays(P)} ${L}`:L,streaming:t.streaming,groupPosition:r,footer:M,testID:b,children:I});if(!x||!y||"Assistant"!==t.author.kind)return V;const C=t.author.displayName||(e.profile?.assistant.name??s.assistant);return _jsxs(View,{style:{flexDirection:"row",alignItems:"flex-end",gap:j.space.xs},children:[_jsx(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:v?void 0:{opacity:0},children:_jsx(ReplyRing,{active:T&&t.streaming&&v,reduced:k,children:_jsx(Avatar,{size:"xs",name:C,source:v?{uri:y}:void 0})})}),_jsx(View,{style:{flex:1,minWidth:0},children:V})]})}const ThreadMessage=memo(ThreadMessageView,sameMessage),TYPING_ORB_MARK=14,TYPING_ASSISTANT_MARK=8,TypingMark=({size:e})=>{const t=useTheme();return _jsx(View,{style:{width:e,height:e,borderRadius:t.radius.pill,backgroundColor:t.colors.primary}})},TYPING_DOT=6,TypingDots=()=>{const e=useTheme();return _jsx(View,{style:{flexDirection:"row",alignItems:"center",gap:e.space.xxs},children:[0,1,2].map(t=>_jsx(View,{style:{width:6,height:6,borderRadius:3,backgroundColor:e.colors["text-muted"]}},t))})},TurnGap=()=>{const e=useTheme();return _jsx(View,{style:{height:e.space.lg}})},followNew=()=>!0;export function ChatThread({chat:e,labels:t,renderers:s,layoutParts:a,loader:i="Steps",motion:r="On",avatar:n,replyAvatars:o=!0,expressive:l=!1,pickAttachments:d,onOpenAttachment:c,onOpenTarget:g,onNavigate:m,openTicket:p,handoffHosts:u,resolveLink:h,focusComposer:f,keyboardAware:y,keyboardOffset:x,empty:v,style:T,testID:k="chat-thread"}){const A=useTheme(),b=useReducedMotion(),j="Reduced"===r||b,w=useMemo(()=>({...defaultRenderers,...s}),[s]),_=e.messages[0],M=e.greeting??"",N=useMemo(()=>""!==M&&void 0!==_&&MINE.has(_.author.kind)?{..._,id:"greeting",author:{..._.author,kind:"Assistant",displayName:null,avatarUrl:null},parts:[{kind:"Text",text:M}],stored:!1,streaming:!1,restored:!1,rating:null}:null,[M,_]),P=useMemo(()=>{const t=e.messages.filter(e=>!(e.streaming&&0===e.parts.length)).reverse();return N?[...t,N]:t},[e.messages,N]),R=e.messages[e.messages.length-1]?.id,S=useRef(new Map),I=useRef(null);useEffect(()=>{if(null!==I.current)for(const s of e.messages){if(MINE.has(s.author.kind)||s.streaming||s.restored||I.current.has(s.id))continue;if("Agent"===s.author.kind&&!s.stored)continue;I.current.add(s.id);const e=messagePlainText(s.parts);""!==e&&AccessibilityInfo.announceForAccessibility("Agent"===s.author.kind?`${t.agentSays(s.author.displayName||t.agent)} ${e}`:e)}else I.current=new Set(e.messages.map(e=>e.id))},[e.messages,t]);const L=useMemo(()=>{for(let t=e.messages.length-1;t>=0;t-=1){const s=e.messages[t];if(s?.stored&&"Visitor"===s.author.kind)return s.id}},[e.messages]),V=useMemo(()=>{const t=new Set;return e.messages.forEach((s,a)=>{if("Agent"!==s.author.kind)return;const i=e.messages[a-1];"Agent"===i?.author.kind&&(i.author.displayName||"")===(s.author.displayName||"")||t.add(s.id)}),t},[e.messages]),C=useMemo(()=>{const t=new Set,s=e.messages.filter(e=>!(e.streaming&&0===e.parts.length));return N&&t.add(N.id),s.forEach((e,a)=>{"Assistant"===e.author.kind&&"Assistant"!==s[a-1]?.author.kind&&t.add(e.id)}),t},[e.messages,N]),$=useMemo(()=>handoffSettledIds(e.messages),[e.messages]),D=e.turnError,O="daily_limit"===D?.code,E=null!==D&&/feature_off$/.test(D.code),B=O&&D?.resetsDateTimeUtc?` ${t.dailyLimitRefresh(formatChatDateTime(D.resetsDateTimeUtc))}`:"",H=e.streaming||null===D&&!e.stopped?null:_jsxs(View,{style:{gap:A.space.xs},testID:`${k}-error`,children:[_jsx(Text,null!==D?{variant:"bodySmall",color:"danger",accessibilityRole:O?void 0:"alert",accessibilityLiveRegion:O?"polite":void 0,children:`${D.message}${B}`}:{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:t.stopped}),!e.features.Retry||O||E?null:_jsx(View,{style:{flexDirection:"row"},children:_jsx(Button,{label:t.retry,variant:"link",size:"sm",onPress:()=>{e.retry()},testID:`${k}-retry`})})]}),z=e.thinking&&null!==e.profile?_jsx(ChatLoader,{style:i,steps:e.steps,phrases:e.profile.experience.pacing.thinkingPhrases,intervalMs:e.profile.experience.pacing.phraseIntervalMs,announce:t.preparingAnswer(e.profile.assistant.name),motion:r}):null,F=!0===e.pending?.typing?_jsx(TypingPill,{motion:r,mark:_jsx(ReplyRing,{active:l,reduced:j,children:n?_jsx(Avatar,{size:"xs",name:e.profile?.assistant.name??t.panelTitle,source:{uri:n}}):_jsx(TypingMark,{size:"Orb"===i?14:8})})}):null,G=null!==e.agentTyping&&"WithAgent"===e.conversationState?_jsxs(View,{style:{gap:A.space.xs,alignSelf:"flex-start"},children:[_jsx(TypingPill,{motion:r,mark:_jsx(TypingDots,{})}),_jsx(Text,{variant:"caption",color:"secondary",accessibilityLiveRegion:"polite",children:t.agentTyping(e.agentTyping.displayName||t.agent)})]}):null,U=F||z||H||G?_jsxs(View,{style:{gap:A.space.sm},children:[F,z,G,H]}):void 0,K=_jsx(MessageList,{messages:P,keyExtractor:e=>e.id,renderMessage:({item:s,groupPosition:i})=>_jsxs(View,{role:"listitem",children:[MINE.has(s.author.kind)?_jsx(Text,{style:visuallyHidden,children:`${t.you}: `}):null,_jsx(ChatEntrance,{animate:!s.restored,children:_jsx(ThreadMessage,{chat:e,message:s,signature:messageSignature(s),labels:t,all:w,layoutParts:a,groupPosition:i,isLast:s.id===R,isLastVisitor:s.id===L,handoffSettled:$.has(s.id),thinking:e.thinking,streaming:e.streaming,pickAttachments:d,onOpenAttachment:c,onOpenTarget:g,onNavigate:m,openTicket:p,handoffHosts:u,resolveLink:h,focusComposer:f,byline:V.has(s.id),avatar:n,replyAvatars:o,avatarStart:C.has(s.id),expressive:l,reduced:j,sourceRows:S,testID:`${k}-${s.id}`})})]}),getAuthorKey:e=>e.author.kind,getDate:e=>e.createdDateTimeUtc,followNew:followNew,typing:U,empty:v,ItemSeparatorComponent:TurnGap,keyboardAware:y,keyboardOffset:x,accessibilityLabel:t.thread,accessibilityRole:"list",style:T,testID:k});return"web"!==Platform.OS?K:_jsx(View,{role:"log","aria-live":"polite","aria-label":t.thread,style:{flex:1},children:K})}
1
+ "use strict";import{createTurnApi,formatChatDateTime,handoffSettledIds,messagePlainText}from"@webority/chat-core";import{Avatar,Button,MessageBubble,MessageList,Text,useReducedMotion,useTheme}from"@webority/mobile-ui";import{createElement,memo,useEffect,useMemo,useRef}from"react";import{AccessibilityInfo,Platform,View}from"react-native";import{AgentByline}from"./AgentByline.js";import{ChatEntrance}from"./ChatEntrance.js";import{ChatMessageActions}from"./ChatMessageActions.js";import{defaultOpenTarget,focusForAccessibility,messageSignature}from"./chatShared.js";import{ChatLoader}from"./loaders/ChatLoader.js";import{ReplyRing}from"./loaders/ReplyRing.js";import{TypingPill}from"./loaders/TypingPill.js";import{defaultRenderers}from"./renderers/index.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const MINE=new Set(["Visitor","Customer"]),visuallyHidden={position:"absolute",left:-1e4,width:1,height:1,overflow:"hidden"},joinedText=e=>e.filter(e=>"Text"===e.kind).map(e=>e.text).join("\n\n");function isKind(e,t){return e.kind===t}const kindWrappers=new WeakMap;function forKind(e,t){const s=kindWrappers.get(t)??new Map,a=s.get(e);if(a)return a;function KindEntry(s){if(!isKind(s.part,e))throw new Error(`renderer for ${e} received a ${s.part.kind} part`);return createElement(t,{part:s.part,message:s.message,turn:s.turn,pickAttachments:s.pickAttachments})}return s.set(e,KindEntry),kindWrappers.set(t,s),KindEntry}const defaults=defaultRenderers;function entryFor(e,t){return forKind(e,t??defaults[e])}function resolveRenderers(e){return{Text:entryFor("Text",e?.Text),Sources:entryFor("Sources",e?.Sources),QuickReplies:entryFor("QuickReplies",e?.QuickReplies),InputRequest:entryFor("InputRequest",e?.InputRequest),Action:entryFor("Action",e?.Action),Notice:entryFor("Notice",e?.Notice),Table:entryFor("Table",e?.Table),Chart:entryFor("Chart",e?.Chart),Figures:entryFor("Figures",e?.Figures),RecordCard:entryFor("RecordCard",e?.RecordCard),Image:entryFor("Image",e?.Image),File:entryFor("File",e?.File),Ticket:entryFor("Ticket",e?.Ticket),Handoff:entryFor("Handoff",e?.Handoff),VoiceClip:entryFor("VoiceClip",e?.VoiceClip)}}const renderPart=(e,t,s,a,r,i)=>{const n=e[t.kind];return createElement(n,{key:i,part:t,message:s,turn:a,pickAttachments:r})},sameMessage=(e,t)=>e.signature===t.signature&&e.message.id===t.message.id&&e.message.rating===t.message.rating&&e.message.stored===t.message.stored&&e.groupPosition===t.groupPosition&&e.isLast===t.isLast&&e.handoffSettled===t.handoffSettled&&e.isLastVisitor===t.isLastVisitor&&e.thinking===t.thinking&&e.streaming===t.streaming&&e.pickAttachments===t.pickAttachments&&e.labels===t.labels&&e.all===t.all&&e.layoutParts===t.layoutParts&&e.chat.session===t.chat.session&&e.chat.features===t.chat.features&&e.chat.onNavigate===t.chat.onNavigate&&e.onNavigate===t.onNavigate&&e.onOpenAttachment===t.onOpenAttachment&&e.onOpenTarget===t.onOpenTarget&&e.openTicket===t.openTicket&&e.resolveLink===t.resolveLink&&e.focusComposer===t.focusComposer&&e.byline===t.byline&&e.avatar===t.avatar&&e.replyAvatars===t.replyAvatars&&e.avatarStart===t.avatarStart&&e.expressive===t.expressive&&e.reduced===t.reduced&&e.handoffHosts===t.handoffHosts;function ThreadMessageView({chat:e,message:t,labels:s,all:a,layoutParts:r,groupPosition:i,isLast:n,isLastVisitor:o,pickAttachments:l,onOpenAttachment:d,onOpenTarget:c,onNavigate:u,openTicket:p,handoffHosts:g,resolveLink:m,focusComposer:h,byline:f,avatar:y,replyAvatars:x,avatarStart:T,expressive:k,reduced:v,sourceRows:A,testID:b}){const j=useTheme(),w=Object.assign(createTurnApi(e.session,{messageId:t.id,labels:s,openAttachment:d,openTarget:c??defaultOpenTarget,onNavigate:u??e.onNavigate,openTicket:p,handoffHosts:g,openCitation:e=>{return t=String(e),void focusForAccessibility(A.current.get(t));var t}}),{resolveLink:m,focusComposer:h,registerSourceRow:(e,t)=>{t?A.current.set(e,t):A.current.delete(e)}});let _=0;const nextSlot=()=>(_+=1,_),R=_jsx(ChatMessageActions,{chat:e,message:t,labels:s,isLast:n,isLastVisitor:o,testID:`${b}-actions`});if(MINE.has(t.author.kind)){const e=t.parts.filter(e=>"File"===e.kind),s=_jsxs(View,{style:{gap:j.space.xs},children:[e.map(e=>renderPart(a,e,t,w,l,`${t.id}-file-${nextSlot()}`)),R]});return _jsx(MessageBubble,{side:"mine",text:joinedText(t.parts),labels:{you:""},groupPosition:i,footer:s,testID:b})}const M="Agent"===t.author.kind,I=t.author.displayName||s.agent,S=(r?r(t):t.parts).map(e=>Array.isArray(e)?_jsx(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:j.space.xs},children:e.map(e=>renderPart(a,e,t,w,l,`${t.id}-part-${nextSlot()}`))},`${t.id}-group-${nextSlot()}`):renderPart(a,e,t,w,l,`${t.id}-item-${nextSlot()}`)),C=M&&f?_jsx(AgentByline,{author:t.author,labels:s,showAvatar:x},`${t.id}-byline`):null,N=C?[C,...S]:S,P=messagePlainText(t.parts),V=_jsx(MessageBubble,{side:"theirs",...M?{}:{author:t.author.displayName||(e.profile?.assistant.name??s.assistant)},text:M?`${s.agentSays(I)} ${P}`:P,streaming:t.streaming,groupPosition:i,footer:R,testID:b,children:N});if(!x||!y||"Assistant"!==t.author.kind)return V;const F=t.author.displayName||(e.profile?.assistant.name??s.assistant);return _jsxs(View,{style:{flexDirection:"row",alignItems:"flex-end",gap:j.space.xs},children:[_jsx(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:T?void 0:{opacity:0},children:_jsx(ReplyRing,{active:k&&t.streaming&&T,reduced:v,children:_jsx(Avatar,{size:"xs",name:F,...T?{source:{uri:y}}:{}})})}),_jsx(View,{style:{flex:1,minWidth:0},children:V})]})}const ThreadMessage=memo(ThreadMessageView,sameMessage),TYPING_ORB_MARK=14,TYPING_ASSISTANT_MARK=8,TypingMark=({size:e})=>{const t=useTheme();return _jsx(View,{style:{width:e,height:e,borderRadius:t.radius.pill,backgroundColor:t.colors.primary}})},TYPING_DOT=6,TypingDots=()=>{const e=useTheme();return _jsx(View,{style:{flexDirection:"row",alignItems:"center",gap:e.space.xxs},children:[0,1,2].map(t=>_jsx(View,{style:{width:6,height:6,borderRadius:3,backgroundColor:e.colors["text-muted"]}},t))})},TurnGap=()=>{const e=useTheme();return _jsx(View,{style:{height:e.space.lg}})},followNew=()=>!0;export function ChatThread({chat:e,labels:t,renderers:s,layoutParts:a,loader:r="Steps",motion:i="On",avatar:n,replyAvatars:o=!0,expressive:l=!1,pickAttachments:d,onOpenAttachment:c,onOpenTarget:u,onNavigate:p,openTicket:g,handoffHosts:m,resolveLink:h,focusComposer:f,keyboardAware:y,keyboardOffset:x,empty:T,style:k,testID:v="chat-thread"}){const A=useTheme(),b=useReducedMotion(),j="Reduced"===i||b,w=useMemo(()=>resolveRenderers(s),[s]),_=e.messages[0],R=e.greeting??"",M=useMemo(()=>""!==R&&void 0!==_&&MINE.has(_.author.kind)?{..._,id:"greeting",author:{..._.author,kind:"Assistant",displayName:null,avatarUrl:null},parts:[{kind:"Text",text:R}],stored:!1,streaming:!1,restored:!1,rating:null}:null,[R,_]),I=useMemo(()=>{const t=e.messages.filter(e=>!(e.streaming&&0===e.parts.length)).reverse();return M?[...t,M]:t},[e.messages,M]),S=e.messages[e.messages.length-1]?.id,C=useRef(new Map),N=useRef(null);useEffect(()=>{if(null!==N.current)for(const s of e.messages){if(MINE.has(s.author.kind)||s.streaming||s.restored||N.current.has(s.id))continue;if("Agent"===s.author.kind&&!s.stored)continue;N.current.add(s.id);const e=messagePlainText(s.parts);""!==e&&AccessibilityInfo.announceForAccessibility("Agent"===s.author.kind?`${t.agentSays(s.author.displayName||t.agent)} ${e}`:e)}else N.current=new Set(e.messages.map(e=>e.id))},[e.messages,t]);const P=useMemo(()=>{for(let t=e.messages.length-1;t>=0;t-=1){const s=e.messages[t];if(s?.stored&&"Visitor"===s.author.kind)return s.id}},[e.messages]),V=useMemo(()=>{const t=new Set;return e.messages.forEach((s,a)=>{if("Agent"!==s.author.kind)return;const r=e.messages[a-1];"Agent"===r?.author.kind&&(r.author.displayName||"")===(s.author.displayName||"")||t.add(s.id)}),t},[e.messages]),F=useMemo(()=>{const t=new Set,s=e.messages.filter(e=>!(e.streaming&&0===e.parts.length));return M&&t.add(M.id),s.forEach((e,a)=>{"Assistant"===e.author.kind&&"Assistant"!==s[a-1]?.author.kind&&t.add(e.id)}),t},[e.messages,M]),L=useMemo(()=>handoffSettledIds(e.messages),[e.messages]),$=e.turnError,D="daily_limit"===$?.code,E=null!==$&&/feature_off$/.test($.code),O=D&&$?.resetsDateTimeUtc?` ${t.dailyLimitRefresh(formatChatDateTime($.resetsDateTimeUtc))}`:"",H=e.streaming||null===$&&!e.stopped?null:_jsxs(View,{style:{gap:A.space.xs},testID:`${v}-error`,children:[_jsx(Text,null!==$?{variant:"bodySmall",color:"danger",accessibilityRole:D?void 0:"alert",accessibilityLiveRegion:D?"polite":void 0,children:`${$.message}${O}`}:{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:t.stopped}),!e.features.Retry||D||E?null:_jsx(View,{style:{flexDirection:"row"},children:_jsx(Button,{label:t.retry,variant:"link",size:"sm",onPress:()=>{e.retry()},testID:`${v}-retry`})})]}),K=e.thinking&&null!==e.profile?_jsx(ChatLoader,{style:r,steps:e.steps,phrases:e.profile.experience.pacing.thinkingPhrases,intervalMs:e.profile.experience.pacing.phraseIntervalMs,announce:t.preparingAnswer(e.profile.assistant.name),motion:i}):null,B=!0===e.pending?.typing?_jsx(TypingPill,{motion:i,mark:_jsx(ReplyRing,{active:l,reduced:j,children:n?_jsx(Avatar,{size:"xs",name:e.profile?.assistant.name??t.panelTitle,source:{uri:n}}):_jsx(TypingMark,{size:"Orb"===r?14:8})})}):null,W=null!==e.agentTyping&&"WithAgent"===e.conversationState?_jsxs(View,{style:{gap:A.space.xs,alignSelf:"flex-start"},children:[_jsx(TypingPill,{motion:i,mark:_jsx(TypingDots,{})}),_jsx(Text,{variant:"caption",color:"secondary",accessibilityLiveRegion:"polite",children:t.agentTyping(e.agentTyping.displayName||t.agent)})]}):null,z=B||K||H||W?_jsxs(View,{style:{gap:A.space.sm},children:[B,K,W,H]}):void 0,G=_jsx(MessageList,{messages:I,keyExtractor:e=>e.id,renderMessage:({item:s,groupPosition:r})=>_jsxs(View,{role:"listitem",children:[MINE.has(s.author.kind)?_jsx(Text,{style:visuallyHidden,children:`${t.you}: `}):null,_jsx(ChatEntrance,{animate:!s.restored,children:_jsx(ThreadMessage,{chat:e,message:s,signature:messageSignature(s),labels:t,all:w,layoutParts:a,groupPosition:r,isLast:s.id===S,isLastVisitor:s.id===P,handoffSettled:L.has(s.id),thinking:e.thinking,streaming:e.streaming,pickAttachments:d,onOpenAttachment:c,onOpenTarget:u,onNavigate:p,openTicket:g,handoffHosts:m,resolveLink:h,focusComposer:f,byline:V.has(s.id),avatar:n,replyAvatars:o,avatarStart:F.has(s.id),expressive:l,reduced:j,sourceRows:C,testID:`${v}-${s.id}`})})]}),getAuthorKey:e=>e.author.kind,getDate:e=>e.createdDateTimeUtc,followNew:followNew,typing:z,empty:T,ItemSeparatorComponent:TurnGap,...void 0===y?{}:{keyboardAware:y},...void 0===x?{}:{keyboardOffset:x},accessibilityLabel:t.thread,accessibilityRole:"list",style:k,testID:v});return"web"!==Platform.OS?G:_jsx(View,{role:"log","aria-live":"polite","aria-label":t.thread,style:{flex:1},children:G})}
@@ -1 +1 @@
1
- "use strict";import{Logger}from"@webority/mobile-core";import{AccessibilityInfo,findNodeHandle,Linking,Platform}from"react-native";export function focusForAccessibility(t){if(null==t)return;if("web"===Platform.OS)return void t.focus?.();const e=findNodeHandle(t);null!=e&&AccessibilityInfo.setAccessibilityFocus(e)}export function messageSignature(t){let e=0;for(const o of t.parts)"Text"===o.kind&&(e+=o.text.length);return`${t.id}|${t.parts.length}|${e}`}const ABSOLUTE_WEB_URL=/^https?:\/\//i;export function openExternalUrl(t){Linking.openURL(t).catch(t=>{throw Logger.error("[chat] link did not open",t),t})}export function defaultOpenTarget(t){ABSOLUTE_WEB_URL.test(t)&&openExternalUrl(t)}export const WEB_STRONG="web"===Platform.OS?{role:"strong"}:{};
1
+ "use strict";import{Logger}from"@webority/mobile-core";import{AccessibilityInfo,findNodeHandle,Linking,Platform}from"react-native";export function focusForAccessibility(t){if(null==t)return;if("web"===Platform.OS)return void("object"==typeof t&&"focus"in t&&"function"==typeof t.focus&&t.focus());const o=findNodeHandle(t);null!=o&&AccessibilityInfo.setAccessibilityFocus(o)}export function messageSignature(t){let o=0;for(const e of t.parts)"Text"===e.kind&&(o+=e.text.length);return`${t.id}|${t.parts.length}|${o}`}const ABSOLUTE_WEB_URL=/^https?:\/\//i;export function openExternalUrl(t){Linking.openURL(t).catch(t=>{throw Logger.error("[chat] link did not open",t),t})}export function defaultOpenTarget(t){ABSOLUTE_WEB_URL.test(t)&&openExternalUrl(t)}export const WEB_STRONG="web"===Platform.OS?{role:"strong"}:{};
@@ -0,0 +1 @@
1
+ "use strict";const isRecord=o=>"object"==typeof o&&null!==o,isExpoAudio=o=>isRecord(o)&&isRecord(o.AudioModule)&&"function"==typeof o.AudioModule.AudioRecorder&&isRecord(o.RecordingPresets)&&isRecord(o.RecordingPresets.HIGH_QUALITY)&&"function"==typeof o.setAudioModeAsync&&"function"==typeof o.createAudioPlayer,isExpoFileSystem=o=>isRecord(o)&&"function"==typeof o.File&&isRecord(o.Paths)&&"cache"in o.Paths;export const loadExpoAudio=()=>{const o=require("expo-audio");if(!isExpoAudio(o))throw new Error("expo-audio did not load.");return o};export const loadExpoFileSystem=()=>{const o=require("expo-file-system");if(!isExpoFileSystem(o))throw new Error("expo-file-system did not load.");return o};
@@ -0,0 +1 @@
1
+ "use strict";import{ICON_NAMES}from"@webority/mobile-ui/icons";export function iconNameOf(i){return i?ICON_NAMES.find(n=>n===i)??null:null}
@@ -1 +1 @@
1
- "use strict";import{LOADER_STYLES,loaderView}from"@webority/chat-core";import{Text,useReducedMotion}from"@webority/mobile-ui";import{useEffect,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{OrbLoader}from"./OrbLoader.js";import{PhrasesLoader}from"./PhrasesLoader.js";import{SkeletonLoader}from"./SkeletonLoader.js";import{StepsLoader}from"./StepsLoader.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const ANNOUNCE_DELAY_MS=500;export function ChatLoader({style:e="Steps",steps:t=[],phrases:r,intervalMs:s,motion:o="On",announce:i,testID:a="chat-loader"}){if(!LOADER_STYLES.includes(e))throw new Error(`ChatLoader style must be one of ${LOADER_STYLES.join(", ")}; got "${e}".`);const n=useReducedMotion(),c="Reduced"===o||n,[u,d]=useState({style:e,count:0});useEffect(()=>{d({style:e,count:0})},[e]),useEffect(()=>{if(c)return;const t=setInterval(()=>{d(t=>({style:e,count:(t.style===e?t.count:0)+1}))},s);return()=>clearInterval(t)},[e,s,c]);const l=useRef(i),[f,m]=useState("");useEffect(()=>{const e=setTimeout(()=>m(l.current),500);return()=>clearTimeout(e)},[]);const L=c||u.style!==e?0:u.count,S=loaderView(e,t,r,L);return _jsxs(View,{role:"status",accessibilityLabel:S.label,accessibilityLiveRegion:"polite",testID:a,children:[loaderBody(e,S,c),_jsx(Text,{accessibilityLiveRegion:"polite",style:styles.announce,children:f})]})}const loaderBody=(e,t,r)=>{switch(e){case"Steps":return _jsx(StepsLoader,{view:t,reduced:r});case"Phrases":return _jsx(PhrasesLoader,{view:t,reduced:r});case"Orb":return _jsx(OrbLoader,{view:t,reduced:r});case"Skeleton":return _jsx(SkeletonLoader,{view:t,reduced:r})}},styles=StyleSheet.create({announce:{position:"absolute",width:1,height:1,opacity:0,overflow:"hidden"}});
1
+ "use strict";import{loaderView}from"@webority/chat-core";import{Text,useReducedMotion}from"@webority/mobile-ui";import{useEffect,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{OrbLoader}from"./OrbLoader.js";import{PhrasesLoader}from"./PhrasesLoader.js";import{SkeletonLoader}from"./SkeletonLoader.js";import{StepsLoader}from"./StepsLoader.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const ANNOUNCE_DELAY_MS=500;export function ChatLoader({style:e="Steps",steps:t=[],phrases:s,intervalMs:r,motion:o="On",announce:a,testID:i="chat-loader"}){const c=useReducedMotion(),n="Reduced"===o||c,[u,d]=useState({style:e,count:0});useEffect(()=>{d({style:e,count:0})},[e]),useEffect(()=>{if(n)return;const t=setInterval(()=>{d(t=>({style:e,count:(t.style===e?t.count:0)+1}))},r);return()=>clearInterval(t)},[e,r,n]);const l=useRef(a),[m,f]=useState("");useEffect(()=>{const e=setTimeout(()=>f(l.current),500);return()=>clearTimeout(e)},[]);const p=n||u.style!==e?0:u.count,y=loaderView(e,t,s,p);return _jsxs(View,{role:"status",accessibilityLabel:y.label,accessibilityLiveRegion:"polite",testID:i,children:[loaderBody(e,y,n),_jsx(Text,{accessibilityLiveRegion:"polite",style:styles.announce,children:m})]})}const loaderBody=(e,t,s)=>{switch(e){case"Steps":return _jsx(StepsLoader,{view:t,reduced:s});case"Phrases":return _jsx(PhrasesLoader,{view:t,reduced:s});case"Orb":return _jsx(OrbLoader,{view:t,reduced:s});case"Skeleton":return _jsx(SkeletonLoader,{view:t,reduced:s})}},styles=StyleSheet.create({announce:{position:"absolute",width:1,height:1,opacity:0,overflow:"hidden"}});
@@ -1 +1 @@
1
- "use strict";import{formatChatDate}from"@webority/chat-core";import{parseInline}from"@webority/markdown-core";import{Button,Card,OptionSheet,Text,useTheme}from"@webority/mobile-ui";import{useState}from"react";import{Text as RNText,View}from"react-native";import{openExternalUrl}from"../chatShared.js";import{NoticePart}from"./NoticePart.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LEAD_CAPTURE="ChatLeadCapture",SAFE_LINK=/^https?:\/\//i,inlineNodes=(e,t)=>e.map(e=>{if("text"===e.type||"code"===e.type||"citation"===e.type)return e.text;if("link"===e.type){const n=inlineNodes(e.children,t);return SAFE_LINK.test(e.href)?_jsx(RNText,{accessibilityRole:"link",style:{color:t.colors.link,textDecorationLine:"underline"},onPress:()=>openExternalUrl(e.href),children:n},e.key):_jsx(RNText,{children:n},e.key)}if("image"===e.type)return null;const n="strong"===e.type?{fontWeight:t.weight.bold}:"em"===e.type?{fontStyle:"italic"}:{textDecorationLine:"line-through"};return _jsx(RNText,{style:n,children:inlineNodes(e.children,t)},e.key)}),splitLine=e=>{const t=e.indexOf(": ");return t<0?{term:e,detail:null}:{term:e.slice(0,t),detail:e.slice(t+2)}},statusLine=(e,t)=>{switch(e.state){case"Confirmed":return t.actionConfirmed;case"Done":return e.decidedDateTimeUtc?`${t.actionDone} ${formatChatDate(e.decidedDateTimeUtc)}`:t.actionDone;case"Rejected":return t.actionRejected;case"Expired":return t.actionExpired;case"Failed":return t.actionFailed;case"Repeat":return e.decidedDateTimeUtc?t.actionRepeat(formatChatDate(e.decidedDateTimeUtc)):t.actionDone;case"Pending":return""}};function ActionBody({part:e,turn:t}){const n=useTheme(),{labels:i,features:a}=t,[r,o]=useState(null),[s,l]=useState(""),[c,d]=useState(!1),run=async(e,t)=>{o(e),l("");try{await t()}catch(e){const t=e?.message;l("string"==typeof t&&""!==t?t:i.actionFailed),o(null)}},u=(e.editFields??[]).map(e=>({label:e.label,value:e.id})),m=a.LeadRecap&&e.actionKind===LEAD_CAPTURE,p=m&&u.length>0,x=m&&e.confirmLabel||i.actionConfirm,h=m&&e.rejectLabel||i.actionDismiss,f=null!==r;return _jsxs(Card,{variant:"outline",padding:"sm",children:[_jsxs(View,{style:{gap:n.space.sm},children:[_jsx(Text,{variant:"label",children:e.title}),e.lines.map(e=>{if(!m)return _jsx(Text,{variant:"bodySmall",children:e},e);const{term:t,detail:i}=splitLine(e);return _jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:n.space.xs},children:[_jsx(Text,{variant:"label",children:t}),null!==i?_jsx(Text,{variant:"bodySmall",children:i}):null]},e)}),m&&e.consentText?_jsx(Text,{variant:"caption",color:"secondary",children:inlineNodes(parseInline(e.consentText),n)}):null,"Pending"===e.state?_jsxs(_Fragment,{children:[""!==s?_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:s}):null,_jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:n.space.sm},children:[_jsx(Button,{label:"confirm"===r?i.actionWorking:x,loading:"confirm"===r,disabled:f,onPress:()=>{run("confirm",()=>t.confirmAction(e.actionId))}}),_jsx(Button,{label:h,variant:"ghost",disabled:f,onPress:()=>{run("reject",()=>t.rejectAction(e.actionId))}})]})]}):_jsx(Text,{variant:"bodySmall",color:"Done"===e.state||"Confirmed"===e.state||"Repeat"===e.state?"success":"secondary",children:statusLine(e,i)}),p?_jsx(Button,{label:i.editSomething,variant:"ghost",disabled:f||"Pending"!==e.state,onPress:()=>d(!0)}):null,e.note?_jsx(Text,{variant:"caption",color:"secondary",children:e.note}):null]}),p?_jsx(OptionSheet,{open:c,onClose:()=>d(!1),title:i.editSomething,options:u,onChange:(e,n)=>{d(!1),t.chooseQuickReply({id:`lead.edit:${String(n.value)}`,label:n.label,action:"Send",target:null,navigateAfterMs:null,icon:null,variant:null})}}):null]})}export function ActionPart(e){const{part:t,message:n,turn:i}=e;if("Action"!==t.kind){const e={kind:"Notice",code:"NeedsNewerApp",text:i.labels.needsNewerApp};return _jsx(NoticePart,{part:e,message:n,turn:i})}return _jsx(ActionBody,{part:t,turn:i},t.actionId)}
1
+ "use strict";import{ChatApiError,formatChatDate}from"@webority/chat-core";import{parseInline}from"@webority/markdown-core";import{Logger}from"@webority/mobile-core";import{Button,Card,OptionSheet,Text,useTheme}from"@webority/mobile-ui";import{useState}from"react";import{Text as RNText,View}from"react-native";import{openExternalUrl}from"../chatShared.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const LEAD_CAPTURE="ChatLeadCapture",SAFE_LINK=/^https?:\/\//i,inlineNodes=(e,t)=>e.map(e=>{if("text"===e.type||"code"===e.type||"citation"===e.type)return e.text;if("link"===e.type){const n=inlineNodes(e.children,t);return SAFE_LINK.test(e.href)?_jsx(RNText,{accessibilityRole:"link",style:{color:t.colors.link,textDecorationLine:"underline"},onPress:()=>openExternalUrl(e.href),children:n},e.key):_jsx(RNText,{children:n},e.key)}if("image"===e.type)return null;const n="strong"===e.type?{fontWeight:t.weight.bold}:"em"===e.type?{fontStyle:"italic"}:{textDecorationLine:"line-through"};return _jsx(RNText,{style:n,children:inlineNodes(e.children,t)},e.key)}),splitLine=e=>{const t=e.indexOf(": ");return t<0?{term:e,detail:null}:{term:e.slice(0,t),detail:e.slice(t+2)}},statusLine=(e,t)=>{switch(e.state){case"Confirmed":return t.actionConfirmed;case"Done":return e.decidedDateTimeUtc?`${t.actionDone} ${formatChatDate(e.decidedDateTimeUtc)}`:t.actionDone;case"Rejected":return t.actionRejected;case"Expired":return t.actionExpired;case"Failed":return t.actionFailed;case"Repeat":return e.decidedDateTimeUtc?t.actionRepeat(formatChatDate(e.decidedDateTimeUtc)):t.actionDone;case"Pending":return""}};function ActionBody({part:e,turn:t}){const n=useTheme(),{labels:i,features:a}=t,[r,o]=useState(null),[l,s]=useState(""),[c,d]=useState(!1),run=async(e,t)=>{o(e),s("");try{await t()}catch(t){Logger.error(`[chat] action ${e} failed`,t),s(t instanceof ChatApiError&&""!==t.message?t.message:i.actionFailed),o(null)}},m=(e.editFields??[]).map(e=>({label:e.label,value:e.id})),u=a.LeadRecap&&e.actionKind===LEAD_CAPTURE,p=u&&m.length>0,x=u&&e.confirmLabel||i.actionConfirm,h=u&&e.rejectLabel||i.actionDismiss,f=null!==r;return _jsxs(Card,{variant:"outline",padding:"sm",children:[_jsxs(View,{style:{gap:n.space.sm},children:[_jsx(Text,{variant:"label",children:e.title}),e.lines.map(e=>{if(!u)return _jsx(Text,{variant:"bodySmall",children:e},e);const{term:t,detail:i}=splitLine(e);return _jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:n.space.xs},children:[_jsx(Text,{variant:"label",children:t}),null!==i?_jsx(Text,{variant:"bodySmall",children:i}):null]},e)}),u&&e.consentText?_jsx(Text,{variant:"caption",color:"secondary",children:inlineNodes(parseInline(e.consentText),n)}):null,"Pending"===e.state?_jsxs(_Fragment,{children:[""!==l?_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:l}):null,_jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:n.space.sm},children:[_jsx(Button,{label:"confirm"===r?i.actionWorking:x,loading:"confirm"===r,disabled:f,onPress:()=>{run("confirm",()=>t.confirmAction(e.actionId))}}),_jsx(Button,{label:h,variant:"ghost",disabled:f,onPress:()=>{run("reject",()=>t.rejectAction(e.actionId))}})]})]}):_jsx(Text,{variant:"bodySmall",color:"Done"===e.state||"Confirmed"===e.state||"Repeat"===e.state?"success":"secondary",children:statusLine(e,i)}),p?_jsx(Button,{label:i.editSomething,variant:"ghost",disabled:f||"Pending"!==e.state,onPress:()=>d(!0)}):null,e.note?_jsx(Text,{variant:"caption",color:"secondary",children:e.note}):null]}),p?_jsx(OptionSheet,{open:c,onClose:()=>d(!1),title:i.editSomething,options:m,onChange:(e,n)=>{d(!1),t.chooseQuickReply({id:`lead.edit:${String(n.value)}`,label:n.label,action:"Send",target:null,navigateAfterMs:null,icon:null,variant:null})}}):null]})}export function ActionPart({part:e,turn:t}){return _jsx(ActionBody,{part:e,turn:t},e.actionId)}
@@ -1 +1 @@
1
- "use strict";import{formatFigure,toFigureText}from"@webority/chat-core";import{formatCompactNumber,formatNumber,formatPercent}from"@webority/mobile-core";import{BarChart,Button,ProgressBar,Sparkline,Text,useTheme}from"@webority/mobile-ui";import{useState}from"react";import{View}from"react-native";import{FigureText,runsToText}from"./FigureText.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const TONES=["primary","info","success","warning","danger","neutral"],toneAt=e=>TONES[e%TONES.length]??"primary",MAX_SERIES=8,withPositions=e=>e.reduce((e,t)=>(e.push({key:e.length,item:t}),e),[]),writeValue=(e,t)=>{const r=0!==e&&Math.abs(e)<.001?runsToText(formatFigure(e)):formatNumber(e,{maximumFractionDigits:2});return t?`${r} ${t}`:r};export function ChartPart({part:e,turn:t}){const r=useTheme(),[a,i]=useState(!1),l="Donut"===e.chartType?e.series.slice(0,1):e.series.slice(0,8);if(l.every(e=>0===e.points.length))return _jsxs(View,{style:{gap:r.space.sm},children:[e.title?_jsx(FigureText,{text:e.title,variant:"label",color:"primary",strong:!0}):null,_jsx(Text,{variant:"bodySmall",color:"secondary",children:t.labels.chartEmpty})]});const{unit:s}=e,o=e.title?toFigureText(e.title):t.labels.chart,n=l.length>1;return _jsxs(View,{accessibilityLabel:o,style:{gap:r.space.sm},children:[e.title?_jsx(FigureText,{text:e.title,variant:"label",color:"primary",strong:!0}):null,_jsx(Button,{label:a?t.labels.chartShowChart:t.labels.chartShowTable,variant:"link",size:"sm",onPress:()=>i(e=>!e)}),withPositions(l).map(({key:i,item:l})=>{const c=toneAt(i),m=toFigureText(l.name)||o,u=l.points;if(0===u.length)return _jsxs(View,{style:{gap:r.space.xs},children:[n?_jsx(Text,{variant:"caption",color:"secondary",children:toFigureText(l.name)}):null,_jsx(Text,{variant:"bodySmall",color:"secondary",children:t.labels.chartEmpty})]},i);const x=u.map(e=>e.value),h=x.reduce((e,t)=>Math.min(e,t)),p=x.reduce((e,t)=>Math.max(e,t)),b=u[0],y=u[u.length-1];let g;if(a)g=_jsx(View,{accessibilityRole:"summary",style:{gap:r.space.xs},children:withPositions(u).map(({key:e,item:t})=>_jsxs(View,{style:{flexDirection:"row",justifyContent:"space-between",gap:r.space.sm},children:[_jsx(Text,{variant:"bodySmall",color:"primary",children:toFigureText(t.label)}),_jsx(Text,{variant:"bodySmall",color:"primary",children:writeValue(t.value,s)})]},e))});else if("Bar"===e.chartType)g=_jsx(BarChart,{data:u.map(e=>({label:toFigureText(e.label),value:e.value})),height:u.length>4?300:240,label:m,formatValue:e=>writeValue(e,s),formatTick:e=>s?`${formatCompactNumber(e)} ${s}`:formatCompactNumber(e),tone:c});else if("Line"===e.chartType)g=_jsxs(View,{style:{gap:r.space.xs},children:[_jsx(Sparkline,{data:x,height:160,fill:!0,tone:c,label:m,formatLabel:e=>writeValue(e,s)}),_jsxs(View,{style:{flexDirection:"row",justifyContent:"space-between"},children:[_jsx(Text,{variant:"caption",color:"tertiary",children:toFigureText(b.label)}),u.length>1?_jsx(Text,{variant:"caption",color:"tertiary",children:toFigureText(y.label)}):null]}),_jsx(Text,{variant:"caption",color:"secondary",children:`${t.labels.chartLow(writeValue(h,s))} ${t.labels.chartHigh(writeValue(p,s))}`})]});else{const e=x.reduce((e,t)=>e+(Number.isFinite(t)&&t>0?t:0),0);g=_jsx(View,{accessibilityRole:"list",style:{gap:r.space.sm},children:withPositions(u).map(({key:t,item:r})=>{const a=e>0&&Number.isFinite(r.value)&&r.value>0?r.value/e:0;return _jsx(ProgressBar,{progress:a,height:8,tone:toneAt(t),label:_jsx(FigureText,{text:r.label,variant:"bodySmall"}),valueLabel:`${writeValue(r.value,s)} (${formatPercent(a,{maximumFractionDigits:0})})`},t)})})}return _jsxs(View,{style:{gap:r.space.xs},children:[n?_jsx(Text,{variant:"caption",color:"secondary",children:toFigureText(l.name)}):null,g]},i)})]})}
1
+ "use strict";import{formatFigure,toFigureText}from"@webority/chat-core";import{formatCompactNumber,formatNumber,formatPercent}from"@webority/mobile-core";import{BarChart,Button,ProgressBar,Sparkline,Text,useTheme}from"@webority/mobile-ui";import{useState}from"react";import{View}from"react-native";import{FigureText,runsToText}from"./FigureText.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const TONES=["primary","info","success","warning","danger","neutral"],toneAt=e=>TONES[e%TONES.length]??"primary",MAX_SERIES=8,withPositions=e=>e.reduce((e,t)=>(e.push({key:e.length,item:t}),e),[]),writeValue=(e,t)=>{const r=0!==e&&Math.abs(e)<.001?runsToText(formatFigure(e)):formatNumber(e,{maximumFractionDigits:2});return t?`${r} ${t}`:r};export function ChartPart({part:e,turn:t}){const r=useTheme(),[a,i]=useState(!1),l="Donut"===e.chartType?e.series.slice(0,1):e.series.slice(0,8);if(l.every(e=>0===e.points.length))return _jsxs(View,{style:{gap:r.space.sm},children:[e.title?_jsx(FigureText,{text:e.title,variant:"label",color:"primary",strong:!0}):null,_jsx(Text,{variant:"bodySmall",color:"secondary",children:t.labels.chartEmpty})]});const{unit:s}=e,o=e.title?toFigureText(e.title):t.labels.chart,n=l.length>1;return _jsxs(View,{accessibilityLabel:o,style:{gap:r.space.sm},children:[e.title?_jsx(FigureText,{text:e.title,variant:"label",color:"primary",strong:!0}):null,_jsx(Button,{label:a?t.labels.chartShowChart:t.labels.chartShowTable,variant:"link",size:"sm",onPress:()=>i(e=>!e)}),withPositions(l).map(({key:i,item:l})=>{const c=toneAt(i),m=toFigureText(l.name)||o,u=l.points;if(0===u.length)return _jsxs(View,{style:{gap:r.space.xs},children:[n?_jsx(Text,{variant:"caption",color:"secondary",children:toFigureText(l.name)}):null,_jsx(Text,{variant:"bodySmall",color:"secondary",children:t.labels.chartEmpty})]},i);const x=u.map(e=>e.value),h=x.reduce((e,t)=>Math.min(e,t)),p=x.reduce((e,t)=>Math.max(e,t)),b=u[0];if(void 0===b)throw new Error("A chart with points has no first point.");const y=u[u.length-1];if(void 0===y)throw new Error("A chart with points has no last point.");let g;if(a)g=_jsx(View,{accessibilityRole:"summary",style:{gap:r.space.xs},children:withPositions(u).map(({key:e,item:t})=>_jsxs(View,{style:{flexDirection:"row",justifyContent:"space-between",gap:r.space.sm},children:[_jsx(Text,{variant:"bodySmall",color:"primary",children:toFigureText(t.label)}),_jsx(Text,{variant:"bodySmall",color:"primary",children:writeValue(t.value,s)})]},e))});else if("Bar"===e.chartType)g=_jsx(BarChart,{data:u.map(e=>({label:toFigureText(e.label),value:e.value})),height:u.length>4?300:240,label:m,formatValue:e=>writeValue(e,s),formatTick:e=>s?`${formatCompactNumber(e)} ${s}`:formatCompactNumber(e),tone:c});else if("Line"===e.chartType)g=_jsxs(View,{style:{gap:r.space.xs},children:[_jsx(Sparkline,{data:x,height:160,fill:!0,tone:c,label:m,formatLabel:e=>writeValue(e,s)}),_jsxs(View,{style:{flexDirection:"row",justifyContent:"space-between"},children:[_jsx(Text,{variant:"caption",color:"tertiary",children:toFigureText(b.label)}),u.length>1?_jsx(Text,{variant:"caption",color:"tertiary",children:toFigureText(y.label)}):null]}),_jsx(Text,{variant:"caption",color:"secondary",children:`${t.labels.chartLow(writeValue(h,s))} ${t.labels.chartHigh(writeValue(p,s))}`})]});else{const e=x.reduce((e,t)=>e+(Number.isFinite(t)&&t>0?t:0),0);g=_jsx(View,{accessibilityRole:"list",style:{gap:r.space.sm},children:withPositions(u).map(({key:t,item:r})=>{const a=e>0&&Number.isFinite(r.value)&&r.value>0?r.value/e:0;return _jsx(ProgressBar,{progress:a,height:8,tone:toneAt(t),label:_jsx(FigureText,{text:r.label,variant:"bodySmall"}),valueLabel:`${writeValue(r.value,s)} (${formatPercent(a,{maximumFractionDigits:0})})`},t)})})}return _jsxs(View,{style:{gap:r.space.xs},children:[n?_jsx(Text,{variant:"caption",color:"secondary",children:toFigureText(l.name)}):null,g]},i)})]})}
@@ -1 +1 @@
1
- "use strict";import{toFigureRuns}from"@webority/chat-core";import{Text,useTheme}from"@webority/mobile-ui";import{Fragment,useMemo}from"react";import{Text as RNText,View}from"react-native";import{jsx as _jsx}from"react/jsx-runtime";const sizeStepOf=e=>"caption"===e?"xs":"bodySmall"===e||"label"===e?"sm":"title"===e?"lg":"base",inkFor=(e,t)=>"secondary"===t?e.colors["text-muted"]:"tertiary"===t?e.colors["text-subtle"]:"success"===t||"warning"===t||"danger"===t||"info"===t?e.colors[`${t}-text`]:e.colors["text-body"];export function runsToText(e){return e.map(e=>e.text).join("")}const withOffsets=e=>e.reduce((e,t)=>{const r=e[e.length-1],n=r?r.offset+r.run.text.length:0;return e.push({offset:n,run:t}),e},[]);function runNode(e,t,r){if("text"===e.kind)return e.text;const n="sub"===e.kind?Math.round(.4*t):-Math.round(.45*t),o=Math.round(.75*t);return _jsx(View,{style:{transform:[{translateY:n}]},children:_jsx(RNText,{style:{fontSize:o,lineHeight:o,includeFontPadding:!1,color:r},children:e.text})})}export function FigureRuns({runs:e,variant:t="bodySmall",color:r,strong:n=!1,numberOfLines:o,accessibilityLabel:s,testID:i,heading:u}){const a=useTheme(),c=a.text[sizeStepOf(t)].size,l=inkFor(a,r);return _jsx(Text,{variant:t,color:r,weight:n?"semibold":void 0,numberOfLines:o,testID:i,accessibilityRole:u?"header":void 0,accessibilityLabel:s??runsToText(e),children:withOffsets(e).map(({offset:e,run:t})=>_jsx(Fragment,{children:runNode(t,c,l)},e))})}export function FigureText({text:e,variant:t="bodySmall",enabled:r=!0,...n}){const o=useMemo(()=>r?toFigureRuns(e):[{kind:"text",text:e}],[e,r]);return _jsx(FigureRuns,{runs:o,variant:t,...n})}
1
+ "use strict";import{toFigureRuns}from"@webority/chat-core";import{Text,useTheme}from"@webority/mobile-ui";import{Fragment,useMemo}from"react";import{Text as RNText,View}from"react-native";import{jsx as _jsx}from"react/jsx-runtime";const sizeStepOf=e=>"caption"===e?"xs":"bodySmall"===e||"label"===e?"sm":"title"===e?"lg":"base",inkFor=(e,t)=>"secondary"===t?e.colors["text-muted"]:"tertiary"===t?e.colors["text-subtle"]:"success"===t||"warning"===t||"danger"===t||"info"===t?e.colors[`${t}-text`]:e.colors["text-body"];export function runsToText(e){return e.map(e=>e.text).join("")}const withOffsets=e=>e.reduce((e,t)=>{const r=e[e.length-1],n=r?r.offset+r.run.text.length:0;return e.push({offset:n,run:t}),e},[]);function runNode(e,t,r){if("text"===e.kind)return e.text;const n="sub"===e.kind?Math.round(.4*t):-Math.round(.45*t),o=Math.round(.75*t);return _jsx(View,{style:{transform:[{translateY:n}]},children:_jsx(RNText,{style:{fontSize:o,lineHeight:o,includeFontPadding:!1,color:r},children:e.text})})}export function FigureRuns({runs:e,variant:t="bodySmall",color:r,strong:n=!1,numberOfLines:o,accessibilityLabel:i,testID:s,heading:u}){const a=useTheme(),c=a.text[sizeStepOf(t)].size,l=inkFor(a,r);return _jsx(Text,{variant:t,...void 0===r?{}:{color:r},...n?{weight:"semibold"}:{},...void 0===o?{}:{numberOfLines:o},...void 0===s?{}:{testID:s},...u?{accessibilityRole:"header"}:{},accessibilityLabel:i??runsToText(e),children:withOffsets(e).map(({offset:e,run:t})=>_jsx(Fragment,{children:runNode(t,c,l)},e))})}export function FigureText({text:e,variant:t="bodySmall",enabled:r=!0,...n}){const o=useMemo(()=>r?toFigureRuns(e):[{kind:"text",text:e}],[e,r]);return _jsx(FigureRuns,{runs:o,variant:t,...n})}
@@ -1 +1 @@
1
- "use strict";import{formatFileSize}from"@webority/chat-core";import{Chip}from"@webority/mobile-ui";import{NoticePart}from"./NoticePart.js";import{jsx as _jsx}from"react/jsx-runtime";export function FilePart(e){const{part:t,message:i,turn:r}=e;if("File"!==t.kind){const e={kind:"Notice",code:"NeedsNewerApp",text:r.labels.needsNewerApp};return _jsx(NoticePart,{part:e,message:i,turn:r})}const{openAttachment:o}=r;return _jsx(Chip,{label:`${t.fileName} (${formatFileSize(t.length)})`,leftIcon:"document-text",variant:"soft",size:"sm",accessibilityLabel:r.labels.fileOpen(t.fileName),onPress:o?()=>o(t):void 0})}
1
+ "use strict";import{formatFileSize}from"@webority/chat-core";import{Chip}from"@webority/mobile-ui";import{jsx as _jsx}from"react/jsx-runtime";export function FilePart({part:e,turn:t}){const{openAttachment:i}=t;return _jsx(Chip,{label:`${e.fileName} (${formatFileSize(e.length)})`,leftIcon:"document-text",variant:"soft",size:"sm",accessibilityLabel:t.labels.fileOpen(e.fileName),...i?{onPress:()=>i(e)}:{}})}
@@ -1 +1 @@
1
- "use strict";import{Avatar,Card,Spinner,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export function HandoffPart({part:e,turn:t}){const s=useTheme(),{labels:i}=t;if(!0===t.handoffSettled&&("Requested"===e.state||"Waiting"===e.state))return null;const a=t.isLast&&("Requested"===e.state||"Waiting"===e.state||"Joined"===e.state),n=e.agent?.displayName||i.handoffAgentFallback,r=e.agent?.avatarUrl;let o;switch(e.state){case"Requested":o=_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:s.space.sm},children:[_jsx(Spinner,{size:"sm"}),_jsx(Text,{variant:"bodySmall",children:i.handoffRequested})]});break;case"Waiting":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:s.space.sm},children:[_jsx(Spinner,{size:"sm"}),"number"==typeof e.queuePosition?null:_jsx(Text,{variant:"label",children:i.handoffWaiting})]}),"number"==typeof e.queuePosition?_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffQueued(e.queuePosition)}):null,_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffQueuedText})]});break;case"Joined":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:s.space.sm},children:[_jsxs(View,{style:{position:"relative"},children:[_jsx(Avatar,{size:"sm",name:n,source:r?{uri:r}:void 0}),_jsx(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{position:"absolute",right:0,bottom:0,width:8,height:8,borderRadius:s.radius.pill,backgroundColor:s.colors["success-text"]}})]}),_jsx(Text,{variant:"label",children:i.handoffJoined(n)})]}),_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffJoinedText(n)})]});break;case"Left":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsx(Text,{variant:"bodySmall",children:i.handoffLeft(n)}),_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffLeftText})]});break;case"Ended":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsx(Text,{variant:"bodySmall",children:i.handoffEnded}),_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffEndedText})]})}return void 0===o?null:_jsx(Card,{variant:"outline",padding:"sm",accessibilityLiveRegion:a?"polite":void 0,children:o})}
1
+ "use strict";import{Avatar,Card,Spinner,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export function HandoffPart({part:e,turn:t}){const s=useTheme(),{labels:i}=t;if(!0===t.handoffSettled&&("Requested"===e.state||"Waiting"===e.state))return null;const a=t.isLast&&("Requested"===e.state||"Waiting"===e.state||"Joined"===e.state),n=e.agent?.displayName||i.handoffAgentFallback,r=e.agent?.avatarUrl;let o;switch(e.state){case"Requested":o=_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:s.space.sm},children:[_jsx(Spinner,{size:"sm"}),_jsx(Text,{variant:"bodySmall",children:i.handoffRequested})]});break;case"Waiting":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:s.space.sm},children:[_jsx(Spinner,{size:"sm"}),"number"==typeof e.queuePosition?null:_jsx(Text,{variant:"label",children:i.handoffWaiting})]}),"number"==typeof e.queuePosition?_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffQueued(e.queuePosition)}):null,_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffQueuedText})]});break;case"Joined":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:s.space.sm},children:[_jsxs(View,{style:{position:"relative"},children:[_jsx(Avatar,{size:"sm",name:n,...r?{source:{uri:r}}:{}}),_jsx(View,{accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{position:"absolute",right:0,bottom:0,width:8,height:8,borderRadius:s.radius.pill,backgroundColor:s.colors["success-text"]}})]}),_jsx(Text,{variant:"label",children:i.handoffJoined(n)})]}),_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffJoinedText(n)})]});break;case"Left":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsx(Text,{variant:"bodySmall",children:i.handoffLeft(n)}),_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffLeftText})]});break;case"Ended":o=_jsxs(View,{style:{gap:s.space.xs},children:[_jsx(Text,{variant:"bodySmall",children:i.handoffEnded}),_jsx(Text,{variant:"caption",color:"secondary",children:i.handoffEndedText})]})}return void 0===o?null:_jsx(Card,{variant:"outline",padding:"sm",accessibilityLiveRegion:a?"polite":void 0,children:o})}
@@ -1 +1 @@
1
- "use strict";import{Button,Card,Checkbox,Chip,ChoiceGroup,Input,ProgressBar,Text,useTheme}from"@webority/mobile-ui";import{useCallback,useEffect,useRef,useState}from"react";import{View}from"react-native";import{focusForAccessibility}from"../chatShared.js";import{NoticePart}from"./NoticePart.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const FIELD_TYPES=new Set(["Email","Phone","Name","Company","Text","LongText","Choice","MultiChoice","TimeSlot","File","Consent"]),isUndrawnField=e=>!FIELD_TYPES.has(e.type),fileNameOf=(e,t)=>{const i=e.name;return"string"==typeof i&&""!==i?i:t},slotFormat=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"numeric",minute:"2-digit"}),selectedIds=e=>""===e?[]:JSON.parse(e),KEYBOARD_TYPES={Email:"email-address",Phone:"phone-pad"},AUTO_COMPLETE={Email:"email",Phone:"tel",Name:"name",Company:"organization"},optionalSuffix=(e,t)=>e.required?"":` (${t.inputOptional})`,firstErrorKey=(e,t)=>e.find(e=>void 0!==t[e.key])?.key;function OpenRequest({part:e,turn:t,pickAttachments:i}){const r=useTheme(),{labels:s,features:a}=t,[n,l]=useState({}),[o,c]=useState({}),[u,d]=useState(""),[p,y]=useState(!1),[f,m]=useState({}),[x,h]=useState({}),[b,k]=useState({}),v=useRef({}),g=useRef({}),j=useRef(f),_=useRef(0),T=useRef(!1),C=useCallback(e=>{const t=v.current[e];if(t)return void t.focus();const i=g.current[e];i&&focusForAccessibility(i)},[]);useEffect(()=>{if(p||!T.current)return;T.current=!1;const t=firstErrorKey(e.fields,o);void 0!==t&&C(t)},[p,o,e.fields,C]);const setValue=(e,t)=>l(i=>({...i,[e]:t})),commitUploads=e=>{j.current=e,m(e)},patchUpload=(e,t)=>{const i=j.current[e];i&&commitUploads({...j.current,[e]:{...i,...t}})},isLiveUpload=(e,t)=>j.current[e]?.token===t,S=Object.values(f).some(e=>"Ready"!==e.status),leave=async e=>{y(!0),d("");try{await e()}catch{d(s.errorGeneric),y(!1)}},w=a.LeadShortcuts,R=w&&1===e.fields.length&&!e.fields[0].required,E=w&&e.cancellable;return _jsx(Card,{variant:"outline",padding:"sm",accessibilityLabel:e.title||void 0,children:_jsxs(View,{style:{gap:r.space.sm},children:[e.title?_jsx(Text,{variant:"label",accessibilityRole:"header",children:e.title}):null,e.allowTyped?_jsx(Text,{variant:"caption",color:"secondary",children:s.typeAnswer}):null,e.fields.map(a=>{const l=n[a.key]??"",c=o[a.key];if("File"===a.type){const e=f[a.key];return _jsxs(View,{style:{gap:r.space.xs},children:[_jsx(Text,{variant:"label",children:`${a.label}${optionalSuffix(a,s)}`}),e?_jsxs(View,{style:{gap:r.space.xxs},children:[_jsx(Chip,{label:e.fileName,variant:"soft",onRemove:()=>{return e=a.key,commitUploads(Object.fromEntries(Object.entries(j.current).filter(([t])=>t!==e))),void setValue(e,"");var e},labels:{remove:s.inputRemoveFile}}),"Uploading"===e.status?_jsx(ProgressBar,{progress:e.progress??void 0,label:s.attachmentUploading,height:4}):null,"Failed"===e.status?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"assertive",children:s.attachmentFailed}):null]}):_jsx(View,{style:{flexDirection:"row"},children:_jsx(Button,{label:s.inputChooseFile,variant:"soft",size:"sm",leftIcon:"paperclip",disabled:p||void 0===i,onPress:()=>{(async e=>{if(!i)return;let r;try{r=await i(e.accept??void 0)}catch{return void d(s.errorGeneric)}const a=r[0];if(!a)return;_.current+=1;const n=_.current;commitUploads({...j.current,[e.key]:{fileName:fileNameOf(a,e.label),status:"Uploading",progress:null,token:n}});try{const i=await t.uploadInputFile(a,t=>{isLiveUpload(e.key,n)&&patchUpload(e.key,{progress:t})});isLiveUpload(e.key,n)&&(setValue(e.key,i),patchUpload(e.key,{status:"Ready",progress:null}))}catch{isLiveUpload(e.key,n)&&(setValue(e.key,""),patchUpload(e.key,{status:"Failed",progress:null}))}})(a)}})}),c?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"assertive",children:c}):null]},a.key)}if("MultiChoice"===a.type){const e=(a.options??[]).map(e=>({label:e.label,value:e.id}));return _jsxs(View,{style:{gap:r.space.xs},children:[_jsx(Text,{variant:"label",children:`${a.label}${optionalSuffix(a,s)}`}),_jsx(View,{ref:e=>{g.current[a.key]=e},children:_jsx(ChoiceGroup,{selectionMode:"multiple",options:e,value:selectedIds(l),onChange:t=>setValue(a.key,JSON.stringify(e.filter(e=>t.includes(e.value)).map(e=>e.value))),accessibilityLabel:a.label,error:c,disabled:p})})]},a.key)}if("Choice"===a.type||"TimeSlot"===a.type){const e="TimeSlot"===a.type?(a.slots??[]).map(e=>({label:slotFormat.format(new Date(e.startDateTimeUtc)),value:e.id})):(a.options??[]).map(e=>({label:e.label,value:e.id}));return _jsxs(View,{style:{gap:r.space.xs},children:[_jsx(Text,{variant:"label",children:`${a.label}${optionalSuffix(a,s)}`}),_jsx(View,{ref:e=>{g.current[a.key]=e},children:_jsx(ChoiceGroup,{options:e,value:""===l?void 0:l,onChange:e=>setValue(a.key,String(e)),accessibilityLabel:a.label,error:c,disabled:p})})]},a.key)}if("Consent"===a.type)return _jsx(Checkbox,{checked:"true"===l,onChange:e=>setValue(a.key,e?"true":"false"),label:a.consentText??a.label,error:c,disabled:p},a.key);const u=_jsx(Input,{ref:e=>{v.current[a.key]=e},label:a.label,placeholder:a.placeholder??void 0,value:l,onChangeText:e=>setValue(a.key,e),maxLength:a.maxLength??void 0,required:a.required,error:c,help:a.required?void 0:s.inputOptional,labelMode:"top",disabled:p,type:a.secret?"password":"LongText"===a.type?"textarea":"input",keyboardType:KEYBOARD_TYPES[a.type]??"default",autoCapitalize:"Email"===a.type?"none":void 0,autoComplete:AUTO_COMPLETE[a.type]},a.key);if(!("Otp"===a.verify&&("Email"===a.type||"Phone"===a.type)))return u;const y=b[a.key];return _jsxs(View,{style:{gap:r.space.xs},children:[u,_jsxs(View,{style:{gap:r.space.xs},children:[_jsx(Button,{label:s.inputSendCode,variant:"soft",size:"sm",disabled:p,onPress:()=>{(async i=>{if("Otp"===i.verify)try{await t.sendOtp(e.requestId,{fieldKey:i.key,value:(n[i.key]??"").trim()}),k(e=>({...e,[i.key]:"sent"}))}catch{k(e=>({...e,[i.key]:"failed"}))}})(a)},testID:`otp-send-${a.key}`}),_jsx(Input,{label:s.inputEnterCode,value:x[a.key]??"",onChangeText:e=>h(t=>({...t,[a.key]:e})),keyboardType:"number-pad",autoComplete:"one-time-code",disabled:p}),y?_jsx(Text,{variant:"caption",color:"failed"===y?"danger":"secondary",accessibilityLiveRegion:"polite",children:"failed"===y?s.inputCodeFailed:s.inputCodeSent}):null]})]},a.key)}),""!==u?_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:u}):null,_jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:r.space.sm},children:[_jsx(Button,{label:p?s.inputSubmitting:e.submitLabel,loading:p,disabled:p||S,onPress:()=>{(async()=>{if(S)return;const i={},r={};for(const t of e.fields){const e=n[t.key]??"";if("Consent"===t.type){const a="true"===e;t.required&&!a&&(i[t.key]=s.inputConsentRequired),r[t.key]=a?"true":"false"}else if("Choice"===t.type||"TimeSlot"===t.type)t.required&&""===e&&(i[t.key]=s.inputRequired),r[t.key]=e;else if("MultiChoice"===t.type){const a=selectedIds(e);t.required&&0===a.length&&(i[t.key]=s.inputRequired),r[t.key]=JSON.stringify(a)}else if("File"===t.type)t.required&&""===e&&(i[t.key]=s.inputRequired),r[t.key]=e;else{const a=t.secret?e:e.trim();t.required&&""===a&&(i[t.key]=s.inputRequired),r[t.key]=a}}const a={};for(const t of e.fields){if("Otp"!==t.verify)continue;const e=(x[t.key]??"").trim();""===e&&(i[t.key]=s.inputRequired),a[t.key]=e}if(c(i),Object.keys(i).length>0){const t=firstErrorKey(e.fields,i);return void(void 0!==t&&C(t))}y(!0),d("");try{const i=await t.answerInput(e.requestId,r,Object.keys(a).length>0?a:null);if(i.ok)return;c(i.errors),T.current=!0,d(i.message??"")}catch{d(s.errorGeneric)}y(!1)})()}}),S?_jsx(Text,{variant:"caption",color:"secondary",children:s.attachmentUploading}):null,R?_jsx(Button,{label:s.skip,variant:"ghost",disabled:p,onPress:()=>{leave(()=>t.skipInput(e.requestId))}}):null,E?_jsx(Button,{label:s.cancel,variant:"ghost",disabled:p,onPress:()=>{leave(()=>t.cancelLead())}}):null]})]})})}export function InputRequestPart(e){const{part:t,message:i,turn:r,pickAttachments:s}=e;if("InputRequest"!==t.kind||t.fields.some(isUndrawnField)){const e={kind:"Notice",code:"NeedsNewerApp",text:r.labels.needsNewerApp};return _jsx(NoticePart,{part:e,message:i,turn:r})}return"Answered"===t.state?_jsx(Text,{variant:"bodySmall",color:"secondary",children:t.answeredSummary||r.labels.inputAnswered}):"Skipped"===t.state?_jsx(Text,{variant:"bodySmall",color:"secondary",children:r.labels.inputSkipped}):"Expired"===t.state?_jsx(Text,{variant:"bodySmall",color:"secondary",children:r.labels.inputExpired}):_jsx(OpenRequest,{part:t,turn:r,pickAttachments:s},t.requestId)}
1
+ "use strict";import{Button,Card,Checkbox,Chip,ChoiceGroup,Input,ProgressBar,Text,useTheme}from"@webority/mobile-ui";import{useCallback,useEffect,useRef,useState}from"react";import{View}from"react-native";import{focusForAccessibility}from"../chatShared.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const fileNameOf=(e,t)=>{const r="object"==typeof e&&null!==e&&"name"in e?e.name:void 0;return"string"==typeof r&&""!==r?r:t},slotFormat=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"numeric",minute:"2-digit"}),isStringList=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e),selectedIds=e=>{if(""===e)return[];const t=JSON.parse(e);if(!isStringList(t))throw new Error("Selected ids are not a list of strings.");return t},KEYBOARD_TYPES={Email:"email-address",Phone:"phone-pad"},AUTO_COMPLETE={Email:"email",Phone:"tel",Name:"name",Company:"organization"},optionalSuffix=(e,t)=>e.required?"":` (${t.inputOptional})`,firstErrorKey=(e,t)=>e.find(e=>void 0!==t[e.key])?.key;function OpenRequest({part:e,turn:t,pickAttachments:r}){const i=useTheme(),{labels:s,features:n}=t,[a,l]=useState({}),[o,c]=useState({}),[u,d]=useState(""),[p,y]=useState(!1),[f,h]=useState({}),[m,x]=useState({}),[b,k]=useState({}),v=useRef({}),g=useRef({}),j=useRef(f),_=useRef(0),S=useRef(!1),T=useCallback(e=>{const t=v.current[e];if(t)return void t.focus();const r=g.current[e];r&&focusForAccessibility(r)},[]);useEffect(()=>{if(p||!S.current)return;S.current=!1;const t=firstErrorKey(e.fields,o);void 0!==t&&T(t)},[p,o,e.fields,T]);const setValue=(e,t)=>l(r=>({...r,[e]:t})),commitUploads=e=>{j.current=e,h(e)},patchUpload=(e,t)=>{const r=j.current[e];r&&commitUploads({...j.current,[e]:{...r,...t}})},isLiveUpload=(e,t)=>j.current[e]?.token===t,w=Object.values(f).some(e=>"Ready"!==e.status),leave=async e=>{y(!0),d("");try{await e()}catch{d(s.errorGeneric),y(!1)}},C=n.LeadShortcuts,O=e.fields[0];if(C&&1===e.fields.length&&void 0===O)throw new Error("A one-field form has no field.");const R=C&&1===e.fields.length&&void 0!==O&&!O.required,E=C&&e.cancellable;return _jsx(Card,{variant:"outline",padding:"sm",...e.title?{accessibilityLabel:e.title}:{},children:_jsxs(View,{style:{gap:i.space.sm},children:[e.title?_jsx(Text,{variant:"label",accessibilityRole:"header",children:e.title}):null,e.allowTyped?_jsx(Text,{variant:"caption",color:"secondary",children:s.typeAnswer}):null,e.fields.map(n=>{const l=a[n.key]??"",c=o[n.key];if("File"===n.type){const e=f[n.key];return _jsxs(View,{style:{gap:i.space.xs},children:[_jsx(Text,{variant:"label",children:`${n.label}${optionalSuffix(n,s)}`}),e?_jsxs(View,{style:{gap:i.space.xxs},children:[_jsx(Chip,{label:e.fileName,variant:"soft",onRemove:()=>{return e=n.key,commitUploads(Object.fromEntries(Object.entries(j.current).filter(([t])=>t!==e))),void setValue(e,"");var e},labels:{remove:s.inputRemoveFile}}),"Uploading"===e.status?_jsx(ProgressBar,{..."number"==typeof e.progress?{progress:e.progress}:{},label:s.attachmentUploading,height:4}):null,"Failed"===e.status?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"assertive",children:s.attachmentFailed}):null]}):_jsx(View,{style:{flexDirection:"row"},children:_jsx(Button,{label:s.inputChooseFile,variant:"soft",size:"sm",leftIcon:"paperclip",disabled:p||void 0===r,onPress:()=>{(async e=>{if(!r)return;let i;try{i=await r(e.accept??void 0)}catch{return void d(s.errorGeneric)}const n=i[0];if(!n)return;_.current+=1;const a=_.current;commitUploads({...j.current,[e.key]:{fileName:fileNameOf(n,e.label),status:"Uploading",progress:null,token:a}});try{const r=await t.uploadInputFile(n,t=>{isLiveUpload(e.key,a)&&patchUpload(e.key,{progress:t})});isLiveUpload(e.key,a)&&(setValue(e.key,r),patchUpload(e.key,{status:"Ready",progress:null}))}catch{isLiveUpload(e.key,a)&&(setValue(e.key,""),patchUpload(e.key,{status:"Failed",progress:null}))}})(n)}})}),c?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"assertive",children:c}):null]},n.key)}if("MultiChoice"===n.type){const e=(n.options??[]).map(e=>({label:e.label,value:e.id}));return _jsxs(View,{style:{gap:i.space.xs},children:[_jsx(Text,{variant:"label",children:`${n.label}${optionalSuffix(n,s)}`}),_jsx(View,{ref:e=>{g.current[n.key]=e},children:_jsx(ChoiceGroup,{selectionMode:"multiple",options:e,value:selectedIds(l),onChange:t=>setValue(n.key,JSON.stringify(e.filter(e=>t.includes(e.value)).map(e=>e.value))),accessibilityLabel:n.label,...void 0===c?{}:{error:c},disabled:p})})]},n.key)}if("Choice"===n.type||"TimeSlot"===n.type){const e="TimeSlot"===n.type?(n.slots??[]).map(e=>({label:slotFormat.format(new Date(e.startDateTimeUtc)),value:e.id})):(n.options??[]).map(e=>({label:e.label,value:e.id}));return _jsxs(View,{style:{gap:i.space.xs},children:[_jsx(Text,{variant:"label",children:`${n.label}${optionalSuffix(n,s)}`}),_jsx(View,{ref:e=>{g.current[n.key]=e},children:_jsx(ChoiceGroup,{options:e,...""===l?{}:{value:l},onChange:e=>setValue(n.key,String(e)),accessibilityLabel:n.label,...void 0===c?{}:{error:c},disabled:p})})]},n.key)}if("Consent"===n.type)return _jsx(Checkbox,{checked:"true"===l,onChange:e=>setValue(n.key,e?"true":"false"),label:n.consentText??n.label,...void 0===c?{}:{error:c},disabled:p},n.key);const u=_jsx(Input,{ref:e=>{v.current[n.key]=e},label:n.label,..."string"==typeof n.placeholder?{placeholder:n.placeholder}:{},value:l,onChangeText:e=>setValue(n.key,e),..."number"==typeof n.maxLength?{maxLength:n.maxLength}:{},required:n.required,...void 0===c?{}:{error:c},...n.required?{}:{help:s.inputOptional},labelMode:"top",disabled:p,type:n.secret?"password":"LongText"===n.type?"textarea":"input",keyboardType:KEYBOARD_TYPES[n.type]??"default",..."Email"===n.type?{autoCapitalize:"none"}:{},...void 0===AUTO_COMPLETE[n.type]?{}:{autoComplete:AUTO_COMPLETE[n.type]}},n.key);if(!("Otp"===n.verify&&("Email"===n.type||"Phone"===n.type)))return u;const y=b[n.key];return _jsxs(View,{style:{gap:i.space.xs},children:[u,_jsxs(View,{style:{gap:i.space.xs},children:[_jsx(Button,{label:s.inputSendCode,variant:"soft",size:"sm",disabled:p,onPress:()=>{(async r=>{if("Otp"===r.verify)try{await t.sendOtp(e.requestId,{fieldKey:r.key,value:(a[r.key]??"").trim()}),k(e=>({...e,[r.key]:"sent"}))}catch{k(e=>({...e,[r.key]:"failed"}))}})(n)},testID:`otp-send-${n.key}`}),_jsx(Input,{label:s.inputEnterCode,value:m[n.key]??"",onChangeText:e=>x(t=>({...t,[n.key]:e})),keyboardType:"number-pad",autoComplete:"one-time-code",disabled:p}),y?_jsx(Text,{variant:"caption",color:"failed"===y?"danger":"secondary",accessibilityLiveRegion:"polite",children:"failed"===y?s.inputCodeFailed:s.inputCodeSent}):null]})]},n.key)}),""!==u?_jsx(Text,{variant:"bodySmall",color:"danger",accessibilityLiveRegion:"polite",children:u}):null,_jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:i.space.sm},children:[_jsx(Button,{label:p?s.inputSubmitting:e.submitLabel,loading:p,disabled:p||w,onPress:()=>{(async()=>{if(w)return;const r={},i={};for(const t of e.fields){const e=a[t.key]??"";if("Consent"===t.type){const n="true"===e;t.required&&!n&&(r[t.key]=s.inputConsentRequired),i[t.key]=n?"true":"false"}else if("Choice"===t.type||"TimeSlot"===t.type)t.required&&""===e&&(r[t.key]=s.inputRequired),i[t.key]=e;else if("MultiChoice"===t.type){const n=selectedIds(e);t.required&&0===n.length&&(r[t.key]=s.inputRequired),i[t.key]=JSON.stringify(n)}else if("File"===t.type)t.required&&""===e&&(r[t.key]=s.inputRequired),i[t.key]=e;else{const n=t.secret?e:e.trim();t.required&&""===n&&(r[t.key]=s.inputRequired),i[t.key]=n}}const n={};for(const t of e.fields){if("Otp"!==t.verify)continue;const e=(m[t.key]??"").trim();""===e&&(r[t.key]=s.inputRequired),n[t.key]=e}if(c(r),Object.keys(r).length>0){const t=firstErrorKey(e.fields,r);return void(void 0!==t&&T(t))}y(!0),d("");try{const r=await t.answerInput(e.requestId,i,Object.keys(n).length>0?n:null);if(r.ok)return;c(r.errors),S.current=!0,d(r.message??"")}catch{d(s.errorGeneric)}y(!1)})()}}),w?_jsx(Text,{variant:"caption",color:"secondary",children:s.attachmentUploading}):null,R?_jsx(Button,{label:s.skip,variant:"ghost",disabled:p,onPress:()=>{leave(()=>t.skipInput(e.requestId))}}):null,E?_jsx(Button,{label:s.cancel,variant:"ghost",disabled:p,onPress:()=>{leave(()=>t.cancelLead())}}):null]})]})})}export function InputRequestPart({part:e,turn:t,pickAttachments:r}){return"Answered"===e.state?_jsx(Text,{variant:"bodySmall",color:"secondary",children:e.answeredSummary||t.labels.inputAnswered}):"Skipped"===e.state?_jsx(Text,{variant:"bodySmall",color:"secondary",children:t.labels.inputSkipped}):"Expired"===e.state?_jsx(Text,{variant:"bodySmall",color:"secondary",children:t.labels.inputExpired}):_jsx(OpenRequest,{part:e,turn:t,pickAttachments:r},e.requestId)}
@@ -1 +1 @@
1
- "use strict";import{Banner}from"@webority/mobile-ui";import{jsx as _jsx}from"react/jsx-runtime";export function NoticePart({part:e}){const t="AssistantUnavailable"===e.code?"danger":"ActionLimitReached"===e.code||"ConversationTooLong"===e.code?"warning":"info";return _jsx(Banner,{message:e.text,tone:t,accessibilityRole:"alert"})}
1
+ "use strict";import{Banner}from"@webority/mobile-ui";import{jsx as _jsx}from"react/jsx-runtime";export function NoticePart({part:e,turn:t}){const o="AssistantUnavailable"===e.code?"danger":"ActionLimitReached"===e.code||"ConversationTooLong"===e.code?"warning":"info",n="NeedsNewerApp"===e.code?t.labels.needsNewerApp:e.text;return _jsx(Banner,{message:n,tone:o,accessibilityRole:"alert"})}
@@ -1 +1 @@
1
- "use strict";import{CHAT_HANDOFF_REQUEST_ID,isHandoffTarget}from"@webority/chat-core";import{Chip,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{ChatEntrance}from"../ChatEntrance.js";import{defaultOpenTarget}from"../chatShared.js";import{chipLook}from"./chipLook.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const QUIET_LOOK={variant:"outline"};export function QuickRepliesPart({part:e,turn:n}){const i=useTheme();if(!n.features.SuggestedReplies||!n.isLast||n.busy||0===e.replies.length)return null;const t=n.openTarget,a=n.onNavigate,r=void 0!==t&&t!==defaultOpenTarget,o="Composer"===e.placement,s=e.replies.filter(e=>"Send"===e.action||"Open"===e.action&&e.target&&t||"Navigate"===e.action&&n.features.LinkHandoff);if(0===s.length)return null;const l=o?void 0:s.find(e=>e.id===CHAT_HANDOFF_REQUEST_ID&&"Send"===e.action),c=l?s.filter(e=>e!==l):s,d=l?1:0,sendChip=(e,i)=>_jsx(Chip,{label:e.label,variant:i.variant,tone:i.tone,leftIcon:e.icon?e.icon:void 0,onPress:()=>{n.chooseQuickReply(e),n.focusComposer?.()}});return _jsxs(View,{role:"group",accessibilityLabel:n.labels.quickReplies,accessibilityLiveRegion:n.handoffPause?"polite":void 0,style:{flexDirection:"row",flexWrap:"wrap",gap:i.space.xs,...o?{paddingHorizontal:i.space.md}:null},children:[l?_jsx(ChatEntrance,{index:0,children:_jsxs(View,{style:{flexBasis:"100%",alignItems:"flex-start",gap:i.space.xs},children:[_jsx(Text,{variant:"label",children:l.label}),sendChip(l,chipLook("Primary"))]})},l.id):null,c.map((e,i)=>{const o=i+d,s=l?QUIET_LOOK:chipLook(e.variant),c=e.icon?e.icon:void 0;if("Send"===e.action)return _jsx(ChatEntrance,{index:o,children:sendChip(e,s)},e.id);const f=e.target;if("Open"===e.action&&f&&t)return _jsx(ChatEntrance,{index:o,children:_jsx(Chip,{label:e.label,variant:s.variant,tone:s.tone,leftIcon:c,onPress:()=>t(f)})},e.id);if("Navigate"===e.action){const i=(e=>{if(!e)return null;if(isHandoffTarget(e,n.handoffHosts))return e;const i=n.resolveLink?.(e);return"string"==typeof i&&""!==i?i:null})(f),l=null===i?void 0:(e=>e.startsWith("/")?t&&r?()=>t(e):a?()=>a(e):void 0:t?()=>t(e):void 0)(i);return _jsx(ChatEntrance,null===i||void 0===l?{index:o,children:_jsx(Text,{variant:"bodySmall",color:"primary",children:e.label})}:{index:o,children:_jsx(Chip,{label:n.handoffPause?n.labels.handoffMoment:e.label,variant:n.handoffPause?QUIET_LOOK.variant:s.variant,tone:n.handoffPause?void 0:s.tone,leftIcon:c,disabled:n.handoffPause,onPress:()=>n.beginHandoff(e,l)})},e.id)}return null})]})}
1
+ "use strict";import{CHAT_HANDOFF_REQUEST_ID,isHandoffTarget}from"@webority/chat-core";import{Chip,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{ChatEntrance}from"../ChatEntrance.js";import{defaultOpenTarget}from"../chatShared.js";import{iconNameOf}from"../iconName.js";import{chipLook}from"./chipLook.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const QUIET_LOOK={variant:"outline"};export function QuickRepliesPart({part:e,turn:n}){const i=useTheme();if(!n.features.SuggestedReplies||!n.isLast||n.busy||0===e.replies.length)return null;const t=n.openTarget,a=n.onNavigate,o=void 0!==t&&t!==defaultOpenTarget,r="Composer"===e.placement,s=e.replies.filter(e=>"Send"===e.action||"Open"===e.action&&e.target&&t||"Navigate"===e.action&&n.features.LinkHandoff);if(0===s.length)return null;const l=r?void 0:s.find(e=>e.id===CHAT_HANDOFF_REQUEST_ID&&"Send"===e.action),c=l?s.filter(e=>e!==l):s,d=l?1:0,sendChip=(e,i)=>{const t=iconNameOf(e.icon);return _jsx(Chip,{label:e.label,variant:i.variant,...void 0===i.tone?{}:{tone:i.tone},...t?{leftIcon:t}:{},onPress:()=>{n.chooseQuickReply(e),n.focusComposer?.()}})};return _jsxs(View,{role:"group",accessibilityLabel:n.labels.quickReplies,accessibilityLiveRegion:n.handoffPause?"polite":void 0,style:{flexDirection:"row",flexWrap:"wrap",gap:i.space.xs,...r?{paddingHorizontal:i.space.md}:null},children:[l?_jsx(ChatEntrance,{index:0,children:_jsxs(View,{style:{flexBasis:"100%",alignItems:"flex-start",gap:i.space.xs},children:[_jsx(Text,{variant:"label",children:l.label}),sendChip(l,chipLook("Primary"))]})},l.id):null,c.map((e,i)=>{const r=i+d,s=l?QUIET_LOOK:chipLook(e.variant),c=iconNameOf(e.icon)??void 0;if("Send"===e.action)return _jsx(ChatEntrance,{index:r,children:sendChip(e,s)},e.id);const f=e.target;if("Open"===e.action&&f&&t)return _jsx(ChatEntrance,{index:r,children:_jsx(Chip,{label:e.label,variant:s.variant,...void 0===s.tone?{}:{tone:s.tone},...void 0===c?{}:{leftIcon:c},onPress:()=>t(f)})},e.id);if("Navigate"===e.action){const i=(e=>{if(!e)return null;if(isHandoffTarget(e,n.handoffHosts))return e;const i=n.resolveLink?.(e);return"string"==typeof i&&""!==i?i:null})(f),l=null===i?void 0:(e=>e.startsWith("/")?t&&o?()=>t(e):a?()=>a(e):void 0:t?()=>t(e):void 0)(i);return _jsx(ChatEntrance,null===i||void 0===l?{index:r,children:_jsx(Text,{variant:"bodySmall",color:"primary",children:e.label})}:{index:r,children:_jsx(Chip,{label:n.handoffPause?n.labels.handoffMoment:e.label,variant:n.handoffPause?QUIET_LOOK.variant:s.variant,...n.handoffPause||void 0===s.tone?{}:{tone:s.tone},...void 0===c?{}:{leftIcon:c},disabled:n.handoffPause,onPress:()=>n.beginHandoff(e,l)})},e.id)}return null})]})}
@@ -1 +1 @@
1
- "use strict";import{Chip,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{ChatEntrance}from"../ChatEntrance.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const HTTP_LINK=/^https?:\/\//i;export function SourcesPart({part:e,turn:r}){const s=useTheme();if(!r.features.Sources||0===e.sources.length)return null;const t=r.openTarget;return _jsxs(View,{style:{gap:s.space.xs},children:[_jsx(Text,{variant:"caption",color:"secondary",children:r.labels.sources}),_jsx(View,{accessibilityRole:"list",accessibilityLabel:r.labels.sources,style:{flexDirection:"row",flexWrap:"wrap",gap:s.space.xs},children:e.sources.map((e,s)=>{const i=e.url,a=null!==i&&HTTP_LINK.test(i)&&void 0!==t?()=>t(i):void 0;return _jsx(ChatEntrance,{index:s,animate:!1,children:_jsx(View,{ref:s=>r.registerSourceRow?.(String(e.marker),s),children:_jsx(Chip,{label:`${e.marker} ${e.title}`,variant:"outline",size:"sm",accessibilityLabel:a?r.labels.openSource(e.title):void 0,onPress:a})})},e.marker)})})]})}
1
+ "use strict";import{Chip,Text,useTheme}from"@webority/mobile-ui";import{View}from"react-native";import{ChatEntrance}from"../ChatEntrance.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const HTTP_LINK=/^https?:\/\//i;export function SourcesPart({part:e,turn:r}){const s=useTheme();if(!r.features.Sources||0===e.sources.length)return null;const t=r.openTarget;return _jsxs(View,{style:{gap:s.space.xs},children:[_jsx(Text,{variant:"caption",color:"secondary",children:r.labels.sources}),_jsx(View,{accessibilityRole:"list",accessibilityLabel:r.labels.sources,style:{flexDirection:"row",flexWrap:"wrap",gap:s.space.xs},children:e.sources.map((e,s)=>{const i=e.url,a=null!==i&&HTTP_LINK.test(i)&&void 0!==t?()=>t(i):void 0;return _jsx(ChatEntrance,{index:s,animate:!1,children:_jsx(View,{ref:s=>r.registerSourceRow?.(String(e.marker),s),children:_jsx(Chip,{label:`${e.marker} ${e.title}`,variant:"outline",size:"sm",...void 0===a?{}:{accessibilityLabel:r.labels.openSource(e.title),onPress:a}})})},e.marker)})})]})}
@@ -1 +1 @@
1
- "use strict";import{isHandoffTarget,toFigureRuns}from"@webority/chat-core";import{Markdown,Text}from"@webority/mobile-ui";import{View}from"react-native";import{FigureText}from"./FigureText.js";import{jsx as _jsx}from"react/jsx-runtime";const CITATION=/^\d+$/,PARAGRAPH_ROLE="paragraph";export function TextPart({part:t,message:e,turn:r}){const i="Visitor"===e.author.kind||"Customer"===e.author.kind;return _jsx(View,{role:"paragraph",children:i?r.features.FigureText?_jsx(FigureText,{text:t.text,variant:"body",color:"primary"}):_jsx(Text,{variant:"body",children:t.text}):_jsx(Markdown,{links:"app",headings:"text",resolveLink:t=>r.openTarget&&isHandoffTarget(t,r.handoffHosts)?t:null,onAppLinkPress:t=>r.openTarget?.(t),isCitation:t=>CITATION.test(t),figureText:r.features.FigureText?toFigureRuns:void 0,onOpenCitation:r.openCitation?t=>r.openCitation?.(Number(t)):void 0,children:t.text})})}
1
+ "use strict";import{isHandoffTarget,toFigureRuns}from"@webority/chat-core";import{Markdown,Text}from"@webority/mobile-ui";import{View}from"react-native";import{FigureText}from"./FigureText.js";import{jsx as _jsx}from"react/jsx-runtime";const CITATION=/^\d+$/;export function TextPart({part:t,message:e,turn:r}){const i="Visitor"===e.author.kind||"Customer"===e.author.kind;return _jsx(View,{children:i?r.features.FigureText?_jsx(FigureText,{text:t.text,variant:"body",color:"primary"}):_jsx(Text,{variant:"body",children:t.text}):_jsx(Markdown,{links:"app",headings:"text",resolveLink:t=>r.openTarget&&isHandoffTarget(t,r.handoffHosts)?t:null,onAppLinkPress:t=>r.openTarget?.(t),isCitation:t=>CITATION.test(t),...r.features.FigureText?{figureText:toFigureRuns}:{},...r.openCitation?{onOpenCitation:t=>r.openCitation?.(Number(t))}:{},children:t.text})})}
@@ -1 +1 @@
1
- "use strict";import{voiceClipBars}from"@webority/chat-core";import{Logger}from"@webority/mobile-core";import{Button,IconButton,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{playFile}from"../speech/expoAudio.js";import{discardFile,PhoneSpeechError}from"../speech/phoneSpeech.js";import{audioExtension,formatClipTime}from"../speech/speechText.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const expoFileSystem=()=>{try{return require("expo-file-system")}catch{throw new PhoneSpeechError("Unavailable","Unavailable","Voice files are not available in this app.")}};export function VoiceClipPart({part:e,turn:t}){const r=useTheme(),i=useMemo(()=>buildStyles(r),[r]),a=t.labels,[o,s]=useState(!1),[c,l]=useState(!1),[n,u]=useState(!1),[p,m]=useState(0),[h,d]=useState(!1),x=useRef(null),y=useRef(null),f=useRef(!0);useEffect(()=>(f.current=!0,()=>{f.current=!1,x.current?.stop(),x.current=null,null!==y.current&&discardFile(y.current)}),[]);const startPlayback=e=>{const t=playFile(e,e=>{f.current&&(m(e.positionMs),u(e.playing))});x.current=t;const release=()=>!(!f.current||x.current!==t)&&(x.current=null,u(!1),!0);t.finished.then(()=>{release()&&m(0)},e=>{release()&&(l(!0),Logger.error("[chat] voice clip playback failed",e))})},v=t.features.VoiceClips,b=null!==e.transcript&&""!==e.transcript?e.transcript:null,w=e.durationMs>0?Math.min(1,Math.max(0,p/e.durationMs)):0,g=useMemo(()=>voiceClipBars(e.attachmentId,40).map((e,t)=>({id:`bar-${t}`,position:t,level:e})),[e.attachmentId]);return _jsxs(View,{accessibilityRole:"summary",accessibilityLabel:a.voiceClip,testID:"chat-voice-clip",style:i.root,children:[v?_jsxs(View,{style:i.row,children:[_jsx(IconButton,{icon:n?"pause":"play",accessibilityLabel:n?a.voiceClipPause:a.voiceClipPlay,variant:"ghost",tone:"neutral",size:"sm",loading:o,disabled:o,onPress:()=>{const r=x.current;null===r?null===y.current?o||(async()=>{s(!0),l(!1);try{const r=new Uint8Array(await t.readAttachment(e.attachmentId)),{File:i,Paths:a}=expoFileSystem(),o=new i(a.cache,`wchat-clip-${e.attachmentId}${audioExtension(r)}`);if(o.create({overwrite:!0}),o.write(r),!f.current)return void discardFile(o.uri);y.current=o.uri,startPlayback(o.uri)}catch(e){if(!f.current)return;l(!0),Logger.error("[chat] voice clip failed to load",e)}finally{f.current&&s(!1)}})():startPlayback(y.current):n?r.pause():r.resume()},testID:"chat-voice-clip-play"}),_jsx(View,{style:i.wave,children:g.map(e=>_jsx(View,{testID:"chat-voice-clip-bar",style:[i.bar,{height:Math.max(4,Math.round(28*e.level)),backgroundColor:e.position<Math.floor(40*w)?r.colors.primary:r.colors["text-subtle"]}]},e.id))}),_jsx(Text,{variant:"caption",color:"secondary",children:a.voiceClipTime(formatClipTime(p),formatClipTime(e.durationMs))})]}):null,v&&null!==b?_jsxs(_Fragment,{children:[_jsx(Button,{label:h?a.voiceClipHideTranscript:a.voiceClipShowTranscript,variant:"link",size:"sm",accessibilityState:{expanded:h},onPress:()=>d(e=>!e),testID:"chat-voice-clip-transcript-toggle"}),h?_jsx(Text,{variant:"body",children:b}):null]}):null,v||null===b?null:_jsx(Text,{variant:"body",children:b}),c?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:a.voiceClipFailed}):null]})}const buildStyles=e=>StyleSheet.create({root:{gap:e.space.xs},row:{flexDirection:"row",alignItems:"center",gap:e.space.xs},wave:{flexDirection:"row",alignItems:"center",gap:e.space.xxs},bar:{width:3}});
1
+ "use strict";import{voiceClipBars}from"@webority/chat-core";import{Logger}from"@webority/mobile-core";import{Button,IconButton,Text,useTheme}from"@webority/mobile-ui";import{useEffect,useMemo,useRef,useState}from"react";import{StyleSheet,View}from"react-native";import{loadExpoFileSystem}from"../expoModules.js";import{playFile}from"../speech/expoAudio.js";import{discardFile,PhoneSpeechError}from"../speech/phoneSpeech.js";import{audioExtension,formatClipTime}from"../speech/speechText.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const expoFileSystem=()=>{try{return loadExpoFileSystem()}catch{throw new PhoneSpeechError("Unavailable","Unavailable","Voice files are not available in this app.")}};export function VoiceClipPart({part:e,turn:t}){const r=useTheme(),i=useMemo(()=>buildStyles(r),[r]),a=t.labels,[o,s]=useState(!1),[l,c]=useState(!1),[n,u]=useState(!1),[p,m]=useState(0),[h,d]=useState(!1),x=useRef(null),y=useRef(null),f=useRef(!0);useEffect(()=>(f.current=!0,()=>{f.current=!1,x.current?.stop(),x.current=null,null!==y.current&&discardFile(y.current)}),[]);const startPlayback=e=>{const t=playFile(e,e=>{f.current&&(m(e.positionMs),u(e.playing))});x.current=t;const release=()=>!(!f.current||x.current!==t)&&(x.current=null,u(!1),!0);t.finished.then(()=>{release()&&m(0)},e=>{release()&&(c(!0),Logger.error("[chat] voice clip playback failed",e))})},v=t.features.VoiceClips,b=null!==e.transcript&&""!==e.transcript?e.transcript:null,w=e.durationMs>0?Math.min(1,Math.max(0,p/e.durationMs)):0,g=useMemo(()=>voiceClipBars(e.attachmentId,40).map((e,t)=>({id:`bar-${t}`,position:t,level:e})),[e.attachmentId]);return _jsxs(View,{accessibilityRole:"summary",accessibilityLabel:a.voiceClip,testID:"chat-voice-clip",style:i.root,children:[v?_jsxs(View,{style:i.row,children:[_jsx(IconButton,{icon:n?"pause":"play",accessibilityLabel:n?a.voiceClipPause:a.voiceClipPlay,variant:"ghost",tone:"neutral",size:"sm",loading:o,disabled:o,onPress:()=>{const r=x.current;null===r?null===y.current?o||(async()=>{s(!0),c(!1);try{const r=new Uint8Array(await t.readAttachment(e.attachmentId)),{File:i,Paths:a}=expoFileSystem(),o=new i(a.cache,`wchat-clip-${e.attachmentId}${audioExtension(r)}`);if(o.create({overwrite:!0}),o.write(r),!f.current)return void discardFile(o.uri);y.current=o.uri,startPlayback(o.uri)}catch(e){if(!f.current)return;c(!0),Logger.error("[chat] voice clip failed to load",e)}finally{f.current&&s(!1)}})():startPlayback(y.current):n?r.pause():r.resume()},testID:"chat-voice-clip-play"}),_jsx(View,{style:i.wave,children:g.map(e=>_jsx(View,{testID:"chat-voice-clip-bar",style:[i.bar,{height:Math.max(4,Math.round(28*e.level)),backgroundColor:e.position<Math.floor(40*w)?r.colors.primary:r.colors["text-subtle"]}]},e.id))}),_jsx(Text,{variant:"caption",color:"secondary",children:a.voiceClipTime(formatClipTime(p),formatClipTime(e.durationMs))})]}):null,v&&null!==b?_jsxs(_Fragment,{children:[_jsx(Button,{label:h?a.voiceClipHideTranscript:a.voiceClipShowTranscript,variant:"link",size:"sm",accessibilityState:{expanded:h},onPress:()=>d(e=>!e),testID:"chat-voice-clip-transcript-toggle"}),h?_jsx(Text,{variant:"body",children:b}):null]}):null,v||null===b?null:_jsx(Text,{variant:"body",children:b}),l?_jsx(Text,{variant:"caption",color:"danger",accessibilityLiveRegion:"polite",children:a.voiceClipFailed}):null]})}const buildStyles=e=>StyleSheet.create({root:{gap:e.space.xs},row:{flexDirection:"row",alignItems:"center",gap:e.space.xs},wave:{flexDirection:"row",alignItems:"center",gap:e.space.xxs},bar:{width:3}});
@@ -1 +1 @@
1
- "use strict";import{ChatSpeechError}from"@webority/chat-core";import{fetchWithRetry}from"@webority/mobile-core";import{buildSsml,clampSpeakText}from"./speechText.js";const TRANSCRIBE_API_VERSION="2024-11-15",TTS_OUTPUT_FORMAT="audio-24khz-48kbitrate-mono-mp3",REQUEST_TIMEOUT_MS=15e3,REGION_PATTERN=/^[a-z0-9]+$/,SPEECH_RETRY={sideEffectFree:!0};export class SpeechRequestError extends Error{constructor(e){super(`Speech request failed with status ${e}`),this.name="SpeechRequestError",this.status=e}}const assertRegion=e=>{if(!REGION_PATTERN.test(e))throw new ChatSpeechError("Unavailable","Speech is not available.")},withTimeout=async(e,t)=>{const r=new AbortController,abort=()=>r.abort(),o=setTimeout(abort,15e3);e?.aborted&&r.abort(),e?.addEventListener("abort",abort);try{return await t(r.signal)}finally{clearTimeout(o),e?.removeEventListener("abort",abort)}};export async function transcribeClip(e){const{token:t,uri:r,language:o,signal:i,fetchImpl:a=fetch}=e;assertRegion(t.region);const n=new FormData;return n.append("audio",{uri:r,name:"dictation.m4a",type:"audio/mp4"}),n.append("definition",JSON.stringify({locales:[o]})),withTimeout(i,async e=>{const r=await fetchWithRetry(a,`https://${t.region}.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2024-11-15`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`},body:n,signal:e},SPEECH_RETRY);if(!r.ok)throw new SpeechRequestError(r.status);const o=await r.json();if(!Array.isArray(o.combinedPhrases))throw new ChatSpeechError("Unavailable","Speech is not available.");return o.combinedPhrases.map(e=>e.text??"").join(" ").trim()})}export async function synthesizeSpeech(e){const{token:t,text:r,language:o,voice:i,signal:a,fetchImpl:n=fetch}=e;return assertRegion(t.region),withTimeout(a,async e=>{const a=await fetchWithRetry(n,`https://${t.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":TTS_OUTPUT_FORMAT,"User-Agent":"webority-chat"},body:buildSsml(clampSpeakText(r),o,i),signal:e},SPEECH_RETRY);if(!a.ok)throw new SpeechRequestError(a.status);return new Uint8Array(await a.arrayBuffer())})}
1
+ "use strict";import{ChatSpeechError}from"@webority/chat-core";import{fetchWithRetry}from"@webority/mobile-core";import{buildSsml,clampSpeakText}from"./speechText.js";const TRANSCRIBE_API_VERSION="2024-11-15",TTS_OUTPUT_FORMAT="audio-24khz-48kbitrate-mono-mp3",REQUEST_TIMEOUT_MS=15e3,REGION_PATTERN=/^[a-z0-9]+$/,SPEECH_RETRY={sideEffectFree:!0};export class SpeechRequestError extends Error{constructor(e){super(`Speech request failed with status ${e}`),this.name="SpeechRequestError",this.status=e}}const isUnknownArray=e=>Array.isArray(e),readTranscription=e=>{const t="object"==typeof e&&null!==e&&"combinedPhrases"in e?e.combinedPhrases:void 0;if(!isUnknownArray(t))throw new Error("Azure Speech returned no combinedPhrases.");return{combinedPhrases:t.map(e=>({text:"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text?e.text:""}))}},assertRegion=e=>{if(!REGION_PATTERN.test(e))throw new ChatSpeechError("Unavailable","Speech is not available.")},withTimeout=async(e,t)=>{const r=new AbortController,abort=()=>r.abort(),o=setTimeout(abort,15e3);e?.aborted&&r.abort(),e?.addEventListener("abort",abort);try{return await t(r.signal)}finally{clearTimeout(o),e?.removeEventListener("abort",abort)}};export async function transcribeClip(e){const{token:t,uri:r,language:o,signal:i,fetchImpl:n=fetch}=e;assertRegion(t.region);const a=new FormData;return a.append("audio",{uri:r,name:"dictation.m4a",type:"audio/mp4"}),a.append("definition",JSON.stringify({locales:[o]})),withTimeout(i,async e=>{const r=await fetchWithRetry(n,`https://${t.region}.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2024-11-15`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`},body:a,signal:e},SPEECH_RETRY);if(!r.ok)throw new SpeechRequestError(r.status);const o=await r.json();return readTranscription(o).combinedPhrases.map(e=>e.text).join(" ").trim()})}export async function synthesizeSpeech(e){const{token:t,text:r,language:o,voice:i,signal:n,fetchImpl:a=fetch}=e;return assertRegion(t.region),withTimeout(n,async e=>{const n=await fetchWithRetry(a,`https://${t.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":TTS_OUTPUT_FORMAT,"User-Agent":"webority-chat"},body:buildSsml(clampSpeakText(r),o,i),signal:e},SPEECH_RETRY);if(!n.ok)throw new SpeechRequestError(n.status);return new Uint8Array(await n.arrayBuffer())})}
@@ -1 +1 @@
1
- "use strict";import{ChatSpeechError}from"@webority/chat-core";import{Logger}from"@webority/mobile-core";const expoAudio=()=>require("expo-audio"),expoFileSystem=()=>{try{return require("expo-file-system")}catch{throw new ChatSpeechError("Unavailable","Voice files are not available in this app.")}},RECORDING_OPTIONS={sampleRate:16e3,numberOfChannels:1,bitRate:48e3},setRecordingMode=e=>expoAudio().setAudioModeAsync({allowsRecording:e,playsInSilentMode:!0});export async function startRecording(){const e=expoAudio();await setRecordingMode(!0);const t=new e.AudioModule.AudioRecorder({...e.RecordingPresets.HIGH_QUALITY,...RECORDING_OPTIONS});let o=0;try{await t.prepareToRecordAsync(),o=Date.now(),t.record()}catch(e){throw await setRecordingMode(!1),e}return{async stop(){try{await t.stop();const e=t.uri;if(null===e)throw new Error("The recorder finished without a file.");const i=t.getStatus().durationMillis;return{uri:e,durationMs:i>0?i:Date.now()-o}}finally{await setRecordingMode(!1)}},async cancel(){try{t.isRecording&&await t.stop();const e=t.uri;if(null!==e){const{File:t}=expoFileSystem();try{new t(e).delete()}catch(e){Logger.warn("Removing a cancelled recording failed:",e)}}}finally{await setRecordingMode(!1)}}}}let active=null;export function playFile(e,t){active?.stop();let o=null,i=null,r=!1,resolveFinished=()=>{},rejectFinished=()=>{};const n=new Promise((e,t)=>{resolveFinished=e,rejectFinished=t}),release=()=>{i?.remove(),i=null,null!==o&&(o.pause(),o.remove(),o=null),active===a&&(active=null)},a={finished:n,pause:()=>o?.pause(),resume:()=>o?.play(),stop:()=>{r||(r=!0,release(),resolveFinished())}};active=a;const l=expoAudio();return l.setAudioModeAsync({playsInSilentMode:!0,allowsRecording:!1}).then(()=>{if(r)return;const n=l.createAudioPlayer({uri:e});o=n,i=n.addListener("playbackStatusUpdate",e=>{t?.({positionMs:1e3*e.currentTime,durationMs:e.duration>0?1e3*e.duration:null,playing:e.playing}),e.didJustFinish&&(r=!0,release(),resolveFinished())}),n.play()}).catch(e=>{r||(r=!0,release(),rejectFinished(e))}),a}
1
+ "use strict";import{ChatSpeechError}from"@webority/chat-core";import{Logger}from"@webority/mobile-core";import{loadExpoAudio,loadExpoFileSystem}from"../expoModules.js";const expoFileSystem=()=>{try{return loadExpoFileSystem()}catch(e){throw Logger.warn("[chat] expo-file-system could not be loaded",e),new ChatSpeechError("Unavailable","Voice files are not available in this app.")}},RECORDING_OPTIONS={sampleRate:16e3,numberOfChannels:1,bitRate:48e3},setRecordingMode=e=>loadExpoAudio().setAudioModeAsync({allowsRecording:e,playsInSilentMode:!0});export async function startRecording(){const e=loadExpoAudio();await setRecordingMode(!0);const o=new e.AudioModule.AudioRecorder({...e.RecordingPresets.HIGH_QUALITY,...RECORDING_OPTIONS});let t=0;try{await o.prepareToRecordAsync(),t=Date.now(),o.record()}catch(e){throw await setRecordingMode(!1),e}return{async stop(){try{await o.stop();const e=o.uri;if(null===e)throw new Error("The recorder finished without a file.");const i=o.getStatus().durationMillis;return{uri:e,durationMs:i>0?i:Date.now()-t}}finally{await setRecordingMode(!1)}},async cancel(){try{o.isRecording&&await o.stop();const e=o.uri;if(null!==e){const{File:o}=expoFileSystem();try{new o(e).delete()}catch(e){Logger.warn("Removing a cancelled recording failed:",e)}}}finally{await setRecordingMode(!1)}}}}let active=null;export function playFile(e,o){active?.stop();let t=null,i=null,r=!1,resolveFinished=()=>{},rejectFinished=()=>{};const a=new Promise((e,o)=>{resolveFinished=e,rejectFinished=o}),release=()=>{i?.remove(),i=null,null!==t&&(t.pause(),t.remove(),t=null),active===n&&(active=null)},n={finished:a,pause:()=>t?.pause(),resume:()=>t?.play(),stop:()=>{r||(r=!0,release(),resolveFinished())}};active=n;const l=loadExpoAudio();return l.setAudioModeAsync({playsInSilentMode:!0,allowsRecording:!1}).then(()=>{if(r)return;const a=l.createAudioPlayer({uri:e});t=a,i=a.addListener("playbackStatusUpdate",e=>{o?.({positionMs:1e3*e.currentTime,durationMs:e.duration>0?1e3*e.duration:null,playing:e.playing}),e.didJustFinish&&(r=!0,release(),resolveFinished())}),a.play()}).catch(e=>{r||(r=!0,release(),rejectFinished(e))}),n}