hubchat-react-native 0.0.0-stage → 1.0.2

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 ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HubChat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # hubchat-react-native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ویجت چت پشتیبانی هاب‌چت برای اپ‌های React Native (iOS و اندروید)، با همان ظاهر و امکانات ویجت سایت.
4
+
5
+ ## امکانات
6
+ - دکمه‌ی شناور با رنگ، آیکن، متن و جایگاهی که در پنل هاب‌چت تنظیم کرده‌اید
7
+ - پنل گفتگو با همان ظاهر و امکانات ویجت سایت: ارسال فایل و عکس، پایگاه دانش، ساعات کاری و نظرسنجی رضایت
8
+ - شمارنده‌ی پیام‌های خوانده‌نشده روی دکمه، حتی وقتی پنل بسته است
9
+ - تغییر ظاهر از پنل، بدون نیاز به انتشار نسخه‌ی جدید اپ
10
+ - پیام‌های کاربران در صندوق ورودی هاب‌چت، کنار تلگرام، بله، روبیکا و بقیه‌ی کانال‌ها
11
+
12
+ ## کلید کانال
13
+ کلید را از پنل هاب‌چت بگیرید: «تنظیمات > کانال‌ها > افزودن کانال > اپلیکیشن موبایل». کلید با `hc_` شروع می‌شود و در صفحه‌ی همان کانال، کنار نمونه‌کد نصب، نمایش داده می‌شود.
14
+
15
+ ## نصب
16
+ ```bash
17
+ npm install hubchat-react-native react-native-webview
18
+ cd ios && pod install
19
+ ```
20
+
21
+ ## استفاده
22
+ ```tsx
23
+ import { HubChatProvider, useHubChat } from 'hubchat-react-native';
24
+
25
+ export default function App() {
26
+ return (
27
+ <HubChatProvider widgetKey="hc_xxxxxxxxxxxxxxxxxxxxxxxx" bottomOffset={56}>
28
+ <RootNavigator />
29
+ </HubChatProvider>
30
+ );
31
+ }
32
+
33
+ function SupportButton() {
34
+ const chat = useHubChat();
35
+ return <Button title="پشتیبانی" onPress={chat.open} />;
36
+ }
37
+ ```
38
+
39
+ ## ویژگی‌ها (props)
40
+ | prop | توضیح |
41
+ |---|---|
42
+ | `widgetKey` | کلید ویجت از پنل (`hc_...`) |
43
+ | `showLauncher` | نمایش دکمه‌ی شناور (پیش‌فرض `true`) |
44
+ | `bottomOffset` | فاصله‌ی اضافه از پایین (مثلاً بالای تب‌بار) |
45
+ | `onUnreadChange` | تعداد پیام‌های خوانده‌نشده |
46
+ | `onEvent` | رویدادهای `ready`، `close`، `unread` |
47
+
48
+ ## تنظیمات iOS
49
+ برای آپلود فایل در iOS این کلیدها را به `Info.plist` اضافه کنید: `NSCameraUsageDescription`، `NSPhotoLibraryUsageDescription`، `NSMicrophoneUsageDescription`.
50
+
51
+ ## پشتیبانی
52
+ - مستندات: https://hubchat.ir/docs/connect-channel/mobile_sdk
53
+ - گزارش مشکل: بخش Issues همین مخزن
54
+ - وب‌سایت: https://hubchat.ir
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "hubchat-react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.2",
4
+ "description": "HubChat support chat widget for React Native (iOS & Android)",
5
+ "main": "src/index.tsx",
6
+ "types": "src/index.tsx",
7
+ "files": [
8
+ "src",
9
+ "README.md",
10
+ "LICENSE"
11
+ ],
12
+ "license": "MIT",
13
+ "peerDependencies": {
14
+ "react": ">=17",
15
+ "react-native": ">=0.68",
16
+ "react-native-webview": ">=11"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/HubChat-ai/HubChat-react-native.git"
21
+ },
22
+ "keywords": [
23
+ "hubchat",
24
+ "live-chat",
25
+ "chat",
26
+ "customer-support",
27
+ "react-native",
28
+ "webview"
29
+ ],
30
+ "homepage": "https://hubchat.ir",
31
+ "bugs": {
32
+ "url": "https://github.com/HubChat-ai/HubChat-react-native/issues"
33
+ },
34
+ "author": "HubChat"
35
+ }
package/src/index.tsx ADDED
@@ -0,0 +1,218 @@
1
+ import React, { createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
2
+ import { Animated, Image, Platform, Pressable, SafeAreaView, StyleSheet, Text, View, type ViewStyle } from 'react-native';
3
+ import { WebView, type WebViewMessageEvent } from 'react-native-webview';
4
+ import { contrastOn, DEFAULT_BASE_URL, faDigits, fetchSettings, hostCommand, widgetUrl, type HubChatEvent, type HubChatSettings } from './protocol';
5
+
6
+ export type { HubChatSettings, HubChatEvent } from './protocol';
7
+
8
+ export type HubChatProps = {
9
+ /** Widget key from the HubChat panel (hc_...). */
10
+ widgetKey: string;
11
+ /** Custom widget host. Leave empty to use https://widget.hubchat.ir. */
12
+ baseUrl?: string;
13
+ /** Show the floating launcher button. Set false to open only via ref / useHubChat(). */
14
+ showLauncher?: boolean;
15
+ /** Extra offset of the launcher from the bottom (e.g. above a tab bar). */
16
+ bottomOffset?: number;
17
+ onEvent?: (event: HubChatEvent) => void;
18
+ onUnreadChange?: (count: number) => void;
19
+ };
20
+
21
+ export type HubChatHandle = { open: () => void; close: () => void; isOpen: () => boolean };
22
+
23
+ const HubChatContext = createContext<HubChatHandle | null>(null);
24
+
25
+ /** Access open/close from anywhere under <HubChatProvider>. */
26
+ export function useHubChat(): HubChatHandle {
27
+ const handle = useContext(HubChatContext);
28
+
29
+ if (!handle) {
30
+ throw new Error('useHubChat must be used inside <HubChatProvider>.');
31
+ }
32
+
33
+ return handle;
34
+ }
35
+
36
+ const BRIDGE = `window.HubChatBridge={postMessage:function(m){window.ReactNativeWebView.postMessage(m);}};true;`;
37
+
38
+ export const HubChat = forwardRef<HubChatHandle, HubChatProps>(function HubChat(
39
+ { widgetKey, baseUrl = DEFAULT_BASE_URL, showLauncher = true, bottomOffset = 0, onEvent, onUnreadChange },
40
+ ref,
41
+ ) {
42
+ const [settings, setSettings] = useState<HubChatSettings | null>(null);
43
+ const [open, setOpen] = useState(false);
44
+ const [unread, setUnread] = useState(0);
45
+ const [mounted, setMounted] = useState(false);
46
+ const webView = useRef<WebView>(null);
47
+ const openRef = useRef(false);
48
+ const pop = useRef(new Animated.Value(0)).current;
49
+
50
+ useEffect(() => {
51
+ let alive = true;
52
+
53
+ fetchSettings(baseUrl, widgetKey).then((value) => {
54
+ if (alive && value) {
55
+ setSettings(value);
56
+ Animated.spring(pop, { toValue: 1, useNativeDriver: true, friction: 6 }).start();
57
+ }
58
+ });
59
+ // Preload the page like widget.js does, so unread messages arrive while closed.
60
+ const timer = setTimeout(() => setMounted(true), 2500);
61
+
62
+ return () => {
63
+ alive = false;
64
+ clearTimeout(timer);
65
+ };
66
+ }, [baseUrl, widgetKey, pop]);
67
+
68
+ const changeUnread = useCallback((count: number) => {
69
+ setUnread(count);
70
+ onUnreadChange?.(count);
71
+ }, [onUnreadChange]);
72
+
73
+ const show = useCallback(() => {
74
+ setMounted(true);
75
+ openRef.current = true;
76
+ setOpen(true);
77
+ changeUnread(0);
78
+ webView.current?.injectJavaScript(hostCommand('open'));
79
+ }, [changeUnread]);
80
+
81
+ const hide = useCallback(() => {
82
+ openRef.current = false;
83
+ setOpen(false);
84
+ webView.current?.injectJavaScript(hostCommand('closed'));
85
+ }, []);
86
+
87
+ const handle = useMemo<HubChatHandle>(() => ({ open: show, close: hide, isOpen: () => openRef.current }), [show, hide]);
88
+
89
+ useImperativeHandle(ref, () => handle, [handle]);
90
+
91
+ const onMessage = (event: WebViewMessageEvent) => {
92
+ let data: (HubChatEvent & { source?: string }) | null = null;
93
+
94
+ try {
95
+ data = JSON.parse(event.nativeEvent.data);
96
+ } catch {
97
+ return;
98
+ }
99
+
100
+ if (!data || data.source !== 'hubchat') {
101
+ return;
102
+ }
103
+
104
+ if (data.type === 'close') {
105
+ hide();
106
+ }
107
+
108
+ if (data.type === 'ready' && openRef.current) {
109
+ webView.current?.injectJavaScript(hostCommand('open'));
110
+ }
111
+
112
+ if (data.type === 'unread' && !openRef.current) {
113
+ changeUnread(data.count);
114
+ }
115
+
116
+ onEvent?.(data);
117
+ };
118
+
119
+ const brand = settings?.color ?? '#2563eb';
120
+ const side: ViewStyle = settings?.position === 'right' ? { right: 20 } : { left: 20 };
121
+ const hasText = !!settings?.launcher_text;
122
+
123
+ return (
124
+ <View pointerEvents="box-none" style={StyleSheet.absoluteFill}>
125
+ {mounted && (
126
+ <SafeAreaView pointerEvents={open ? 'auto' : 'none'} style={[StyleSheet.absoluteFill, styles.panel, { opacity: open ? 1 : 0 }]}>
127
+ <WebView
128
+ ref={webView}
129
+ source={{ uri: widgetUrl(baseUrl, widgetKey) }}
130
+ injectedJavaScriptBeforeContentLoaded={BRIDGE}
131
+ onMessage={onMessage}
132
+ javaScriptEnabled
133
+ domStorageEnabled
134
+ allowFileAccess
135
+ mediaPlaybackRequiresUserAction={false}
136
+ allowsInlineMediaPlayback
137
+ setSupportMultipleWindows={false}
138
+ style={styles.webView}
139
+ />
140
+ </SafeAreaView>
141
+ )}
142
+ {showLauncher && settings && !open && (
143
+ <Animated.View style={[styles.launcherWrap, side, { bottom: 20 + bottomOffset, transform: [{ scale: pop }] }]}>
144
+ <Pressable
145
+ accessibilityRole="button"
146
+ accessibilityLabel="گفتگوی آنلاین"
147
+ onPress={show}
148
+ style={[styles.launcher, hasText ? styles.launcherWide : styles.launcherRound, { backgroundColor: brand, shadowColor: brand }]}
149
+ >
150
+ {settings.launcher_image ? (
151
+ <Image source={{ uri: settings.launcher_image }} style={hasText ? styles.picSmall : styles.pic} />
152
+ ) : (
153
+ <ChatGlyph color={contrastOn(brand)} />
154
+ )}
155
+ {hasText && <Text style={[styles.label, { color: contrastOn(brand) }]}>{settings.launcher_text}</Text>}
156
+ </Pressable>
157
+ {unread > 0 && (
158
+ <View style={[styles.badge, settings.position === 'right' ? { left: -4 } : { right: -4 }]}>
159
+ <Text style={styles.badgeText}>{faDigits(unread > 9 ? '9+' : unread)}</Text>
160
+ </View>
161
+ )}
162
+ </Animated.View>
163
+ )}
164
+ </View>
165
+ );
166
+ });
167
+
168
+ /** Chat bubble with three dots, drawn with Views (no SVG dependency). */
169
+ function ChatGlyph({ color }: { color: string }) {
170
+ return (
171
+ <View style={[styles.glyph, { borderColor: color }]}>
172
+ {[0, 1, 2].map((dot) => (
173
+ <View key={dot} style={[styles.dot, { backgroundColor: color }]} />
174
+ ))}
175
+ </View>
176
+ );
177
+ }
178
+
179
+ /** Wrap your app to get useHubChat() everywhere and the launcher on every screen. */
180
+ export function HubChatProvider({ children, ...props }: HubChatProps & { children: React.ReactNode }) {
181
+ const ref = useRef<HubChatHandle>(null);
182
+ const handle = useMemo<HubChatHandle>(() => ({
183
+ open: () => ref.current?.open(),
184
+ close: () => ref.current?.close(),
185
+ isOpen: () => ref.current?.isOpen() ?? false,
186
+ }), []);
187
+
188
+ return (
189
+ <HubChatContext.Provider value={handle}>
190
+ <View style={styles.flex}>
191
+ {children}
192
+ <HubChat ref={ref} {...props} />
193
+ </View>
194
+ </HubChatContext.Provider>
195
+ );
196
+ }
197
+
198
+ const styles = StyleSheet.create({
199
+ flex: { flex: 1 },
200
+ panel: { backgroundColor: '#f4f6fa', zIndex: 1000, elevation: 1000 },
201
+ webView: { flex: 1, backgroundColor: 'transparent' },
202
+ launcherWrap: { position: 'absolute', zIndex: 999, elevation: 12 },
203
+ launcher: {
204
+ height: 60, minWidth: 60, borderRadius: 999, flexDirection: 'row-reverse', alignItems: 'center', justifyContent: 'center',
205
+ shadowOpacity: 0.45, shadowRadius: 14, shadowOffset: { width: 0, height: 8 }, elevation: 10, overflow: Platform.OS === 'android' ? 'hidden' : 'visible',
206
+ },
207
+ launcherRound: { width: 60 },
208
+ launcherWide: { paddingHorizontal: 16, gap: 10 },
209
+ label: { fontSize: 15, fontWeight: '700' },
210
+ pic: { width: 60, height: 60, borderRadius: 30 },
211
+ picSmall: { width: 44, height: 44, borderRadius: 22 },
212
+ glyph: { width: 26, height: 22, borderWidth: 2, borderRadius: 11, borderBottomLeftRadius: 3, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 3 },
213
+ dot: { width: 3.5, height: 3.5, borderRadius: 2 },
214
+ badge: { position: 'absolute', top: -4, minWidth: 22, height: 22, paddingHorizontal: 6, borderRadius: 11, backgroundColor: '#ef4444', borderWidth: 3, borderColor: '#fff', alignItems: 'center', justifyContent: 'center' },
215
+ badgeText: { color: '#fff', fontSize: 11, fontWeight: '800' },
216
+ });
217
+
218
+ export default HubChat;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Shared protocol with the HubChat widget page (/widget/{key}).
3
+ * The page calls window.HubChatBridge.postMessage(json) for: ready, close, unread.
4
+ * The host opens/closes the panel with window.postMessage({source:'hubchat-loader', type}).
5
+ */
6
+ export const DEFAULT_BASE_URL = 'https://widget.hubchat.ir';
7
+
8
+ export type HubChatSettings = {
9
+ color: string;
10
+ position: 'left' | 'right';
11
+ launcher_text?: string | null;
12
+ launcher_image?: string | null;
13
+ title?: string | null;
14
+ subtitle?: string | null;
15
+ };
16
+
17
+ export type HubChatEvent =
18
+ | { type: 'ready' }
19
+ | { type: 'close' }
20
+ | { type: 'unread'; count: number; preview?: string; agent?: string | null };
21
+
22
+ export function widgetUrl(baseUrl: string, widgetKey: string): string {
23
+ return `${baseUrl.replace(/\/$/, '')}/widget/${widgetKey}`;
24
+ }
25
+
26
+ export async function fetchSettings(baseUrl: string, widgetKey: string): Promise<HubChatSettings | null> {
27
+ try {
28
+ const response = await fetch(`${widgetUrl(baseUrl, widgetKey)}/config`);
29
+ const data = response.ok ? await response.json() : null;
30
+
31
+ return data?.settings ?? null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ export function hostCommand(type: 'open' | 'closed'): string {
38
+ return `window.postMessage({source:'hubchat-loader',type:'${type}'},'*');true;`;
39
+ }
40
+
41
+ /** Same contrast rule as widget.js so launcher text color matches the website. */
42
+ export function contrastOn(hex: string): string {
43
+ const channel = (offset: number) => {
44
+ const value = parseInt(hex.slice(offset, offset + 2), 16) / 255;
45
+
46
+ return value <= 0.03928 ? value / 12.92 : Math.pow((value + 0.055) / 1.055, 2.4);
47
+ };
48
+
49
+ return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5) > 0.45 ? '#0b1220' : '#ffffff';
50
+ }
51
+
52
+ export function faDigits(value: string | number): string {
53
+ return String(value).replace(/\d/g, (digit) => '۰۱۲۳۴۵۶۷۸۹'[Number(digit)]);
54
+ }