@connectycube/chat-widget
Version:
A customizable React chat widget built on the ConnectyCube platform, enabling real-time messaging, calls, and user engagement in any web app.
994 lines • 1.09 MB
JavaScript
import ct from "i18next";
import { initReactI18next as gt, useTranslation as G } from "react-i18next";
import * as a from "react";
import t, { useRef as W, useEffect as U, useState as P, useMemo as H, useCallback as tq, memo as FV } from "react";
import { create as _ } from "zustand";
import { ConnectyCube as aq, DevicePlatform as mt, NotificationChannel as ut, initConnectyCube as dt, useConnectyCube as v, CallType as VA, CallDataType as mA, DialogType as Yq, ActiveMedia as OA, ChatStatus as yq, ChatType as wt } from "@connectycube/react";
import Mt from "get-browser-fingerprint";
import * as oq from "@radix-ui/react-alert-dialog";
import { clsx as KV } from "clsx";
import { twMerge as RV } from "tailwind-merge";
import { Slot as zV } from "@radix-ui/react-slot";
import { cva as JV } from "class-variance-authority";
import { LoaderCircle as pt, Loader as ht, VideoOff as Et, Video as WA, MicOff as Bt, Mic as kt, Phone as eA, ScreenShareOff as Ct, ScreenShare as It, Minimize as Qt, Maximize as St, PictureInPicture2 as ft, PhoneOff as Ut, ChevronRightIcon as yt, Ellipsis as Dt, LogOut as RA, Paperclip as Tt, FilePlusCorner as Nt, WandSparkles as xt, SendHorizontal as Gt, FileXCorner as bt, File as vt, PhoneOutgoing as Yt, PhoneIncoming as Ft, PhoneMissed as Kt, Ban as Rt, CheckCheck as zt, Check as Jt, Clock as jt, Globe as Lt, Sparkles as Ot, CheckIcon as Wt, XIcon as Zt, Users as Pt, Search as Ht, X as Xt } from "lucide-react";
import { toast as nq, Toaster as $t } from "sonner";
import { createPortal as _t } from "react-dom";
import * as zA from "@radix-ui/react-avatar";
import * as Uq from "@radix-ui/react-dropdown-menu";
import { Root as qa } from "@radix-ui/react-label";
import { generateText as jV } from "ai";
import { createGoogleGenerativeAI as Aa } from "@ai-sdk/google";
import Va from "react-textarea-autosize";
import ea from "linkify-react";
import { useInView as ta } from "react-intersection-observer";
import { formatDistanceToNow as aa, isToday as oa, format as JA, differenceInCalendarDays as ra } from "date-fns";
import { Virtualizer as na, VList as ia } from "virtua";
import { useForm as qV } from "react-hook-form";
import * as MV from "@radix-ui/react-checkbox";
import * as EA from "@radix-ui/react-tabs";
import * as Sq from "@radix-ui/react-dialog";
import { DialogDescription as LV } from "@radix-ui/react-dialog";
import * as Oq from "@radix-ui/react-tooltip";
import * as pV from "@radix-ui/react-switch";
const hV = (q = []) => q.slice().filter(Boolean).sort((A, V) => A.id - V.id).reduce((A, { id: V }) => `${A}:${V}`, wA), sa = (q) => new Promise((A) => setTimeout(A, q)), la = (q) => q.replace(
/@supports\s*\(\(*\s*-webkit-hyphens\s*:\s*none\s*\)*\s*and\s*\(not\s*\(margin-trim\s*:\s*inline\)\)\s*\)\s*or\s*\(\(*\s*-moz-orient\s*:\s*inline\s*\)*\s*and\s*\(not\s*\(color\s*:\s*rgb\(from\s+red\s+r\s+g\s+b\)\)\)\s*\)\s*\{\s*([\s\S]*?)\s*\}/gm,
(A, V) => V.trim()
), lq = () => typeof window < "u" && typeof document < "u";
var $q = /* @__PURE__ */ ((q) => (q.WRAPPER = "data-connectycube-chat-widget-wrapper", q.FOCUSED = "data-connectycube-chat-widget-focused", q))($q || {});
const EV = "15px", BV = "400", wA = "external_id", kV = "::current_user";
var Qq = /* @__PURE__ */ ((q) => (q.GET_SUMMARY = "ai:get-summary", q.CHANGE_TONE = "ai:change-tone", q.DEFAULT = "ai:default", q))(Qq || {}), vq = /* @__PURE__ */ ((q) => (q.LAST_7_DAYS = "last-7-days", q.LAST_DAY = "last-day", q.UNREADS = "unreads", q))(vq || {}), uA = /* @__PURE__ */ ((q) => (q.POSITIVE = "positive", q.NEGATIVE = "negative", q.CRINGE = "cringe", q))(uA || {}), AV = /* @__PURE__ */ ((q) => (q.AI_TEXT_SUMMARY = "ai-text-summary", q))(AV || {});
const ca = "Add members", ga = "Admin", ma = "are typing", ua = "Cancel", da = "Chat name", wa = "Chat name is required", Ma = "Chat", pa = "Chats", ha = "Choose a chat", Ea = "Continue", Ba = "Create group chat", ka = "Delete", Ca = "Draft", Ia = "Enter message", Qa = "Enter user name", Sa = "Exit chat", fa = "Are you sure you want to leave this chat?", Ua = "File format is not supported", ya = "is typing", Da = "me", Ta = "Members", Na = "members", xa = "New group", Ga = "New message", ba = "Begin your first chat and see what happens!", va = "No messages yet", Ya = "No online users", Fa = "Profile", Ka = "Remove members", Ra = "Reset", za = "Search", Ja = "Select", ja = "Send", La = "Start chat", Oa = "Send message to user", Wa = "Start a new Group", Za = "typing", Pa = "Users", Ha = "you", Xa = "Video", $a = "Call", _a = "Block", qo = "Unblock", Ao = "Report", Vo = "Report user", eo = "What's wrong with this user?", to = "Reason for reporting", ao = "Report has been created successfully", oo = "Failed to submit report", ro = "My profile", no = "You are blocked by this user", io = "Block list", so = "Add to block list", lo = "Remove from block list", co = "Block list is empty", go = "Notification settings", mo = "Notifications", uo = "Notification sound", wo = "Push notifications", Mo = "Please wait", po = "Available", ho = "Busy", Eo = "Away", Bo = "Online", ko = "Incoming call", Co = "Incoming audio call from {{name}}", Io = "Incoming video call from {{name}}", Qo = "Accept", So = "Reject", fo = "{{name}} rejected the call", Uo = "Missed call from {{name}}", yo = { Login: "Login", Password: "Password", Register: "Register", Registration: "Registration", LoginRequired: "Login is required", LoginMinLimit: "Login must be at least {{limit}} symbols", LoginMaxLimit: "Login must be at most {{limit}} symbols", PasswordRequired: "Login is required", PasswordMinLimit: "Password must be at least {{limit}} symbols", PasswordMaxLimit: "Password must be at most {{limit}} symbols", LoginDescription: "Enter your login and password to access your account", RegisterDescription: "Fill in the form below to sign up", "ToRegister?": "Don't have an account?", "ToLogin?": "Already have an account?" }, Do = { Title: "Submit your contact data to start a chat", Subtitle: "We will not share your email address. Your email address is used solely to contact you", NamePlaceholder: "Name", NameRequired: "Name is required", EmailPlaceholder: "Email", EmailRequired: "Email is required", EmailInvalid: "Invalid email format", AcceptTermsAndConditions: "Accept terms and conditions", AcceptTermsAndConditionsError: "You must accept the terms and conditions", TermsAndConditionsText: "By clicking this checkbox, you agree to the", TermsAndConditionsLink: "terms and conditions", RememberMe: "Remember me", RememberMeText: "This is my private device", Next: "Next" }, To = "Opponent(s) for the chat not found", No = "Information", xo = { GetSummary: "Get summary", ChangeMessageTone: "Change message tone", SummaryMessageTitle: "Only you can see this message", forLast7Days: "for last 7 days", forLastDay: "for last day", forUnreads: "for unreads", MessageTone: "Change message tone", EmptyMessageTone: "Can't change tone of empty message", positive: "positive", negative: "negative", cringe: "cringe" }, Go = { RejectedIncoming: "Rejected incoming", RejectedOutgoing: "Rejected outgoing", Unanswered: "Unanswered", Missed: "Missed", Canceled: "Canceled", Ended: "Ended", videoCall: "video call", audioCall: "audio call", defaultCall: "call" }, bo = "Drop files here", vo = {
AddMembers: ca,
Admin: ga,
areTyping: ma,
Cancel: ua,
ChatName: da,
ChatNameRequired: wa,
Chat: Ma,
Chats: pa,
ChooseChat: ha,
Continue: Ea,
CreateGroupChat: Ba,
Delete: ka,
Draft: Ca,
EnterMessage: Ia,
EnterUserName: Qa,
ExitChat: Sa,
ExitChatConfirm: fa,
FileTypeNotSupported: Ua,
isTyping: ya,
me: Da,
Members: Ta,
members: Na,
NewGroup: xa,
NewMessage: Ga,
NoChats: ba,
NoMessages: va,
NoOnlineUsers: Ya,
Profile: Fa,
RemoveMembers: Ka,
"RemoveMembers?": "Are you sure you want to remove members?",
Reset: Ra,
Search: za,
Select: Ja,
Send: ja,
StartChat: La,
NewUserChatDialogTitle: Oa,
NewGroupChatDialogTitle: Wa,
typing: Za,
Users: Pa,
you: Ha,
Video: Xa,
Call: $a,
Block: _a,
UnBlock: qo,
Report: Ao,
ReportUser: Vo,
WhatsWrongWithThisUser: eo,
ProvideReason: to,
ReportCreatedSuccessfully: ao,
ReportSubmitFailed: oo,
MyProfile: ro,
YouBlocked: no,
BlockList: io,
AddToBlockList: so,
"AddToBlockList?": "Are you sure you want to add {{name}} to block list?",
RemoveFromBlockList: lo,
"RemoveFromBlockList?": "Are you sure you want to remove {{name}} from block list?",
BlockListEmpty: co,
NotificationSettings: go,
Notifications: mo,
NotificationSound: uo,
PushNotifications: wo,
PleaseWait: Mo,
Available: po,
Busy: ho,
Away: Eo,
Online: Bo,
IncomingCall: ko,
IncomingAudioCall: Co,
IncomingVideoCall: Io,
Accept: Qo,
Reject: So,
RejectedCall: fo,
MissedCall: Uo,
AuthForm: yo,
SingleViewForm: Do,
SingleViewChatError: To,
Information: No,
AI: xo,
CallHistory: Go,
DragAndDrop: bo
}, Yo = "Προσθήκη μελών", Fo = "Διαχειριστής", Ko = "είναι", Ro = "Ακύρωση", zo = "Όνομα συνομιλίας", Jo = "Το όνομα συνομιλίας είναι υποχρεωτικό", jo = "Συνομιλία", Lo = "Συνομιλίες", Oo = "Επιλέξτε συνομιλία", Wo = "Συνέχεια", Zo = "Δημιουργία ομαδικής συνομιλίας", Po = "Διαγραφή", Ho = "Πρόχειρο", Xo = "Εισάγετε μήνυμα", $o = "Εισάγετε όνομα χρήστη", _o = "Έξοδος από τη συνομιλία", qr = "Είστε σίγουροι ότι θέλετε να φύγετε από αυτή τη συνομιλία;", Ar = "Η μορφή αρχείου δεν υποστηρίζεται", Vr = "είναι", er = "εγώ", tr = "Μέλη", ar = "μέλη", or = "Νέα ομάδα", rr = "Νέο μήνυμα", nr = "Επιλέξτε κάποιο χρήστη από τη λίστα Χρήστες και ξεκινήστε την πρώτη σας συνομιλία!", ir = "Δεν υπάρχουν μηνύματα", sr = "Δεν υπάρχουν συνδεδεμένοι χρήστες", lr = "Προφίλ", cr = "Αφαίρεση μελών", gr = "Επαναφορά", mr = "Αναζήτηση", ur = "Επιλογή", dr = "Αποστολή", wr = "Έναρξη συνομιλίας", Mr = "Αποστολή μηνύματος σε μέλος", pr = "Δημιουργία νέας ομάδας", hr = "πληκτρολογεί", Er = "Χρήστες", Br = "εσύ", kr = "Βίντεο", Cr = "Κλήση", Ir = "Block", Qr = "Unblock", Sr = "Αναφορά", fr = "Αναφορά χρήστη", Ur = "Τι θέλετε να αναφέρετε για αυτόν το χρήστη;", yr = "Λόγος αναφοράς", Dr = "Η αναφορά για το χρήστη έγινε", Tr = "Σφάλμα στη δημιουργία αναφοράς", Nr = "Το προφίλ μου", xr = "Αυτός ο χρήστης σας έχει κάνει Block", Gr = "Λίστα Blocked χρηστών", br = "Προσθήκη στη λίστα Blocked", vr = "Αφαίρεση από τη λίστα Blocked", Yr = "Η Blocked λίστα είναι άδεια", Fr = "Ρυθμίσεις ειδοποιήσεων", Kr = "Ειδοποιήσεις", Rr = "Ήχος ειδοποίησης", zr = "Ειδοποιήσεις push", Jr = "Παρακαλώ περιμένετε", jr = "Διαθέσιμος/η", Lr = "Απασχολημένος/η", Or = "Απουσιάζω", Wr = "Συνδεδεμένος/η", Zr = "Εισερχόμενη κλήση", Pr = "Εισερχόμενη κλήση ήχου από τον χρήστη {{name}}", Hr = "Εισερχόμενη κλήση βίντεο από τον χρήστη {{name}}", Xr = "Αποδοχή", $r = "Απόρριψη", _r = "Ο χρήστης {{name}} απέρριψε την κλήση", qn = "Αναπάντητη κλήση από τον χρήστη {{name}}", An = { Login: "Σύνδεση", Password: "Κωδικός πρόσβασης", Register: "Εγγραφή", Registration: "Εγγραφή", LoginRequired: "Το όνομα χρήστη είναι υποχρεωτικό", LoginMinLimit: "Το όνομα χρήστη πρέπει να έχει τουλάχιστον {{limit}} χαρακτήρες", LoginMaxLimit: "Το όνομα χρήστη πρέπει να έχει το πολύ {{limit}} χαρακτήρες", PasswordRequired: "Ο κωδικός πρόσβασης είναι υποχρεωτικός", PasswordMinLimit: "Ο κωδικός πρόσβασης πρέπει να έχει τουλάχιστον {{limit}} χαρακτήρες", PasswordMaxLimit: "Ο κωδικός πρόσβασης πρέπει να έχει το πολύ {{limit}} χαρακτήρες", LoginDescription: "Εισάγετε το όνομα χρήστη και τον κωδικό πρόσβασης για να αποκτήσετε πρόσβαση στον λογαριασμό σας", RegisterDescription: "Συμπληρώστε την παρακάτω φόρμα για να εγγραφείτε", "ToRegister?": "Δεν έχετε λογαριασμό;", "ToLogin?": "Έχετε ήδη λογαριασμό;" }, Vn = { Title: "Υποβάλετε τα στοιχεία επικοινωνίας σας για να ξεκινήσετε μια συνομιλία", Subtitle: "Δεν θα κοινοποιήσουμε τη διεύθυνση email σας. Η διεύθυνση email σας χρησιμοποιείται αποκλειστικά για να επικοινωνήσουμε μαζί σας.", NamePlaceholder: "Όνομα", NameRequired: "Το όνομα είναι υποχρεωτικό", EmailPlaceholder: "E-mail", EmailRequired: "Απαιτείται email", Emailnvalid: "Μη έγκυρη μορφή email", AcceptTermsAndConditions: "Αποδοχή όρων και προϋποθέσεων", AcceptTermsAndConditionsError: "Πρέπει να αποδεχτείτε τους όρους και τις προϋποθέσεις", TermsAndConditionsText: "Κάνοντας κλικ σε αυτό το πλαίσιο, συμφωνείτε με τους", TermsAndConditionsLink: "όρους και προϋποθέσεις", RememberMe: "Να με θυμάσαι", RememberMeText: "Αυτή είναι η προσωπική μου συσκευή", Next: "Επόμενο" }, en = "Δεν βρέθηκαν αντίπαλοι για τη συνομιλία", tn = "Πληροφορίες", an = { GetSummary: "Λήψη σύνοψης", ChangeMessageTone: "Αλλαγή τόνου μηνύματος", SummaryMessageTitle: "Μόνο εσείς μπορείτε να δείτε αυτό το μήνυμα", forLast7Days: "για τις τελευταίες 7 ημέρες", forLastDay: "για την τελευταία ημέρα", forUnreads: "για μη αναγνωσμένα", MessageTone: "Αλλαγή τόνου μηνύματος", EmptyMessageTone: "Δεν είναι δυνατή η αλλαγή του τόνου ενός κενού μηνύματος", positive: "θετικός", negative: "αρνητικός", cringe: "κρίμα" }, on = { RejectedIncoming: "Απορρίφθηκε εισερχόμενη κλήση", RejectedOutgoing: "Απορρίφθηκε εξερχόμενη κλήση", Unanswered: "Μη απαντημένη κλήση", Missed: "Αναπάντητη κλήση", Canceled: "Ακυρώθηκε", Ended: "Ολοκληρώθηκε", videoCall: "βιντεοκλήση", audioCall: "ηχητική κλήση", defaultCall: "κλήση" }, rn = "Αποθέστε αρχεία εδώ", nn = {
AddMembers: Yo,
Admin: Fo,
areTyping: Ko,
Cancel: Ro,
ChatName: zo,
ChatNameRequired: Jo,
Chat: jo,
Chats: Lo,
ChooseChat: Oo,
Continue: Wo,
CreateGroupChat: Zo,
Delete: Po,
Draft: Ho,
EnterMessage: Xo,
EnterUserName: $o,
ExitChat: _o,
ExitChatConfirm: qr,
FileTypeNotSupported: Ar,
isTyping: Vr,
me: er,
Members: tr,
members: ar,
NewGroup: or,
NewMessage: rr,
NoChats: nr,
NoMessages: ir,
NoOnlineUsers: sr,
Profile: lr,
RemoveMembers: cr,
"RemoveMembers?": "Είστε σίγουροι ότι θέλετε να αφαιρέσετε τα μέλη;",
Reset: gr,
Search: mr,
Select: ur,
Send: dr,
StartChat: wr,
NewUserChatDialogTitle: Mr,
NewGroupChatDialogTitle: pr,
typing: hr,
Users: Er,
you: Br,
Video: kr,
Call: Cr,
Block: Ir,
UnBlock: Qr,
Report: Sr,
ReportUser: fr,
WhatsWrongWithThisUser: Ur,
ProvideReason: yr,
ReportCreatedSuccessfully: Dr,
ReportSubmitFailed: Tr,
MyProfile: Nr,
YouBlocked: xr,
BlockList: Gr,
AddToBlockList: br,
"AddToBlockList?": "Σίγουρα θέλετε να προσθέσετε το χρήστη {{name}} στη λίστα Blocked;",
RemoveFromBlockList: vr,
"RemoveFromBlockList?": "Σίγουρα θέλετε να αφαιρέσετε το χρήστη {{name}} από τη λίστα Blocked;",
BlockListEmpty: Yr,
NotificationSettings: Fr,
Notifications: Kr,
NotificationSound: Rr,
PushNotifications: zr,
PleaseWait: Jr,
Available: jr,
Busy: Lr,
Away: Or,
Online: Wr,
IncomingCall: Zr,
IncomingAudioCall: Pr,
IncomingVideoCall: Hr,
Accept: Xr,
Reject: $r,
RejectedCall: _r,
MissedCall: qn,
AuthForm: An,
SingleViewForm: Vn,
SingleViewChatError: en,
Information: tn,
AI: an,
CallHistory: on,
DragAndDrop: rn
}, sn = "Додати учасників", ln = "Адмін", cn = "пишуть", gn = "Скасувати", mn = "Назва чату", un = "Назва чату є обов'язковою", dn = "Чат", wn = "Чати", Mn = "Оберіть чат", pn = "Продовжити", hn = "Створити груповий чат", En = "Видалити", Bn = "Чернетка", kn = "Введіть повідомлення", Cn = "Введіть ім'я користувача", In = "Вийти з чату", Qn = "Ви впевнені, що хочете вийти з цього чату?", Sn = "Формат файлу не підтримується", fn = "пише", Un = "я", yn = "Учасники", Dn = "учасники", Tn = "Нова група", Nn = "Нове повідомлення", xn = "Почніть свою першу розмову та подивіться, що станеться!", Gn = "Поки що немає повідомлень", bn = "Немає онлайн-користувачів", vn = "Профіль", Yn = "Видалити учасників", Fn = "Скинути", Kn = "Пошук", Rn = "Вибрати", zn = "Надіслати", Jn = "Розпочати чат", jn = "Новий чат з користувачем", Ln = "Нова група", On = "друкує", Wn = "Користувачі", Zn = "ви", Pn = "Відео", Hn = "Виклик", Xn = "Заблокувати", $n = "Розблокувати", _n = "Поскаржитися", qi = "Поскаржитися на користувача", Ai = "Що не так з цим користувачем?", Vi = "Підстава", ei = "Звіт поданий успішно", ti = "Помилка при поданні звіту", ai = "Мій профіль", oi = "Цей користувача вас заблокував", ri = "Список заблокованих", ni = "Додати до списку заблокованих", ii = "Видалити зі списку заблокованих", si = "Список заблокованих порожній", li = "Налаштування сповіщень", ci = "Сповіщення", gi = "Звук сповіщення", mi = "Push-сповіщення", ui = "Будь ласка, зачекайте", di = "Присутній", wi = "Зайнятий", Mi = "Відсутній", pi = "В мережі", hi = "Вхідний виклик", Ei = "Вхідний аудіо виклик від {{name}}", Bi = "Вхідний відео виклик від {{name}}", ki = "Прийняти", Ci = "Відхилити", Ii = "{{name}} відхилив виклик", Qi = "Пропущений виклик від {{name}}", Si = { Login: "Логін", Password: "Пароль", Register: "Зареєструвати", Registration: "Реєстрація", LoginRequired: "Логін є обов'язковим", LoginMinLimit: "Логін має містити щонайменше {{limit}} символів", LoginMaxLimit: "Логін має містити не більше {{limit}} символів", PasswordRequired: "Пароль є обов'язковим", PasswordMinLimit: "Пароль має містити щонайменше {{limit}} символів", PasswordMaxLimit: "Пароль має містити не більше {{limit}} символів", LoginDescription: "Введіть ваш логін та пароль для доступу до акаунту", RegisterDescription: "Заповніть форму нижче для реєстрації", "ToRegister?": "Ще не маєте акаунту?", "ToLogin?": "Вже маєте акаунт?" }, fi = { Title: "Введіть свою електронну пошту, щоб почати чат", Subtitle: "Ми не будемо передавати вашу електронну пошту. Ваша електронна пошта використовується виключно для зв'язку з вами", NamePlaceholder: "Ім'я", NameRequired: "Ім'я є обов'язковим", EmailPlaceholder: "Електронна пошта", EmailRequired: "Електронна пошта є обов'язковою", EmailInvalid: "Невірний формат електронної пошти", AcceptTermsAndConditions: "Прийняти умови та положення", AcceptTermsAndConditionsError: "Ви повинні прийняти умови та положення", TermsAndConditionsText: "Натискаючи цю галочку, ви погоджуєтесь з", TermsAndConditionsLink: "умовами та положеннями", RememberMe: "Запам'ятати мене", RememberMeText: "Це мій приватний пристрій", Next: "Далі" }, Ui = "Опонента(ів) для чату не знайдено", yi = "Інформація", Di = { GetSummary: "Отримати резюме", ChangeMessageTone: "Змінити тон повідомлення", SummaryMessageTitle: "Тільки ти можеш бачити це повідомлення", forLast7Days: "за останні 7 днів", forLastDay: "за останній день", forUnreads: "для непрочитаних", MessageTone: "Змінити тон повідомлення", EmptyMessageTone: "Неможливо змінити тон пустого повідомлення", positive: "позитивний", negative: "негативний", cringe: "крінж" }, Ti = { RejectedIncoming: "Відхилений вхідний", RejectedOutgoing: "Відхилений вихідний", Unanswered: "Неприйнятий", Missed: "Пропущений", Canceled: "Скасований", Ended: "Завершений", videoCall: "відео виклик", audioCall: "аудіо виклик", defaultCall: "виклик" }, Ni = "Перетягніть файли сюди", xi = {
AddMembers: sn,
Admin: ln,
areTyping: cn,
Cancel: gn,
ChatName: mn,
ChatNameRequired: un,
Chat: dn,
Chats: wn,
ChooseChat: Mn,
Continue: pn,
CreateGroupChat: hn,
Delete: En,
Draft: Bn,
EnterMessage: kn,
EnterUserName: Cn,
ExitChat: In,
ExitChatConfirm: Qn,
FileTypeNotSupported: Sn,
isTyping: fn,
me: Un,
Members: yn,
members: Dn,
NewGroup: Tn,
NewMessage: Nn,
NoChats: xn,
NoMessages: Gn,
NoOnlineUsers: bn,
Profile: vn,
RemoveMembers: Yn,
"RemoveMembers?": "Ви впевнені, що хочете видалити учасників?",
Reset: Fn,
Search: Kn,
Select: Rn,
Send: zn,
StartChat: Jn,
NewUserChatDialogTitle: jn,
NewGroupChatDialogTitle: Ln,
typing: On,
Users: Wn,
you: Zn,
Video: Pn,
Call: Hn,
Block: Xn,
UnBlock: $n,
Report: _n,
ReportUser: qi,
WhatsWrongWithThisUser: Ai,
ProvideReason: Vi,
ReportCreatedSuccessfully: ei,
ReportSubmitFailed: ti,
MyProfile: ai,
YouBlocked: oi,
BlockList: ri,
AddToBlockList: ni,
"AddToBlockList?": "Ви впевнені, що хочете додати {{name}} до списку заблокованих?",
RemoveFromBlockList: ii,
"RemoveFromBlockList?": "Ви впевнені, що хочете видалити {{name}} зі списку заблокованих?",
BlockListEmpty: si,
NotificationSettings: li,
Notifications: ci,
NotificationSound: gi,
PushNotifications: mi,
PleaseWait: ui,
Available: di,
Busy: wi,
Away: Mi,
Online: pi,
IncomingCall: hi,
IncomingAudioCall: Ei,
IncomingVideoCall: Bi,
Accept: ki,
Reject: Ci,
RejectedCall: Ii,
MissedCall: Qi,
AuthForm: Si,
SingleViewForm: fi,
SingleViewChatError: Ui,
Information: yi,
AI: Di,
CallHistory: Ti,
DragAndDrop: Ni
}, Gi = "Añadir miembros", bi = "Administrador", vi = "están escribiendo", Yi = "Cancelar", Fi = "Nombre del chat", Ki = "El nombre del chat es obligatorio", Ri = "Chat", zi = "Chats", Ji = "Elegir un chat", ji = "Continuar", Li = "Crear chat de grupo", Oi = "Eliminar", Wi = "Borrador", Zi = "Escribe un mensaje", Pi = "Introduce el nombre de usuario", Hi = "Salir del chat", Xi = "¿Estás seguro de que quieres salir de este chat?", $i = "El formato de archivo no es compatible", _i = "está escribiendo", qs = "yo", As = "Miembros", Vs = "miembros", es = "Nuevo grupo", ts = "Nuevo mensaje", as = "¡Inicia tu primer chat y mira qué pasa!", os = "Aún no hay mensajes", rs = "No hay usuarios en línea", ns = "Perfil", is = "Eliminar miembros", ss = "Restablecer", ls = "Buscar", cs = "Seleccionar", gs = "Enviar", ms = "Iniciar chat", us = "Enviar mensaje al usuario", ds = "Iniciar un nuevo grupo", ws = "escribiendo", Ms = "Usuarios", ps = "tú", hs = "Vídeo", Es = "Llamada", Bs = "Bloquear", ks = "Desbloquear", Cs = "Reportar", Is = "Reportar usuario", Qs = "¿Qué ocurre con este usuario?", Ss = "Motivo del reporte", fs = "El reporte se ha creado correctamente", Us = "Error al enviar el reporte", ys = "Mi perfil", Ds = "Este usuario te ha bloqueado", Ts = "Lista de bloqueados", Ns = "Añadir a la lista de bloqueados", xs = "Eliminar de la lista de bloqueados", Gs = "La lista de bloqueados está vacía", bs = "Configuración de notificaciones", vs = "Notificaciones", Ys = "Sonido de notificación", Fs = "Notificaciones push", Ks = "Por favor, espera", Rs = "Disponible", zs = "Ocupado", Js = "Ausente", js = "En línea", Ls = "Llamada entrante", Os = "Llamada de audio entrante de {{name}}", Ws = "Llamada de vídeo entrante de {{name}}", Zs = "Aceptar", Ps = "Rechazar", Hs = "{{name}} rechazó la llamada", Xs = "Llamada perdida de {{name}}", $s = { Login: "Iniciar sesión", Password: "Contraseña", Register: "Registrarse", Registration: "Registro", LoginRequired: "El usuario es obligatorio", LoginMinLimit: "El usuario debe tener al menos {{limit}} caracteres", LoginMaxLimit: "El usuario debe tener como máximo {{limit}} caracteres", PasswordRequired: "La contraseña es obligatoria", PasswordMinLimit: "La contraseña debe tener al menos {{limit}} caracteres", PasswordMaxLimit: "La contraseña debe tener como máximo {{limit}} caracteres", LoginDescription: "Introduce tu usuario y contraseña para acceder a tu cuenta", RegisterDescription: "Rellena el formulario para registrarte", "ToRegister?": "¿No tienes una cuenta?", "ToLogin?": "¿Ya tienes una cuenta?" }, _s = { Title: "Envía tus datos de contacto para iniciar un chat", Subtitle: "No compartiremos tu dirección de correo electrónico. Se utilizará únicamente para contactarte", NamePlaceholder: "Nombre", NameRequired: "El nombre es obligatorio", EmailPlaceholder: "Correo electrónico", EmailRequired: "El correo electrónico es obligatorio", EmailInvalid: "Formato de correo electrónico no válido", AcceptTermsAndConditions: "Aceptar términos y condiciones", AcceptTermsAndConditionsError: "Debes aceptar los términos y condiciones", TermsAndConditionsText: "Al marcar esta casilla, aceptas los", TermsAndConditionsLink: "términos y condiciones", RememberMe: "Recordarme", RememberMeText: "Este es mi dispositivo privado", Next: "Siguiente" }, ql = "No se encontraron los participantes del chat", Al = "Información", Vl = { GetSummary: "Obtener resumen", ChangeMessageTone: "Cambiar el tono del mensaje", SummaryMessageTitle: "Solo tú puedes ver este mensaje", forLast7Days: "de los últimos 7 días", forLastDay: "del último día", forUnreads: "de los no leídos", MessageTone: "Cambiar tono del mensaje", EmptyMessageTone: "No se puede cambiar el tono de un mensaje vacío", positive: "positivo", negative: "negativo", cringe: "vergonzoso" }, el = { RejectedIncoming: "Entrante rechazada", RejectedOutgoing: "Saliente rechazada", Unanswered: "No respondida", Missed: "Perdida", Canceled: "Cancelada", Ended: "Finalizada", videoCall: "videollamada", audioCall: "llamada de audio", defaultCall: "llamada" }, tl = "Suelta los archivos aquí", al = {
AddMembers: Gi,
Admin: bi,
areTyping: vi,
Cancel: Yi,
ChatName: Fi,
ChatNameRequired: Ki,
Chat: Ri,
Chats: zi,
ChooseChat: Ji,
Continue: ji,
CreateGroupChat: Li,
Delete: Oi,
Draft: Wi,
EnterMessage: Zi,
EnterUserName: Pi,
ExitChat: Hi,
ExitChatConfirm: Xi,
FileTypeNotSupported: $i,
isTyping: _i,
me: qs,
Members: As,
members: Vs,
NewGroup: es,
NewMessage: ts,
NoChats: as,
NoMessages: os,
NoOnlineUsers: rs,
Profile: ns,
RemoveMembers: is,
"RemoveMembers?": "¿Seguro que quieres eliminar a los miembros?",
Reset: ss,
Search: ls,
Select: cs,
Send: gs,
StartChat: ms,
NewUserChatDialogTitle: us,
NewGroupChatDialogTitle: ds,
typing: ws,
Users: Ms,
you: ps,
Video: hs,
Call: Es,
Block: Bs,
UnBlock: ks,
Report: Cs,
ReportUser: Is,
WhatsWrongWithThisUser: Qs,
ProvideReason: Ss,
ReportCreatedSuccessfully: fs,
ReportSubmitFailed: Us,
MyProfile: ys,
YouBlocked: Ds,
BlockList: Ts,
AddToBlockList: Ns,
"AddToBlockList?": "¿Seguro que quieres añadir a {{name}} a la lista de bloqueados?",
RemoveFromBlockList: xs,
"RemoveFromBlockList?": "¿Seguro que quieres eliminar a {{name}} de la lista de bloqueados?",
BlockListEmpty: Gs,
NotificationSettings: bs,
Notifications: vs,
NotificationSound: Ys,
PushNotifications: Fs,
PleaseWait: Ks,
Available: Rs,
Busy: zs,
Away: Js,
Online: js,
IncomingCall: Ls,
IncomingAudioCall: Os,
IncomingVideoCall: Ws,
Accept: Zs,
Reject: Ps,
RejectedCall: Hs,
MissedCall: Xs,
AuthForm: $s,
SingleViewForm: _s,
SingleViewChatError: ql,
Information: Al,
AI: Vl,
CallHistory: el,
DragAndDrop: tl
}, OV = {
en: "English",
ua: "Ukrainian",
el: "Greek",
es: "Spanish"
}, ol = lq() && localStorage.getItem("translation") || "en";
ct.use(gt).init({
resources: {
en: { translation: vo },
el: { translation: nn },
ua: { translation: xi },
es: { translation: al }
},
lng: ol,
fallbackLng: "en",
interpolation: {
escapeValue: !1
}
});
var Iq = /* @__PURE__ */ ((q) => (q.CHATS = "chats", q.USERS = "users", q))(Iq || {});
const CV = {
activeTab: "chats"
/* CHATS */
}, BA = _((q) => ({
...CV,
setActiveTab: (A) => q({ activeTab: A }),
resetActiveTab: () => q({ activeTab: CV.activeTab })
})), rl = () => {
BA.setState({
activeTab: "chats"
/* CHATS */
});
}, ZA = {
visible: !1,
title: ""
}, kA = _((q) => ({
...ZA,
showAlertBusy: (A = "") => q({ visible: !0, title: A }),
hideAlertBusy: () => q({ visible: !1, title: ZA.title })
})), nl = () => {
kA.setState({ visible: !1, title: ZA.title });
}, il = {}, {
CHAT_WIDGET_CONNECTYCUBE_SINGLE_VIEW_CHAT_EXTERNAL_ID: sl,
CHAT_WIDGET_CONNECTYCUBE_SINGLE_VIEW_CHAT_NAME: ll,
CHAT_WIDGET_CONNECTYCUBE_SINGLE_VIEW_CHAT_PHOTO: cl,
CHAT_WIDGET_CONNECTYCUBE_SINGLE_VIEW_CHAT_OPPONENTS_IDS: gl
} = il || process.env;
var dA = /* @__PURE__ */ ((q) => (q.SINGLE = "1on1", q.GROUP = "group", q))(dA || {});
const Wq = {
defaultChat: null,
singleViewChat: {
externalId: sl,
opponentUserIds: gl,
name: ll,
photo: cl
}
}, VV = _((q) => ({
...Wq,
setDefaultChat: (A) => q({ defaultChat: A }),
setSingleViewChat: (A) => q({ singleViewChat: A }),
resetDefaultChat: () => q({ defaultChat: Wq.defaultChat }),
resetSingleViewChat: () => q({ singleViewChat: Wq.singleViewChat })
})), ml = (q) => {
VV.setState(q);
}, ul = () => {
VV.setState(Wq);
}, z = {
opened: !1,
splitView: !1,
singleView: !1,
showChatStatus: !1,
showChatActionsAsMenu: !0,
showOnlineUsersTab: !1,
hideNewChatButton: !1,
hideNewUserChatOption: !1,
hideNewGroupChatOption: !1,
imgLogoSource: "/logo.png"
}, X = _((q, A) => ({
...z,
setOpened: (V) => q({ opened: V }),
setSplitView: (V) => q({ splitView: V }),
setSingleView: (V) => q({ singleView: V, splitView: !1 }),
setShowChatStatus: (V) => q({ showChatStatus: V }),
setShowChatActionsAsMenu: (V) => q({ showChatActionsAsMenu: V }),
setShowOnlineUsersTab: (V) => q({ showOnlineUsersTab: V }),
setHideNewChatButton: (V) => q({ hideNewChatButton: V }),
setHideNewUserChatOption: (V) => q({ hideNewUserChatOption: V }),
setHideNewGroupChatOption: (V) => q({ hideNewGroupChatOption: V }),
setImgLogoSource: (V) => q({ imgLogoSource: V }),
toggleOpened: () => q({ opened: !A().opened }),
resetOpened: () => q({ opened: z.opened }),
resetSplitView: () => q({ splitView: z.splitView }),
resetSingleView: () => q({ singleView: z.singleView }),
resetShowChatStatus: () => q({ showChatStatus: z.showChatStatus }),
resetShowChatActionsAsMenu: () => q({ showChatActionsAsMenu: z.showChatActionsAsMenu }),
resetShowOnlineUsersTab: () => q({ showOnlineUsersTab: z.showOnlineUsersTab }),
resetHideNewChatButton: () => q({ hideNewChatButton: z.hideNewChatButton }),
resetHideNewUserChatOption: () => q({ hideNewUserChatOption: z.hideNewUserChatOption }),
resetHideNewGroupChatOption: () => q({ hideNewGroupChatOption: z.hideNewGroupChatOption }),
resetImgLogoSource: () => q({ imgLogoSource: z.imgLogoSource })
})), dl = (q) => {
X.setState(q);
}, wl = () => {
X.setState(z);
}, CA = "@connectycube/chat-widget:draftMessages", Ml = () => {
try {
const q = lq() ? localStorage?.getItem(CA) : null;
return q ? JSON.parse(q) : {};
} catch (q) {
return console.error("Could not load state from localStorage", q), {};
}
}, cA = (q) => {
if (lq())
try {
const A = JSON.stringify(q);
localStorage?.setItem(CA, A);
} catch (A) {
console.error("Could not save state to localStorage", A);
}
}, pl = () => {
if (lq())
try {
localStorage?.removeItem(CA);
} catch (q) {
console.error("Could not clear state from localStorage", q);
}
}, jA = Ml(), IA = _((q) => ({
draftMessages: jA,
setDraftMessages: (A) => {
q({ draftMessages: A }), cA(A);
},
upsertDraftMessage: (A) => {
q((V) => {
const e = { ...V.draftMessages, ...A };
return cA(e), { draftMessages: e };
});
},
deleteDraftMessage: (A) => {
q((V) => {
const e = { ...V.draftMessages };
return delete e[A], cA(e), { draftMessages: e };
});
},
resetDraftMessages: () => {
q({ draftMessages: jA }), cA(jA);
}
})), hl = () => {
pl(), IA.setState({ draftMessages: {} });
};
var $ = /* @__PURE__ */ ((q) => (q.AVAILABLE = "available", q.AWAY = "away", q.BUSY = "busy", q.UNKNOWN = "unknown", q))($ || {}), WV = /* @__PURE__ */ ((q) => (q.UPDATE_USER = "user/UPDATE", q))(WV || {});
const eV = "@connectycube/chat-widget:session", PA = "@connectycube/chat-widget:guest", HA = "@connectycube/chat-widget:rememberMe", IV = "widget_", El = async (q) => {
const A = !ee();
if (A) {
const V = Dq();
V && (aq.setSession(V), await _V(V, q));
}
return A;
}, ZV = async () => {
const A = Dq()?.user?.login, V = typeof A == "string" && (await te(A)).substring(0, 32);
return A && V ? await QA(A, V) : null;
}, QA = async (q, A) => {
const V = await aq.createSession({ login: q, password: A });
return SA(V, oA()), V;
}, PV = async (q) => {
const A = Il(q?.userId), V = (await te(A)).substring(0, 32);
let e;
try {
e = await QA(A, V), await _V(e, q);
} catch (o) {
if (o?.code === 404)
e = await $V(A, V, q);
else
throw o;
}
return e;
}, HV = async () => {
try {
await aq.destroySession(), tV();
} catch (q) {
console.error(q);
}
}, XV = () => {
const q = aq.service?.getSession();
return q || null;
}, $V = async (q, A, V) => {
const e = { login: q, password: A, full_name: V?.userName || q };
return V?.userId && (e.external_id = V.userId.toString()), V?.userEmail && (e.email = V.userEmail), V?.userAvatar && (e.avatar = V.userAvatar), V?.userProfileLink && (e.website = V.userProfileLink), await aq.users.signup(e), QA(q, A);
}, Bl = (q = {}) => aq.service?.sdkInstance?.config?.set?.(q), XA = async (q, A) => {
const V = A?.user_id ?? Ve(), e = A?.token ?? kl(), o = V && e ? { userId: V, password: e } : null;
return o ? q(o) : Promise.reject(new Error("[useConnectyCube.connect] Missing userId and password"));
}, _V = async (q, A) => {
const V = {};
if (A?.userId && q?.user?.external_id !== A.userId.toString() && (V.external_id = A.userId.toString()), A?.userName && q?.user?.full_name !== A.userName && (V.full_name = A.userName), A?.userEmail && q?.user?.email !== A.userEmail && (V.email = A.userEmail), A?.userAvatar && q?.user?.avatar !== A.userAvatar && (V.avatar = A.userAvatar), A?.userProfileLink && q?.user?.website !== A.userProfileLink && (V.website = A.userProfileLink), Object.keys(V).length > 0) {
const { user: e } = await aq.users.update(V);
e && (q.user = e, SA(q, oA()));
}
return q;
}, SA = (q, A = !1) => {
lq() && !A && localStorage.setItem(eV, JSON.stringify(q));
}, Dq = () => {
const q = lq() && localStorage.getItem(eV);
return q ? JSON.parse(q) : oA() ? XV() : null;
}, tV = () => {
lq() && (localStorage.removeItem(eV), localStorage.removeItem(CA));
}, Tq = () => {
const q = Dq();
return q ? q.user : null;
}, qe = (q) => {
if (typeof q?.custom_data == "string")
try {
return JSON.parse(q.custom_data);
} catch (A) {
return console.error("Error parsing custom data:", A), null;
}
return null;
}, Ae = () => {
const q = Tq();
return qe(q);
}, aA = (q) => qe(q || Tq())?.userStatus ?? "available", gA = async (q, A = !1) => {
const V = Ae(), e = Object.assign({}, V, q), o = JSON.stringify(e), r = Dq();
let n = Tq();
return n && A ? n = { ...n, custom_data: o } : n = (await aq.users.update({ custom_data: o })).user, r && SA({ ...r, user: n }, oA()), n;
}, kl = () => {
const q = Dq();
return q ? q.token : null;
}, Ve = () => {
const q = Dq();
return q ? q.user_id : null;
}, ee = () => {
const A = (oA() ? null : Dq())?.updated_at ?? (/* @__PURE__ */ new Date(0)).toISOString(), V = new Date(A).getTime(), o = Date.now() - V, r = 6e4 * 119;
return o > r;
}, Cl = (q) => {
const A = Dq();
return A ? !!(q && A.user?.external_id !== q) : !1;
}, te = async (q) => {
const A = new TextEncoder().encode(q);
let V;
try {
V = await crypto.subtle.digest("SHA-256", A);
} catch {
V = new Uint8Array(A.length).map(() => Math.random() * 256 | 0).buffer;
}
return Array.from(new Uint8Array(V)).map((e) => e.toString(16).padStart(2, "0")).join("");
}, Vq = (q, A = !0) => q ? q.full_name || q.login || `Unknown:${q.id}` : A ? "Unknown" : "", pq = (q) => q ? /^(https?:\/\/|\/|\.\/|\.\.\/)/.test(q) ? q : aq.storage.privateUrl(q) : "", Il = (q) => q ? `${IV}${q}` : `${IV}${Math.random().toString(36).substring(2, 14)}`, Ql = async (q, A) => aq.data.create("UserReports", { reportedUserId: q, reason: A }), Sl = async (q) => {
const A = await Mt(), V = Ve(), e = btoa(`${V}:${A}`), { endpoint: o, auth: r, p256dh: n } = q ?? {};
if (o && r && n && e)
return aq.pushnotifications.subscriptions.create({
notification_channel: ut.WEB,
push_token: {
environment: "production",
web_endpoint: o,
web_auth: r,
web_p256dh: n
},
device: {
platform: mt.WEB,
udid: btoa(`${V}:${A}`)
}
});
}, fl = async () => {
const A = (await aq.pushnotifications.subscriptions.list()).map(
({ subscription: V }) => aq.pushnotifications.subscriptions.delete(V.id)
);
return Promise.all(A);
}, Ul = !!aq.videochat, yl = (q = !1) => {
lq() && (q ? localStorage.setItem(HA, "1") : localStorage.removeItem(HA));
}, Dl = (q = !1) => {
lq() && (q ? localStorage.setItem(PA, "1") : localStorage.removeItem(PA));
}, Tl = () => lq() ? !!localStorage.getItem(HA) : !1, Nl = () => lq() ? !!localStorage.getItem(PA) : !1, oA = () => Nl() && !Tl(), xl = {}, { CHAT_WIDGET_CONNECTYCUBE_TERMS_AND_CONDITIONS: Gl } = xl || process.env, R = {
userAuthorized: !1,
attachmentsAccept: "*/*",
enableUserLogin: !1,
enableCalls: !1,
enableUserStatuses: !1,
enableLastSeen: !1,
enableContentReporting: !1,
enableBlockList: !1,
enableUrlPreview: !1,
limitUrlsPreviews: 1,
termsAndConditions: Gl
}, J = _((q) => ({
...R,
setUserAuthorized: (A) => q({ userAuthorized: A }),
setAttachmentsAccept: (A) => q({ attachmentsAccept: A }),
setEnableUserLogin: (A) => q({ enableUserLogin: A }),
setEnableCalls: (A) => q({ enableCalls: A && Ul }),
setEnableUserStatuses: (A) => q({ enableUserStatuses: A }),
setEnableLastSeen: (A) => q({ enableLastSeen: A }),
setEnableContentReporting: (A) => q({ enableContentReporting: A }),
setEnableBlockList: (A) => q({ enableBlockList: A }),
setEnableUrlPreview: (A) => q({ enableUrlPreview: A }),
setLimitUrlsPreviews: (A) => q({ limitUrlsPreviews: A > 5 ? 5 : A }),
setTermsAndConditions: (A) => q({ termsAndConditions: A }),
resetUserAuthorized: () => q({ userAuthorized: R.userAuthorized }),
resetAttachmentsAccept: () => q({ attachmentsAccept: R.attachmentsAccept }),
resetEnableUserLogin: () => q({ enableUserLogin: R.enableUserLogin }),
resetEnableCalls: () => q({ enableCalls: R.enableCalls }),
resetEnableUserStatuses: () => q({ enableUserStatuses: R.enableUserStatuses }),
resetEnableLastSeen: () => q({ enableLastSeen: R.enableLastSeen }),
resetEnableContentReporting: () => q({ enableContentReporting: R.enableContentReporting }),
resetEnableBlockList: () => q({ enableBlockList: R.enableBlockList }),
resetEnableUrlPreview: () => q({ enableUrlPreview: R.enableUrlPreview }),
resetLimitUrlsPreviews: () => q({ limitUrlsPreviews: R.limitUrlsPreviews }),
resetTermsAndConditions: () => q({ termsAndConditions: R.termsAndConditions })
})), ae = (q) => {
q.limitUrlsPreviews && (q.limitUrlsPreviews = q.limitUrlsPreviews > 5 ? 5 : q.limitUrlsPreviews), J.setState(q);
}, bl = () => {
J.setState(R);
}, vl = {}, { CHAT_WIDGET_CONNECTYCUBE_WEB_PUSH_VAPID_PUBLIC_KEY: Yl, CHAT_WIDGET_CONNECTYCUBE_WEB_PUSH_SERVICE_WORKER_PATH: Fl } = vl || process.env, rq = {
muted: !1,
showNotifications: !1,
playSound: !0,
webPushNotifications: !1,
webPushVapidPublicKey: Yl,
serviceWorkerPath: Fl
}, Fq = _((q) => ({
...rq,
setMuted: (A) => q({ muted: A }),
resetMuted: () => q({ muted: rq.muted }),
setShowNotifications: (A) => q({ showNotifications: A }),
resetShowNotifications: () => q({ showNotifications: rq.showNotifications }),
setPlaySound: (A) => q({ playSound: A }),
resetPlaySound: () => q({ playSound: rq.playSound }),
setWebPushNotifications: (A) => q({ webPushNotifications: A }),
resetWebPushNotifications: () => q({ webPushNotifications: rq.webPushNotifications }),
setWebPushVapidPublicKey: (A) => q({ webPushVapidPublicKey: A }),
resetWebPushVapidPublicKey: () => q({ webPushVapidPublicKey: rq.webPushVapidPublicKey }),
setServiceWorkerPath: (A) => q({ serviceWorkerPath: A }),
resetServiceWorkerPath: () => q({ serviceWorkerPath: rq.serviceWorkerPath })
})), Kl = (q) => {
Fq.setState(q);
}, Rl = () => {
Fq.setState(rq);
}, MA = {
quickActions: {
title: "",
description: "",
actions: []
}
}, aV = _((q) => ({
...MA,
setQuickActions: (A) => q({ quickActions: A }),
resetQuickActions: () => q({ quickActions: MA.quickActions })
})), zl = (q) => {
aV.setState(q);
}, Jl = () => {
aV.setState(MA);
}, Cq = {
requestOnlineUsersInterval: 300,
// in seconds
enableOnlineUsersBadge: !1,
onlineUsersCount: 0
}, rA = _((q) => ({
requestOnlineUsersInterval: Cq.requestOnlineUsersInterval,
// in seconds
enableOnlineUsersBadge: Cq.enableOnlineUsersBadge,
onlineUsersCount: Cq.onlineUsersCount,
setRequestOnlineUsersInterval: (A) => {
q({
requestOnlineUsersInterval: typeof A == "number" ? A > 30 ? A : 30 : Cq.requestOnlineUsersInterval
});
},
setEnableOnlineUsersBadge: (A) => q({ enableOnlineUsersBadge: A }),
setOnlineUsersCount: (A) => q({ onlineUsersCount: A }),
resetRequestOnlineUsersInterval: () => q({ requestOnlineUsersInterval: Cq.requestOnlineUsersInterval }),
resetEnableOnlineUsersBadge: () => q({ enableOnlineUsersBadge: Cq.enableOnlineUsersBadge }),
resetOnlineUsersCount: () => q({ onlineUsersCount: Cq.onlineUsersCount })
})), jl = () => {
rA.setState({ onlineUsersCount: 0 });
}, oe = {
fetchedCount: 0,
queue: [],
urlPreviews: /* @__PURE__ */ new Map(),
isProcessing: !1
}, oV = _((q, A) => ({
...oe,
addUrls: async (V) => {
const e = A(), o = V.filter((i) => !e.urlPreviews.has(i) && !e.queue.includes(i));
if (e.isProcessing || o.length === 0) return;
q({ queue: [...e.queue, ...o], isProcessing: !0 });
let r = e.fetchedCount;
const n = new Map(e.urlPreviews);
for (const i of o)
try {
const s = await aq.linkpreview.get(i);
n.set(i, s), r++;
} catch (s) {
console.warn(`Failed to fetch link preview for ${i}`, s);
}
q({
urlPreviews: n,
fetchedCount: r,
isProcessing: !1,
queue: []
});
},
matchUrlsFromMessage: (V = "") => {
const e = J.getState().limitUrlsPreviews;
return (V.match(/https?:\/\/[^\s]+/g) || []).slice(0, e);
}
})), Ll = () => {
oV.setState(oe);
}, nA = _((q) => ({
visible: !1,
userId: void 0,
showProfile: (A) => q({ visible: !0, userId: A }),
hideProfile: () => q({ visible: !1, userId: void 0 })
})), re = () => {
nA.setState({ visible: !1, userId: void 0 });
}, fA = _((q) => ({
unreadCount: 0,
setUnreadCount: (A) => q({ unreadCount: A }),
resetUnreadCount: () => q({ unreadCount: 0 })
})), Ol = () => {
fA.setState({ unreadCount: 0 });
}, Wl = async () => "Notification" in window ? Notification.permission === "granted" ? !0 : await Notification.requestPermission() === "granted" ? (console.log("Notifications are enabled"), !0) : (console.warn("Notifications are disabled"), !1) : (console.error("Notifications are not supported in this browser"), !1), Zl = async (q) => {
let A = !1;
try {
q && "serviceWorker" in navigator && (A = !!await navigator.serviceWorker.register(q, { type: "module" }));
} catch (V) {
throw new Error(`Registration failed: ${V}`);
}
return A;
}, ne = async (q) => {
try {
if (q && "serviceWorker" in navigator)
return navigator.serviceWorker.getRegistration(q);
} catch (A) {
throw new Error(`Get registration failed: ${A}`);
}
}, Pl = (q) => {
const { endpoint: A = "", keys: V = {} } = q?.toJSON() ?? {}, { p256dh: e = "", auth: o = "" } = V;
return { endpoint: A, p256dh: e, auth: o };
}, ie = async (q, A) => {
const V = await ne(q);
let e = null;
return V?.pushManager && (e = await V.pushManager.getSubscription(), !e && A && (e = await V?.pushManager.subscribe({
applicationServerKey: A,
userVisibleOnly: !0
}) ?? null)), e;
}, Hl = async (q) => (await ie(q))?.unsubscribe() ?? !1, se = () => {
const q = Ae(), { showNotifications: A, playSound: V, webPushNotifications: e } = Fq.getState();
return {
userStatus: q?.userStatus ?? $.AVAILABLE,
isNotifications: q?.notifications ?? A,
isNotificationSound: q?.notificationSound ?? V,
isPushNotifications: q?.pushNotifications ?? e
};
}, Xl = se(), Pq = _((q) => ({
...Xl,
setUserStatus: async (A, V) => {
await gA({ userStatus: A }, V), q({ userStatus: A });
},
setIsNotifications: async (A, V) => {
await gA({ notifications: A }, V), q({ isNotifications: A });
},
setIsNotificationSound: async (A, V) => {
await gA({ notificationSound: A }, V), q({ isNotificationSound: A });
},
setIsPushNotifications: async (A, V) => {
const e = await le(A);
await gA({ pushNotifications: e }, V), q({ isPushNotifications: e });
}
})), le = async (q) => {
const { serviceWorkerPath: A, webPushVapidPublicKey: V } = Fq.getState();
let e = !1;
try {
if (q) {
const o = await ie(A, V), r = Pl(o);
await Sl(r), e = !0;
} else
await Hl(A), await fl();
} catch (o) {
console.error("Error managing push notifications subscription:", o);
}
return e;
}, ce = async () => {
const q = se(), A = await le(q.isPushNotifications);
Pq.setState({ ...q, isPushNotifications: A });
}, $l = {}, { CHAT_WIDGET_CONNECTYCUBE_GOOGLE_GENERATIVE_AI_API_KEY: _l } = $l || process.env, _q = {
changeMessageTone: !1,
textSummarization: !1,
apiKey: _l
}, ge = _((q) => ({
..._q,
setChangeMessageTone: (A) => q({ changeMessageTone: !!A }),
setTextSummarization: (A) => q({ textSummarization: !!A }),
setApiKey: (A) => q({ apiKey: A }),
resetChangeMessageTone: () => q({ changeMessageTone: _q.changeMessageTone }),
resetTextSummarization: () => q({ textSummarization: _q.textSummarization }),
resetApiKey: () => q({ apiKey: _q.apiKey })
})), UA = _((q) => ({
onMessageBeforeSend: void 0,
onMessageBeforeDisplay: void 0,
setMessageTransforms: ({ onMessageBeforeSend: A, onMessageBeforeDisplay: V }) => q({ onMessageBeforeSend: A, onMessageBeforeDisplay: V })
})), Nq = _((q) => ({
shadowRoot: lq() ? document : {},
shadowPortal: lq() ? document.body : null,
setShadowRoot: (A) => q({ shadowRoot: A ?? document, shadowPortal: A ?? document.body })
})), qc = {
chat: {
streamManagement: { enable: !0 }
}
}, Ac = ({ creds: q, config: A = {}, user: V = {}, enableUserLogin: e }) => {
const o = W(!1), r = Object.assign(qc, A), n = X((s) => s.singleView), i = J((s) => s.setUserAuthorized);
Dl(n), U(() => {
o.current || (o.current = !0, dt(q, r), ae({ userAuthorized: !ee() }), !e && Cl(V.userId) ? (console.info(`[useAppAuthorization] user changed to id: ${V.userId}, name: ${V.userName}`), tV(), i(!1)) : El(V));
}, []);
}, QV = (q) => Symbol.iterator in q, SV = (q) => (
// HACK: avoid checking entries type
"entries" in q
), fV = (q, A) => {
const V = q instanceof Map ? q : new Map(q.entries()), e = A instanceof Map ? A : new Map(A.entries());
if (V.size !== e.size)
return !1;
for (const [o, r] of V)
if (!e.has(o) || !Object.is(r, e.get(o)))
return !1;
return !0;
}, Vc = (q, A) => {
const V = q[Symbol.iterator](), e = A[Symbol.iterator]();
let o = V.next(), r = e.next();
for (; !o.done && !r.done; ) {
if (!Object.is(o.value, r.value))
return !1;
o = V.next(), r = e.next();
}
return !!o.done && !!r.done;
};
function ec(q, A) {
return Object.is(q, A) ? !0 : typeof q != "object" || q === null || typeof A != "object" || A === null || Object.getPrototypeOf(q) !== Object.getPrototypeOf(A) ? !1 : QV(q) && QV(A) ? SV(q) && SV(A) ? fV(q, A) : Vc(q, A) : fV(
{ entries: () => Object.entries(q) },
{ entries: () => Object.entries(A) }
);
}
function x(q) {
const A = t.useRef(void 0);
return (V) => {
const e = q(V);
return ec(A.current, e) ? A.current : A.current = e;
};
}
const tc = ({
open: q = z.opened,
embedView: A = !1,
splitView: V = z.splitView,
singleView: e = z.singleView,
showChatStatus: o = z.showChatStatus,
showChatActionsAsMenu: r = z.showChatActionsAsMenu,
showOnlineUsersTab: n = z.showOnlineUsersTab,
hideNewChatButton: i = z.hideNewChatButton,
hideNewUserChatOption: s = z.hideNewUserChatOption,
hideNewGroupChatOption: c = z.hideNewGroupChatOption,
imgLogoSource: l = z.imgLogoSource,
muted: g = rq.muted,
showNotifications: m = rq.showNotifications,
playSound: u = rq.playSound,
webPushNotifications: M = rq.webPushNotifications,
serviceWorkerPath: w = rq.serviceWorkerPath,
webPushVapidPublicKey: d = rq.webPushVapidPublicKey,
attachmentsAccept: C = R.attachmentsAccept,
enableUserLogin: k = R.enableUserLogin,
enableCalls: I = R.enableCalls,
enableUserStatuses: E = R.enableUserStatuses,
enableLastSeen: B = R.enableLastSeen,
enableContentReporting: Q = R.enableContentReporting,
enableBlockList: p = R.enableBlockList,
enableUrlPreview: T = R.enableUrlPreview,
limitUrlsPreviews: f = R.limitUrlsPreviews,
termsAndConditions: N = R.termsAndConditions,
quickActions: D = MA.quickActions,
defaultChat: S = Wq.defaultChat,
singleViewChat: b = Wq.singleViewChat,
enableOnlineUsersBadge: Z = Cq.enableOnlineUsersBadge,
getOnlineUsersInterval: O = Cq.requestOnlineUsersInterval,
ai: Y = _q,
onUnreadCountChange: mq,
onOnlineUsersCountChange: qq,
onOpenChange: xq,
onMessageBeforeSend: uq,
onMessageBeforeDisplay: Rq
}) => {
const [zq, kq, Gq] = X(
x((K) => [K.opened, K.setOpened, K.toggleOpened])
), Jq = fA((K) => K.unreadCount), [sA, Hq, y] = rA(
x((K) => [
K.onlineUsersCount,
K.setRequestOnlineUsersInterval,
K.setEnableOnlineUsersBadge
])
), [Aq, dq, hq] = ge(
x((K) => [K.setChangeMessageTone, K.setTextSummarization, K.setApiKey])
), wq = UA((K) => K.setMessageTransforms);
U(() => {
wq({ onMessageBeforeSend: uq, onMessageBeforeDisplay: Rq });
}, [uq, Rq, wq]), U(() => {
dl({
opened: A || q,
splitView: V && !e,
singleView: e,
showChatStatus: o,
showChatActionsAsMenu: r,
showOnlineUsersTab: n && !e,
hideNewChatButton: i,
hideNewUserChatOption: s,
hideNewGroupChatOption: c,
imgLogoSource: l
});
}, [
q,
A,
V,
e,
o,
r,
n,
i,
s,
c,
l
]), U(() => {
Kl({
muted: g,
showNotifications: m,
playSound: u,
webPushNotifications: M,
webPushVapidPublic