@shotik/react-native 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sheet.tsx ADDED
@@ -0,0 +1,538 @@
1
+ // The chat sheet: a bottom sheet (drag handle, spring open and close, keyboard-avoiding) holding the conversation list
2
+ // or one thread with receipts, typing, quick replies, the handoff to a person, attachments and the offline queue.
3
+ // Every visual and motion decision is logged in REFS.md.
4
+
5
+ import { memo, useEffect, useMemo, useRef, useState } from 'react'
6
+ import {
7
+ AccessibilityInfo, ActionSheetIOS, Animated, Dimensions, FlatList, Image, Keyboard, LayoutAnimation, Modal, PanResponder, Platform, Pressable,
8
+ StatusBar, StyleSheet, TextInput, View, useWindowDimensions
9
+ } from 'react-native'
10
+ import type { KeyboardEvent } from 'react-native'
11
+ import type { Conversation, LocalAttachment, Message, Receipt } from './client'
12
+ import { attachmentsOf, receiptOf } from './client'
13
+ import { ArrowUp, Avatar, Chevron, Clock, Cross, Dots, Plus, Spark, T, attachPeers, captureScreen, font, motion, pickPhoto, useReduceMotion } from './parts'
14
+ import type { SupportApi } from './react'
15
+ import type { Copy, Resolved } from './theme'
16
+ import { fill } from './theme'
17
+
18
+ export interface SheetProps {
19
+ s: SupportApi
20
+ c: Resolved
21
+ t: Copy
22
+ title: string
23
+ team: string
24
+ quickReplies: string[]
25
+ // 'inline' renders the panel at the parent's size, without Modal, backdrop, drag or open animation.
26
+ presentation?: 'modal' | 'inline'
27
+ }
28
+
29
+ function insets(): { top: number; bottom: number } {
30
+ try {
31
+ const m = require('react-native-safe-area-context')?.initialWindowMetrics?.insets
32
+ if (m) return { top: m.top, bottom: m.bottom }
33
+ } catch {}
34
+ return Platform.OS === 'ios' ? { top: 50, bottom: 20 } : { top: StatusBar.currentHeight ?? 24, bottom: 0 }
35
+ }
36
+
37
+ const clock = (at: number) => {
38
+ const d = new Date(at)
39
+ return new Date().toDateString() === d.toDateString() ? d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : d.toLocaleDateString([], { month: 'short', day: 'numeric' })
40
+ }
41
+
42
+ export function Sheet({ s, c, t, title, team, quickReplies, presentation = 'modal' }: SheetProps) {
43
+ const inline = presentation === 'inline'
44
+ const { height } = useWindowDimensions()
45
+ const inset = useMemo(insets, [])
46
+ const H = Math.round(height - inset.top - 10)
47
+ const reduce = useReduceMotion()
48
+ const [shown, setShown] = useState(false)
49
+ const y = useRef(new Animated.Value(H)).current
50
+ const fade = useRef(new Animated.Value(0)).current
51
+ const [composing, setComposing] = useState(false)
52
+ const [draft, setDraft] = useState('')
53
+ const [pending, setPending] = useState<LocalAttachment[]>([])
54
+
55
+ const animate = (open: boolean, done?: () => void) => {
56
+ const slide = reduce
57
+ ? Animated.timing(y, { toValue: open ? 0 : H, duration: 0, useNativeDriver: true })
58
+ : Animated.spring(y, { toValue: open ? 0 : H, useNativeDriver: true, ...motion.sheet, overshootClamping: !open, restDisplacementThreshold: 0.5, restSpeedThreshold: 0.5 })
59
+ Animated.parallel([Animated.timing(fade, { toValue: open ? 1 : 0, duration: open ? 260 : 200, useNativeDriver: true }), slide]).start(({ finished }) => finished && done?.())
60
+ }
61
+
62
+ useEffect(() => {
63
+ if (inline) return
64
+ if (s.visible) {
65
+ setShown(true)
66
+ y.setValue(H)
67
+ requestAnimationFrame(() => animate(true))
68
+ } else if (shown) {
69
+ Keyboard.dismiss()
70
+ animate(false, () => setShown(false))
71
+ }
72
+ }, [s.visible])
73
+
74
+ const pan = useMemo(
75
+ () =>
76
+ PanResponder.create({
77
+ onMoveShouldSetPanResponder: (_, g) => g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx),
78
+ onPanResponderMove: (_, g) => y.setValue(Math.max(0, g.dy)),
79
+ onPanResponderRelease: (_, g) => (g.dy > 120 || g.vy > 1 ? s.close() : animate(true)),
80
+ onPanResponderTerminate: () => animate(true)
81
+ }),
82
+ [s.close, H, reduce]
83
+ )
84
+
85
+ // Screenshot of the app: the sheet steps aside, the screen is captured, the sheet comes back with the image attached.
86
+ const screenshot = () => {
87
+ Keyboard.dismiss()
88
+ animate(false, () =>
89
+ setTimeout(() => {
90
+ captureScreen()
91
+ .then((a) => a && setPending((p) => [...p, a]))
92
+ .catch(() => {})
93
+ .finally(() => animate(true))
94
+ }, 120)
95
+ )
96
+ }
97
+
98
+ const active = s.activeConversationId ? s.conversations.find((x) => x.id === s.activeConversationId) ?? null : null
99
+ const inThread = !!s.activeConversationId || composing || s.conversations.length === 0
100
+ const back = () => {
101
+ setComposing(false)
102
+ s.select(null)
103
+ }
104
+ const queued = Object.values(s.messages).reduce((n, l) => n + l.filter((m) => m.pending && m.pending !== 'failed').length, 0)
105
+ const status =
106
+ s.status === 'live' ? { color: c.ok, text: t.online }
107
+ : s.status === 'offline' ? { color: c.danger, text: queued ? t.offline + ' · ' + fill(t.queuedN, { n: queued }) : t.offline }
108
+ : s.status === 'error' ? { color: c.danger, text: t.error + ' · ' + t.retry }
109
+ : { color: c.faint, text: t.connecting }
110
+
111
+ const bottom = inline ? 0 : inset.bottom
112
+ const body = (
113
+ <>
114
+ <View {...(inline ? {} : pan.panHandlers)}>
115
+ <View style={[st.grabber, { backgroundColor: c.line }]} />
116
+ <View style={st.header}>
117
+ {inThread && s.conversations.length > 0 ? (
118
+ <Pressable onPress={back} hitSlop={10} accessibilityRole="button" accessibilityLabel={t.back} style={st.back}>
119
+ <Chevron color={c.text} />
120
+ </Pressable>
121
+ ) : null}
122
+ <Avatar c={c} label={title} size={32} />
123
+ <View style={st.fill}>
124
+ <T c={c} bold style={st.title} numberOfLines={1} accessibilityRole="header">{title}</T>
125
+ <Pressable disabled={s.status !== 'error'} onPress={() => s.identify()} style={st.statusRow} accessibilityRole={s.status === 'error' ? 'button' : undefined} accessibilityLiveRegion="polite">
126
+ <View style={[st.dot, { backgroundColor: status.color }]} />
127
+ <T c={c} style={[st.status, { color: c.sub }]} numberOfLines={1}>{status.text}</T>
128
+ </Pressable>
129
+ </View>
130
+ <Pressable onPress={s.close} hitSlop={10} accessibilityRole="button" accessibilityLabel={t.close} style={[st.close, { backgroundColor: c.raised }]}>
131
+ <Cross color={c.sub} size={9} />
132
+ </Pressable>
133
+ </View>
134
+ </View>
135
+ <View style={[st.hair, { backgroundColor: c.line }]} />
136
+ {inThread ? (
137
+ <Thread
138
+ s={s} c={c} t={t} team={team} conversation={active} quickReplies={quickReplies} reduce={reduce} inset={bottom}
139
+ draft={draft} setDraft={setDraft} pending={pending} setPending={setPending} onScreenshot={screenshot}
140
+ onSent={() => setComposing(false)}
141
+ />
142
+ ) : (
143
+ <List s={s} c={c} t={t} inset={bottom} onNew={() => setComposing(true)} />
144
+ )}
145
+ </>
146
+ )
147
+ if (inline) return <View style={[st.fill, { backgroundColor: c.bg }]}>{body}</View>
148
+ return (
149
+ <Modal visible={shown} transparent animationType="none" statusBarTranslucent onRequestClose={s.close}>
150
+ <Animated.View style={[StyleSheet.absoluteFill, { backgroundColor: c.backdrop, opacity: fade }]}>
151
+ <Pressable style={st.fill} onPress={s.close} accessibilityLabel={t.close} />
152
+ </Animated.View>
153
+ <Animated.View
154
+ accessibilityViewIsModal
155
+ style={[st.sheet, { height: H, backgroundColor: c.bg, borderTopStartRadius: c.radius + 10, borderTopEndRadius: c.radius + 10, opacity: reduce ? fade : 1, transform: [{ translateY: y }] }]}
156
+ >
157
+ {body}
158
+ </Animated.View>
159
+ </Modal>
160
+ )
161
+ }
162
+
163
+ function List({ s, c, t, inset, onNew }: { s: SupportApi; c: Resolved; t: Copy; inset: number; onNew: () => void }) {
164
+ return (
165
+ <View style={st.fill}>
166
+ <FlatList
167
+ data={s.conversations}
168
+ keyExtractor={(x) => x.id}
169
+ contentContainerStyle={st.listPad}
170
+ renderItem={({ item }) => <ConvRow c={c} t={t} conv={item} unread={!!s.unreadBy[item.id]} onPress={() => s.select(item.id)} />}
171
+ />
172
+ <View style={[st.footer, { paddingBottom: 12 + inset }]}>
173
+ <Pressable onPress={onNew} accessibilityRole="button" style={({ pressed }) => [st.cta, { backgroundColor: c.accent, opacity: pressed ? 0.85 : 1 }]}>
174
+ <Plus color={c.onAccent} />
175
+ <T c={c} bold style={[st.ctaText, { color: c.onAccent }]}>{t.newMessage}</T>
176
+ </Pressable>
177
+ </View>
178
+ </View>
179
+ )
180
+ }
181
+
182
+ const ConvRow = memo(function ConvRow({ c, t, conv, unread, onPress }: { c: Resolved; t: Copy; conv: Conversation; unread: boolean; onPress: () => void }) {
183
+ const pill = conv.status === 'needs_human' ? { text: t.person, color: c.warn } : conv.status === 'resolved' || conv.status === 'closed' ? { text: t.resolved, color: c.ok } : null
184
+ const who = conv.lastAuthor === 'user' ? t.you + ': ' : conv.lastAuthor === 'ai' ? t.ai + ': ' : ''
185
+ return (
186
+ <Pressable onPress={onPress} accessibilityRole="button" style={({ pressed }) => [st.row, pressed && { backgroundColor: c.raised }]}>
187
+ <Avatar c={c} label={conv.subject ?? '?'} size={36} ai={conv.lastAuthor === 'ai'} />
188
+ <View style={st.fill}>
189
+ <View style={st.rowTop}>
190
+ <T c={c} bold={unread} style={st.rowTitle} numberOfLines={1}>{conv.subject ?? t.newMessage}</T>
191
+ <T c={c} style={[st.meta, { color: c.faint }]}>{clock(conv.lastMessageAt)}</T>
192
+ </View>
193
+ <View style={st.rowTop}>
194
+ <T c={c} style={[st.preview, { color: unread ? c.text : c.sub }]} numberOfLines={1}>{who + (conv.lastPreview ?? '')}</T>
195
+ {pill ? (
196
+ <View style={[st.pill, { backgroundColor: pill.color + '22' }]}>
197
+ <T c={c} bold style={[st.pillText, { color: pill.color }]}>{pill.text}</T>
198
+ </View>
199
+ ) : null}
200
+ {unread ? <View style={[st.unread, { backgroundColor: c.accent }]} /> : null}
201
+ </View>
202
+ </View>
203
+ </Pressable>
204
+ )
205
+ })
206
+
207
+ type Row =
208
+ | { k: string; kind: 'msg'; m: Message; label: string | null; receipt: Receipt | null; gap: number }
209
+ | { k: string; kind: 'typing'; who: string }
210
+ | { k: string; kind: 'chips'; items: string[]; talk: boolean }
211
+
212
+ interface ThreadProps {
213
+ s: SupportApi
214
+ c: Resolved
215
+ t: Copy
216
+ team: string
217
+ conversation: Conversation | null
218
+ quickReplies: string[]
219
+ reduce: boolean
220
+ inset: number
221
+ draft: string
222
+ setDraft: (v: string) => void
223
+ pending: LocalAttachment[]
224
+ setPending: (fn: (p: LocalAttachment[]) => LocalAttachment[]) => void
225
+ onScreenshot: () => void
226
+ onSent: () => void
227
+ }
228
+
229
+ function Thread({ s, c, t, team, conversation, quickReplies, reduce, inset, draft, setDraft, pending, setPending, onScreenshot, onSent }: ThreadProps) {
230
+ const id = s.activeConversationId
231
+ const messages = (id && s.messages[id]) || []
232
+ const typing = id ? s.typing[id] : undefined
233
+ const offline = s.status !== 'live'
234
+ const handed = conversation?.status === 'needs_human'
235
+ const closed = conversation?.status === 'resolved' || conversation?.status === 'closed'
236
+ const since = useRef(Date.now()).current
237
+
238
+ const rows = useMemo(() => {
239
+ const out: Row[] = []
240
+ const lastMine = messages.reduce((at, m, i) => (m.author === 'user' ? i : at), -1)
241
+ messages.forEach((m, i) => {
242
+ const prev = messages[i - 1]
243
+ const first = !prev || prev.author !== m.author || m.createdAt - prev.createdAt > 5 * 60_000
244
+ const label = m.author === 'ai' || m.author === 'founder' ? (first ? (m.author === 'ai' ? t.ai : team) : null) : null
245
+ const receipt = i === lastMine || m.pending ? receiptOf(m, messages, conversation ?? undefined, offline) : null
246
+ out.push({ k: m.localId ?? m.id, kind: 'msg', m, label, receipt, gap: first ? 12 : 3 })
247
+ })
248
+ const last = messages[messages.length - 1]
249
+ if (typing) out.push({ k: 'typing', kind: 'typing', who: typing === 'ai' ? t.ai : team })
250
+ else if (last?.author === 'ai' && !handed && !closed) {
251
+ const q = Array.isArray(last.meta?.['quickReplies']) ? (last.meta['quickReplies'] as string[]) : []
252
+ out.push({ k: 'chips' + last.id, kind: 'chips', items: q.slice(0, 3), talk: true })
253
+ }
254
+ return out.reverse()
255
+ }, [messages, typing, conversation, offline, handed, closed, t, team])
256
+
257
+ const last = messages[messages.length - 1]
258
+ useEffect(() => {
259
+ if (last && last.author !== 'user' && last.createdAt > since) AccessibilityInfo.announceForAccessibility?.((last.author === 'ai' ? t.ai : team) + ': ' + last.body)
260
+ }, [last?.id])
261
+ useEffect(() => {
262
+ if (typing) AccessibilityInfo.announceForAccessibility?.(fill(t.typing, { who: typing === 'ai' ? t.ai : team }))
263
+ }, [typing])
264
+
265
+ const send = (body: string, atts: LocalAttachment[] = []) => {
266
+ s.send(body, id, atts)
267
+ onSent()
268
+ }
269
+
270
+ const kb = useKeyboardInset()
271
+ const empty = !messages.length
272
+ return (
273
+ <View style={[st.fill, { paddingBottom: kb }]}>
274
+ {empty ? (
275
+ <View style={st.empty}>
276
+ <Avatar c={c} label={team} size={44} />
277
+ <T c={c} bold style={st.greet} accessibilityRole="header">{t.greeting}</T>
278
+ <Chips c={c} items={quickReplies} reduce={reduce} onPick={(q) => send(q)} center />
279
+ </View>
280
+ ) : (
281
+ <FlatList
282
+ inverted
283
+ data={rows}
284
+ keyExtractor={(r) => r.k}
285
+ contentContainerStyle={st.thread}
286
+ keyboardShouldPersistTaps="handled"
287
+ keyboardDismissMode="interactive"
288
+ initialNumToRender={14}
289
+ windowSize={9}
290
+ removeClippedSubviews={Platform.OS === 'android'}
291
+ renderItem={({ item }) =>
292
+ item.kind === 'msg' ? (
293
+ <Bubble r={item} c={c} t={t} fresh={item.m.createdAt > since - 1000} reduce={reduce} url={s.url} onRetry={s.retry} />
294
+ ) : item.kind === 'typing' ? (
295
+ <View style={[st.theirs, st.typing]} accessible accessibilityLabel={fill(t.typing, { who: item.who })}>
296
+ <T c={c} style={[st.label, { color: c.sub }]}>{item.who}</T>
297
+ <View style={[st.bubble, { backgroundColor: c.raised, borderRadius: c.radius }]}>
298
+ <Dots color={c.sub} reduce={reduce} />
299
+ </View>
300
+ </View>
301
+ ) : (
302
+ <Chips c={c} items={item.items} reduce={reduce} onPick={(q) => send(q)} talk={t.talk} onTalk={() => id && s.handoff(id)} />
303
+ )
304
+ }
305
+ />
306
+ )}
307
+ {handed ? (
308
+ <View style={[st.strip, { borderColor: c.line }]} accessibilityLiveRegion="polite">
309
+ <View style={[st.stripBar, { backgroundColor: c.warn }]} />
310
+ <T c={c} style={[st.stripText, { color: c.sub }]}>{t.handedOff}</T>
311
+ </View>
312
+ ) : null}
313
+ <Composer c={c} t={t} inset={inset} draft={draft} setDraft={setDraft} pending={pending} setPending={setPending} onScreenshot={onScreenshot} onSend={() => {
314
+ send(draft, pending)
315
+ setDraft('')
316
+ setPending(() => [])
317
+ }} />
318
+ </View>
319
+ )
320
+ }
321
+
322
+ const Bubble = memo(function Bubble({ r, c, t, fresh, reduce, url, onRetry }: { r: Extract<Row, { kind: 'msg' }>; c: Resolved; t: Copy; fresh: boolean; reduce: boolean; url: (p: string) => string; onRetry: (id: string) => void }) {
323
+ const { m } = r
324
+ const v = useRef(new Animated.Value(fresh && !reduce ? 0 : 1)).current
325
+ useEffect(() => {
326
+ if (fresh && !reduce) Animated.timing(v, { toValue: 1, useNativeDriver: true, ...motion.bubble }).start()
327
+ }, [])
328
+ if (m.author === 'system')
329
+ return (
330
+ <View style={[st.system, { marginTop: r.gap }]}>
331
+ <T c={c} style={[st.systemText, { color: c.sub }]}>{m.body}</T>
332
+ </View>
333
+ )
334
+ const mine = m.author === 'user'
335
+ const atts = attachmentsOf(m)
336
+ const rc = r.receipt
337
+ const receiptText = rc ? (rc === 'failed' ? t.failed : t[rc] + (rc === 'seen' || rc === 'delivered' || rc === 'sent' ? ' · ' + clock(m.createdAt) : '')) : null
338
+ const anim = { opacity: v, transform: [{ translateY: v.interpolate({ inputRange: [0, 1], outputRange: [4, 0] }) }] }
339
+ return (
340
+ <Animated.View style={[mine ? st.mine : st.theirs, { marginTop: r.gap }, anim]} accessible accessibilityLabel={(mine ? t.you : r.label ?? '') + ': ' + (m.body || t.photo) + (receiptText ? '. ' + receiptText : '')}>
341
+ {r.label ? (
342
+ <View style={st.labelRow}>
343
+ {m.author === 'ai' ? <Spark color={c.accent} size={6} /> : null}
344
+ <T c={c} style={[st.label, { color: c.sub }]}>{r.label}</T>
345
+ </View>
346
+ ) : null}
347
+ {atts.map((a, i) => {
348
+ const w = 200
349
+ const h = a.width && a.height ? Math.min(260, Math.round((w * a.height) / a.width)) : 150
350
+ return <Image key={i} source={{ uri: a.uri ?? url(a.path ?? '') }} style={[st.image, { width: w, height: h, borderRadius: c.radius - 4, backgroundColor: c.raised, opacity: m.pending ? 0.6 : 1 }]} accessibilityIgnoresInvertColors />
351
+ })}
352
+ {m.body ? (
353
+ <View style={[st.bubble, { backgroundColor: mine ? c.accent : c.raised, borderRadius: c.radius, opacity: m.pending === 'failed' ? 0.6 : 1 }]}>
354
+ <T c={c} style={[st.body, { color: mine ? c.onAccent : c.text }]}>{m.body}</T>
355
+ </View>
356
+ ) : null}
357
+ {receiptText ? (
358
+ <Pressable disabled={rc !== 'failed'} onPress={() => m.localId && onRetry(m.localId)} hitSlop={8} style={st.receipt} accessibilityRole={rc === 'failed' ? 'button' : undefined}>
359
+ {rc === 'queued' ? <Clock color={c.faint} /> : null}
360
+ <T c={c} style={[st.receiptText, { color: rc === 'failed' ? c.danger : c.faint }]}>{receiptText}</T>
361
+ </Pressable>
362
+ ) : null}
363
+ </Animated.View>
364
+ )
365
+ })
366
+
367
+ function Chips({ c, items, reduce, onPick, talk, onTalk, center }: { c: Resolved; items: string[]; reduce: boolean; onPick: (q: string) => void; talk?: string; onTalk?: () => void; center?: boolean }) {
368
+ const all = talk ? [...items, talk] : items
369
+ const vals = useRef(all.map(() => new Animated.Value(reduce ? 1 : 0))).current
370
+ useEffect(() => {
371
+ if (!reduce) Animated.stagger(motion.chips.stagger, vals.map((v) => Animated.timing(v, { toValue: 1, duration: motion.chips.duration, useNativeDriver: true }))).start()
372
+ }, [])
373
+ if (!all.length) return null
374
+ return (
375
+ <View style={[st.chips, center && st.chipsCenter]}>
376
+ {all.map((q, i) => {
377
+ const isTalk = !!talk && i === all.length - 1
378
+ const v = vals[i] ?? new Animated.Value(1)
379
+ return (
380
+ <Animated.View key={q + i} style={{ opacity: v, transform: [{ translateY: v.interpolate({ inputRange: [0, 1], outputRange: [6, 0] }) }] }}>
381
+ <Pressable
382
+ onPress={() => (isTalk ? onTalk?.() : onPick(q))}
383
+ accessibilityRole="button"
384
+ style={({ pressed }) => [st.chip, { borderColor: isTalk ? c.accent + '55' : c.line, backgroundColor: pressed ? c.raised : c.bg }]}
385
+ >
386
+ <T c={c} style={[st.chipText, { color: isTalk ? c.accent : c.text }]}>{q}</T>
387
+ </Pressable>
388
+ </Animated.View>
389
+ )
390
+ })}
391
+ </View>
392
+ )
393
+ }
394
+
395
+ function useKeyboardInset(): number {
396
+ const [h, setH] = useState(0)
397
+ useEffect(() => {
398
+ if (Platform.OS !== 'ios') return
399
+ const move = (e: KeyboardEvent, next: number) => {
400
+ LayoutAnimation.configureNext({ duration: e.duration || 250, update: { type: LayoutAnimation.Types.keyboard } })
401
+ setH(next)
402
+ }
403
+ const a = Keyboard.addListener('keyboardWillChangeFrame', (e) => {
404
+ const screen = Dimensions.get('screen').height
405
+ move(e, Math.max(0, screen - e.endCoordinates.screenY))
406
+ })
407
+ const b = Keyboard.addListener('keyboardWillHide', (e) => move(e, 0))
408
+ return () => (a.remove(), b.remove())
409
+ }, [])
410
+ return h
411
+ }
412
+
413
+ function Composer({ c, t, inset, draft, setDraft, pending, setPending, onScreenshot, onSend }: {
414
+ c: Resolved; t: Copy; inset: number; draft: string; setDraft: (v: string) => void; pending: LocalAttachment[]
415
+ setPending: (fn: (p: LocalAttachment[]) => LocalAttachment[]) => void; onScreenshot: () => void; onSend: () => void
416
+ }) {
417
+ const [kb, setKb] = useState(false)
418
+ const [menu, setMenu] = useState(false)
419
+ useEffect(() => {
420
+ const ios = Platform.OS === 'ios'
421
+ const a = Keyboard.addListener(ios ? 'keyboardWillShow' : 'keyboardDidShow', () => setKb(true))
422
+ const b = Keyboard.addListener(ios ? 'keyboardWillHide' : 'keyboardDidHide', () => setKb(false))
423
+ return () => (a.remove(), b.remove())
424
+ }, [])
425
+ const peers = attachPeers()
426
+ const photo = () => pickPhoto().then((a) => a && setPending((p) => [...p, a]), () => {})
427
+ const options = [peers.picker ? { label: t.photo, run: photo } : null, peers.shot ? { label: t.screenshot, run: onScreenshot } : null].filter((x) => !!x)
428
+ const attach = () => {
429
+ if (options.length === 1) return options[0].run()
430
+ if (Platform.OS === 'ios') return ActionSheetIOS.showActionSheetWithOptions({ options: [...options.map((o) => o.label), t.cancel], cancelButtonIndex: options.length }, (i) => options[i]?.run())
431
+ setMenu((x) => !x)
432
+ }
433
+ const ready = !!draft.trim() || pending.length > 0
434
+ return (
435
+ <View style={[st.composer, { paddingBottom: kb ? 8 : 8 + inset }]}>
436
+ {menu ? (
437
+ <View style={st.chips}>
438
+ {options.map((o) => (
439
+ <Pressable key={o.label} onPress={() => (setMenu(false), o.run())} accessibilityRole="button" style={[st.chip, { borderColor: c.line }]}>
440
+ <T c={c} style={st.chipText}>{o.label}</T>
441
+ </Pressable>
442
+ ))}
443
+ </View>
444
+ ) : null}
445
+ {pending.length ? (
446
+ <View style={st.pending}>
447
+ {pending.map((a, i) => (
448
+ <View key={a.uri + i}>
449
+ <Image source={{ uri: a.uri }} style={[st.thumb, { borderRadius: c.radius / 2, backgroundColor: c.raised }]} />
450
+ <Pressable onPress={() => setPending((p) => p.filter((_, j) => j !== i))} hitSlop={8} accessibilityRole="button" accessibilityLabel={t.remove} style={[st.thumbX, { backgroundColor: c.text, borderColor: c.bg }]}>
451
+ <Cross color={c.bg} size={7} />
452
+ </Pressable>
453
+ </View>
454
+ ))}
455
+ </View>
456
+ ) : null}
457
+ <View style={[st.field, { borderColor: c.line, borderRadius: c.radius + 4, backgroundColor: c.bg }]}>
458
+ {options.length ? (
459
+ <Pressable onPress={attach} hitSlop={6} accessibilityRole="button" accessibilityLabel={t.attach} style={st.attach}>
460
+ <Plus color={c.sub} />
461
+ </Pressable>
462
+ ) : (
463
+ <View style={st.attachGap} />
464
+ )}
465
+ <TextInput
466
+ value={draft}
467
+ onChangeText={setDraft}
468
+ placeholder={t.placeholder}
469
+ placeholderTextColor={c.faint}
470
+ multiline
471
+ maxFontSizeMultiplier={2}
472
+ accessibilityLabel={t.placeholder}
473
+ style={[st.input, font(c), { color: c.text }]}
474
+ />
475
+ <Pressable onPress={onSend} disabled={!ready} accessibilityRole="button" accessibilityLabel={t.send} accessibilityState={{ disabled: !ready }} style={[st.send, { backgroundColor: ready ? c.accent : c.raised }]}>
476
+ <ArrowUp color={ready ? c.onAccent : c.faint} />
477
+ </Pressable>
478
+ </View>
479
+ </View>
480
+ )
481
+ }
482
+
483
+ const st = StyleSheet.create({
484
+ fill: { flex: 1 },
485
+ sheet: { position: 'absolute', start: 0, end: 0, bottom: 0, overflow: 'hidden' },
486
+ grabber: { alignSelf: 'center', width: 36, height: 5, borderRadius: 2.5, marginTop: 8 },
487
+ header: { flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 16, paddingTop: 10, paddingBottom: 12 },
488
+ back: { width: 24, height: 32, justifyContent: 'center' },
489
+ title: { fontSize: 16, lineHeight: 20 },
490
+ statusRow: { flexDirection: 'row', alignItems: 'center', gap: 5, marginTop: 1, alignSelf: 'flex-start' },
491
+ dot: { width: 6, height: 6, borderRadius: 3 },
492
+ status: { fontSize: 12, lineHeight: 16 },
493
+ close: { width: 28, height: 28, borderRadius: 14, alignItems: 'center', justifyContent: 'center' },
494
+ hair: { height: StyleSheet.hairlineWidth },
495
+ listPad: { paddingVertical: 6 },
496
+ row: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, paddingVertical: 10 },
497
+ rowTop: { flexDirection: 'row', alignItems: 'center', gap: 8 },
498
+ rowTitle: { flex: 1, fontSize: 15, lineHeight: 20 },
499
+ preview: { flex: 1, fontSize: 14, lineHeight: 19 },
500
+ meta: { fontSize: 12, fontVariant: ['tabular-nums'] },
501
+ unread: { width: 8, height: 8, borderRadius: 4 },
502
+ pill: { borderRadius: 999, paddingHorizontal: 7, paddingVertical: 2 },
503
+ pillText: { fontSize: 11, lineHeight: 14 },
504
+ footer: { paddingHorizontal: 16, paddingTop: 8 },
505
+ cta: { minHeight: 46, borderRadius: 23, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 8, paddingHorizontal: 20 },
506
+ ctaText: { fontSize: 16 },
507
+ empty: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 24, gap: 12 },
508
+ greet: { fontSize: 20, lineHeight: 26, textAlign: 'center' },
509
+ thread: { paddingHorizontal: 14, paddingVertical: 12 },
510
+ mine: { alignSelf: 'flex-end', alignItems: 'flex-end', maxWidth: '82%' },
511
+ theirs: { alignSelf: 'flex-start', alignItems: 'flex-start', maxWidth: '82%' },
512
+ typing: { marginTop: 12 },
513
+ labelRow: { flexDirection: 'row', alignItems: 'center', gap: 5, marginBottom: 4, marginStart: 4 },
514
+ label: { fontSize: 12, lineHeight: 16 },
515
+ bubble: { paddingHorizontal: 13, paddingVertical: 8 },
516
+ body: { fontSize: 16, lineHeight: 21 },
517
+ image: { marginBottom: 3 },
518
+ receipt: { flexDirection: 'row', alignItems: 'center', gap: 4, marginTop: 4, marginEnd: 4 },
519
+ receiptText: { fontSize: 12, lineHeight: 16 },
520
+ system: { alignSelf: 'center', paddingVertical: 4 },
521
+ systemText: { fontSize: 12, lineHeight: 16, textAlign: 'center' },
522
+ chips: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginTop: 12 },
523
+ chipsCenter: { justifyContent: 'center' },
524
+ chip: { minHeight: 34, borderRadius: 17, borderWidth: 1, paddingHorizontal: 14, justifyContent: 'center' },
525
+ chipText: { fontSize: 15, lineHeight: 20 },
526
+ strip: { flexDirection: 'row', alignItems: 'center', gap: 10, marginHorizontal: 12, marginBottom: 2, paddingVertical: 8 },
527
+ stripBar: { width: 3, height: 16, borderRadius: 1.5 },
528
+ stripText: { fontSize: 13, lineHeight: 18 },
529
+ composer: { paddingHorizontal: 12, paddingTop: 6 },
530
+ pending: { flexDirection: 'row', gap: 8, paddingBottom: 8, paddingHorizontal: 4 },
531
+ thumb: { width: 56, height: 56 },
532
+ thumbX: { position: 'absolute', top: -6, end: -6, width: 20, height: 20, borderRadius: 10, borderWidth: 2, alignItems: 'center', justifyContent: 'center' },
533
+ field: { flexDirection: 'row', alignItems: 'flex-end', borderWidth: 1, paddingEnd: 5, paddingVertical: 5 },
534
+ attach: { width: 38, height: 32, alignItems: 'center', justifyContent: 'center' },
535
+ attachGap: { width: 12 },
536
+ input: { flex: 1, minHeight: 32, maxHeight: 132, fontSize: 16, lineHeight: 21, paddingTop: 6, paddingBottom: 5, paddingHorizontal: 0 },
537
+ send: { width: 32, height: 32, borderRadius: 16, alignItems: 'center', justifyContent: 'center', marginStart: 6 }
538
+ })
package/src/support.ts ADDED
@@ -0,0 +1,55 @@
1
+ // The app-facing singleton: configure once, identify after sign-in, open the widget from anywhere. Calls made before
2
+ // configure() (an auth listener at module scope, a push token on launch) are held and applied when it runs.
3
+
4
+ import { Platform } from 'react-native'
5
+ import { SupportClient } from './client'
6
+ import type { SupportConfig, UserInfo } from './client'
7
+ import { nativeDevice, nativeStorage } from './native'
8
+
9
+ let current: SupportClient | null = null
10
+ const watchers = new Set<(c: SupportClient) => void>()
11
+ const held: { user: UserInfo | null; push: { token: string | null; platform: string } | null; open: boolean } = { user: null, push: null, open: false }
12
+
13
+ export const ShotikSupport = {
14
+ configure(config: SupportConfig): SupportClient {
15
+ if (current && current.config.appKey === config.appKey && current.config.serverUrl === config.serverUrl.replace(/\/+$/, '')) return current
16
+ current?.stop()
17
+ const c = new SupportClient({ storage: nativeStorage(), device: nativeDevice, ...config })
18
+ current = c
19
+ if (held.push) c.setPushToken(held.push.token, held.push.platform).catch(() => {})
20
+ if (held.user) c.identify(held.user).catch(() => {})
21
+ if (held.open) c.open()
22
+ held.user = held.push = null
23
+ held.open = false
24
+ for (const fn of watchers) fn(c)
25
+ return c
26
+ },
27
+ get client(): SupportClient | null {
28
+ return current
29
+ },
30
+ onConfigure(fn: (c: SupportClient) => void): () => void {
31
+ watchers.add(fn)
32
+ return () => void watchers.delete(fn)
33
+ },
34
+ identify(user: UserInfo = {}): Promise<void> {
35
+ if (current) return current.identify(user)
36
+ held.user = { ...held.user, ...user }
37
+ return Promise.resolve()
38
+ },
39
+ setPushToken(token: string | null, platform: string = Platform.OS): Promise<void> {
40
+ if (current) return current.setPushToken(token, platform)
41
+ held.push = { token, platform }
42
+ return Promise.resolve()
43
+ },
44
+ open(conversationId?: string | null): void {
45
+ if (current) current.open(conversationId)
46
+ else held.open = true
47
+ },
48
+ close(): void {
49
+ current?.close()
50
+ },
51
+ reset(): Promise<void> {
52
+ held.user = null
53
+ return current ? current.reset() : Promise.resolve()
54
+ }
55
+ }