@shotik/react-native 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ // @shotik/react-native: in-app support chat for React Native and Expo, backed by a Shotik workspace.
2
+
3
+ export { ShotikSupport } from './support'
4
+ export { ShotikSupportProvider, SupportRoute, SupportSheet, SupportWidget, useSupport } from './react'
5
+ export type { ProviderProps, SheetViewProps, SupportApi, WidgetProps } from './react'
6
+ export { SupportClient, HttpError, memoryStorage, receiptOf, attachmentsOf } from './client'
7
+ export type { Attachment, Author, Conversation, ConversationStatus, DeviceInfo, KeyValueStorage, LocalAttachment, Message, Receipt, Status, SupportConfig, SupportState, Typing, UserInfo } from './client'
8
+ export type { Colors, Copy, SupportTheme } from './theme'
9
+ export { catalogs } from './theme'
10
+ export { nativeDevice, nativeStorage } from './native'
package/src/native.ts ADDED
@@ -0,0 +1,90 @@
1
+ // React Native glue: persistence and device context from whatever the app already has installed. Every optional
2
+ // module is a guarded require, so the SDK needs no native code of its own and works in any Expo dev client.
3
+
4
+ import { Platform } from 'react-native'
5
+ import { memoryStorage } from './client'
6
+ import type { DeviceInfo, KeyValueStorage } from './client'
7
+
8
+ interface AsyncStorageLike {
9
+ getItem(k: string): Promise<string | null>
10
+ setItem(k: string, v: string): Promise<void>
11
+ removeItem(k: string): Promise<void>
12
+ }
13
+
14
+ interface SecureStoreLike {
15
+ getItemAsync(k: string): Promise<string | null>
16
+ setItemAsync(k: string, v: string): Promise<void>
17
+ deleteItemAsync(k: string): Promise<void>
18
+ }
19
+
20
+ function asyncStorage(): AsyncStorageLike | null {
21
+ try {
22
+ const m = require('@react-native-async-storage/async-storage')
23
+ return (m?.default ?? m) as AsyncStorageLike
24
+ } catch {
25
+ return null
26
+ }
27
+ }
28
+
29
+ function secureStore(): SecureStoreLike | null {
30
+ try {
31
+ const m = require('expo-secure-store')
32
+ return typeof m?.getItemAsync === 'function' ? (m as SecureStoreLike) : null
33
+ } catch {
34
+ return null
35
+ }
36
+ }
37
+
38
+ export function nativeStorage(): KeyValueStorage {
39
+ const a = asyncStorage()
40
+ if (a) return { get: (k) => a.getItem(k), set: (k, v) => a.setItem(k, v), remove: (k) => a.removeItem(k) }
41
+ const s = secureStore()
42
+ if (s) return { get: (k) => s.getItemAsync(k), set: (k, v) => s.setItemAsync(k, v), remove: (k) => s.deleteItemAsync(k) }
43
+ return memoryStorage()
44
+ }
45
+
46
+ function expoDevice(): { modelName?: string | null; osVersion?: string | null } | null {
47
+ try {
48
+ return require('expo-device')
49
+ } catch {
50
+ return null
51
+ }
52
+ }
53
+
54
+ function expoApplication(): { nativeApplicationVersion?: string | null; nativeBuildVersion?: string | null } | null {
55
+ try {
56
+ return require('expo-application')
57
+ } catch {
58
+ return null
59
+ }
60
+ }
61
+
62
+ function expoLocalization(): { getLocales?: () => { languageTag?: string }[]; getCalendars?: () => { timeZone?: string | null }[] } | null {
63
+ try {
64
+ return require('expo-localization')
65
+ } catch {
66
+ return null
67
+ }
68
+ }
69
+
70
+ export function nativeDevice(): DeviceInfo {
71
+ const device = expoDevice()
72
+ const app = expoApplication()
73
+ const loc = expoLocalization()
74
+ const intl = Intl.DateTimeFormat().resolvedOptions()
75
+ let locale: string | undefined
76
+ let timezone: string | undefined
77
+ try {
78
+ locale = loc?.getLocales?.()[0]?.languageTag
79
+ timezone = loc?.getCalendars?.()[0]?.timeZone ?? undefined
80
+ } catch {}
81
+ return {
82
+ platform: Platform.OS,
83
+ osVersion: device?.osVersion ?? String(Platform.Version),
84
+ model: device?.modelName ?? undefined,
85
+ appVersion: app?.nativeApplicationVersion ?? undefined,
86
+ build: app?.nativeBuildVersion ?? undefined,
87
+ locale: locale ?? intl.locale,
88
+ timezone: timezone ?? intl.timeZone
89
+ }
90
+ }
package/src/parts.tsx ADDED
@@ -0,0 +1,243 @@
1
+ // Small building blocks: Hugeicons glyphs (drawn with react-native-svg when the app has it, else plain View stand-ins),
2
+ // the typing dots, the floating launcher, motion tokens and the optional photo / screenshot / svg peers.
3
+
4
+ import { useEffect, useRef, useState } from 'react'
5
+ import type { ComponentType, ReactNode } from 'react'
6
+ import { AccessibilityInfo, Animated, Easing, I18nManager, Platform, Pressable, StyleSheet, Text, View } from 'react-native'
7
+ import type { StyleProp, TextStyle, ViewStyle } from 'react-native'
8
+ import type { LocalAttachment } from './client'
9
+ import type { Copy, Resolved } from './theme'
10
+ import { fill } from './theme'
11
+
12
+ // Motion tokens. Sheet: iOS-sheet spring (refs/REFS.md "Sheet"); bubble in: 170 ms, y 4 -> 0 (0e8776a2);
13
+ // chips: 200 ms, 40 ms stagger (00e8aade); dots: 900 ms loop, 150 ms apart (f35c684d).
14
+ export const motion = {
15
+ sheet: { damping: 30, stiffness: 320, mass: 1 },
16
+ bubble: { duration: 170, easing: Easing.bezier(0.25, 0.1, 0.25, 1) },
17
+ chips: { duration: 200, stagger: 40 },
18
+ dots: { period: 900, gap: 150 }
19
+ }
20
+
21
+ export function useReduceMotion(): boolean {
22
+ const [reduce, setReduce] = useState(false)
23
+ useEffect(() => {
24
+ AccessibilityInfo.isReduceMotionEnabled?.().then(setReduce, () => {})
25
+ const sub = AccessibilityInfo.addEventListener?.('reduceMotionChanged', setReduce)
26
+ return () => sub?.remove()
27
+ }, [])
28
+ return reduce
29
+ }
30
+
31
+ export const font = (c: Resolved, bold?: boolean): TextStyle => (bold ? { fontFamily: c.fontBold ?? c.font, fontWeight: c.fontBold ? undefined : '600' } : { fontFamily: c.font })
32
+
33
+ export function T({ c, bold, style, ...p }: { c: Resolved; bold?: boolean; style?: StyleProp<TextStyle>; children?: ReactNode; numberOfLines?: number; accessibilityRole?: 'header' | 'text' }) {
34
+ return <Text {...p} maxFontSizeMultiplier={2} style={[{ color: c.text }, font(c, bold), style]} />
35
+ }
36
+
37
+ const flip = I18nManager.isRTL ? [{ scaleX: -1 }] : []
38
+
39
+ // Hugeicons free set (@hugeicons/core-free-icons 4.4.0, MIT), 24x24 stroke paths; names in REFS.md.
40
+ const icons = {
41
+ back: ['M15 6C15 6 9.00001 10.4189 9 12C8.99999 13.5812 15 18 15 18'],
42
+ close: ['M18.9991 19L5 5.00098','M19 5L5.00092 18.999'],
43
+ send: ['M12 5.5V19','M18 11C18 11 13.5811 5.00001 12 5C10.4188 4.99999 6 11 6 11'],
44
+ attach: ['M12 4V20M20 12H4'],
45
+ clock: ['M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0','M12 8V12L14 14'],
46
+ ai: ['M15 2L15.5387 4.39157C15.9957 6.42015 17.5798 8.00431 19.6084 8.46127L22 9L19.6084 9.53873C17.5798 9.99569 15.9957 11.5798 15.5387 13.6084L15 16L14.4613 13.6084C14.0043 11.5798 12.4202 9.99569 10.3916 9.53873L8 9L10.3916 8.46127C12.4201 8.00431 14.0043 6.42015 14.4613 4.39158L15 2Z','M7 12L7.38481 13.7083C7.71121 15.1572 8.84275 16.2888 10.2917 16.6152L12 17L10.2917 17.3848C8.84275 17.7112 7.71121 18.8427 7.38481 20.2917L7 22L6.61519 20.2917C6.28879 18.8427 5.15725 17.7112 3.70827 17.3848L2 17L3.70827 16.6152C5.15725 16.2888 6.28879 15.1573 6.61519 13.7083L7 12Z'],
47
+ chat: ['M12 21.5C17.2467 21.5 21.5 17.2467 21.5 12C21.5 6.75329 17.2467 2.5 12 2.5C6.75329 2.5 2.5 6.75329 2.5 12C2.5 13.3377 2.66372 14.5604 3.1189 15.6954C3.81756 17.4374 3.68195 18.9241 2.5 20.5C3.86146 21.1644 5.86811 21.1419 7 20.0725C8.45323 20.9748 10.1636 21.5 12 21.5Z','M12.2 12.0002H12M7.69961 11.9999H7.49961M16.6996 11.9999H16.4996M12.4 12.0002C12.4 12.2212 12.2209 12.4002 12 12.4002C11.7791 12.4002 11.6 12.2212 11.6 12.0002C11.6 11.7793 11.7791 11.6002 12 11.6002C12.2209 11.6002 12.4 11.7793 12.4 12.0002ZM7.89961 11.9999C7.89961 12.2208 7.72052 12.3999 7.49961 12.3999C7.2787 12.3999 7.09961 12.2208 7.09961 11.9999C7.09961 11.7789 7.2787 11.5999 7.49961 11.5999C7.72052 11.5999 7.89961 11.7789 7.89961 11.9999ZM16.8996 11.9999C16.8996 12.2208 16.7205 12.3999 16.4996 12.3999C16.2787 12.3999 16.0996 12.2208 16.0996 11.9999C16.0996 11.7789 16.2787 11.5999 16.4996 11.5999C16.7205 11.5999 16.8996 11.7789 16.8996 11.9999Z']
48
+ }
49
+
50
+ // Stroke scaled so every glyph renders about 1.7 pt wide whatever its size.
51
+ function hi(name: keyof typeof icons, color: string, size: number, style?: StyleProp<ViewStyle>) {
52
+ const s = attachPeers().svg
53
+ if (!s) return null
54
+ return (
55
+ <s.Svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={style}>
56
+ {icons[name].map((d) => (
57
+ <s.Path key={d} d={d} stroke={color} strokeWidth={(1.7 * 24) / size} strokeLinecap="round" strokeLinejoin="round" />
58
+ ))}
59
+ </s.Svg>
60
+ )
61
+ }
62
+
63
+ export function Chevron({ color }: { color: string }) {
64
+ return hi('back', color, 22, { transform: flip }) ?? (
65
+ <View style={[g.box, { transform: flip }]}>
66
+ <View style={[g.chev, { borderColor: color }]} />
67
+ </View>
68
+ )
69
+ }
70
+
71
+ export function Cross({ color, size = 12 }: { color: string; size?: number }) {
72
+ return hi('close', color, Math.round((size * 24) / 14)) ?? (
73
+ <View style={[g.box, { width: size, height: size }]}>
74
+ <View style={[g.bar, { width: size * 1.2, backgroundColor: color, transform: [{ rotate: '45deg' }] }]} />
75
+ <View style={[g.bar, { width: size * 1.2, backgroundColor: color, transform: [{ rotate: '-45deg' }] }]} />
76
+ </View>
77
+ )
78
+ }
79
+
80
+ export function Plus({ color }: { color: string }) {
81
+ return hi('attach', color, 20) ?? (
82
+ <View style={g.box}>
83
+ <View style={[g.bar, { width: 14, backgroundColor: color }]} />
84
+ <View style={[g.bar, { width: 14, backgroundColor: color, transform: [{ rotate: '90deg' }] }]} />
85
+ </View>
86
+ )
87
+ }
88
+
89
+ export function ArrowUp({ color }: { color: string }) {
90
+ return hi('send', color, 18) ?? (
91
+ <View style={g.box}>
92
+ <View style={[g.bar, { width: 12, backgroundColor: color, transform: [{ rotate: '90deg' }, { translateX: 1 }] }]} />
93
+ <View style={[g.up, { borderColor: color }]} />
94
+ </View>
95
+ )
96
+ }
97
+
98
+ export function Clock({ color }: { color: string }) {
99
+ return hi('clock', color, 12) ?? (
100
+ <View style={[g.clock, { borderColor: color }]}>
101
+ <View style={[g.hand, { backgroundColor: color }]} />
102
+ </View>
103
+ )
104
+ }
105
+
106
+ // AI mark: Hugeicons sparkles (a small accent diamond without react-native-svg).
107
+ export function Spark({ color, size = 7 }: { color: string; size?: number }) {
108
+ return hi('ai', color, Math.round(size * 1.7)) ?? <View style={{ width: size, height: size, borderRadius: 1.5, backgroundColor: color, transform: [{ rotate: '45deg' }] }} />
109
+ }
110
+
111
+ export function Avatar({ c, label, size = 28, ai }: { c: Resolved; label: string; size?: number; ai?: boolean }) {
112
+ return (
113
+ <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: ai ? c.raised : c.accent, alignItems: 'center', justifyContent: 'center' }}>
114
+ {ai ? <Spark color={c.accent} size={size * 0.3} /> : <Text allowFontScaling={false} style={[font(c, true), { color: c.onAccent, fontSize: size * 0.42 }]}>{label.slice(0, 1).toUpperCase()}</Text>}
115
+ </View>
116
+ )
117
+ }
118
+
119
+ // Three dots fading in a wave (f35c684d "Running command" pill dots), native driver.
120
+ export function Dots({ color, reduce }: { color: string; reduce: boolean }) {
121
+ const v = useRef(new Animated.Value(0)).current
122
+ useEffect(() => {
123
+ if (reduce) return
124
+ const loop = Animated.loop(Animated.timing(v, { toValue: 1, duration: motion.dots.period, easing: Easing.linear, useNativeDriver: true }))
125
+ loop.start()
126
+ return () => loop.stop()
127
+ }, [reduce, v])
128
+ const p = motion.dots.gap / motion.dots.period
129
+ return (
130
+ <View style={g.dots}>
131
+ {[0, 1, 2].map((i) => {
132
+ const s = i * p
133
+ const opacity = reduce ? 0.6 : v.interpolate({ inputRange: [0, s, s + 0.2, s + 0.45, 1], outputRange: [0.3, 0.3, 1, 0.3, 0.3] })
134
+ return <Animated.View key={i} style={[g.dot, { backgroundColor: color, opacity }]} />
135
+ })}
136
+ </View>
137
+ )
138
+ }
139
+
140
+ // Floating launcher: accent circle with a chat glyph, unread count badge at the top end.
141
+ export function Launcher({ c, t, unread, onPress, style }: { c: Resolved; t: Copy; unread: number; onPress: () => void; style?: StyleProp<ViewStyle> }) {
142
+ const scale = useRef(new Animated.Value(1)).current
143
+ const to = (v: number) => Animated.spring(scale, { toValue: v, useNativeDriver: true, damping: 15, stiffness: 400 }).start()
144
+ return (
145
+ <Animated.View style={[g.launcher, { transform: [{ scale }] }, style]}>
146
+ <Pressable
147
+ onPress={onPress}
148
+ onPressIn={() => to(0.92)}
149
+ onPressOut={() => to(1)}
150
+ accessibilityRole="button"
151
+ accessibilityLabel={t.open}
152
+ accessibilityValue={unread ? { text: fill(t.unreadN, { n: unread }) } : undefined}
153
+ style={[g.fab, { backgroundColor: c.accent }]}
154
+ >
155
+ {hi('chat', c.onAccent, 26) ?? (
156
+ <>
157
+ <View style={[g.glyph, { backgroundColor: c.onAccent }]}>
158
+ {[0, 1, 2].map((i) => (
159
+ <View key={i} style={[g.gdot, { backgroundColor: c.accent }]} />
160
+ ))}
161
+ </View>
162
+ <View style={[g.tail, { borderTopColor: c.onAccent }]} />
163
+ </>
164
+ )}
165
+ </Pressable>
166
+ {unread > 0 ? (
167
+ <View pointerEvents="none" style={[g.badge, { backgroundColor: c.danger, borderColor: c.bg }]}>
168
+ <Text allowFontScaling={false} style={g.badgeText}>{unread > 99 ? '99+' : unread}</Text>
169
+ </View>
170
+ ) : null}
171
+ </Animated.View>
172
+ )
173
+ }
174
+
175
+ // Optional peers, detected at runtime: the attach button only shows what the app has installed.
176
+ type Picker = { launchImageLibraryAsync(o: object): Promise<{ canceled?: boolean; assets?: { uri: string; width?: number; height?: number; mimeType?: string; fileName?: string | null }[] | null }>; MediaTypeOptions?: { Images?: unknown }; MediaType?: unknown }
177
+ type Shot = { captureScreen(o: object): Promise<string> }
178
+ type SvgLib = { Svg: ComponentType<Record<string, unknown> & { children?: ReactNode }>; Path: ComponentType<Record<string, unknown>> }
179
+ // Each require sits directly in its own try block: that is what makes Metro treat it as optional, so an app without
180
+ // the package still bundles.
181
+ function picker(): Picker | null {
182
+ try {
183
+ const m = require('expo-image-picker') as Picker
184
+ return typeof m?.launchImageLibraryAsync === 'function' ? m : null
185
+ } catch {
186
+ return null
187
+ }
188
+ }
189
+ function shot(): Shot | null {
190
+ try {
191
+ const m = require('react-native-view-shot') as Shot
192
+ return typeof m?.captureScreen === 'function' ? m : null
193
+ } catch {
194
+ return null
195
+ }
196
+ }
197
+ function svg(): SvgLib | null {
198
+ try {
199
+ const m = require('react-native-svg') as { default?: SvgLib['Svg']; Svg?: SvgLib['Svg']; Path?: SvgLib['Path'] }
200
+ const Svg = m?.Svg ?? m?.default
201
+ return Svg && m.Path ? { Svg, Path: m.Path } : null
202
+ } catch {
203
+ return null
204
+ }
205
+ }
206
+ let peers: { picker: Picker | null; shot: Shot | null; svg: SvgLib | null } | null = null
207
+ export function attachPeers() {
208
+ peers ??= { picker: picker(), shot: shot(), svg: svg() }
209
+ return peers
210
+ }
211
+
212
+ export async function pickPhoto(): Promise<LocalAttachment | null> {
213
+ const m = attachPeers().picker
214
+ if (!m) return null
215
+ const r = await m.launchImageLibraryAsync({ mediaTypes: m.MediaType ? ['images'] : m.MediaTypeOptions?.Images, quality: 0.7, exif: false })
216
+ const a = r.canceled ? null : r.assets?.[0]
217
+ return a ? { uri: a.uri, width: a.width, height: a.height, type: a.mimeType ?? 'image/jpeg', name: a.fileName ?? undefined } : null
218
+ }
219
+
220
+ export async function captureScreen(): Promise<LocalAttachment | null> {
221
+ const m = attachPeers().shot
222
+ if (!m) return null
223
+ const uri = await m.captureScreen({ format: 'jpg', quality: 0.8, result: 'tmpfile' })
224
+ return { uri: uri.startsWith('/') ? 'file://' + uri : uri, type: 'image/jpeg', name: 'screenshot.jpg' }
225
+ }
226
+
227
+ const g = StyleSheet.create({
228
+ box: { width: 16, height: 16, alignItems: 'center', justifyContent: 'center' },
229
+ chev: { width: 10, height: 10, borderStartWidth: 2, borderBottomWidth: 2, borderRadius: 1, transform: [{ rotate: '45deg' }], marginStart: 4 },
230
+ bar: { position: 'absolute', height: 2, borderRadius: 1 },
231
+ up: { position: 'absolute', top: 2, width: 8, height: 8, borderStartWidth: 2, borderTopWidth: 2, borderRadius: 1, transform: [{ rotate: '45deg' }] },
232
+ clock: { width: 10, height: 10, borderRadius: 5, borderWidth: 1.2, alignItems: 'center' },
233
+ hand: { width: 1.2, height: 3.5, marginTop: 1 },
234
+ dots: { flexDirection: 'row', gap: 4, paddingVertical: 4 },
235
+ dot: { width: 7, height: 7, borderRadius: 3.5 },
236
+ launcher: { position: 'absolute', end: 20, bottom: Platform.OS === 'ios' ? 40 : 24 },
237
+ fab: { width: 56, height: 56, borderRadius: 28, alignItems: 'center', justifyContent: 'center', shadowColor: '#000', shadowOpacity: 0.18, shadowRadius: 12, shadowOffset: { width: 0, height: 6 }, elevation: 6 },
238
+ glyph: { width: 24, height: 18, borderRadius: 8, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 3, marginTop: -2 },
239
+ gdot: { width: 3.5, height: 3.5, borderRadius: 2 },
240
+ tail: { width: 0, height: 0, borderStartWidth: 5, borderEndWidth: 0, borderTopWidth: 5, borderStartColor: 'transparent', borderEndColor: 'transparent', marginStart: -10, marginTop: -1 },
241
+ badge: { position: 'absolute', top: -4, end: -4, minWidth: 22, height: 22, borderRadius: 11, borderWidth: 2, paddingHorizontal: 5, alignItems: 'center', justifyContent: 'center' },
242
+ badgeText: { color: '#FFFFFF', fontSize: 12, fontWeight: '600', fontVariant: ['tabular-nums'] }
243
+ })
package/src/react.tsx ADDED
@@ -0,0 +1,140 @@
1
+ // React bindings: <ShotikSupportProvider> (state, AppState catch-up, the widget), useSupport() and <SupportWidget/>:
2
+ // an optional floating launcher with an unread badge, and the chat sheet, mounted on first open only.
3
+
4
+ import { createContext, useContext, useEffect, useMemo, useState, useSyncExternalStore } from 'react'
5
+ import type { ReactNode } from 'react'
6
+ import { AppState, useColorScheme } from 'react-native'
7
+ import type { StyleProp, ViewStyle } from 'react-native'
8
+ import { SupportClient } from './client'
9
+ import type { LocalAttachment, SupportState, UserInfo } from './client'
10
+ import { nativeDevice } from './native'
11
+ import { Launcher } from './parts'
12
+ import { Sheet } from './sheet'
13
+ import { ShotikSupport } from './support'
14
+ import { copyFor, resolveTheme } from './theme'
15
+ import type { SupportTheme } from './theme'
16
+
17
+ const Ctx = createContext<SupportClient | null>(null)
18
+
19
+ export interface WidgetProps {
20
+ // Header title (default "Support" in the user's language).
21
+ title?: string
22
+ // Who answers besides the AI, shown above founder replies (default "Team").
23
+ teamName?: string
24
+ // Brand: accent, onAccent, radius, font, fontBold, scheme, light/dark color overrides.
25
+ theme?: SupportTheme
26
+ // Show the floating launcher with the unread badge (default false: open with ShotikSupport.open()).
27
+ launcher?: boolean
28
+ launcherStyle?: StyleProp<ViewStyle>
29
+ // Chips on the empty thread; a tap sends it as the first message.
30
+ quickReplies?: string[]
31
+ // 'en' | 'ru' (or any tag; unknown languages fall back to en). Default: the device locale.
32
+ locale?: string
33
+ // Deprecated: use theme.accent.
34
+ accentColor?: string
35
+ }
36
+
37
+ export interface ProviderProps extends WidgetProps {
38
+ appKey?: string
39
+ serverUrl?: string
40
+ children?: ReactNode
41
+ widget?: boolean
42
+ }
43
+
44
+ export function ShotikSupportProvider({ appKey, serverUrl, children, widget = true, ...ui }: ProviderProps) {
45
+ const configured = useMemo(() => (appKey && serverUrl ? ShotikSupport.configure({ appKey, serverUrl }) : ShotikSupport.client), [appKey, serverUrl])
46
+ const [client, setClient] = useState<SupportClient | null>(configured)
47
+ useEffect(() => {
48
+ setClient(configured)
49
+ return ShotikSupport.onConfigure(setClient)
50
+ }, [configured])
51
+ useEffect(() => {
52
+ if (!client) return
53
+ client.ensureIdentified().catch(() => {})
54
+ const sub = AppState.addEventListener('change', (s) => {
55
+ if (s === 'active') client.foreground()
56
+ else if (s === 'background') client.disconnect()
57
+ })
58
+ return () => sub.remove()
59
+ }, [client])
60
+ return (
61
+ <Ctx.Provider value={client}>
62
+ {children}
63
+ {widget && client ? <SupportWidget {...ui} /> : null}
64
+ </Ctx.Provider>
65
+ )
66
+ }
67
+
68
+ const idle: SupportState = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {} }
69
+ const noop = () => () => {}
70
+
71
+ export function useSupport() {
72
+ const client = useContext(Ctx) ?? ShotikSupport.client
73
+ const state = useSyncExternalStore(client ? client.subscribe : noop, client ? client.getState : () => idle)
74
+ return useMemo(
75
+ () => ({
76
+ ...state,
77
+ visible: state.open,
78
+ client,
79
+ send: (body: string, conversationId?: string | null, attachments?: LocalAttachment[]) => client?.send(body, conversationId, attachments) ?? null,
80
+ retry: (localId: string) => client?.retry(localId),
81
+ handoff: (conversationId: string) => client?.handoff(conversationId).catch(() => {}),
82
+ url: (path: string) => client?.url(path) ?? path,
83
+ open: (conversationId?: string | null) => client?.open(conversationId),
84
+ close: () => client?.close(),
85
+ select: (conversationId: string | null) => client?.select(conversationId),
86
+ identify: (user?: UserInfo) => client?.identify(user) ?? Promise.resolve()
87
+ }),
88
+ [state, client]
89
+ )
90
+ }
91
+
92
+ export type SupportApi = ReturnType<typeof useSupport>
93
+
94
+ // The sheet embedded in a screen of your own (or a preview): no Modal, at the parent's size, fed by `api` (default: the live
95
+ // useSupport()). `presentation="modal"` renders the regular sheet driven by api.visible.
96
+ export interface SheetViewProps extends Omit<WidgetProps, 'launcher' | 'launcherStyle'> {
97
+ api?: SupportApi
98
+ presentation?: 'modal' | 'inline'
99
+ }
100
+
101
+ export function SupportSheet({ api, presentation = 'inline', title, teamName, theme, quickReplies = [], locale, accentColor }: SheetViewProps) {
102
+ const live = useSupport()
103
+ const s = api ?? live
104
+ const system = useColorScheme() === 'dark' ? 'dark' : 'light'
105
+ const c = useMemo(() => resolveTheme(accentColor && !theme?.accent ? { ...theme, accent: accentColor } : theme, system), [theme, accentColor, system])
106
+ const t = useMemo(() => copyFor(locale ?? nativeDevice().locale), [locale])
107
+ return <Sheet s={s} c={c} t={t} title={title ?? t.title} team={teamName ?? t.team} quickReplies={quickReplies} presentation={presentation} />
108
+ }
109
+
110
+ // A route that opens the widget and steps back, so <scheme>://support deep links and push taps land in support.
111
+ // Expo Router: export { SupportRoute as default } from '@shotik/react-native' in app/support.tsx.
112
+ export function SupportRoute() {
113
+ useEffect(() => {
114
+ try {
115
+ const { router } = require('expo-router') as { router: { canGoBack(): boolean; back(): void; replace(href: string): void } }
116
+ if (router.canGoBack()) router.back()
117
+ else router.replace('/')
118
+ } catch {}
119
+ setTimeout(() => ShotikSupport.open(), 450)
120
+ }, [])
121
+ return null
122
+ }
123
+
124
+ // Nothing but the (optional) launcher renders until the first open; the sheet stays mounted afterwards.
125
+ export function SupportWidget({ title, teamName, theme, launcher = false, launcherStyle, quickReplies = [], locale, accentColor }: WidgetProps) {
126
+ const s = useSupport()
127
+ const system = useColorScheme() === 'dark' ? 'dark' : 'light'
128
+ const c = useMemo(() => resolveTheme(accentColor && !theme?.accent ? { ...theme, accent: accentColor } : theme, system), [theme, accentColor, system])
129
+ const t = useMemo(() => copyFor(locale ?? nativeDevice().locale), [locale])
130
+ const [mounted, setMounted] = useState(s.visible)
131
+ useEffect(() => {
132
+ if (s.visible) setMounted(true)
133
+ }, [s.visible])
134
+ return (
135
+ <>
136
+ {launcher && !s.visible ? <Launcher c={c} t={t} unread={s.unread} onPress={() => s.open()} style={launcherStyle} /> : null}
137
+ {mounted ? <Sheet s={s} c={c} t={t} title={title ?? t.title} team={teamName ?? t.team} quickReplies={quickReplies} /> : null}
138
+ </>
139
+ )
140
+ }