@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/LICENSE +21 -0
- package/README.md +192 -2
- package/README.ru.md +191 -0
- package/dist/analytics/core.d.ts +104 -0
- package/dist/analytics/core.js +345 -0
- package/dist/analytics/index.d.ts +5 -0
- package/dist/analytics/index.js +3 -0
- package/dist/analytics/rn.d.ts +84 -0
- package/dist/analytics/rn.js +413 -0
- package/dist/analytics/wire.d.ts +53 -0
- package/dist/analytics/wire.js +56 -0
- package/dist/client.d.ts +153 -0
- package/dist/client.js +596 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +6 -0
- package/dist/native.d.ts +3 -0
- package/dist/native.js +77 -0
- package/dist/parts.d.ts +103 -0
- package/dist/parts.js +157 -0
- package/dist/react.d.ts +51 -0
- package/dist/react.js +88 -0
- package/dist/sheet.d.ts +12 -0
- package/dist/sheet.js +273 -0
- package/dist/support.d.ts +12 -0
- package/dist/support.js +60 -0
- package/dist/theme.d.ts +72 -0
- package/dist/theme.js +95 -0
- package/guide.json +136 -0
- package/package.json +114 -4
- package/recipe.json +263 -0
- package/src/analytics/README.md +32 -0
- package/src/analytics/core.ts +380 -0
- package/src/analytics/index.ts +7 -0
- package/src/analytics/recipe.json +263 -0
- package/src/analytics/rn.tsx +425 -0
- package/src/analytics/wire.ts +123 -0
- package/src/client.ts +685 -0
- package/src/index.ts +10 -0
- package/src/native.ts +90 -0
- package/src/parts.tsx +243 -0
- package/src/react.tsx +140 -0
- package/src/sheet.tsx +538 -0
- package/src/support.ts +55 -0
- package/src/theme.ts +141 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Shotik
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,193 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @shotik/react-native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Shotik SDK for React Native and Expo: in-app support chat and product analytics in one package. Русская версия:
|
|
4
|
+
[README.ru.md](README.ru.md).
|
|
5
|
+
|
|
6
|
+
Support is in-app chat for your app. Users write from your app; the conversation lands in Shotik's
|
|
7
|
+
Support inbox on your Mac, where you (or the AI) answer. Replies arrive live, and push-ready events are recorded for
|
|
8
|
+
users who closed the app.
|
|
9
|
+
|
|
10
|
+
- Pure TypeScript with no native code, so it runs in any Expo dev client or bare RN app without a rebuild.
|
|
11
|
+
- Peer dependencies: `react`, `react-native`. It uses these when your app already has them: `expo-device`,
|
|
12
|
+
`expo-application`, `expo-localization` (device context), and `@react-native-async-storage/async-storage` or
|
|
13
|
+
`expo-secure-store` (persistence). Without them it falls back to `Platform`, `Intl` and in-memory storage.
|
|
14
|
+
- Anonymous users get a persisted id. When they sign in, their chats move to the signed-in user.
|
|
15
|
+
- Sends are optimistic and queued while offline. The stream reconnects with backoff and catches up when the app
|
|
16
|
+
returns to the foreground.
|
|
17
|
+
- A native-feeling chat sheet: drag handle, spring open and close, keyboard-avoiding, an optional floating launcher
|
|
18
|
+
with an unread badge, receipts (sending, sent, delivered, seen), a typing indicator while the AI drafts or you type
|
|
19
|
+
in Shotik, quick-reply chips, "Talk to a person", photos and screenshots, light and dark, Dynamic Type, VoiceOver
|
|
20
|
+
and RTL. Copy is English or Russian, picked from the device locale.
|
|
21
|
+
- Small: about 44 KB minified for the whole SDK (14 KB gzipped). Nothing renders until the first open except the
|
|
22
|
+
launcher, and every animation runs on the native driver.
|
|
23
|
+
|
|
24
|
+
## 1. Install
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npx expo install @shotik/react-native # or: npm install / bun add / pnpm add / yarn add @shotik/react-native
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Moving from the vendored copy (`vendor/shotik-support-react-native`)? Remove that dependency and folder, then change
|
|
31
|
+
imports from `@shotik/support-react-native` to `@shotik/react-native`. The exports are the same.
|
|
32
|
+
|
|
33
|
+
## 2. Wrap your root
|
|
34
|
+
|
|
35
|
+
Get the public key (`spk_…`) from Shotik → Support → SDK. It is a public app key, so it is safe in the bundle.
|
|
36
|
+
|
|
37
|
+
```tsx
|
|
38
|
+
// app/_layout.tsx (Expo Router) or App.tsx
|
|
39
|
+
import { ShotikSupportProvider } from '@shotik/react-native'
|
|
40
|
+
|
|
41
|
+
export default function RootLayout() {
|
|
42
|
+
return (
|
|
43
|
+
<GestureHandlerRootView style={{ flex: 1 }}>
|
|
44
|
+
<ShotikSupportProvider appKey="spk_…" serverUrl="https://support.example.com">
|
|
45
|
+
<Stack />
|
|
46
|
+
</ShotikSupportProvider>
|
|
47
|
+
</GestureHandlerRootView>
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The provider identifies the user anonymously, keeps the live stream open while the app is in the foreground, and
|
|
53
|
+
renders `<SupportWidget/>`, a bottom sheet that mounts on the first open. Pass `widget={false}` to place
|
|
54
|
+
`<SupportWidget/>` yourself; it takes the same props.
|
|
55
|
+
|
|
56
|
+
### Brand it
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
<ShotikSupportProvider
|
|
60
|
+
appKey="spk_…"
|
|
61
|
+
serverUrl="https://support.example.com"
|
|
62
|
+
launcher // floating button with the unread badge (default off)
|
|
63
|
+
title="Walkito" // header (default "Support" / "Поддержка")
|
|
64
|
+
teamName="Rahim" // label above your replies (default "Team" / "Команда")
|
|
65
|
+
quickReplies={['Billing', 'Report a bug']} // chips on a new conversation
|
|
66
|
+
theme={{ accent: '#FF5A1F', radius: 18, font: 'Inter-Regular', fontBold: 'Inter-SemiBold' }}
|
|
67
|
+
locale="ru" // default: the device locale; en is the fallback
|
|
68
|
+
>
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| `theme` | Default | |
|
|
72
|
+
|---|---|---|
|
|
73
|
+
| `accent` | iOS blue | Your bubbles, send button, launcher, links |
|
|
74
|
+
| `onAccent` | `#FFFFFF` | Text and glyphs on the accent |
|
|
75
|
+
| `radius` | `18` | Bubble radius; the sheet, chips and field follow it |
|
|
76
|
+
| `font`, `fontBold` | system | `fontFamily` for regular and semibold text |
|
|
77
|
+
| `scheme` | system | Force `'light'` or `'dark'` |
|
|
78
|
+
| `light`, `dark` | | Override colors: `bg raised line text sub faint danger ok warn backdrop` |
|
|
79
|
+
|
|
80
|
+
Light and dark follow the system. Text scales with Dynamic Type, every control has a VoiceOver label, new replies are
|
|
81
|
+
announced, and layouts use start/end so RTL works.
|
|
82
|
+
|
|
83
|
+
### Attachments (optional)
|
|
84
|
+
|
|
85
|
+
The attach button appears only when the app already has one of these installed (both need a native build, so the SDK
|
|
86
|
+
never adds them for you):
|
|
87
|
+
|
|
88
|
+
- `expo-image-picker`: a photo from the library.
|
|
89
|
+
- `react-native-view-shot`: a screenshot of the app (the sheet steps aside while it is taken).
|
|
90
|
+
|
|
91
|
+
Images upload to the Shotik server (8 MB cap) and show in your Shotik inbox.
|
|
92
|
+
|
|
93
|
+
### Icons (optional)
|
|
94
|
+
|
|
95
|
+
With `react-native-svg` installed (Expo apps usually have it), the widget draws its icons from the Hugeicons set.
|
|
96
|
+
Without it, simple built-in shapes stand in.
|
|
97
|
+
|
|
98
|
+
## 3. Open it
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
import { ShotikSupport } from '@shotik/react-native'
|
|
102
|
+
|
|
103
|
+
<Row label="Help" onPress={() => ShotikSupport.open()} />
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Deep link (and push taps): with Expo Router, add `app/support.tsx`:
|
|
107
|
+
|
|
108
|
+
```tsx
|
|
109
|
+
export { SupportRoute as default } from '@shotik/react-native'
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`myapp://support` then opens the chat over the current screen.
|
|
113
|
+
|
|
114
|
+
## 4. Identify after sign-in
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
ShotikSupport.identify({ userId: user.id, email: user.email, name: user.name, attributes: { plan: 'pro' } })
|
|
118
|
+
// sign-out
|
|
119
|
+
ShotikSupport.reset()
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
You can call it anywhere, including at module scope before the provider mounts, because calls made before
|
|
123
|
+
`configure` are held until it runs. Every identify sends the device context: platform, OS version, model, app
|
|
124
|
+
version and build, locale and time zone.
|
|
125
|
+
|
|
126
|
+
## 5. Push
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
const { data: token } = await Notifications.getExpoPushTokenAsync({ projectId })
|
|
130
|
+
ShotikSupport.setPushToken(token, Platform.OS)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Every founder or AI reply is recorded as a push-ready event (`GET /v1/support/events`) with the user's token and a
|
|
134
|
+
preview. A reply already delivered over the live stream is marked delivered.
|
|
135
|
+
|
|
136
|
+
## Hook and API
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
const { conversations, messages, unread, unreadBy, typing, status, open, send, retry, handoff, select, close } = useSupport()
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
| | |
|
|
143
|
+
|---|---|
|
|
144
|
+
| `ShotikSupport.configure({ appKey, serverUrl })` | Done by the provider when it gets props. Call it yourself to use the hook without the provider's props. |
|
|
145
|
+
| `identify(user?)`, `reset()` | Signed-in user / sign-out (new anonymous id). |
|
|
146
|
+
| `setPushToken(token, platform?)` | Expo or APNs/FCM token; `null` clears it. |
|
|
147
|
+
| `open(conversationId?)`, `close()` | Show or hide the sheet. |
|
|
148
|
+
| `status` | `idle · identifying · connecting · live · offline · error` |
|
|
149
|
+
| `send(body, conversationId?, attachments?)` | Optimistic. Without an id it starts a new conversation. `attachments`: `[{ uri, type?, width?, height? }]` (file:// or data:). Returns the local message. |
|
|
150
|
+
| `retry(localId)` | Resend a message marked `pending: 'failed'`. |
|
|
151
|
+
| `handoff(conversationId)` | "Talk to a person": the conversation goes to your Needs-human list and the AI stops answering it. |
|
|
152
|
+
| `typing` | `{ [conversationId]: 'ai' \| 'founder' }` while the AI drafts or you type in Shotik. |
|
|
153
|
+
| `receiptOf(message, list, conversation, offline?)` | `sending · queued · failed · sent · delivered · seen` for your messages. Delivered = reached Shotik; seen = you read it there. |
|
|
154
|
+
| `SupportClient` (`@shotik/react-native/client`) | The platform-free core, usable outside React. |
|
|
155
|
+
|
|
156
|
+
Conversation status `needs_human` shows a "A person will reply" strip above the composer. Replies are labelled **AI** or
|
|
157
|
+
with `teamName`. After an AI answer the thread offers its quick replies (from the answer, or the defaults you set in
|
|
158
|
+
Shotik as `support.quickReplies:<appId>`) and "Talk to a person".
|
|
159
|
+
|
|
160
|
+
## Analytics
|
|
161
|
+
|
|
162
|
+
The same package ships analytics at `@shotik/react-native/analytics`, using the same key. See
|
|
163
|
+
[src/analytics/README.md](src/analytics/README.md).
|
|
164
|
+
|
|
165
|
+
## Troubleshooting
|
|
166
|
+
|
|
167
|
+
- **Status stays `offline`.** The phone can't reach `serverUrl`. A simulator reaches the Mac at `http://127.0.0.1:<port>`,
|
|
168
|
+
but a device needs the Mac's LAN address (`http://192.168.x.x:<port>`) or an HTTPS deployment. Check with
|
|
169
|
+
`curl <serverUrl>/health`.
|
|
170
|
+
- **Status is `error` with "unknown app key".** The key doesn't belong to this server. Create it again in Shotik.
|
|
171
|
+
- **Plain `http://` is blocked on a device.** iOS App Transport Security allows only HTTPS in release builds. Use HTTPS,
|
|
172
|
+
or add an ATS exception for development only.
|
|
173
|
+
- **Nothing persists between launches.** Install `expo-secure-store` or `@react-native-async-storage/async-storage`
|
|
174
|
+
(both are optional). Without one, the anonymous id resets on every launch.
|
|
175
|
+
- **TypeScript can't find the types.** They ship in `dist/` and resolve through `exports`. Use
|
|
176
|
+
`moduleResolution: "bundler"` (the Expo default). Metro reads the TypeScript source in `src/`.
|
|
177
|
+
- **`myapp://support` shows "not found".** The route file is missing, or your router root is `src/app`. Put
|
|
178
|
+
`support.tsx` next to your root `_layout.tsx`.
|
|
179
|
+
- **Messages sit at "Sending".** While offline they show "Queued" and the header counts them; they go out when the
|
|
180
|
+
server is reachable. After 3 failed attempts they show "Not sent · Retry".
|
|
181
|
+
- **No attach button.** Neither `expo-image-picker` nor `react-native-view-shot` is in the dev client. Install one
|
|
182
|
+
and rebuild the dev client.
|
|
183
|
+
|
|
184
|
+
## Tests
|
|
185
|
+
|
|
186
|
+
The client is tested against a real Shotik server and a founder's synced store: identify, the user message arriving as
|
|
187
|
+
synced rows, the founder reply arriving on the stream, push-ready events, the offline queue across a restart,
|
|
188
|
+
reconnect, the anonymous-to-identified merge, a bad key, receipts (delivered, seen), typing (founder, throttled, and
|
|
189
|
+
AI drafting), attachments through the offline queue, and a Russian-speaking user (AI answer, handoff note).
|
|
190
|
+
|
|
191
|
+
```sh
|
|
192
|
+
node --disable-warning=ExperimentalWarning --test server/test/support.test.ts
|
|
193
|
+
```
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# @shotik/react-native
|
|
2
|
+
|
|
3
|
+
SDK Shotik для React Native и Expo: чат поддержки внутри приложения и продуктовая аналитика в одном пакете. English:
|
|
4
|
+
[README.md](README.md).
|
|
5
|
+
|
|
6
|
+
Поддержка — это чат внутри вашего приложения. Пользователь пишет из приложения, разговор попадает во входящие Support в
|
|
7
|
+
Shotik на вашем Mac, а отвечаете вы или ИИ. Ответы приходят вживую, а для тех, кто закрыл приложение, записываются
|
|
8
|
+
события, готовые к пушу.
|
|
9
|
+
|
|
10
|
+
- Чистый TypeScript без нативного кода: работает в любом Expo dev client и в bare RN без пересборки.
|
|
11
|
+
- Peer-зависимости: `react`, `react-native`. Если в приложении уже есть `expo-device`, `expo-application`,
|
|
12
|
+
`expo-localization` (контекст устройства) и `@react-native-async-storage/async-storage` или `expo-secure-store`
|
|
13
|
+
(хранилище), SDK ими пользуется. Без них — `Platform`, `Intl` и память.
|
|
14
|
+
- Анонимный пользователь получает сохраняемый id. После входа его чаты переходят к вошедшему пользователю.
|
|
15
|
+
- Отправка оптимистичная и встаёт в очередь без сети. Поток переподключается с паузами и догоняет пропущенное, когда
|
|
16
|
+
приложение возвращается на передний план.
|
|
17
|
+
- Нативный по ощущениям лист чата: ручка, пружинное открытие и закрытие, обход клавиатуры, по желанию плавающая кнопка
|
|
18
|
+
со счётчиком непрочитанного, статусы (отправляется, отправлено, доставлено, прочитано), индикатор набора, быстрые
|
|
19
|
+
ответы, «Позвать человека», фото и скриншоты, светлая и тёмная темы, Dynamic Type, VoiceOver и RTL. Тексты на
|
|
20
|
+
английском или русском, по языку устройства.
|
|
21
|
+
- Небольшой: около 44 КБ минифицированного кода на весь SDK (14 КБ в gzip). До первого открытия рисуется только
|
|
22
|
+
кнопка, а все анимации идут на нативном драйвере.
|
|
23
|
+
|
|
24
|
+
## 1. Установка
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npx expo install @shotik/react-native # или: npm install / bun add / pnpm add / yarn add @shotik/react-native
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Раньше SDK лежал копией в `vendor/shotik-support-react-native`? Удалите эту зависимость и папку и замените импорты
|
|
31
|
+
`@shotik/support-react-native` на `@shotik/react-native`. Экспорты те же.
|
|
32
|
+
|
|
33
|
+
## 2. Оберните корень
|
|
34
|
+
|
|
35
|
+
Публичный ключ (`spk_…`) возьмите в Shotik → Support → SDK. Это публичный ключ приложения, его можно класть в бандл.
|
|
36
|
+
|
|
37
|
+
```tsx
|
|
38
|
+
// app/_layout.tsx (Expo Router) или App.tsx
|
|
39
|
+
import { ShotikSupportProvider } from '@shotik/react-native'
|
|
40
|
+
|
|
41
|
+
export default function RootLayout() {
|
|
42
|
+
return (
|
|
43
|
+
<GestureHandlerRootView style={{ flex: 1 }}>
|
|
44
|
+
<ShotikSupportProvider appKey="spk_…" serverUrl="https://support.example.com">
|
|
45
|
+
<Stack />
|
|
46
|
+
</ShotikSupportProvider>
|
|
47
|
+
</GestureHandlerRootView>
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Провайдер анонимно определяет пользователя, держит поток открытым, пока приложение на переднем плане, и рисует
|
|
53
|
+
`<SupportWidget/>` — нижний лист, который монтируется при первом открытии. С `widget={false}` вы ставите
|
|
54
|
+
`<SupportWidget/>` сами, пропсы те же.
|
|
55
|
+
|
|
56
|
+
### Фирменный вид
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
<ShotikSupportProvider
|
|
60
|
+
appKey="spk_…"
|
|
61
|
+
serverUrl="https://support.example.com"
|
|
62
|
+
launcher // плавающая кнопка со счётчиком (по умолчанию выкл.)
|
|
63
|
+
title="Walkito" // заголовок (по умолчанию "Support" / "Поддержка")
|
|
64
|
+
teamName="Rahim" // подпись над вашими ответами (по умолчанию "Team" / "Команда")
|
|
65
|
+
quickReplies={['Оплата', 'Сообщить об ошибке']} // чипы в новом разговоре
|
|
66
|
+
theme={{ accent: '#FF5A1F', radius: 18, font: 'Inter-Regular', fontBold: 'Inter-SemiBold' }}
|
|
67
|
+
locale="ru" // по умолчанию язык устройства; запасной — en
|
|
68
|
+
>
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| `theme` | По умолчанию | |
|
|
72
|
+
|---|---|---|
|
|
73
|
+
| `accent` | синий iOS | Ваши пузыри, кнопка отправки, плавающая кнопка, ссылки |
|
|
74
|
+
| `onAccent` | `#FFFFFF` | Текст и значки на акцентном цвете |
|
|
75
|
+
| `radius` | `18` | Скругление пузырей; лист, чипы и поле следуют за ним |
|
|
76
|
+
| `font`, `fontBold` | системный | `fontFamily` для обычного и полужирного текста |
|
|
77
|
+
| `scheme` | системная | Принудительно `'light'` или `'dark'` |
|
|
78
|
+
| `light`, `dark` | | Свои цвета: `bg raised line text sub faint danger ok warn backdrop` |
|
|
79
|
+
|
|
80
|
+
### Вложения (необязательно)
|
|
81
|
+
|
|
82
|
+
Кнопка вложения появляется, только если в приложении уже есть один из пакетов (обоим нужна нативная сборка, поэтому SDK
|
|
83
|
+
сам их не добавляет):
|
|
84
|
+
|
|
85
|
+
- `expo-image-picker`: фото из галереи.
|
|
86
|
+
- `react-native-view-shot`: скриншот приложения (лист на это время отходит в сторону).
|
|
87
|
+
|
|
88
|
+
Картинки загружаются на сервер Shotik (до 8 МБ) и видны во входящих Shotik.
|
|
89
|
+
|
|
90
|
+
### Иконки (необязательно)
|
|
91
|
+
|
|
92
|
+
С `react-native-svg` (в Expo-приложениях он обычно есть) виджет рисует иконки из набора Hugeicons. Без него — простые
|
|
93
|
+
встроенные формы.
|
|
94
|
+
|
|
95
|
+
## 3. Откройте чат
|
|
96
|
+
|
|
97
|
+
```tsx
|
|
98
|
+
import { ShotikSupport } from '@shotik/react-native'
|
|
99
|
+
|
|
100
|
+
<Row label="Помощь" onPress={() => ShotikSupport.open()} />
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Диплинк (и тап по пушу): в Expo Router добавьте `app/support.tsx`:
|
|
104
|
+
|
|
105
|
+
```tsx
|
|
106
|
+
export { SupportRoute as default } from '@shotik/react-native'
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Тогда `myapp://support` открывает чат поверх текущего экрана.
|
|
110
|
+
|
|
111
|
+
## 4. Пользователь после входа
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
ShotikSupport.identify({ userId: user.id, email: user.email, name: user.name, attributes: { plan: 'pro' } })
|
|
115
|
+
// выход
|
|
116
|
+
ShotikSupport.reset()
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Вызывать можно где угодно, даже на уровне модуля до монтирования провайдера: вызовы до `configure` ждут его.
|
|
120
|
+
Каждый identify отправляет контекст устройства: платформу, версию ОС, модель, версию и сборку приложения, язык и
|
|
121
|
+
часовой пояс.
|
|
122
|
+
|
|
123
|
+
## 5. Пуши
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const { data: token } = await Notifications.getExpoPushTokenAsync({ projectId })
|
|
127
|
+
ShotikSupport.setPushToken(token, Platform.OS)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Каждый ответ ваш или ИИ записывается как событие для пуша (`GET /v1/support/events`) с токеном пользователя и
|
|
131
|
+
превью. Ответ, уже доставленный по живому потоку, помечается доставленным.
|
|
132
|
+
|
|
133
|
+
## Хук и API
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
const { conversations, messages, unread, unreadBy, typing, status, open, send, retry, handoff, select, close } = useSupport()
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
| | |
|
|
140
|
+
|---|---|
|
|
141
|
+
| `ShotikSupport.configure({ appKey, serverUrl })` | Делает провайдер, когда получает пропсы. Вызовите сами, чтобы пользоваться хуком без пропсов провайдера. |
|
|
142
|
+
| `identify(user?)`, `reset()` | Вошедший пользователь / выход (новый анонимный id). |
|
|
143
|
+
| `setPushToken(token, platform?)` | Токен Expo или APNs/FCM; `null` очищает. |
|
|
144
|
+
| `open(conversationId?)`, `close()` | Показать или скрыть лист. |
|
|
145
|
+
| `status` | `idle · identifying · connecting · live · offline · error` |
|
|
146
|
+
| `send(body, conversationId?, attachments?)` | Оптимистично. Без id начинает новый разговор. `attachments`: `[{ uri, type?, width?, height? }]` (file:// или data:). Возвращает локальное сообщение. |
|
|
147
|
+
| `retry(localId)` | Повторить сообщение с `pending: 'failed'`. |
|
|
148
|
+
| `handoff(conversationId)` | «Позвать человека»: разговор уходит в список Needs human, ИИ перестаёт отвечать. |
|
|
149
|
+
| `typing` | `{ [conversationId]: 'ai' \| 'founder' }`, пока ИИ пишет черновик или вы печатаете в Shotik. |
|
|
150
|
+
| `receiptOf(message, list, conversation, offline?)` | `sending · queued · failed · sent · delivered · seen` для ваших сообщений. Доставлено = дошло до Shotik; прочитано = вы открыли его там. |
|
|
151
|
+
| `SupportClient` (`@shotik/react-native/client`) | Ядро без привязки к платформе, работает и вне React. |
|
|
152
|
+
|
|
153
|
+
## Аналитика
|
|
154
|
+
|
|
155
|
+
В том же пакете есть аналитика: `@shotik/react-native/analytics`, с тем же ключом.
|
|
156
|
+
|
|
157
|
+
```tsx
|
|
158
|
+
import { ShotikAnalytics, ShotikAnalyticsRoot, useShotikExpoRouter } from '@shotik/react-native/analytics'
|
|
159
|
+
|
|
160
|
+
ShotikAnalytics.init({ appKey: 'spk_…', serverUrl: 'https://…' })
|
|
161
|
+
|
|
162
|
+
export default function RootLayout() {
|
|
163
|
+
useShotikExpoRouter()
|
|
164
|
+
return <ShotikAnalyticsRoot>{/* ваши провайдеры и <Stack /> */}</ShotikAnalyticsRoot>
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Сама собирает сессии, экраны (шаблоны маршрутов, без параметров), тапы, rage-тапы, ошибки, медленные экраны, покупки
|
|
169
|
+
RevenueCat и для 20% сессий вайрфреймы экранов (`snapshots: 0.2`; `snapshots: 0` выключает). Вайрфреймы — только
|
|
170
|
+
прямоугольники без символов текста и без картинок. Значения полей ввода не читаются никогда, `<ShotikMask>` скрывает
|
|
171
|
+
вид целиком, а `init({ consent: 'pending' })` держит события на устройстве до согласия. Подробности —
|
|
172
|
+
[src/analytics/README.md](src/analytics/README.md).
|
|
173
|
+
|
|
174
|
+
## Если что-то не так
|
|
175
|
+
|
|
176
|
+
- **Статус остаётся `offline`.** Телефон не достаёт до `serverUrl`. Симулятор видит Mac по `http://127.0.0.1:<порт>`,
|
|
177
|
+
а устройству нужен адрес Mac в локальной сети (`http://192.168.x.x:<порт>`) или HTTPS. Проверьте
|
|
178
|
+
`curl <serverUrl>/health`.
|
|
179
|
+
- **Статус `error` и «unknown app key».** Ключ не от этого сервера. Создайте его заново в Shotik.
|
|
180
|
+
- **Обычный `http://` блокируется на устройстве.** App Transport Security в релизе пускает только HTTPS. Используйте
|
|
181
|
+
HTTPS или исключение ATS только для разработки.
|
|
182
|
+
- **Ничего не сохраняется между запусками.** Поставьте `expo-secure-store` или
|
|
183
|
+
`@react-native-async-storage/async-storage`. Без них анонимный id сбрасывается при каждом запуске.
|
|
184
|
+
- **TypeScript не находит типы.** Они лежат в `dist/` и подключаются через `exports`. Нужен
|
|
185
|
+
`moduleResolution: "bundler"` (по умолчанию в Expo). Metro читает исходники TypeScript из `src/`.
|
|
186
|
+
- **`myapp://support` показывает «not found».** Нет файла маршрута или корень роутера — `src/app`. Положите
|
|
187
|
+
`support.tsx` рядом с корневым `_layout.tsx`.
|
|
188
|
+
- **Сообщения висят в «Отправляется».** Без сети они «В очереди», а шапка показывает их число; уйдут, когда сервер
|
|
189
|
+
станет доступен. После 3 неудачных попыток — «Не отправлено · Повторить».
|
|
190
|
+
- **Нет кнопки вложения.** В dev client нет ни `expo-image-picker`, ни `react-native-view-shot`. Поставьте один и
|
|
191
|
+
пересоберите dev client.
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { DeviceContext, Wireframe } from './wire';
|
|
2
|
+
export interface Storage {
|
|
3
|
+
get(key: string): Promise<string | null>;
|
|
4
|
+
set(key: string, value: string): Promise<void>;
|
|
5
|
+
remove(key: string): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export type Consent = 'granted' | 'denied' | 'pending';
|
|
8
|
+
export interface AnalyticsConfig {
|
|
9
|
+
appKey: string;
|
|
10
|
+
serverUrl: string;
|
|
11
|
+
storage?: Storage;
|
|
12
|
+
device?: () => DeviceContext;
|
|
13
|
+
consent?: Consent;
|
|
14
|
+
snapshots?: number;
|
|
15
|
+
flushMs?: number;
|
|
16
|
+
sessionTimeoutMs?: number;
|
|
17
|
+
debug?: boolean;
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
now?: () => number;
|
|
20
|
+
}
|
|
21
|
+
export declare class Analytics {
|
|
22
|
+
readonly cfg: AnalyticsConfig;
|
|
23
|
+
private st;
|
|
24
|
+
private now;
|
|
25
|
+
private queue;
|
|
26
|
+
private snaps;
|
|
27
|
+
private anon;
|
|
28
|
+
private userId;
|
|
29
|
+
private firstSeen;
|
|
30
|
+
private sessionId;
|
|
31
|
+
private lastActive;
|
|
32
|
+
private seq;
|
|
33
|
+
private sampled;
|
|
34
|
+
private consent;
|
|
35
|
+
private screen;
|
|
36
|
+
private screenAt;
|
|
37
|
+
private screenStats;
|
|
38
|
+
private taps;
|
|
39
|
+
private snapped;
|
|
40
|
+
private timer;
|
|
41
|
+
private saveTimer;
|
|
42
|
+
private sending;
|
|
43
|
+
private inflight;
|
|
44
|
+
private backoff;
|
|
45
|
+
private ready;
|
|
46
|
+
private active;
|
|
47
|
+
private loaded;
|
|
48
|
+
private fresh;
|
|
49
|
+
private storeIssue;
|
|
50
|
+
constructor(cfg: AnalyticsConfig);
|
|
51
|
+
private load;
|
|
52
|
+
private touch;
|
|
53
|
+
private push;
|
|
54
|
+
private save;
|
|
55
|
+
private persist;
|
|
56
|
+
private schedule;
|
|
57
|
+
track(name: string, props?: Record<string, unknown>): void;
|
|
58
|
+
identify(userId: string | null, traits?: Record<string, unknown>): void;
|
|
59
|
+
screenView(name: string): void;
|
|
60
|
+
private leave;
|
|
61
|
+
get currentScreen(): string | undefined;
|
|
62
|
+
screenReady(ms: number): void;
|
|
63
|
+
stall(ms: number): void;
|
|
64
|
+
tap(t: {
|
|
65
|
+
el: string;
|
|
66
|
+
id?: string;
|
|
67
|
+
label?: string;
|
|
68
|
+
x: number;
|
|
69
|
+
y: number;
|
|
70
|
+
nx: number;
|
|
71
|
+
ny: number;
|
|
72
|
+
dead?: boolean;
|
|
73
|
+
input?: boolean;
|
|
74
|
+
ts?: number;
|
|
75
|
+
}): void;
|
|
76
|
+
scroll(depth: number | null, drag: number): void;
|
|
77
|
+
error(e: unknown, fatal?: boolean): void;
|
|
78
|
+
purchase(p: {
|
|
79
|
+
product: string;
|
|
80
|
+
status: 'start' | 'done' | 'cancel' | 'fail';
|
|
81
|
+
price?: number;
|
|
82
|
+
currency?: string;
|
|
83
|
+
store?: string;
|
|
84
|
+
trial?: boolean;
|
|
85
|
+
}): void;
|
|
86
|
+
wantsSnapshot(screen: string): boolean;
|
|
87
|
+
snapshot(w: Omit<Wireframe, 'sessionId' | 'ts'>): void;
|
|
88
|
+
foreground(): void;
|
|
89
|
+
background(): void;
|
|
90
|
+
setConsent(c: Consent): void;
|
|
91
|
+
optOut(): void;
|
|
92
|
+
optIn(): void;
|
|
93
|
+
reset(): Promise<void>;
|
|
94
|
+
flush(): Promise<void>;
|
|
95
|
+
private send;
|
|
96
|
+
stop(): void;
|
|
97
|
+
get ids(): {
|
|
98
|
+
anonymousId: string;
|
|
99
|
+
sessionId: string;
|
|
100
|
+
userId: string | null;
|
|
101
|
+
};
|
|
102
|
+
get pending(): number;
|
|
103
|
+
whenReady(): Promise<void>;
|
|
104
|
+
}
|