-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatScreen.tsx
More file actions
521 lines (493 loc) · 15.3 KB
/
ChatScreen.tsx
File metadata and controls
521 lines (493 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import React, { useState, useEffect, useRef, useCallback } from 'react'
import {
View,
Text,
FlatList,
TextInput,
TouchableOpacity,
ActivityIndicator,
KeyboardAvoidingView,
Platform,
type ViewStyle,
type ListRenderItem,
} from 'react-native'
import { Send, FileText, LifeBuoy } from 'lucide-react-native'
import Markdown from 'react-native-markdown-display'
import { useAppgramContext, useAppgramTheme } from '../../provider'
export interface ChatSource {
article_id: string
title: string
slug: string
similarity: number
flow_slug?: string
flow_id?: string
/** Source type - determines routing behavior */
type?: 'help_article' | 'blog_post'
}
interface ChatMessage {
id: string
content: string
sender: 'agent' | 'user'
timestamp: string
sources?: ChatSource[]
showSupportBanner?: boolean
}
interface QuickOption {
label: string
value?: string
}
export interface ChatScreenProps {
/** Name of the chat agent */
agentName?: string
/** Initial greeting message */
greeting?: string
/** Subtitle shown below greeting */
subtitle?: string
/** Quick reply options shown initially */
options?: QuickOption[]
/** Accent color override */
accentColor?: string
/**
* Callback when an article source is tapped.
* Provides the article slug and full source data for flexible routing.
*
* @example
* ```tsx
* // Simple slug-based routing
* onArticlePress={(slug) => navigation.navigate('HelpArticle', { slug })}
*
* // Using flow context for nested routes
* onArticlePress={(slug, source) => {
* if (source.flow_slug) {
* navigation.navigate('HelpArticle', { flowSlug: source.flow_slug, slug })
* } else {
* navigation.navigate('HelpArticle', { slug })
* }
* }}
* ```
*/
onArticlePress?: (slug: string, source: ChatSource) => void
/** Callback when support button is tapped */
onSupportPress?: () => void
/** Custom style for container */
style?: ViewStyle
/** Input placeholder text */
placeholder?: string
}
/**
* ChatScreen Component
*
* Full-screen AI-powered chat for help center integration.
* Queries the help center API and displays responses with sources.
*
* @example
* ```tsx
* import { ChatScreen } from '@appgram/react-native'
*
* function HelpChatScreen({ navigation }) {
* return (
* <ChatScreen
* agentName="Support Bot"
* greeting="Hi there!"
* subtitle="How can I help you today?"
* options={[
* { label: 'I need help getting started' },
* { label: 'I have a billing question' },
* ]}
* onArticlePress={(slug, articleId) => {
* navigation.navigate('HelpArticle', { slug })
* }}
* onSupportPress={() => navigation.navigate('Support')}
* />
* )
* }
* ```
*
* @example
* ```tsx
* // With custom accent color
* <ChatScreen
* accentColor="#6366F1"
* placeholder="Type your question..."
* onSupportPress={() => setShowSupport(true)}
* />
* ```
*/
export function ChatScreen({
agentName = 'Help Assistant',
greeting = 'Hello',
subtitle = 'How can I help you today?',
options = [
{ label: 'I need help getting started' },
{ label: 'I have a question' },
{ label: 'Just browsing' },
],
accentColor,
onArticlePress,
onSupportPress,
style,
placeholder = 'Ask a question...',
}: ChatScreenProps): React.ReactElement {
const { config, client } = useAppgramContext()
const { colors, radius, typography, spacing } = useAppgramTheme()
const accent = accentColor || colors.primary
const [messages, setMessages] = useState<ChatMessage[]>([])
const [inputValue, setInputValue] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [showOptions, setShowOptions] = useState(true)
const flatListRef = useRef<FlatList>(null)
// Initial greeting message
useEffect(() => {
setMessages([
{
id: 'greeting',
content: `${greeting}\n${subtitle}`,
sender: 'agent',
timestamp: 'now',
},
])
}, [greeting, subtitle])
const scrollToEnd = useCallback(() => {
setTimeout(() => {
flatListRef.current?.scrollToEnd({ animated: true })
}, 100)
}, [])
useEffect(() => {
scrollToEnd()
}, [messages, scrollToEnd])
const askQuestion = async (query: string): Promise<{ answer: string; sources: ChatSource[]; showSupport: boolean }> => {
const response = await fetch(`${config.apiUrl}/portal/help/ask`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ project_id: config.projectId, query }),
})
const data = await response.json()
if (data.success) {
return {
answer: data.data.answer,
sources: data.data.sources || [],
showSupport: data.data.show_user_support || false,
}
}
throw new Error('Failed to get response')
}
const sendMessage = async (text: string) => {
if (!text.trim() || isLoading) return
setShowOptions(false)
const query = text.trim()
setInputValue('')
const userMessage: ChatMessage = {
id: Date.now().toString(),
content: query,
sender: 'user',
timestamp: 'now',
}
setMessages(prev => [...prev, userMessage])
setIsLoading(true)
try {
const { answer, sources, showSupport } = await askQuestion(query)
setMessages(prev => [
...prev,
{
id: (Date.now() + 1).toString(),
content: answer,
sender: 'agent',
timestamp: 'now',
sources,
showSupportBanner: showSupport,
},
])
} catch {
setMessages(prev => [
...prev,
{
id: (Date.now() + 1).toString(),
content: "Sorry, I couldn't process that request. Please try again.",
sender: 'agent',
timestamp: 'now',
},
])
}
setIsLoading(false)
}
const handleOptionPress = (option: QuickOption) => {
sendMessage(option.value || option.label)
}
const handleSourcePress = (source: ChatSource) => {
onArticlePress?.(source.slug, source)
}
const renderMessage: ListRenderItem<ChatMessage> = ({ item }) => {
const isUser = item.sender === 'user'
if (isUser) {
return (
<View
style={{
alignSelf: 'flex-end',
maxWidth: '85%',
marginBottom: spacing.md,
backgroundColor: accent,
borderRadius: radius.lg,
borderTopRightRadius: radius.sm,
padding: spacing.md,
}}
>
<Text style={{ fontSize: typography.sm, color: '#FFF' }}>
{item.content}
</Text>
</View>
)
}
return (
<View
style={{
flexDirection: 'row',
alignItems: 'flex-start',
marginBottom: spacing.md,
maxWidth: '90%',
}}
>
<View
style={{
width: 32,
height: 32,
borderRadius: radius.md,
backgroundColor: accent + '20',
alignItems: 'center',
justifyContent: 'center',
marginRight: spacing.sm,
}}
>
<Text style={{ fontSize: typography.sm, fontWeight: '600', color: accent }}>
{agentName.charAt(0)}
</Text>
</View>
<View style={{ flexShrink: 1 }}>
<Markdown
style={{
body: { fontSize: typography.sm, color: colors.foreground, lineHeight: 22 },
paragraph: { marginTop: 0, marginBottom: 8 },
strong: { fontWeight: '600' },
link: { color: accent },
code_inline: { backgroundColor: colors.muted, paddingHorizontal: 4, borderRadius: 4, fontSize: typography.xs },
code_block: { backgroundColor: colors.muted, padding: spacing.sm, borderRadius: radius.md, fontSize: typography.xs },
bullet_list: { marginVertical: 4 },
ordered_list: { marginVertical: 4 },
list_item: { marginVertical: 2 },
}}
>
{item.content}
</Markdown>
{/* Sources */}
{item.sources && item.sources.length > 0 && (
<View style={{ marginTop: spacing.sm }}>
<Text style={{ fontSize: typography.xs, color: colors.mutedForeground, marginBottom: spacing.xs }}>
Related articles
</Text>
{item.sources.map(source => (
<TouchableOpacity
key={source.article_id}
onPress={() => handleSourcePress(source)}
style={{
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 4,
}}
>
<FileText size={14} color={accent} style={{ marginRight: spacing.xs }} />
<Text
style={{ fontSize: typography.xs, color: accent, flexShrink: 1 }}
numberOfLines={1}
>
{source.title}
</Text>
</TouchableOpacity>
))}
</View>
)}
{/* Support Banner */}
{item.showSupportBanner && onSupportPress && (
<View
style={{
marginTop: spacing.md,
padding: spacing.md,
borderRadius: radius.lg,
backgroundColor: '#F9731615',
borderWidth: 1,
borderColor: '#F9731630',
}}
>
<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
<View
style={{
width: 32,
height: 32,
borderRadius: radius.md,
backgroundColor: '#F97316',
alignItems: 'center',
justifyContent: 'center',
marginRight: spacing.sm,
}}
>
<LifeBuoy size={16} color="#FFF" />
</View>
<View style={{ flexShrink: 1 }}>
<Text style={{ fontSize: typography.sm, fontWeight: '600', color: colors.foreground }}>
Need more help?
</Text>
<Text style={{ fontSize: typography.xs, color: colors.mutedForeground, marginTop: 2 }}>
Our support team is here to assist you.
</Text>
<TouchableOpacity
onPress={onSupportPress}
style={{
marginTop: spacing.sm,
backgroundColor: '#EA580C',
paddingVertical: spacing.xs,
paddingHorizontal: spacing.md,
borderRadius: radius.md,
alignSelf: 'flex-start',
}}
>
<Text style={{ fontSize: typography.xs, fontWeight: '600', color: '#FFF' }}>
Contact Support
</Text>
</TouchableOpacity>
</View>
</View>
</View>
)}
</View>
</View>
)
}
const renderQuickOptions = () => {
if (!showOptions || messages.length > 1) return null
return (
<View style={{ marginLeft: 32 + spacing.sm }}>
{options.map((option, index) => (
<TouchableOpacity
key={index}
onPress={() => handleOptionPress(option)}
style={{
backgroundColor: colors.card,
borderRadius: radius.lg,
padding: spacing.md,
borderWidth: 1,
borderColor: colors.border,
marginBottom: spacing.sm,
}}
>
<Text style={{ fontSize: typography.sm, color: colors.foreground }}>
{option.label}
</Text>
</TouchableOpacity>
))}
</View>
)
}
const renderLoading = () => {
if (!isLoading) return null
return (
<View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: spacing.md }}>
<View
style={{
width: 32,
height: 32,
borderRadius: radius.md,
backgroundColor: accent + '20',
alignItems: 'center',
justifyContent: 'center',
marginRight: spacing.sm,
}}
>
<Text style={{ fontSize: typography.sm, fontWeight: '600', color: accent }}>
{agentName.charAt(0)}
</Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<ActivityIndicator size="small" color={colors.mutedForeground} />
<Text style={{ fontSize: typography.xs, color: colors.mutedForeground, marginLeft: 8 }}>
Thinking...
</Text>
</View>
</View>
)
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={[{ flex: 1, backgroundColor: colors.background }, style]}
keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
>
<FlatList
ref={flatListRef}
data={messages}
renderItem={renderMessage}
keyExtractor={item => item.id}
contentContainerStyle={{ paddingTop: spacing.md, paddingBottom: spacing.lg, paddingHorizontal: spacing.md }}
ListFooterComponent={
<>
{renderQuickOptions()}
{renderLoading()}
</>
}
showsVerticalScrollIndicator={false}
/>
{/* Input Area */}
<View
style={{
flexDirection: 'row',
alignItems: 'center',
padding: spacing.md,
paddingBottom: spacing.md + (Platform.OS === 'ios' ? 20 : 0),
borderTopWidth: 1,
borderTopColor: colors.border,
backgroundColor: colors.card,
}}
>
<TextInput
value={inputValue}
onChangeText={setInputValue}
placeholder={placeholder}
placeholderTextColor={colors.mutedForeground}
editable={!isLoading}
multiline
style={{
flex: 1,
backgroundColor: colors.background,
borderRadius: radius.lg,
paddingHorizontal: spacing.md,
paddingVertical: spacing.md,
fontSize: typography.sm,
color: colors.foreground,
minHeight: 48,
maxHeight: 100,
borderWidth: 1,
borderColor: colors.border,
marginRight: spacing.sm,
}}
onSubmitEditing={() => sendMessage(inputValue)}
blurOnSubmit={false}
/>
<TouchableOpacity
onPress={() => sendMessage(inputValue)}
disabled={!inputValue.trim() || isLoading}
style={{
width: 44,
height: 44,
borderRadius: 22,
backgroundColor: inputValue.trim() && !isLoading ? accent : colors.muted,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Send size={18} color={inputValue.trim() && !isLoading ? '#FFF' : colors.mutedForeground} />
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
)
}
export default ChatScreen