touchstudy-core 0.1.6 → 0.1.8

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.
@@ -2,7 +2,7 @@ import { createBrowserHistory } from 'history';
2
2
  import { createAction, createReducer, configureStore } from '@reduxjs/toolkit';
3
3
  import moment from 'moment';
4
4
  import React, { useState, useCallback, useEffect, Fragment, useRef, useMemo } from 'react';
5
- import { Row, Col, Form, Modal, ModalHeader, ModalBody, ModalFooter, Button, Alert, Pagination, PaginationItem, PaginationLink, Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
5
+ import { Row, Col, Form, Modal, ModalHeader, ModalBody, ModalFooter, Button, Alert, Pagination, PaginationItem, PaginationLink, Dropdown, DropdownToggle, DropdownMenu, DropdownItem, Collapse, InputGroup, Input } from 'reactstrap';
6
6
  import { Formik } from 'formik';
7
7
  import { object, string, boolean } from 'yup';
8
8
  import GoogleLogin, { useGoogleLogout } from '@leecheuk/react-google-login';
@@ -13,6 +13,11 @@ import i18n from 'i18next';
13
13
  import { initReactI18next, useTranslation } from 'react-i18next';
14
14
  export { I18nextProvider, useTranslation } from 'react-i18next';
15
15
  import { IoChevronDown } from 'react-icons/io5';
16
+ import Select from 'react-select';
17
+ import { Link } from 'react-router-dom';
18
+ import { IoIosCloseCircle, IoMdSend } from 'react-icons/io';
19
+ import { ToastContainer, toast } from 'react-toastify';
20
+ import Pusher from 'pusher-js';
16
21
 
17
22
  var setLoading = createAction("common/setLoading");
18
23
  var setAlert = createAction("common/setAlert");
@@ -30,9 +35,10 @@ var BASE_URL = function () {
30
35
  }();
31
36
  var PUSHER_CONFIG = {
32
37
  cluster: "ap1",
33
- key: "9018c77328885a14150b"
38
+ key: "dde049326fbe52b2a749"
34
39
  };
35
- var EXAM_CHANNEL = "EXAM-CHANNEL";
40
+ var EXAM_CHANNEL = "presence-exam-channel";
41
+ var EXAM_STUDENT_CHANNEL = "EXAM-CHANNEL-{examCode}-STUDENT-{studentId}";
36
42
  var getAccessToken = function getAccessToken() {
37
43
  try {
38
44
  return localStorage.getItem(ACCESS_TOKEN);
@@ -637,66 +643,9 @@ var Loading = function Loading() {
637
643
  }))) : null;
638
644
  };
639
645
 
640
- var encodeParams$1 = (function (params) {
641
- return Object.keys(params).filter(function (key) {
642
- return params[key] || params[key] === 0 || params[key] === false;
643
- }).map(function (key) {
644
- if (Array.isArray(params[key])) {
645
- return params[key].map(function (i) {
646
- return encodeURIComponent(key) + "=" + encodeURIComponent(i);
647
- }).join('&');
648
- }
649
- return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
650
- }).join('&');
651
- });
652
-
653
- var api$1 = axios.create({
654
- baseURL: BASE_URL,
655
- timeout: 0,
656
- headers: {
657
- "Content-Type": "application/json"
658
- },
659
- paramsSerializer: function paramsSerializer(params) {
660
- return encodeParams$1(params);
661
- }
662
- });
663
- var apiUpload$1 = axios.create({
664
- baseURL: BASE_URL,
665
- timeout: 60000,
666
- headers: {
667
- "Content-Type": "multipart/form-data"
668
- }
669
- });
670
- [api$1, apiUpload$1].forEach(function (i) {
671
- return i.interceptors.request.use(function (config) {
672
- var token = getAccessToken$1();
673
- if (token) {
674
- config.headers.Authorization = "Bearer " + token;
675
- }
676
- return config;
677
- }, function (error) {
678
- return Promise.reject(error);
679
- });
680
- });
681
- [api$1, apiUpload$1].forEach(function (i) {
682
- return i.interceptors.response.use(function (response) {
683
- return response;
684
- }, function (error) {
685
- if (error.response.status === 401) {
686
- window.location.href = "/login";
687
- }
688
- if (error.response.status == 403) {
689
- localStorage.removeItem(ACCESS_TOKEN);
690
- localStorage.removeItem("USER_EMAIL");
691
- window.location.href = "/login";
692
- }
693
- return Promise.reject(error);
694
- });
695
- });
696
-
697
646
  var AUTH_URL = BASE_URL + "/api/auth";
698
647
  var getInfo = function getInfo() {
699
- return api$1.get(AUTH_URL + "/info");
648
+ return api.get(AUTH_URL + "/info");
700
649
  };
701
650
 
702
651
  var LayoutContext = function LayoutContext(_ref) {
@@ -960,10 +909,8 @@ var ExamEvent;
960
909
  (function (ExamEvent) {
961
910
  ExamEvent["StartExam"] = "start-exam";
962
911
  ExamEvent["TerminateExam"] = "terminate-exam";
963
- ExamEvent["JoinExam"] = "join-exam";
964
912
  ExamEvent["AddExtraDuration"] = "add-extra-duration-exam";
965
- ExamEvent["TeacherDisconnectChannel"] = "teacher-disconnect-channel";
966
- ExamEvent["StudentDisconnectChannel"] = "student-disconnect-channel";
913
+ ExamEvent["TeacherKickOutStudent"] = "teacher-kick-out-student";
967
914
  })(ExamEvent || (ExamEvent = {}));
968
915
 
969
916
  var problem_solving = "문제풀기";
@@ -1022,6 +969,7 @@ var internet_connection_was_lost = "인터넷 연결이 끊어졌습니다";
1022
969
  var problem = "문제";
1023
970
  var problem_solving_time = "문제풀이 시간";
1024
971
  var minutes = "분";
972
+ var correct_rate = "정확한 비율";
1025
973
  var lang_ko = {
1026
974
  problem_solving: problem_solving,
1027
975
  my_story: my_story,
@@ -1078,7 +1026,8 @@ var lang_ko = {
1078
1026
  internet_connection_was_lost: internet_connection_was_lost,
1079
1027
  problem: problem,
1080
1028
  problem_solving_time: problem_solving_time,
1081
- minutes: minutes
1029
+ minutes: minutes,
1030
+ correct_rate: correct_rate
1082
1031
  };
1083
1032
 
1084
1033
  var problem_solving$1 = "Problem Solving";
@@ -1137,6 +1086,7 @@ var internet_connection_was_lost$1 = "Internet connection was lost";
1137
1086
  var problem$1 = "Problem ";
1138
1087
  var problem_solving_time$1 = "Problem solving time";
1139
1088
  var minutes$1 = "m";
1089
+ var correct_rate$1 = "Correct rate";
1140
1090
  var lang_en = {
1141
1091
  problem_solving: problem_solving$1,
1142
1092
  my_story: my_story$1,
@@ -1193,7 +1143,8 @@ var lang_en = {
1193
1143
  internet_connection_was_lost: internet_connection_was_lost$1,
1194
1144
  problem: problem$1,
1195
1145
  problem_solving_time: problem_solving_time$1,
1196
- minutes: minutes$1
1146
+ minutes: minutes$1,
1147
+ correct_rate: correct_rate$1
1197
1148
  };
1198
1149
 
1199
1150
  i18n.use(initReactI18next).init({
@@ -1338,7 +1289,1275 @@ var canAccess = function canAccess(userRoles, componentRoles) {
1338
1289
  return true;
1339
1290
  };
1340
1291
 
1292
+ function _extends() {
1293
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
1294
+ for (var i = 1; i < arguments.length; i++) {
1295
+ var source = arguments[i];
1296
+ for (var key in source) {
1297
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1298
+ target[key] = source[key];
1299
+ }
1300
+ }
1301
+ }
1302
+ return target;
1303
+ };
1304
+ return _extends.apply(this, arguments);
1305
+ }
1306
+ function _objectWithoutPropertiesLoose(source, excluded) {
1307
+ if (source == null) return {};
1308
+ var target = {};
1309
+ var sourceKeys = Object.keys(source);
1310
+ var key, i;
1311
+ for (i = 0; i < sourceKeys.length; i++) {
1312
+ key = sourceKeys[i];
1313
+ if (excluded.indexOf(key) >= 0) continue;
1314
+ target[key] = source[key];
1315
+ }
1316
+ return target;
1317
+ }
1318
+
1319
+ var _excluded = ["defaultValue", "options", "isDisabled", "scrollBottom", "value", "isMulti"];
1320
+ var CustomSelect = function CustomSelect(_ref) {
1321
+ var options = _ref.options,
1322
+ isDisabled = _ref.isDisabled,
1323
+ scrollBottom = _ref.scrollBottom,
1324
+ value = _ref.value,
1325
+ isMulti = _ref.isMulti,
1326
+ rest = _objectWithoutPropertiesLoose(_ref, _excluded);
1327
+ var initialValues = Array.isArray(value) ? options.filter(function (i) {
1328
+ return value.includes(i.value);
1329
+ }) : isMulti ? options.filter(function (i) {
1330
+ return i.value == value;
1331
+ }) : options.find(function (i) {
1332
+ return i.value == value;
1333
+ });
1334
+ return React.createElement(Select, Object.assign({
1335
+ isDisabled: isDisabled,
1336
+ options: options,
1337
+ value: initialValues,
1338
+ menuPlacement: scrollBottom ? "top" : "auto",
1339
+ isMulti: isMulti
1340
+ }, rest));
1341
+ };
1342
+
1343
+ var styles$1 = {"header__avatar":"_2oGcJ","header__select":"_2y2XV","body":"_ntGyI","list":"_m7Fwt","list__item__header":"_3BM8N","list__item__avatar":"_1ReOK","list__item__avatar-container":"_2qbld","list__item__message":"_3s01i","list__item__message--reply-from":"_2Qxi3","list__item__message--reply-from-right":"_34Vx4","list__item__message--reply":"_3uheq","list__item__message--reply-right":"_2iBr7","reply-text":"_3ZPjO"};
1344
+
1345
+ var MessageSortBy;
1346
+ (function (MessageSortBy) {
1347
+ MessageSortBy["CreatedAt"] = "CreatedAt";
1348
+ })(MessageSortBy || (MessageSortBy = {}));
1349
+ var OrderBy;
1350
+ (function (OrderBy) {
1351
+ OrderBy["ASC"] = "ASC";
1352
+ OrderBy["DESC"] = "DESC";
1353
+ })(OrderBy || (OrderBy = {}));
1354
+ var StudentSortBy;
1355
+ (function (StudentSortBy) {
1356
+ StudentSortBy["CreatedAt"] = "CreatedAt";
1357
+ StudentSortBy["DisplayName"] = "DisplayName";
1358
+ })(StudentSortBy || (StudentSortBy = {}));
1359
+ var StudentOrderBy;
1360
+ (function (StudentOrderBy) {
1361
+ StudentOrderBy["ASC"] = "ASC";
1362
+ StudentOrderBy["DESC"] = "DESC";
1363
+ })(StudentOrderBy || (StudentOrderBy = {}));
1364
+ var MessageAction;
1365
+ (function (MessageAction) {
1366
+ MessageAction[MessageAction["Default"] = 0] = "Default";
1367
+ MessageAction[MessageAction["Took"] = 1] = "Took";
1368
+ })(MessageAction || (MessageAction = {}));
1369
+ var MessageSourceType;
1370
+ (function (MessageSourceType) {
1371
+ MessageSourceType[MessageSourceType["Default"] = 0] = "Default";
1372
+ MessageSourceType[MessageSourceType["Exam"] = 1] = "Exam";
1373
+ MessageSourceType[MessageSourceType["Class"] = 2] = "Class";
1374
+ })(MessageSourceType || (MessageSourceType = {}));
1375
+ var MessageStatus;
1376
+ (function (MessageStatus) {
1377
+ MessageStatus["Default"] = "Sent";
1378
+ MessageStatus["Sending"] = "Sending...";
1379
+ MessageStatus["SentError"] = "Sent fail, Retry";
1380
+ })(MessageStatus || (MessageStatus = {}));
1381
+
1382
+ var ChatRightItem = function ChatRightItem(_ref) {
1383
+ var content = _ref.content,
1384
+ createdAt = _ref.createdAt,
1385
+ isRead = _ref.isRead,
1386
+ _ref$type = _ref.type,
1387
+ type = _ref$type === void 0 ? ChatItemType.Default : _ref$type,
1388
+ examCode = _ref.examCode,
1389
+ isSystemLog = _ref.isSystemLog,
1390
+ parentId = _ref.parentId,
1391
+ _ref$showExamHeader = _ref.showExamHeader,
1392
+ showExamHeader = _ref$showExamHeader === void 0 ? false : _ref$showExamHeader,
1393
+ _ref$isFirst = _ref.isFirst,
1394
+ isFirst = _ref$isFirst === void 0 ? true : _ref$isFirst,
1395
+ isLast = _ref.isLast,
1396
+ actionLink = _ref.actionLink,
1397
+ examId = _ref.examId,
1398
+ examTitle = _ref.examTitle,
1399
+ parentContent = _ref.parentContent,
1400
+ status = _ref.status,
1401
+ onAddExamMessage = _ref.onAddExamMessage,
1402
+ onReTrySendMessage = _ref.onReTrySendMessage;
1403
+ var _useState = useState(false),
1404
+ isShowTime = _useState[0],
1405
+ setShowTime = _useState[1];
1406
+ var _useState2 = useState(false),
1407
+ isShowInfo = _useState2[0],
1408
+ setShowInfo = _useState2[1];
1409
+ var handleShowInfo = function handleShowInfo() {
1410
+ setShowInfo(!isShowInfo);
1411
+ !isFirst && !isSystemLog && setShowTime(!isShowInfo);
1412
+ };
1413
+ var handleReTrySendMessage = function handleReTrySendMessage() {
1414
+ if (status !== MessageStatus.SentError || !content) return;
1415
+ onReTrySendMessage === null || onReTrySendMessage === void 0 ? void 0 : onReTrySendMessage({
1416
+ content: content,
1417
+ examId: examId,
1418
+ examTitle: examTitle,
1419
+ parentContent: parentContent,
1420
+ parentId: parentId
1421
+ });
1422
+ };
1423
+ useEffect(function () {
1424
+ setShowTime(isSystemLog || !!isFirst);
1425
+ }, [isFirst, isSystemLog]);
1426
+ return React.createElement("li", {
1427
+ className: "px-3 " + (!isLast ? "pb-1" : "pb-3") + " " + (!!examCode ? "border border-top-0 border-info" : "") + " " + (!!examCode && isLast ? "border-bottom-1 mb-3" : "border-bottom-0")
1428
+ }, showExamHeader && isFirst && React.createElement("div", {
1429
+ className: "d-flex bg-info justify-content-between px-3 mb-3 py-1 " + styles$1["list__item__header"]
1430
+ }, React.createElement(Link, {
1431
+ to: "" + (actionLink || "/"),
1432
+ className: "text-black"
1433
+ }, examTitle), !!examId && !!examTitle && React.createElement("span", {
1434
+ className: "pointer text-black",
1435
+ onClick: function onClick() {
1436
+ return onAddExamMessage === null || onAddExamMessage === void 0 ? void 0 : onAddExamMessage(examId, examTitle);
1437
+ }
1438
+ }, "Add message to exam")), isSystemLog || !!isFirst ? React.createElement("p", {
1439
+ className: "mb-0 py-1 px-3 fs-6 text-muted text-center"
1440
+ }, utcToLocalTime(createdAt, "HH:mm DD MMM YYYY")) : React.createElement(Collapse, {
1441
+ className: "w-100",
1442
+ isOpen: isShowTime
1443
+ }, React.createElement("p", {
1444
+ className: "mb-0 py-1 px-3 fs-6 text-muted text-center"
1445
+ }, utcToLocalTime(createdAt, "HH:mm DD MMM YYYY"))), isSystemLog ? React.createElement("div", {
1446
+ className: "text-center w-100"
1447
+ }, React.createElement(Link, {
1448
+ to: "" + (actionLink || "/"),
1449
+ title: "See the results",
1450
+ className: "text-primary"
1451
+ }, content)) : React.createElement("div", {
1452
+ className: "d-flex align-items-start w-100 flex-row-reverse"
1453
+ }, React.createElement("div", {
1454
+ className: "d-flex flex-column align-items-end"
1455
+ }, parentId && React.createElement("p", {
1456
+ className: "opacity-50 mb-0 py-2 px-3 fw-medium pointer " + styles$1["list__item__message"] + " " + styles$1["list__item__message--reply-from-right"] + " text-end bg-primary text-white"
1457
+ }, React.createElement("b", null, "Reply To:"), " ", parentContent), React.createElement("p", {
1458
+ className: "mb-0 py-2 px-3 fw-medium pointer " + styles$1["list__item__message"] + " " + (parentId ? styles$1["list__item__message--reply-right"] : "") + " text-end bg-primary text-white",
1459
+ onClick: handleShowInfo
1460
+ }, content), status !== MessageStatus.Default && React.createElement("p", {
1461
+ onClick: handleReTrySendMessage,
1462
+ className: "fs-6 mb-0 " + (status === MessageStatus.SentError ? "text-danger text-decoration-underline pointer" : "")
1463
+ }, status), (type !== ChatItemType.Exam || !examCode) && status === MessageStatus.Default && React.createElement(Collapse, {
1464
+ isOpen: isShowInfo
1465
+ }, React.createElement("p", {
1466
+ className: "mb-0 py-1 px-3 fs-6 text-muted text-end"
1467
+ }, isRead ? "seen" : "sent")))));
1468
+ };
1469
+
1470
+ var ChatLeftItem = function ChatLeftItem(_ref) {
1471
+ var id = _ref.id,
1472
+ avatar = _ref.avatar,
1473
+ content = _ref.content,
1474
+ createdAt = _ref.createdAt,
1475
+ examCode = _ref.examCode,
1476
+ isSystemLog = _ref.isSystemLog,
1477
+ parentId = _ref.parentId,
1478
+ _ref$showExamHeader = _ref.showExamHeader,
1479
+ showExamHeader = _ref$showExamHeader === void 0 ? false : _ref$showExamHeader,
1480
+ _ref$isFirst = _ref.isFirst,
1481
+ isFirst = _ref$isFirst === void 0 ? true : _ref$isFirst,
1482
+ isLast = _ref.isLast,
1483
+ actionLink = _ref.actionLink,
1484
+ examId = _ref.examId,
1485
+ examTitle = _ref.examTitle,
1486
+ parentContent = _ref.parentContent,
1487
+ onAddExamMessage = _ref.onAddExamMessage,
1488
+ onReply = _ref.onReply,
1489
+ selectedReplyMessageId = _ref.selectedReplyMessageId,
1490
+ onToggleReply = _ref.onToggleReply,
1491
+ selectedReplyItemRef = _ref.selectedReplyItemRef;
1492
+ var _useState = useState(false),
1493
+ isShowTime = _useState[0],
1494
+ setShowTime = _useState[1];
1495
+ var _useState2 = useState(false),
1496
+ isShowInfo = _useState2[0],
1497
+ setShowInfo = _useState2[1];
1498
+ var handleShowInfo = function handleShowInfo() {
1499
+ if (!id) return;
1500
+ setShowInfo(!isShowInfo);
1501
+ onToggleReply === null || onToggleReply === void 0 ? void 0 : onToggleReply(id);
1502
+ !isFirst && !isSystemLog && setShowTime(!isShowInfo);
1503
+ };
1504
+ var handleReply = function handleReply() {
1505
+ if (!id) return;
1506
+ onReply === null || onReply === void 0 ? void 0 : onReply(id, content || "", examId);
1507
+ };
1508
+ useEffect(function () {
1509
+ setShowTime(isSystemLog || !!isFirst);
1510
+ }, [isFirst, isSystemLog]);
1511
+ return React.createElement("li", {
1512
+ ref: selectedReplyMessageId === id ? selectedReplyItemRef : undefined,
1513
+ className: "px-3 " + (!isLast ? "pb-1" : "pb-3") + " " + (!!examCode ? "border border-top-0 border-info" : "") + " " + (!!examCode && isLast ? "border-bottom-1 mb-3" : "border-bottom-0")
1514
+ }, showExamHeader && isFirst && React.createElement("div", {
1515
+ className: "d-flex bg-info justify-content-between px-3 mb-3 py-1 " + styles$1["list__item__header"]
1516
+ }, React.createElement(Link, {
1517
+ to: "" + (actionLink || "/"),
1518
+ className: "text-black"
1519
+ }, examTitle), !!examId && !!examTitle && React.createElement("span", {
1520
+ className: "pointer text-black",
1521
+ onClick: function onClick() {
1522
+ return onAddExamMessage === null || onAddExamMessage === void 0 ? void 0 : onAddExamMessage(examId, examTitle);
1523
+ }
1524
+ }, "Add message to exam")), isSystemLog || !!isFirst ? React.createElement("p", {
1525
+ className: "mb-0 py-1 px-3 fs-6 text-muted text-center"
1526
+ }, utcToLocalTime(createdAt, "HH:mm DD MMM YYYY")) : React.createElement(Collapse, {
1527
+ className: "w-100",
1528
+ isOpen: isShowTime
1529
+ }, React.createElement("p", {
1530
+ className: "mb-0 py-1 px-3 fs-6 text-muted text-center"
1531
+ }, utcToLocalTime(createdAt, "HH:mm DD MMM YYYY"))), isSystemLog ? React.createElement("div", {
1532
+ className: "text-center w-100"
1533
+ }, React.createElement(Link, {
1534
+ to: "" + (actionLink || "/"),
1535
+ title: "See the results",
1536
+ className: "text-primary"
1537
+ }, content)) : React.createElement("div", {
1538
+ className: "d-flex align-items-start w-100"
1539
+ }, React.createElement("div", {
1540
+ className: "rounded-circle " + styles$1["list__item__avatar-container"] + " bg-light me-2 mt-1 " + (isFirst ? "" : "opacity-0")
1541
+ }, isFirst && React.createElement("img", {
1542
+ className: styles$1["list__item__avatar"] + " bg-light rounded-circle",
1543
+ src: avatar
1544
+ })), React.createElement("div", {
1545
+ className: "d-flex flex-column"
1546
+ }, parentId && React.createElement("p", {
1547
+ className: "opacity-50 mb-0 py-2 px-3 fw-medium pointer " + styles$1["list__item__message"] + " " + styles$1["list__item__message--reply-from"] + " text-start bg-light"
1548
+ }, React.createElement("b", null, "Reply To:"), " ", parentContent), React.createElement("p", {
1549
+ className: "mb-0 py-2 px-3 fw-medium pointer " + styles$1["list__item__message"] + " " + (parentId ? styles$1["list__item__message--reply"] : "") + " text-start bg-light",
1550
+ onClick: handleShowInfo
1551
+ }, content), !isSystemLog && React.createElement(Collapse, {
1552
+ className: "w-100",
1553
+ isOpen: selectedReplyMessageId === id
1554
+ }, React.createElement("p", {
1555
+ onClick: handleReply,
1556
+ className: "mb-0 py-1 px-3 fs-6 text-primary text-left pointer"
1557
+ }, "Reply")))));
1558
+ };
1559
+
1560
+ var ChatItemType;
1561
+ (function (ChatItemType) {
1562
+ ChatItemType[ChatItemType["Default"] = 0] = "Default";
1563
+ ChatItemType[ChatItemType["Exam"] = 1] = "Exam";
1564
+ ChatItemType[ChatItemType["Class"] = 2] = "Class";
1565
+ })(ChatItemType || (ChatItemType = {}));
1566
+ var ChatItem = function ChatItem(props) {
1567
+ var isMe = props.isMe,
1568
+ onReTrySendMessage = props.onReTrySendMessage;
1569
+ return React.createElement(Fragment, null, isMe ? React.createElement(ChatRightItem, Object.assign({}, props, {
1570
+ onReTrySendMessage: onReTrySendMessage
1571
+ })) : React.createElement(ChatLeftItem, Object.assign({}, props)));
1572
+ };
1573
+
1574
+ var ChatList = function ChatList(_ref) {
1575
+ var _ref$messages = _ref.messages,
1576
+ messages = _ref$messages === void 0 ? [] : _ref$messages,
1577
+ onAddExamMessage = _ref.onAddExamMessage,
1578
+ onReply = _ref.onReply,
1579
+ onReTrySendMessage = _ref.onReTrySendMessage,
1580
+ listItemRef = _ref.listItemRef;
1581
+ var _useState = useState(),
1582
+ selectedReplyMessageId = _useState[0],
1583
+ setSelectedReplyMessageId = _useState[1];
1584
+ var selectedReplyItemRef = useRef(null);
1585
+ var handleToggleReply = function handleToggleReply(id) {
1586
+ setSelectedReplyMessageId(id === selectedReplyMessageId ? undefined : id);
1587
+ };
1588
+ useEffect(function () {
1589
+ selectedReplyMessageId && selectedReplyItemRef.current && selectedReplyItemRef.current.scrollIntoView({
1590
+ behavior: "smooth"
1591
+ });
1592
+ }, [selectedReplyMessageId, selectedReplyItemRef.current]);
1593
+ return React.createElement("ul", {
1594
+ ref: listItemRef,
1595
+ className: styles$1["list"] + " h-100 d-flex flex-column py-3 px-0 mb-0"
1596
+ }, React.createElement("li", {
1597
+ className: "flex-grow-1",
1598
+ key: "start-of-list"
1599
+ }), !(messages !== null && messages !== void 0 && messages.length) && React.createElement("li", {
1600
+ className: "text-muted text-center fst-italic fs-6"
1601
+ }, "No message"), !!(messages !== null && messages !== void 0 && messages.length) && messages.map(function (message) {
1602
+ return React.createElement(ChatItem, Object.assign({
1603
+ key: message.id
1604
+ }, message, {
1605
+ onAddExamMessage: onAddExamMessage,
1606
+ onReply: onReply,
1607
+ selectedReplyMessageId: selectedReplyMessageId,
1608
+ onToggleReply: handleToggleReply,
1609
+ selectedReplyItemRef: selectedReplyItemRef,
1610
+ onReTrySendMessage: onReTrySendMessage
1611
+ }));
1612
+ }));
1613
+ };
1614
+
1615
+ var InputChat = function InputChat(_ref) {
1616
+ var text = _ref.text,
1617
+ parentText = _ref.parentText,
1618
+ examTitle = _ref.examTitle,
1619
+ inputRef = _ref.inputRef,
1620
+ onChangeInput = _ref.onChangeInput,
1621
+ onSubmit = _ref.onSubmit,
1622
+ onClearReply = _ref.onClearReply;
1623
+ var handleSubmit = function handleSubmit() {
1624
+ if (!text.trim().length) return;
1625
+ onSubmit();
1626
+ };
1627
+ var handleInputChange = function handleInputChange(event) {
1628
+ onChangeInput(event.target.value);
1629
+ };
1630
+ var handleKeyPressEnter = function handleKeyPressEnter(e) {
1631
+ if (e.code === "Enter") handleSubmit();
1632
+ };
1633
+ var handleClearReply = function handleClearReply() {
1634
+ onClearReply === null || onClearReply === void 0 ? void 0 : onClearReply();
1635
+ };
1636
+ return React.createElement("div", {
1637
+ className: "bg-light rounded-3 p-2"
1638
+ }, React.createElement(Collapse, {
1639
+ isOpen: !!parentText || !!examTitle && !parentText
1640
+ }, !!parentText ? React.createElement("div", {
1641
+ className: "d-flex justify-content-between align-items-center"
1642
+ }, React.createElement("p", {
1643
+ className: "mb-3 " + styles$1["reply-text"]
1644
+ }, React.createElement("b", null, "Reply to:"), " " + parentText), !!onClearReply && React.createElement("span", {
1645
+ className: "pointer ms-3 mb-3 d-flex justify-content-center align-items-center",
1646
+ onClick: handleClearReply
1647
+ }, React.createElement(IoIosCloseCircle, null))) : React.createElement("div", {
1648
+ className: "d-flex justify-content-between align-items-center"
1649
+ }, React.createElement("p", {
1650
+ className: "mb-3 " + styles$1["reply-text"]
1651
+ }, React.createElement("b", null, "Reply to", examTitle ? " exam" : "", ": "), " " + examTitle), !!onClearReply && React.createElement("span", {
1652
+ className: "pointer ms-3 mb-3 d-flex justify-content-center align-items-center",
1653
+ onClick: handleClearReply
1654
+ }, React.createElement(IoIosCloseCircle, null)))), React.createElement(InputGroup, {
1655
+ className: "d-flex align-items"
1656
+ }, React.createElement(Input, {
1657
+ innerRef: inputRef,
1658
+ value: text,
1659
+ placeholder: "Enter something",
1660
+ onKeyUp: handleKeyPressEnter,
1661
+ className: "rounded-pill px-3",
1662
+ onChange: handleInputChange
1663
+ }), React.createElement("div", {
1664
+ className: "p-2 pointer d-flex align-items-center",
1665
+ onClick: handleSubmit
1666
+ }, React.createElement(IoMdSend, {
1667
+ className: "text-primary fs-4"
1668
+ }))));
1669
+ };
1670
+
1671
+ var ChatHeader = function ChatHeader(_ref) {
1672
+ var name = _ref.name,
1673
+ avatar = _ref.avatar,
1674
+ options = _ref.options,
1675
+ onChangeOption = _ref.onChangeOption;
1676
+ var wrapperRef = useRef(null);
1677
+ var actionRef = useRef(null);
1678
+ var handleChangeOption = function handleChangeOption(val) {
1679
+ onChangeOption === null || onChangeOption === void 0 ? void 0 : onChangeOption(val);
1680
+ };
1681
+ useEffect(function () {
1682
+ var handleClickOutside = function handleClickOutside(event) {
1683
+ if (wrapperRef.current && !wrapperRef.current.contains(event.target) && actionRef.current && !actionRef.current.contains(event.target)) ;
1684
+ };
1685
+ document.addEventListener("mousedown", handleClickOutside);
1686
+ return function () {
1687
+ document.removeEventListener("mousedown", handleClickOutside);
1688
+ };
1689
+ }, [wrapperRef, actionRef]);
1690
+ var selectOptions = useMemo(function () {
1691
+ return options === null || options === void 0 ? void 0 : options.map(function (i) {
1692
+ return {
1693
+ value: i.id,
1694
+ label: i.title + " (" + utcToLocalTime(i.startTime) + ")"
1695
+ };
1696
+ });
1697
+ }, [JSON.stringify(options)]);
1698
+ return React.createElement("div", {
1699
+ className: "d-flex bg-light rounded-3 p-3"
1700
+ }, React.createElement("div", null, React.createElement("img", {
1701
+ className: "rounded-circle " + styles$1["header__avatar"],
1702
+ src: avatar,
1703
+ alt: name
1704
+ })), React.createElement("div", {
1705
+ className: "flex-grow-1 px-3 d-flex align-items-center"
1706
+ }, React.createElement("p", {
1707
+ className: "mb-0 text-primary fw-medium"
1708
+ }, name)), React.createElement("div", {
1709
+ className: "d-flex align-items-center"
1710
+ }, selectOptions !== undefined && React.createElement("div", {
1711
+ className: styles$1["header__select"] + " mx-3"
1712
+ }, React.createElement(CustomSelect, {
1713
+ options: selectOptions,
1714
+ onChange: handleChangeOption,
1715
+ isClearable: true
1716
+ })), React.createElement("div", {
1717
+ className: "actions d-flex align-items-center"
1718
+ })));
1719
+ };
1720
+
1721
+ var ChatContainer = function ChatContainer(_ref) {
1722
+ var chatHeaderProps = _ref.chatHeaderProps,
1723
+ chatListProps = _ref.chatListProps,
1724
+ inputProps = _ref.inputProps,
1725
+ onRead = _ref.onRead;
1726
+ var onReply = chatListProps.onReply,
1727
+ onAddExamMessage = chatListProps.onAddExamMessage;
1728
+ var onChangeOption = chatHeaderProps.onChangeOption;
1729
+ var inputRef = useRef(null);
1730
+ var listRef = useRef(null);
1731
+ var listItemRef = useRef(null);
1732
+ var scrollRef = useRef();
1733
+ var focusRef = useRef();
1734
+ var addEventTimeout = useRef();
1735
+ var handleReply = function handleReply(id, content, examId) {
1736
+ var _inputRef$current;
1737
+ (_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 ? void 0 : _inputRef$current.focus();
1738
+ onReply === null || onReply === void 0 ? void 0 : onReply(id, content, examId);
1739
+ };
1740
+ var handleAddExamMessage = function handleAddExamMessage(examId, examTitle) {
1741
+ var _inputRef$current2;
1742
+ (_inputRef$current2 = inputRef.current) === null || _inputRef$current2 === void 0 ? void 0 : _inputRef$current2.focus();
1743
+ onAddExamMessage(examId, examTitle);
1744
+ };
1745
+ var handleChangeExamOption = function handleChangeExamOption(val) {
1746
+ var _inputRef$current3;
1747
+ if (!!(val !== null && val !== void 0 && val.value)) (_inputRef$current3 = inputRef.current) === null || _inputRef$current3 === void 0 ? void 0 : _inputRef$current3.focus();
1748
+ onChangeOption === null || onChangeOption === void 0 ? void 0 : onChangeOption(val);
1749
+ };
1750
+ var handleScroll = function handleScroll() {
1751
+ if (scrollRef.current) clearTimeout(scrollRef.current);
1752
+ scrollRef.current = setTimeout(function () {
1753
+ onRead === null || onRead === void 0 ? void 0 : onRead();
1754
+ }, 800);
1755
+ };
1756
+ var handleFocus = function handleFocus() {
1757
+ if (focusRef.current) clearTimeout(focusRef.current);
1758
+ focusRef.current = setTimeout(function () {
1759
+ onRead === null || onRead === void 0 ? void 0 : onRead();
1760
+ }, 800);
1761
+ };
1762
+ useEffect(function () {
1763
+ var _listRef$current, _listItemRef$current, _listItemRef$current$;
1764
+ scrollRef.current && clearTimeout(scrollRef.current);
1765
+ addEventTimeout.current && clearTimeout(addEventTimeout.current);
1766
+ (_listRef$current = listRef.current) === null || _listRef$current === void 0 ? void 0 : _listRef$current.removeEventListener("scroll", handleScroll);
1767
+ (_listItemRef$current = listItemRef.current) === null || _listItemRef$current === void 0 ? void 0 : (_listItemRef$current$ = _listItemRef$current.lastElementChild) === null || _listItemRef$current$ === void 0 ? void 0 : _listItemRef$current$.scrollIntoView({
1768
+ behavior: "smooth"
1769
+ });
1770
+ addEventTimeout.current = setTimeout(function () {
1771
+ var _listRef$current2;
1772
+ (_listRef$current2 = listRef.current) === null || _listRef$current2 === void 0 ? void 0 : _listRef$current2.addEventListener("scroll", handleScroll);
1773
+ }, 800);
1774
+ return function () {
1775
+ var _listRef$current3;
1776
+ (_listRef$current3 = listRef.current) === null || _listRef$current3 === void 0 ? void 0 : _listRef$current3.removeEventListener("scroll", handleScroll);
1777
+ scrollRef.current && clearTimeout(scrollRef.current);
1778
+ addEventTimeout.current && clearTimeout(addEventTimeout.current);
1779
+ };
1780
+ }, [listItemRef.current, JSON.stringify(chatListProps.messages)]);
1781
+ useEffect(function () {
1782
+ var _inputRef$current4;
1783
+ (_inputRef$current4 = inputRef.current) === null || _inputRef$current4 === void 0 ? void 0 : _inputRef$current4.addEventListener("focus", handleFocus);
1784
+ return function () {
1785
+ var _inputRef$current5;
1786
+ (_inputRef$current5 = inputRef.current) === null || _inputRef$current5 === void 0 ? void 0 : _inputRef$current5.removeEventListener("focus", handleFocus);
1787
+ if (focusRef.current) clearTimeout(focusRef.current);
1788
+ };
1789
+ }, []);
1790
+ return React.createElement("div", {
1791
+ className: "d-flex flex-column w-100 h-100 border border-1 border-light rounded-3 shadow-sm"
1792
+ }, React.createElement("div", null, React.createElement(ChatHeader, Object.assign({}, chatHeaderProps, {
1793
+ onChangeOption: handleChangeExamOption
1794
+ }))), React.createElement("div", {
1795
+ ref: listRef,
1796
+ className: "flex-grow-1 " + styles$1["body"]
1797
+ }, React.createElement(ChatList, Object.assign({}, chatListProps, {
1798
+ listItemRef: listItemRef,
1799
+ onReply: handleReply,
1800
+ onAddExamMessage: handleAddExamMessage
1801
+ }))), React.createElement("div", null, React.createElement(InputChat, Object.assign({}, inputProps, {
1802
+ inputRef: inputRef
1803
+ }))), React.createElement(ToastContainer, null));
1804
+ };
1805
+
1806
+ var CONVERSATION_URL = BASE_URL + "/api/conversation";
1807
+ var getListConversation = function getListConversation(query) {
1808
+ return api.get("" + CONVERSATION_URL, {
1809
+ params: query
1810
+ });
1811
+ };
1812
+ var createConversation = function createConversation(studentId) {
1813
+ return api.post("" + CONVERSATION_URL, {
1814
+ targetUserId: "" + studentId
1815
+ });
1816
+ };
1817
+ var apiAddMessage = function apiAddMessage(conversationId, message) {
1818
+ return api.post(CONVERSATION_URL + "/" + conversationId + "/messages", message);
1819
+ };
1820
+ var getMessagesByConversation = function getMessagesByConversation(conversationId, filter) {
1821
+ return api.get(CONVERSATION_URL + "/" + conversationId + "/messages", {
1822
+ params: filter
1823
+ });
1824
+ };
1825
+ var apiMarkReadMessage = function apiMarkReadMessage(conversationId, messageId) {
1826
+ return api.put(CONVERSATION_URL + "/" + conversationId + "/messages/" + messageId + "/mark-read");
1827
+ };
1828
+ var apiGetConversationByUserId = function apiGetConversationByUserId(userId) {
1829
+ return api.get(CONVERSATION_URL + "/users/" + userId);
1830
+ };
1831
+
1832
+ var ExamStatus;
1833
+ (function (ExamStatus) {
1834
+ ExamStatus["Default"] = "Default";
1835
+ ExamStatus["Pending"] = "Pending";
1836
+ ExamStatus["Inprogress"] = "Inprogress";
1837
+ ExamStatus["Completed"] = "Completed";
1838
+ })(ExamStatus || (ExamStatus = {}));
1839
+ var CONVERSATION_DEFAULT_FILTER = {
1840
+ currentPage: 1,
1841
+ pageSize: -1,
1842
+ textSearch: ""
1843
+ };
1844
+ var MESSAGE_DEFAULT_FILTER = {
1845
+ currentPage: 1,
1846
+ pageSize: -1,
1847
+ textSearch: "",
1848
+ sortColumnDirection: OrderBy.DESC,
1849
+ sortColumnName: MessageSortBy.CreatedAt
1850
+ };
1851
+
1852
+ var EXAM_URL = BASE_URL + "/api/exam";
1853
+ var getListExamApi = function getListExamApi(query) {
1854
+ return api.get(EXAM_URL + "/getList", {
1855
+ params: query
1856
+ });
1857
+ };
1858
+
1859
+ var useExamList = function useExamList(isStudent) {
1860
+ if (isStudent === void 0) {
1861
+ isStudent = true;
1862
+ }
1863
+ var _useState = useState(),
1864
+ exams = _useState[0],
1865
+ setExams = _useState[1];
1866
+ var getListExam = function getListExam(userId) {
1867
+ try {
1868
+ setExams([]);
1869
+ var _temp = _catch(function () {
1870
+ return Promise.resolve(getListExamApi({
1871
+ currentPage: 1,
1872
+ pageSize: -1,
1873
+ sortColumnDirection: "DESC",
1874
+ sortColumnName: "CreatedAt",
1875
+ statuses: [ExamStatus.Completed],
1876
+ studentId: !isStudent ? userId : undefined,
1877
+ teacherId: isStudent ? userId : undefined
1878
+ })).then(function (res) {
1879
+ var _res$data;
1880
+ var data = ((_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.items) || [];
1881
+ setExams(data);
1882
+ });
1883
+ }, function (error) {
1884
+ console.log({
1885
+ error: error
1886
+ });
1887
+ });
1888
+ return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0);
1889
+ } catch (e) {
1890
+ return Promise.reject(e);
1891
+ }
1892
+ };
1893
+ return {
1894
+ getListExam: getListExam,
1895
+ exams: exams
1896
+ };
1897
+ };
1898
+
1899
+ var useMessageList = function useMessageList(userId, getListExamOptions) {
1900
+ var _useState = useState([]),
1901
+ messages = _useState[0],
1902
+ setMessages = _useState[1];
1903
+ var _useState2 = useState(MESSAGE_DEFAULT_FILTER),
1904
+ messageFilter = _useState2[0],
1905
+ setMessageFilter = _useState2[1];
1906
+ var getMessageList = function getMessageList(conversationId, examId) {
1907
+ try {
1908
+ var filter = _extends({}, messageFilter, {
1909
+ examId: !examId ? messageFilter.examId : examId
1910
+ });
1911
+ return Promise.resolve(getMessagesByConversation(conversationId, filter)).then(function (res) {
1912
+ var _res$data$items;
1913
+ function _temp(_getListExamOptions) {
1914
+ _getListExamOptions;
1915
+ }
1916
+ setMessages(((_res$data$items = res.data.items) === null || _res$data$items === void 0 ? void 0 : _res$data$items.reverse()) || []);
1917
+ return getListExamOptions ? Promise.resolve(!!getListExamOptions && getListExamOptions(userId)).then(_temp) : _temp(!!getListExamOptions && getListExamOptions(userId));
1918
+ });
1919
+ } catch (e) {
1920
+ return Promise.reject(e);
1921
+ }
1922
+ };
1923
+ var handleMarkReadMessage = function handleMarkReadMessage(conversationId, messageId) {
1924
+ try {
1925
+ var _temp2 = _catch(function () {
1926
+ return Promise.resolve(apiMarkReadMessage(conversationId, messageId)).then(function () {});
1927
+ }, function (error) {
1928
+ console.log({
1929
+ error: error
1930
+ });
1931
+ });
1932
+ return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(function () {}) : void 0);
1933
+ } catch (e) {
1934
+ return Promise.reject(e);
1935
+ }
1936
+ };
1937
+ var resetMessages = function resetMessages() {
1938
+ setMessages([]);
1939
+ };
1940
+ var handleChangeMessageFilter = function handleChangeMessageFilter(filter) {
1941
+ setMessageFilter(_extends({}, messageFilter, filter));
1942
+ };
1943
+ var handleChangeExamId = function handleChangeExamId(value) {
1944
+ setMessageFilter(_extends({}, messageFilter, {
1945
+ examId: value === null || value === void 0 ? void 0 : value.value,
1946
+ currentPage: 1
1947
+ }));
1948
+ };
1949
+ return {
1950
+ messageFilter: messageFilter,
1951
+ messages: messages,
1952
+ getMessageList: getMessageList,
1953
+ setMessages: setMessages,
1954
+ resetMessages: resetMessages,
1955
+ handleChangeMessageFilter: handleChangeMessageFilter,
1956
+ handleChangeExamId: handleChangeExamId,
1957
+ handleMarkReadMessage: handleMarkReadMessage
1958
+ };
1959
+ };
1960
+
1961
+ var useChatContainer = function useChatContainer(props) {
1962
+ var _selectedConversation, _selectedConversation2, _selectedConversation3, _selectedConversation4, _selectedConversation5, _selectedConversation6;
1963
+ var conversation = props.conversation,
1964
+ userId = props.userId,
1965
+ examId = props.examId,
1966
+ onUpdateLastMessage = props.onUpdateLastMessage,
1967
+ onCreateConversationSuccess = props.onCreateConversationSuccess,
1968
+ onGetMessagesSuccess = props.onGetMessagesSuccess;
1969
+ var pusher = useRef();
1970
+ var channel = useRef();
1971
+ var channelName = useRef();
1972
+ var loadingRef = useRef(false);
1973
+ var dispatch = useDispatch();
1974
+ var roles = useSelector(function (state) {
1975
+ var _state$common, _state$common$user;
1976
+ return state === null || state === void 0 ? void 0 : (_state$common = state.common) === null || _state$common === void 0 ? void 0 : (_state$common$user = _state$common.user) === null || _state$common$user === void 0 ? void 0 : _state$common$user.roles;
1977
+ }) || [];
1978
+ var isStudent = roles.includes("Student");
1979
+ var _useState = useState(),
1980
+ selectedConversation = _useState[0],
1981
+ setSelectedConversation = _useState[1];
1982
+ var _useState2 = useState(),
1983
+ message = _useState2[0],
1984
+ setMessage = _useState2[1];
1985
+ var _useState3 = useState(MessageStatus.Default),
1986
+ messageStatus = _useState3[0],
1987
+ setMessageStatus = _useState3[1];
1988
+ var _useExamList = useExamList(isStudent),
1989
+ exams = _useExamList.exams,
1990
+ getListExam = _useExamList.getListExam;
1991
+ var _useMessageList = useMessageList(isStudent ? selectedConversation === null || selectedConversation === void 0 ? void 0 : (_selectedConversation = selectedConversation.teacher) === null || _selectedConversation === void 0 ? void 0 : _selectedConversation.id : selectedConversation === null || selectedConversation === void 0 ? void 0 : (_selectedConversation2 = selectedConversation.student) === null || _selectedConversation2 === void 0 ? void 0 : _selectedConversation2.id, !userId ? getListExam : undefined),
1992
+ messages = _useMessageList.messages,
1993
+ messageFilter = _useMessageList.messageFilter,
1994
+ getMessageList = _useMessageList.getMessageList,
1995
+ resetMessages = _useMessageList.resetMessages,
1996
+ handleChangeExamId = _useMessageList.handleChangeExamId,
1997
+ setMessages = _useMessageList.setMessages;
1998
+ var handleAddMessage = function handleAddMessage() {
1999
+ try {
2000
+ var _message$content, _message$content$trim;
2001
+ var _temp2 = function _temp2() {
2002
+ loadingRef.current = false;
2003
+ };
2004
+ if (loadingRef.current) return Promise.resolve();
2005
+ if (messages.some(function (i) {
2006
+ return i.id === 0;
2007
+ })) return Promise.resolve();
2008
+ loadingRef.current = true;
2009
+ if (!(selectedConversation !== null && selectedConversation !== void 0 && selectedConversation.id) || !(message !== null && message !== void 0 && (_message$content = message.content) !== null && _message$content !== void 0 && (_message$content$trim = _message$content.trim()) !== null && _message$content$trim !== void 0 && _message$content$trim.length)) return Promise.resolve();
2010
+ setMessages(function (state) {
2011
+ return [].concat(state, [{
2012
+ id: 0,
2013
+ isStudent: isStudent,
2014
+ content: message.content,
2015
+ examId: message.examId,
2016
+ parentId: message.parentId,
2017
+ parentContent: message.parentContent,
2018
+ exam: message.examId ? {
2019
+ id: message.examId,
2020
+ startTime: moment().format("YYYY-MM-DDTHH:mm:ss"),
2021
+ title: message.examTitle || "",
2022
+ code: "temp",
2023
+ createdAt: moment().format("YYYY-MM-DDTHH:mm:ss")
2024
+ } : undefined,
2025
+ isRead: false,
2026
+ createdAt: moment().format("YYYY-MM-DDTHH:mm:ss")
2027
+ }]);
2028
+ });
2029
+ setMessage(function (state) {
2030
+ if (!state) return undefined;
2031
+ return _extends({}, state, {
2032
+ content: "",
2033
+ parentId: undefined,
2034
+ parentContent: "",
2035
+ examId: messageFilter.examId,
2036
+ examTitle: messageFilter.examId ? message.examTitle : ""
2037
+ });
2038
+ });
2039
+ setMessageStatus(MessageStatus.Sending);
2040
+ var _temp = _catch(function () {
2041
+ return Promise.resolve(apiAddMessage(selectedConversation.id, _extends({}, message, {
2042
+ examId: !!userId ? examId : message.examId
2043
+ }))).then(function () {});
2044
+ }, function (error) {
2045
+ var _error$response;
2046
+ console.log({
2047
+ error: error
2048
+ });
2049
+ setMessageStatus(MessageStatus.SentError);
2050
+ setMessages(function (state) {
2051
+ return [].concat(state.filter(function (i) {
2052
+ return i.id !== 0;
2053
+ }));
2054
+ });
2055
+ toast.error((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.data);
2056
+ });
2057
+ return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
2058
+ } catch (e) {
2059
+ return Promise.reject(e);
2060
+ }
2061
+ };
2062
+ var handleAddExamMessage = function handleAddExamMessage(examId, title) {
2063
+ setMessage(!!message ? _extends({}, message, {
2064
+ examId: examId,
2065
+ examTitle: title,
2066
+ parentId: undefined,
2067
+ parentContent: ""
2068
+ }) : {
2069
+ examId: examId,
2070
+ content: "",
2071
+ examTitle: title,
2072
+ parentId: undefined,
2073
+ parentContent: ""
2074
+ });
2075
+ };
2076
+ var handleReplyMessage = function handleReplyMessage(parentId, content, examId) {
2077
+ setMessage({
2078
+ content: "",
2079
+ examId: examId,
2080
+ parentId: parentId,
2081
+ parentContent: content,
2082
+ examTitle: message === null || message === void 0 ? void 0 : message.examTitle
2083
+ });
2084
+ };
2085
+ var handleClearReply = function handleClearReply() {
2086
+ message && setMessage(_extends({}, message, {
2087
+ parentId: undefined,
2088
+ examId: messageFilter.examId ? messageFilter.examId : undefined,
2089
+ parentContent: "",
2090
+ examTitle: messageFilter.examId ? message.examTitle : ""
2091
+ }));
2092
+ };
2093
+ var handleChangeInput = function handleChangeInput(text) {
2094
+ setMessage(_extends({}, message, {
2095
+ content: text
2096
+ }));
2097
+ };
2098
+ var handleFilterExam = function handleFilterExam(val) {
2099
+ var _val$label, _val$label$split;
2100
+ var examTitle = val === null || val === void 0 ? void 0 : (_val$label = val.label) === null || _val$label === void 0 ? void 0 : (_val$label$split = _val$label.split(" ")) === null || _val$label$split === void 0 ? void 0 : _val$label$split.slice(0, -1).join(" ");
2101
+ setMessage({
2102
+ examId: val === null || val === void 0 ? void 0 : val.value,
2103
+ content: "",
2104
+ examTitle: examTitle,
2105
+ parentId: undefined,
2106
+ parentContent: ""
2107
+ });
2108
+ handleChangeExamId(val);
2109
+ };
2110
+ var messageList = useMemo(function () {
2111
+ if (!selectedConversation) return [];
2112
+ var examCode = undefined;
2113
+ var results = messages.map(function (i, index) {
2114
+ var _i$exam, _i$exam4, _i$exam5, _i$exam6, _i$exam7, _i$exam8, _i$exam9, _i$exam10, _i$exam11;
2115
+ var isFirst = index === 0;
2116
+ var isLast = index === messages.length - 1;
2117
+ if (index > 0 && (messages[index - 1].isStudent !== i.isStudent && !i.isSystemLog || i.isSystemLog || messages[index - 1].examId !== i.examId)) isFirst = true;
2118
+ if (index < messages.length - 1 && (messages[index + 1].isStudent !== i.isStudent && i.examId !== messages[index + 1].examId || i.examId !== messages[index + 1].examId || messages[index + 1].isSystemLog)) isLast = true;
2119
+ var name = isStudent ? "You" : selectedConversation.student.displayName;
2120
+ var content = i === null || i === void 0 ? void 0 : i.content;
2121
+ var showExamHeader = false;
2122
+ if (examCode != ((_i$exam = i.exam) === null || _i$exam === void 0 ? void 0 : _i$exam.code) && !messageFilter.examId && !userId) {
2123
+ var _i$exam2, _i$exam3;
2124
+ if ((_i$exam2 = i.exam) !== null && _i$exam2 !== void 0 && _i$exam2.code) showExamHeader = true;
2125
+ examCode = (_i$exam3 = i.exam) === null || _i$exam3 === void 0 ? void 0 : _i$exam3.code;
2126
+ }
2127
+ switch (i.type) {
2128
+ case MessageSourceType.Exam:
2129
+ switch (i.action) {
2130
+ case MessageAction.Took:
2131
+ content = name + " took the exam " + ((_i$exam4 = i.exam) === null || _i$exam4 === void 0 ? void 0 : _i$exam4.title);
2132
+ break;
2133
+ }
2134
+ break;
2135
+ }
2136
+ return {
2137
+ id: i.id,
2138
+ isMe: isStudent === i.isStudent,
2139
+ avatar: isStudent ? selectedConversation.teacher.avatar : selectedConversation.student.avatar,
2140
+ name: selectedConversation.student.displayName,
2141
+ isRead: i.isRead,
2142
+ createdAt: i.createdAt,
2143
+ content: content,
2144
+ isFirst: isFirst,
2145
+ isLast: isLast,
2146
+ isSystemLog: i.isSystemLog,
2147
+ examCode: !messageFilter.examId && !userId ? (_i$exam5 = i.exam) === null || _i$exam5 === void 0 ? void 0 : _i$exam5.code : undefined,
2148
+ examId: (_i$exam6 = i.exam) === null || _i$exam6 === void 0 ? void 0 : _i$exam6.id,
2149
+ examTitle: (_i$exam7 = i.exam) === null || _i$exam7 === void 0 ? void 0 : _i$exam7.title,
2150
+ type: (_i$exam8 = i.exam) !== null && _i$exam8 !== void 0 && _i$exam8.code ? ChatItemType.Exam : undefined,
2151
+ showExamHeader: showExamHeader,
2152
+ actionLink: ((_i$exam9 = i.exam) === null || _i$exam9 === void 0 ? void 0 : _i$exam9.code) && (isStudent ? "/student/check/live-result?examCode=" + ((_i$exam10 = i.exam) === null || _i$exam10 === void 0 ? void 0 : _i$exam10.code) : "/teacher/exam-status/main?examCode=" + ((_i$exam11 = i.exam) === null || _i$exam11 === void 0 ? void 0 : _i$exam11.code)),
2153
+ parentId: i.parentId,
2154
+ parentContent: i.parentContent,
2155
+ status: i.id ? MessageStatus.Default : messageStatus
2156
+ };
2157
+ });
2158
+ return results;
2159
+ }, [JSON.stringify(messages), JSON.stringify(message), isStudent, JSON.stringify(selectedConversation), messageFilter.examId, isStudent, userId, messageStatus]);
2160
+ var handleNewMessageSent = function handleNewMessageSent(data) {
2161
+ if (!messageFilter.examId || messageFilter.examId && data.examId === messageFilter.examId) {
2162
+ setMessages(function (state) {
2163
+ if (state.some(function (i) {
2164
+ return i.id === 0;
2165
+ })) return [].concat(state.filter(function (i) {
2166
+ return i.id !== 0;
2167
+ }), [data]);else return [].concat(state, [data]);
2168
+ });
2169
+ }
2170
+ onUpdateLastMessage === null || onUpdateLastMessage === void 0 ? void 0 : onUpdateLastMessage(data);
2171
+ };
2172
+ var handleMessageMarkRead = function handleMessageMarkRead(data) {
2173
+ setMessages(function (state) {
2174
+ return [].concat(state.map(function (i) {
2175
+ return _extends({}, i, {
2176
+ isRead: data.includes(i.id || 0) ? true : i.isRead
2177
+ });
2178
+ }));
2179
+ });
2180
+ };
2181
+ var cleanupPusher = function cleanupPusher() {
2182
+ var _pusher$current, _pusher$current2;
2183
+ (_pusher$current = pusher.current) === null || _pusher$current === void 0 ? void 0 : _pusher$current.unbind("new-message-event", handleNewMessageSent);
2184
+ (_pusher$current2 = pusher.current) === null || _pusher$current2 === void 0 ? void 0 : _pusher$current2.unbind("message-read-event", handleMessageMarkRead);
2185
+ channelName.current && pusher.current && pusher.current.unsubscribe(channelName.current);
2186
+ };
2187
+ useEffect(function () {
2188
+ if (PUSHER_CONFIG.cluster && PUSHER_CONFIG.key && !!(selectedConversation !== null && selectedConversation !== void 0 && selectedConversation.id)) {
2189
+ var token = getAccessToken();
2190
+ pusher.current = new Pusher(PUSHER_CONFIG.key, {
2191
+ cluster: PUSHER_CONFIG.cluster,
2192
+ authEndpoint: BASE_URL + "/api/auth/pusher",
2193
+ auth: {
2194
+ params: {},
2195
+ headers: {
2196
+ Authorization: "Bearer " + token
2197
+ }
2198
+ }
2199
+ });
2200
+ channelName.current = "presence-conversation-channel-" + (selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.id);
2201
+ channel.current = pusher.current.subscribe(channelName.current);
2202
+ pusher.current.bind("new-message-event", handleNewMessageSent);
2203
+ pusher.current.bind("message-read-event", handleMessageMarkRead);
2204
+ }
2205
+ return cleanupPusher;
2206
+ }, [selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.id, messageFilter.examId]);
2207
+ useEffect(function () {
2208
+ var getConversation = function getConversation() {
2209
+ try {
2210
+ var _temp6 = function _temp6() {
2211
+ dispatch(setLoading(false));
2212
+ };
2213
+ if ((conversation === null || conversation === void 0 ? void 0 : conversation.id) !== undefined) {
2214
+ setSelectedConversation(conversation);
2215
+ return Promise.resolve();
2216
+ }
2217
+ if (!userId) return Promise.resolve();
2218
+ dispatch(setLoading(true));
2219
+ var _temp5 = _catch(function () {
2220
+ return Promise.resolve(apiGetConversationByUserId(userId)).then(function (res) {
2221
+ function _temp4() {
2222
+ setSelectedConversation(res.data.data);
2223
+ }
2224
+ var _temp3 = function () {
2225
+ if (!res.data.data) {
2226
+ return Promise.resolve(createConversation(userId)).then(function (_createConversation) {
2227
+ res = _createConversation;
2228
+ });
2229
+ }
2230
+ }();
2231
+ return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3);
2232
+ });
2233
+ }, function (error) {
2234
+ console.log({
2235
+ error: error
2236
+ });
2237
+ });
2238
+ return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
2239
+ } catch (e) {
2240
+ return Promise.reject(e);
2241
+ }
2242
+ };
2243
+ getConversation();
2244
+ }, [conversation === null || conversation === void 0 ? void 0 : conversation.id, userId]);
2245
+ var handleMarkRead = function handleMarkRead() {
2246
+ try {
2247
+ if (!(selectedConversation !== null && selectedConversation !== void 0 && selectedConversation.id)) return Promise.resolve();
2248
+ var _temp7 = _catch(function () {
2249
+ return Promise.resolve(apiMarkReadMessage(selectedConversation.id, -1)).then(function () {});
2250
+ }, function (error) {
2251
+ console.log({
2252
+ error: error
2253
+ });
2254
+ });
2255
+ return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () {}) : void 0);
2256
+ } catch (e) {
2257
+ return Promise.reject(e);
2258
+ }
2259
+ };
2260
+ var getMessageConversation = function getMessageConversation() {
2261
+ try {
2262
+ var _temp12 = function _temp12() {
2263
+ dispatch(setLoading(false));
2264
+ };
2265
+ if (!roles.length) return Promise.resolve();
2266
+ if ((selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.id) === undefined) return Promise.resolve();
2267
+ if (messageFilter.currentPage === 1) resetMessages();
2268
+ dispatch(setLoading(true));
2269
+ var _temp11 = _catch(function () {
2270
+ var _temp10 = function () {
2271
+ if (selectedConversation.id === 0) {
2272
+ var _userId = isStudent ? selectedConversation.teacher.id : selectedConversation.student.id;
2273
+ return Promise.resolve(createConversation(_userId)).then(function (res) {
2274
+ var _res$data$data;
2275
+ return Promise.resolve(onCreateConversationSuccess === null || onCreateConversationSuccess === void 0 ? void 0 : onCreateConversationSuccess((_res$data$data = res.data.data) === null || _res$data$data === void 0 ? void 0 : _res$data$data.id)).then(function () {});
2276
+ });
2277
+ } else {
2278
+ var _temp9 = function _temp9() {
2279
+ return Promise.resolve(getMessageList(selectedConversation.id, examId)).then(function () {
2280
+ onGetMessagesSuccess === null || onGetMessagesSuccess === void 0 ? void 0 : onGetMessagesSuccess();
2281
+ });
2282
+ };
2283
+ var _temp8 = function () {
2284
+ if (messageFilter.currentPage === 1) return Promise.resolve(handleMarkRead()).then(function () {});
2285
+ }();
2286
+ return _temp8 && _temp8.then ? _temp8.then(_temp9) : _temp9(_temp8);
2287
+ }
2288
+ }();
2289
+ if (_temp10 && _temp10.then) return _temp10.then(function () {});
2290
+ }, function () {
2291
+ toast.error("Fail to fetch data!");
2292
+ });
2293
+ return Promise.resolve(_temp11 && _temp11.then ? _temp11.then(_temp12) : _temp12(_temp11));
2294
+ } catch (e) {
2295
+ return Promise.reject(e);
2296
+ }
2297
+ };
2298
+ useEffect(function () {
2299
+ getMessageConversation();
2300
+ }, [selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.id, selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.teacher.id, selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.student.id, isStudent, roles.length, JSON.stringify(messageFilter), examId]);
2301
+ var userName = isStudent ? selectedConversation === null || selectedConversation === void 0 ? void 0 : (_selectedConversation3 = selectedConversation.teacher) === null || _selectedConversation3 === void 0 ? void 0 : _selectedConversation3.displayName : selectedConversation === null || selectedConversation === void 0 ? void 0 : (_selectedConversation4 = selectedConversation.student) === null || _selectedConversation4 === void 0 ? void 0 : _selectedConversation4.displayName;
2302
+ var userAvatar = isStudent ? selectedConversation === null || selectedConversation === void 0 ? void 0 : (_selectedConversation5 = selectedConversation.teacher) === null || _selectedConversation5 === void 0 ? void 0 : _selectedConversation5.avatar : selectedConversation === null || selectedConversation === void 0 ? void 0 : (_selectedConversation6 = selectedConversation.student) === null || _selectedConversation6 === void 0 ? void 0 : _selectedConversation6.avatar;
2303
+ return {
2304
+ chatHeaderProps: {
2305
+ name: userName || "",
2306
+ avatar: userAvatar || "",
2307
+ options: exams,
2308
+ onChangeOption: handleFilterExam
2309
+ },
2310
+ chatListProps: {
2311
+ messages: messageList,
2312
+ onAddExamMessage: handleAddExamMessage,
2313
+ onReply: handleReplyMessage,
2314
+ onReTrySendMessage: handleAddMessage
2315
+ },
2316
+ inputProps: {
2317
+ text: (message === null || message === void 0 ? void 0 : message.content) || "",
2318
+ parentText: message === null || message === void 0 ? void 0 : message.parentContent,
2319
+ examTitle: message === null || message === void 0 ? void 0 : message.examTitle,
2320
+ onChangeInput: handleChangeInput,
2321
+ onSubmit: handleAddMessage,
2322
+ onClearReply: !messageFilter.examId || message !== null && message !== void 0 && message.parentContent ? handleClearReply : undefined
2323
+ },
2324
+ exams: exams,
2325
+ messageList: messageList,
2326
+ selectedConversation: selectedConversation,
2327
+ messageStatus: messageStatus,
2328
+ messageFilter: messageFilter,
2329
+ getMessageList: getMessageList,
2330
+ handleFilterExam: handleFilterExam,
2331
+ setMessage: setMessage,
2332
+ resetMessages: resetMessages,
2333
+ getMessageConversation: getMessageConversation,
2334
+ handleMarkRead: handleMarkRead
2335
+ };
2336
+ };
2337
+
2338
+ var STUDENT_STATUS_URL = BASE_URL + "/api/user";
2339
+ var getStudentConversationListApi = function getStudentConversationListApi(query) {
2340
+ return api.get(STUDENT_STATUS_URL + "/GetStudentConversations", {
2341
+ params: query
2342
+ });
2343
+ };
2344
+
2345
+ var isFirstLoad = true;
2346
+ var useConversationList = function useConversationList() {
2347
+ var dispatch = useDispatch();
2348
+ var user = useSelector(function (state) {
2349
+ var _state$common;
2350
+ return state === null || state === void 0 ? void 0 : (_state$common = state.common) === null || _state$common === void 0 ? void 0 : _state$common.user;
2351
+ });
2352
+ var roles = (user === null || user === void 0 ? void 0 : user.roles) || [];
2353
+ var isStudent = roles.includes("Student");
2354
+ var _useState = useState(),
2355
+ selectedConversation = _useState[0],
2356
+ setSelectedConversation = _useState[1];
2357
+ var _useState2 = useState([]),
2358
+ conversations = _useState2[0],
2359
+ setConversations = _useState2[1];
2360
+ var _useState3 = useState(CONVERSATION_DEFAULT_FILTER),
2361
+ conversationFilter = _useState3[0],
2362
+ setConversationFilter = _useState3[1];
2363
+ var handleChangeSelectedConversation = function handleChangeSelectedConversation(val) {
2364
+ setSelectedConversation(val);
2365
+ };
2366
+ var handleNewMessageConversation = function handleNewMessageConversation(val) {
2367
+ setConversations(function (state) {
2368
+ var index = state.findIndex(function (i) {
2369
+ return i.id === val.id;
2370
+ });
2371
+ if (index > -1 && JSON.stringify(val) !== JSON.stringify(state[index])) {
2372
+ return [].concat(state.slice(0, index), [val], state.slice(index + 1));
2373
+ } else return [].concat(state, [val]);
2374
+ });
2375
+ setSelectedConversation(function (state) {
2376
+ if (!state) return val;
2377
+ return state;
2378
+ });
2379
+ };
2380
+ var handleMessageReadConversation = function handleMessageReadConversation(id, totalUnread) {
2381
+ setConversations(function (state) {
2382
+ var index = state.findIndex(function (i) {
2383
+ return i.id === id;
2384
+ });
2385
+ if (index === -1 || totalUnread === state[index].totalUnReadMessage) return state;
2386
+ return [].concat(state.slice(0, index), [_extends({}, state[index], {
2387
+ totalUnReadMessage: totalUnread
2388
+ })], state.slice(index + 1));
2389
+ });
2390
+ setSelectedConversation(function (state) {
2391
+ if (!!state) return _extends({}, state, {
2392
+ totalUnReadMessage: totalUnread
2393
+ });
2394
+ return state;
2395
+ });
2396
+ };
2397
+ var handleChangeTextSearch = function handleChangeTextSearch(e) {
2398
+ setConversationFilter(function (state) {
2399
+ return _extends({}, state, {
2400
+ textSearch: e.target.value
2401
+ });
2402
+ });
2403
+ };
2404
+ var handleChangeFilter = function handleChangeFilter(filter) {
2405
+ setConversationFilter(function (state) {
2406
+ return _extends({}, state, filter);
2407
+ });
2408
+ };
2409
+ var formatConversationLastMessageContent = function formatConversationLastMessageContent(conversation) {
2410
+ var _conversation$lastMes;
2411
+ if (!(conversation !== null && conversation !== void 0 && conversation.lastMessage)) return "";
2412
+ var content = conversation.lastMessage.content;
2413
+ switch (conversation.lastMessage.type) {
2414
+ case MessageSourceType.Exam:
2415
+ switch (conversation.lastMessage.action) {
2416
+ case MessageAction.Took:
2417
+ content = (isStudent ? "You" : conversation.student.displayName) + " took the exam " + ((_conversation$lastMes = conversation.lastMessage.exam) === null || _conversation$lastMes === void 0 ? void 0 : _conversation$lastMes.title);
2418
+ break;
2419
+ }
2420
+ break;
2421
+ }
2422
+ return content;
2423
+ };
2424
+ var getConversationList = function getConversationList() {
2425
+ try {
2426
+ var _temp2 = function _temp2() {
2427
+ isFirstLoad && dispatch(setLoading(false));
2428
+ if (isFirstLoad) isFirstLoad = false;
2429
+ };
2430
+ if (!roles.length) return Promise.resolve();
2431
+ isFirstLoad && dispatch(setLoading(true));
2432
+ var _temp = _catch(function () {
2433
+ var apiGetConversations = isStudent ? getListConversation : getStudentConversationListApi;
2434
+ return Promise.resolve(apiGetConversations(conversationFilter)).then(function (res) {
2435
+ var _res$data$items;
2436
+ setConversations(res.data.items || []);
2437
+ !selectedConversation && setSelectedConversation((_res$data$items = res.data.items) === null || _res$data$items === void 0 ? void 0 : _res$data$items[0]);
2438
+ });
2439
+ }, function () {
2440
+ setSelectedConversation(undefined);
2441
+ dispatch(setAlert({
2442
+ type: "danger",
2443
+ message: "Fail to fetch data!"
2444
+ }));
2445
+ });
2446
+ return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
2447
+ } catch (e) {
2448
+ return Promise.reject(e);
2449
+ }
2450
+ };
2451
+ var handleUpdateTotalUnreadMessage = function handleUpdateTotalUnreadMessage() {
2452
+ if (!(selectedConversation !== null && selectedConversation !== void 0 && selectedConversation.id)) return;
2453
+ setConversations(function (state) {
2454
+ var updateIndex = state.findIndex(function (i) {
2455
+ return i.id === selectedConversation.id;
2456
+ });
2457
+ if (updateIndex < 0) return state;
2458
+ return [].concat(state.slice(0, updateIndex), [_extends({}, state[updateIndex], {
2459
+ totalUnReadMessage: 0
2460
+ })], state.slice(updateIndex + 1));
2461
+ });
2462
+ };
2463
+ var handleUpdateLastMessage = function handleUpdateLastMessage(lastMessage) {
2464
+ setConversations(function (state) {
2465
+ var updateIndex = state.findIndex(function (i) {
2466
+ return i.id === lastMessage.conversationId;
2467
+ });
2468
+ if (updateIndex < 0) return state;
2469
+ return [].concat(state.slice(0, updateIndex), [_extends({}, state[updateIndex], {
2470
+ lastMessage: lastMessage
2471
+ })], state.slice(updateIndex + 1));
2472
+ });
2473
+ };
2474
+ var handleCreateConversationSuccess = function handleCreateConversationSuccess(id) {
2475
+ try {
2476
+ if (!selectedConversation) return Promise.resolve();
2477
+ setSelectedConversation(_extends({}, selectedConversation, {
2478
+ id: id
2479
+ }));
2480
+ var index = conversations.findIndex(function (i) {
2481
+ return i.student.id === (selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.student.id) && i.teacher.id === (selectedConversation === null || selectedConversation === void 0 ? void 0 : selectedConversation.teacher.id);
2482
+ });
2483
+ if (index > -1) {
2484
+ setConversations([].concat(conversations.slice(0, index), [_extends({}, selectedConversation, {
2485
+ id: id
2486
+ })], conversations.slice(index + 1)));
2487
+ }
2488
+ return Promise.resolve();
2489
+ } catch (e) {
2490
+ return Promise.reject(e);
2491
+ }
2492
+ };
2493
+ useEffect(function () {
2494
+ getConversationList();
2495
+ }, [JSON.stringify(conversationFilter), roles.length]);
2496
+ useEffect(function () {
2497
+ window.document.title = "Q&A";
2498
+ }, []);
2499
+ return {
2500
+ isStudent: isStudent,
2501
+ conversationFilter: conversationFilter,
2502
+ selectedConversation: selectedConversation,
2503
+ conversations: conversations,
2504
+ handleUpdateTotalUnreadMessage: handleUpdateTotalUnreadMessage,
2505
+ handleChangeFilter: handleChangeFilter,
2506
+ handleChangeSelectedConversation: handleChangeSelectedConversation,
2507
+ handleChangeTextSearch: handleChangeTextSearch,
2508
+ setSelectedConversation: setSelectedConversation,
2509
+ handleUpdateLastMessage: handleUpdateLastMessage,
2510
+ getConversationList: getConversationList,
2511
+ formatConversationLastMessageContent: formatConversationLastMessageContent,
2512
+ handleNewMessageConversation: handleNewMessageConversation,
2513
+ handleCreateConversationSuccess: handleCreateConversationSuccess,
2514
+ handleMessageReadConversation: handleMessageReadConversation
2515
+ };
2516
+ };
2517
+
2518
+ var usePusherConversation = function usePusherConversation(onNewMessageConversation, onReadMessageConversation) {
2519
+ var pusher = useRef();
2520
+ var channel = useRef();
2521
+ var channelName = useRef();
2522
+ var userId = useSelector(function (state) {
2523
+ var _state$common, _state$common$user;
2524
+ return state === null || state === void 0 ? void 0 : (_state$common = state.common) === null || _state$common === void 0 ? void 0 : (_state$common$user = _state$common.user) === null || _state$common$user === void 0 ? void 0 : _state$common$user.id;
2525
+ });
2526
+ var handleNewMessageConversationCreated = function handleNewMessageConversationCreated(data) {
2527
+ onNewMessageConversation === null || onNewMessageConversation === void 0 ? void 0 : onNewMessageConversation(data);
2528
+ };
2529
+ var handleReadMessageConversation = function handleReadMessageConversation(data) {
2530
+ onReadMessageConversation === null || onReadMessageConversation === void 0 ? void 0 : onReadMessageConversation(data.id, data.totalUnReadMessage);
2531
+ };
2532
+ var cleanupPusher = function cleanupPusher() {
2533
+ channel.current && channel.current.unbind("message-conversation-event", handleNewMessageConversationCreated);
2534
+ channel.current && channel.current.unbind("message-conversation-read-event", handleReadMessageConversation);
2535
+ channelName.current && pusher.current && pusher.current.unsubscribe(channelName.current);
2536
+ };
2537
+ useEffect(function () {
2538
+ if (PUSHER_CONFIG.cluster && PUSHER_CONFIG.key && !!userId) {
2539
+ var token = getAccessToken$1();
2540
+ pusher.current = new Pusher(PUSHER_CONFIG.key, {
2541
+ cluster: PUSHER_CONFIG.cluster,
2542
+ authEndpoint: BASE_URL + "/api/auth/pusher",
2543
+ auth: {
2544
+ params: {},
2545
+ headers: {
2546
+ Authorization: "Bearer " + token
2547
+ }
2548
+ }
2549
+ });
2550
+ channelName.current = "presence-conversation-channel-userId-" + userId;
2551
+ channel.current = pusher.current.subscribe(channelName.current);
2552
+ channel.current.bind("message-conversation-event", handleNewMessageConversationCreated);
2553
+ channel.current.bind("message-conversation-read-event", handleReadMessageConversation);
2554
+ }
2555
+ return cleanupPusher;
2556
+ }, [userId]);
2557
+ return {};
2558
+ };
2559
+
1341
2560
  var historyCore = createBrowserHistory();
1342
2561
 
1343
- export { ACCESS_TOKEN, BASE_URL, CommonAlert, CommonDialog, ConfirmDialog, CustomPagination, DATE_MIN_VALUE, EXAM_CHANNEL, ExamEvent, LayoutContext, Loading, Login, NotFound, PUSHER_CONFIG, TheLanguageDropdown, api$1 as api, canAccess as canAccessRoute, diffFromNow, formatTime, historyCore, i18n, minutesToTimeSpan, setAlert, setLanguage, setLoading, setUser, store, toISOString, useGoogleSignOut, utcToLocalTime };
2562
+ export { ACCESS_TOKEN, BASE_URL, ChatContainer, ChatItemType, CommonAlert, CommonDialog, ConfirmDialog, CustomPagination, CustomSelect, DATE_MIN_VALUE, EXAM_CHANNEL, EXAM_STUDENT_CHANNEL, ExamEvent, LayoutContext, Loading, Login, NotFound, PUSHER_CONFIG, TheLanguageDropdown, api, canAccess as canAccessRoute, diffFromNow, formatTime, getAccessToken$1 as getAccessToken, historyCore, i18n, minutesToTimeSpan, setAlert, setLanguage, setLoading, setUser, store, toISOString, useChatContainer, useConversationList, useGoogleSignOut, usePusherConversation, utcToLocalTime };
1344
2563
  //# sourceMappingURL=index.modern.js.map