chore: Replace eventBus with mitt.js [CW-3275] (#9539)

# Replace the deprecated `eventBus` with mitt.js

## Description

Since eventBus and it's respective methods are deprecated and removed
from all future releases of vue, this was blocking us from migrating.
This PR replaces eventBus with
[mitt](https://github.com/developit/mitt). I have created a wrapper
mitt.js to simulate the same old event names so it's backwards
compatible, without making a lot of changes.


Fixes # (issue)

## Type of change

Please delete options that are not relevant.

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality not to work as expected)
- [ ] This change requires a documentation update

## How Has This Been Tested?

1. Made sure all the places we're listening to bus events are working as
expected.
2. Respective specsf or the events from mitt.


## Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [x] I have commented on my code, particularly in hard-to-understand
areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] Any dependent changes have been merged and published in downstream
modules
This commit is contained in:
Fayaz Ahmed
2024-05-31 15:50:36 +05:30
committed by GitHub
parent e3eca47c31
commit b474929f5e
60 changed files with 276 additions and 161 deletions

View File

@@ -514,14 +514,14 @@ export default {
this.$store.dispatch('campaigns/get'); this.$store.dispatch('campaigns/get');
} }
bus.$on('fetch_conversation_stats', () => { this.$emitter.on('fetch_conversation_stats', () => {
this.$store.dispatch('conversationStats/get', this.conversationFilters); this.$store.dispatch('conversationStats/get', this.conversationFilters);
}); });
bus.$on(CMD_SNOOZE_CONVERSATION, this.onCmdSnoozeConversation); this.$emitter.on(CMD_SNOOZE_CONVERSATION, this.onCmdSnoozeConversation);
}, },
beforeDestroy() { beforeDestroy() {
bus.$off(CMD_SNOOZE_CONVERSATION, this.onCmdSnoozeConversation); this.$emitter.off(CMD_SNOOZE_CONVERSATION, this.onCmdSnoozeConversation);
}, },
methods: { methods: {
updateVirtualListProps(key, value) { updateVirtualListProps(key, value) {
@@ -742,7 +742,7 @@ export default {
updateAssigneeTab(selectedTab) { updateAssigneeTab(selectedTab) {
if (this.activeAssigneeTab !== selectedTab) { if (this.activeAssigneeTab !== selectedTab) {
this.resetBulkActions(); this.resetBulkActions();
bus.$emit('clearSearchInput'); this.$emitter.emit('clearSearchInput');
this.activeAssigneeTab = selectedTab; this.activeAssigneeTab = selectedTab;
if (!this.currentPage) { if (!this.currentPage) {
this.fetchConversations(); this.fetchConversations();

View File

@@ -25,8 +25,10 @@
<script> <script>
import 'highlight.js/styles/default.css'; import 'highlight.js/styles/default.css';
import { copyTextToClipboard } from 'shared/helpers/clipboard'; import { copyTextToClipboard } from 'shared/helpers/clipboard';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
mixins: [alertMixin],
props: { props: {
script: { script: {
type: String, type: String,
@@ -59,7 +61,7 @@ export default {
async onCopy(e) { async onCopy(e) {
e.preventDefault(); e.preventDefault();
await copyTextToClipboard(this.script); await copyTextToClipboard(this.script);
bus.$emit('newToastMessage', this.$t('COMPONENTS.CODE.COPY_SUCCESSFUL')); this.showAlert(this.$t('COMPONENTS.CODE.COPY_SUCCESSFUL'));
}, },
}, },
}; };

View File

@@ -270,10 +270,10 @@ export default {
}, },
mounted() { mounted() {
this.editedValue = this.formattedValue; this.editedValue = this.formattedValue;
bus.$on(BUS_EVENTS.FOCUS_CUSTOM_ATTRIBUTE, this.onFocusAttribute); this.$emitter.on(BUS_EVENTS.FOCUS_CUSTOM_ATTRIBUTE, this.onFocusAttribute);
}, },
destroyed() { destroyed() {
bus.$off(BUS_EVENTS.FOCUS_CUSTOM_ATTRIBUTE, this.onFocusAttribute); this.$emitter.off(BUS_EVENTS.FOCUS_CUSTOM_ATTRIBUTE, this.onFocusAttribute);
}, },
methods: { methods: {
onFocusAttribute(focusAttributeKey) { onFocusAttribute(focusAttributeKey) {

View File

@@ -18,8 +18,10 @@
<script> <script>
import 'highlight.js/styles/default.css'; import 'highlight.js/styles/default.css';
import { copyTextToClipboard } from 'shared/helpers/clipboard'; import { copyTextToClipboard } from 'shared/helpers/clipboard';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
mixins: [alertMixin],
props: { props: {
value: { value: {
type: String, type: String,
@@ -35,7 +37,7 @@ export default {
async onCopy(e) { async onCopy(e) {
e.preventDefault(); e.preventDefault();
await copyTextToClipboard(this.value); await copyTextToClipboard(this.value);
bus.$emit('newToastMessage', this.$t('COMPONENTS.CODE.COPY_SUCCESSFUL')); this.showAlert(this.$t('COMPONENTS.CODE.COPY_SUCCESSFUL'));
}, },
toggleMasked() { toggleMasked() {
this.masked = !this.masked; this.masked = !this.masked;

View File

@@ -55,7 +55,7 @@ export default {
mounted() { mounted() {
window.addEventListener('offline', this.updateOnlineStatus); window.addEventListener('offline', this.updateOnlineStatus);
window.bus.$on(BUS_EVENTS.WEBSOCKET_DISCONNECT, () => { this.$emitter.on(BUS_EVENTS.WEBSOCKET_DISCONNECT, () => {
// TODO: Remove this after completing the conversation list refetching // TODO: Remove this after completing the conversation list refetching
// TODO: DIRTY FIX : CLEAN UP THIS WITH PROPER FIX, DELAYING THE RECONNECT FOR NOW // TODO: DIRTY FIX : CLEAN UP THIS WITH PROPER FIX, DELAYING THE RECONNECT FOR NOW
// THE CABLE IS FIRING IS VERY COMMON AND THUS INTERFERING USER EXPERIENCE // THE CABLE IS FIRING IS VERY COMMON AND THUS INTERFERING USER EXPERIENCE

View File

@@ -21,7 +21,7 @@ export default {
}, },
methods: { methods: {
onMenuItemClick() { onMenuItemClick() {
bus.$emit(BUS_EVENTS.TOGGLE_SIDEMENU); this.$emitter.emit(BUS_EVENTS.TOGGLE_SIDEMENU);
}, },
}, },
}; };

View File

@@ -15,11 +15,13 @@
<script> <script>
import WootSnackbar from './Snackbar.vue'; import WootSnackbar from './Snackbar.vue';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { components: {
WootSnackbar, WootSnackbar,
}, },
mixins: [alertMixin],
props: { props: {
duration: { duration: {
type: Number, type: Number,
@@ -34,10 +36,10 @@ export default {
}, },
mounted() { mounted() {
bus.$on('newToastMessage', this.onNewToastMessage); this.$emitter.on('newToastMessage', this.onNewToastMessage);
}, },
beforeDestroy() { beforeDestroy() {
bus.$off('newToastMessage', this.onNewToastMessage); this.$emitter.off('newToastMessage', this.onNewToastMessage);
}, },
methods: { methods: {
onNewToastMessage(message, action) { onNewToastMessage(message, action) {

View File

@@ -128,12 +128,12 @@ export default {
}, },
}, },
mounted() { mounted() {
bus.$on(CMD_REOPEN_CONVERSATION, this.onCmdOpenConversation); this.$emitter.on(CMD_REOPEN_CONVERSATION, this.onCmdOpenConversation);
bus.$on(CMD_RESOLVE_CONVERSATION, this.onCmdResolveConversation); this.$emitter.on(CMD_RESOLVE_CONVERSATION, this.onCmdResolveConversation);
}, },
destroyed() { destroyed() {
bus.$off(CMD_REOPEN_CONVERSATION, this.onCmdOpenConversation); this.$emitter.off(CMD_REOPEN_CONVERSATION, this.onCmdOpenConversation);
bus.$off(CMD_RESOLVE_CONVERSATION, this.onCmdResolveConversation); this.$emitter.off(CMD_RESOLVE_CONVERSATION, this.onCmdResolveConversation);
}, },
methods: { methods: {
getKeyboardEvents() { getKeyboardEvents() {

View File

@@ -22,7 +22,7 @@ import {
setYear, setYear,
isAfter, isAfter,
} from 'date-fns'; } from 'date-fns';
import { useAlert } from 'dashboard/composables';
import DatePickerButton from './components/DatePickerButton.vue'; import DatePickerButton from './components/DatePickerButton.vue';
import CalendarDateInput from './components/CalendarDateInput.vue'; import CalendarDateInput from './components/CalendarDateInput.vue';
import CalendarDateRange from './components/CalendarDateRange.vue'; import CalendarDateRange from './components/CalendarDateRange.vue';
@@ -185,7 +185,7 @@ const updateManualInput = (newDate, calendarType) => {
}; };
const handleManualInputError = message => { const handleManualInputError = message => {
bus.$emit('newToastMessage', message); useAlert(message);
}; };
const resetDatePicker = () => { const resetDatePicker = () => {
@@ -201,7 +201,7 @@ const resetDatePicker = () => {
const emitDateRange = () => { const emitDateRange = () => {
if (!isValid(selectedStartDate.value) || !isValid(selectedEndDate.value)) { if (!isValid(selectedStartDate.value) || !isValid(selectedEndDate.value)) {
bus.$emit('newToastMessage', 'Please select a valid time range'); useAlert('Please select a valid time range');
} else { } else {
showDatePicker.value = false; showDatePicker.value = false;
emit('dateRangeChanged', [selectedStartDate.value, selectedEndDate.value]); emit('dateRangeChanged', [selectedStartDate.value, selectedEndDate.value]);

View File

@@ -81,7 +81,7 @@ export default {
}, },
mounted() { mounted() {
bus.$on(CMD_AI_ASSIST, this.onAIAssist); this.$emitter.on(CMD_AI_ASSIST, this.onAIAssist);
this.initialMessage = this.draftMessage; this.initialMessage = this.draftMessage;
}, },

View File

@@ -352,10 +352,16 @@ export default {
// Components using this // Components using this
// 1. SearchPopover.vue // 1. SearchPopover.vue
bus.$on(BUS_EVENTS.INSERT_INTO_RICH_EDITOR, this.insertContentIntoEditor); this.$emitter.on(
BUS_EVENTS.INSERT_INTO_RICH_EDITOR,
this.insertContentIntoEditor
);
}, },
beforeDestroy() { beforeDestroy() {
bus.$off(BUS_EVENTS.INSERT_INTO_RICH_EDITOR, this.insertContentIntoEditor); this.$emitter.off(
BUS_EVENTS.INSERT_INTO_RICH_EDITOR,
this.insertContentIntoEditor
);
}, },
methods: { methods: {
reloadState(content = this.value) { reloadState(content = this.value) {

View File

@@ -473,11 +473,11 @@ export default {
}, },
mounted() { mounted() {
this.hasMediaLoadError = false; this.hasMediaLoadError = false;
bus.$on(BUS_EVENTS.ON_MESSAGE_LIST_SCROLL, this.closeContextMenu); this.$emitter.on(BUS_EVENTS.ON_MESSAGE_LIST_SCROLL, this.closeContextMenu);
this.setupHighlightTimer(); this.setupHighlightTimer();
}, },
beforeDestroy() { beforeDestroy() {
bus.$off(BUS_EVENTS.ON_MESSAGE_LIST_SCROLL, this.closeContextMenu); this.$emitter.off(BUS_EVENTS.ON_MESSAGE_LIST_SCROLL, this.closeContextMenu);
clearTimeout(this.higlightTimeout); clearTimeout(this.higlightTimeout);
}, },
methods: { methods: {
@@ -531,7 +531,7 @@ export default {
const { conversation_id: conversationId, id: replyTo } = this.data; const { conversation_id: conversationId, id: replyTo } = this.data;
LocalStorage.updateJsonStore(replyStorageKey, conversationId, replyTo); LocalStorage.updateJsonStore(replyStorageKey, conversationId, replyTo);
bus.$emit(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE, this.data); this.$emitter.emit(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE, this.data);
}, },
setupHighlightTimer() { setupHighlightTimer() {
if (Number(this.$route.query.messageId) !== Number(this.data.id)) { if (Number(this.$route.query.messageId) !== Number(this.data.id)) {

View File

@@ -324,12 +324,12 @@ export default {
}, },
created() { created() {
bus.$on(BUS_EVENTS.SCROLL_TO_MESSAGE, this.onScrollToMessage); this.$emitter.on(BUS_EVENTS.SCROLL_TO_MESSAGE, this.onScrollToMessage);
// when a new message comes in, we refetch the label suggestions // when a new message comes in, we refetch the label suggestions
bus.$on(BUS_EVENTS.FETCH_LABEL_SUGGESTIONS, this.fetchSuggestions); this.$emitter.on(BUS_EVENTS.FETCH_LABEL_SUGGESTIONS, this.fetchSuggestions);
// when a message is sent we set the flag to true this hides the label suggestions, // when a message is sent we set the flag to true this hides the label suggestions,
// until the chat is changed and the flag is reset in the watch for currentChat // until the chat is changed and the flag is reset in the watch for currentChat
bus.$on(BUS_EVENTS.MESSAGE_SENT, () => { this.$emitter.on(BUS_EVENTS.MESSAGE_SENT, () => {
this.messageSentSinceOpened = true; this.messageSentSinceOpened = true;
}); });
}, },
@@ -396,7 +396,7 @@ export default {
this.$store.dispatch('fetchAllAttachments', this.currentChat.id); this.$store.dispatch('fetchAllAttachments', this.currentChat.id);
}, },
removeBusListeners() { removeBusListeners() {
bus.$off(BUS_EVENTS.SCROLL_TO_MESSAGE, this.onScrollToMessage); this.$emitter.off(BUS_EVENTS.SCROLL_TO_MESSAGE, this.onScrollToMessage);
}, },
onScrollToMessage({ messageId = '' } = {}) { onScrollToMessage({ messageId = '' } = {}) {
this.$nextTick(() => { this.$nextTick(() => {
@@ -514,7 +514,7 @@ export default {
} else { } else {
this.hasUserScrolled = true; this.hasUserScrolled = true;
} }
bus.$emit(BUS_EVENTS.ON_MESSAGE_LIST_SCROLL); this.$emitter.emit(BUS_EVENTS.ON_MESSAGE_LIST_SCROLL);
this.fetchPreviousMessages(e.target.scrollTop); this.fetchPreviousMessages(e.target.scrollTop);
}, },

View File

@@ -61,14 +61,14 @@ export default {
...mapGetters({ currentChat: 'getSelectedChat' }), ...mapGetters({ currentChat: 'getSelectedChat' }),
}, },
mounted() { mounted() {
bus.$on(CMD_MUTE_CONVERSATION, this.mute); this.$emitter.on(CMD_MUTE_CONVERSATION, this.mute);
bus.$on(CMD_UNMUTE_CONVERSATION, this.unmute); this.$emitter.on(CMD_UNMUTE_CONVERSATION, this.unmute);
bus.$on(CMD_SEND_TRANSCRIPT, this.toggleEmailActionsModal); this.$emitter.on(CMD_SEND_TRANSCRIPT, this.toggleEmailActionsModal);
}, },
destroyed() { destroyed() {
bus.$off(CMD_MUTE_CONVERSATION, this.mute); this.$emitter.off(CMD_MUTE_CONVERSATION, this.mute);
bus.$off(CMD_UNMUTE_CONVERSATION, this.unmute); this.$emitter.off(CMD_UNMUTE_CONVERSATION, this.unmute);
bus.$off(CMD_SEND_TRANSCRIPT, this.toggleEmailActionsModal); this.$emitter.off(CMD_SEND_TRANSCRIPT, this.toggleEmailActionsModal);
}, },
methods: { methods: {
mute() { mute() {

View File

@@ -596,12 +596,15 @@ export default {
); );
this.fetchAndSetReplyTo(); this.fetchAndSetReplyTo();
bus.$on(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE, this.fetchAndSetReplyTo); this.$emitter.on(
BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE,
this.fetchAndSetReplyTo
);
// A hacky fix to solve the drag and drop // A hacky fix to solve the drag and drop
// Is showing on top of new conversation modal drag and drop // Is showing on top of new conversation modal drag and drop
// TODO need to find a better solution // TODO need to find a better solution
bus.$on( this.$emitter.on(
BUS_EVENTS.NEW_CONVERSATION_MODAL, BUS_EVENTS.NEW_CONVERSATION_MODAL,
this.onNewConversationModalActive this.onNewConversationModalActive
); );
@@ -609,10 +612,13 @@ export default {
destroyed() { destroyed() {
document.removeEventListener('paste', this.onPaste); document.removeEventListener('paste', this.onPaste);
document.removeEventListener('keydown', this.handleKeyEvents); document.removeEventListener('keydown', this.handleKeyEvents);
bus.$off(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE, this.fetchAndSetReplyTo); this.$emitter.off(
BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE,
this.fetchAndSetReplyTo
);
}, },
beforeDestroy() { beforeDestroy() {
bus.$off( this.$emitter.off(
BUS_EVENTS.NEW_CONVERSATION_MODAL, BUS_EVENTS.NEW_CONVERSATION_MODAL,
this.onNewConversationModalActive this.onNewConversationModalActive
); );
@@ -625,7 +631,7 @@ export default {
const lines = title.split('\n'); const lines = title.split('\n');
const nonEmptyLines = lines.filter(line => line.trim() !== ''); const nonEmptyLines = lines.filter(line => line.trim() !== '');
const filteredMarkdown = nonEmptyLines.join(' '); const filteredMarkdown = nonEmptyLines.join(' ');
bus.$emit( this.$emitter.emit(
BUS_EVENTS.INSERT_INTO_RICH_EDITOR, BUS_EVENTS.INSERT_INTO_RICH_EDITOR,
`[${filteredMarkdown}](${url})` `[${filteredMarkdown}](${url})`
); );
@@ -867,8 +873,8 @@ export default {
'createPendingMessageAndSend', 'createPendingMessageAndSend',
messagePayload messagePayload
); );
bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE); this.$emitter.emit(BUS_EVENTS.SCROLL_TO_MESSAGE);
bus.$emit(BUS_EVENTS.MESSAGE_SENT); this.$emitter.emit(BUS_EVENTS.MESSAGE_SENT);
this.removeFromDraft(); this.removeFromDraft();
this.sendMessageAnalyticsData(messagePayload.private); this.sendMessageAnalyticsData(messagePayload.private);
} catch (error) { } catch (error) {
@@ -1194,7 +1200,7 @@ export default {
resetReplyToMessage() { resetReplyToMessage() {
const replyStorageKey = LOCAL_STORAGE_KEYS.MESSAGE_REPLY_TO; const replyStorageKey = LOCAL_STORAGE_KEYS.MESSAGE_REPLY_TO;
LocalStorage.deleteFromJsonStore(replyStorageKey, this.conversationId); LocalStorage.deleteFromJsonStore(replyStorageKey, this.conversationId);
bus.$emit(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE); this.$emitter.emit(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE);
}, },
onNewConversationModalActive(isActive) { onNewConversationModalActive(isActive) {
// Issue is if the new conversation modal is open and we drag and drop the file // Issue is if the new conversation modal is open and we drag and drop the file

View File

@@ -47,7 +47,9 @@ export default {
}, },
methods: { methods: {
scrollToMessage() { scrollToMessage() {
bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE, { messageId: this.message.id }); this.$emitter.emit(BUS_EVENTS.SCROLL_TO_MESSAGE, {
messageId: this.message.id,
});
}, },
}, },
}; };

View File

@@ -167,17 +167,29 @@ export default {
}; };
}, },
mounted() { mounted() {
bus.$on(CMD_BULK_ACTION_SNOOZE_CONVERSATION, this.onCmdSnoozeConversation); this.$emitter.on(
bus.$on(CMD_BULK_ACTION_REOPEN_CONVERSATION, this.onCmdReopenConversation); CMD_BULK_ACTION_SNOOZE_CONVERSATION,
bus.$on( this.onCmdSnoozeConversation
);
this.$emitter.on(
CMD_BULK_ACTION_REOPEN_CONVERSATION,
this.onCmdReopenConversation
);
this.$emitter.on(
CMD_BULK_ACTION_RESOLVE_CONVERSATION, CMD_BULK_ACTION_RESOLVE_CONVERSATION,
this.onCmdResolveConversation this.onCmdResolveConversation
); );
}, },
destroyed() { destroyed() {
bus.$off(CMD_BULK_ACTION_SNOOZE_CONVERSATION, this.onCmdSnoozeConversation); this.$emitter.off(
bus.$off(CMD_BULK_ACTION_REOPEN_CONVERSATION, this.onCmdReopenConversation); CMD_BULK_ACTION_SNOOZE_CONVERSATION,
bus.$off( this.onCmdSnoozeConversation
);
this.$emitter.off(
CMD_BULK_ACTION_REOPEN_CONVERSATION,
this.onCmdReopenConversation
);
this.$emitter.off(
CMD_BULK_ACTION_RESOLVE_CONVERSATION, CMD_BULK_ACTION_RESOLVE_CONVERSATION,
this.onCmdResolveConversation this.onCmdResolveConversation
); );

View File

@@ -2,12 +2,21 @@ import { createLocalVue, mount } from '@vue/test-utils';
import Vuex from 'vuex'; import Vuex from 'vuex';
import VueI18n from 'vue-i18n'; import VueI18n from 'vue-i18n';
import VTooltip from 'v-tooltip'; import VTooltip from 'v-tooltip';
import Button from 'dashboard/components/buttons/Button'; import Button from 'dashboard/components/buttons/Button';
import i18n from 'dashboard/i18n'; import i18n from 'dashboard/i18n';
import FluentIcon from 'shared/components/FluentIcon/DashboardIcon'; import FluentIcon from 'shared/components/FluentIcon/DashboardIcon';
import MoreActions from '../MoreActions'; import MoreActions from '../MoreActions';
jest.mock('shared/helpers/mitt', () => ({
emitter: {
emit: jest.fn(),
on: jest.fn(),
off: jest.fn(),
},
}));
import { emitter } from 'shared/helpers/mitt';
const localVue = createLocalVue(); const localVue = createLocalVue();
localVue.use(Vuex); localVue.use(Vuex);
localVue.use(VueI18n); localVue.use(VueI18n);
@@ -16,6 +25,12 @@ localVue.use(VTooltip);
localVue.component('fluent-icon', FluentIcon); localVue.component('fluent-icon', FluentIcon);
localVue.component('woot-button', Button); localVue.component('woot-button', Button);
localVue.prototype.$emitter = {
emit: jest.fn(),
on: jest.fn(),
off: jest.fn(),
};
const i18nConfig = new VueI18n({ locale: 'en', messages: i18n }); const i18nConfig = new VueI18n({ locale: 'en', messages: i18n });
describe('MoveActions', () => { describe('MoveActions', () => {
@@ -29,12 +44,6 @@ describe('MoveActions', () => {
let moreActions = null; let moreActions = null;
beforeEach(() => { beforeEach(() => {
window.bus = {
$emit: jest.fn(),
$on: jest.fn(),
$off: jest.fn(),
};
state = { state = {
authenticated: true, authenticated: true,
currentChat, currentChat,
@@ -76,7 +85,7 @@ describe('MoveActions', () => {
it('shows alert', async () => { it('shows alert', async () => {
await moreActions.find('button:first-child').trigger('click'); await moreActions.find('button:first-child').trigger('click');
expect(window.bus.$emit).toBeCalledWith( expect(emitter.emit).toBeCalledWith(
'newToastMessage', 'newToastMessage',
'This contact is blocked successfully. You will not be notified of any future conversations.', 'This contact is blocked successfully. You will not be notified of any future conversations.',
undefined undefined
@@ -102,7 +111,7 @@ describe('MoveActions', () => {
it('shows alert', async () => { it('shows alert', async () => {
await moreActions.find('button:first-child').trigger('click'); await moreActions.find('button:first-child').trigger('click');
expect(window.bus.$emit).toBeCalledWith( expect(emitter.emit).toBeCalledWith(
'newToastMessage', 'newToastMessage',
'This contact is unblocked successfully.', 'This contact is unblocked successfully.',
undefined undefined

View File

@@ -1,4 +1,5 @@
import { getCurrentInstance } from 'vue'; import { getCurrentInstance } from 'vue';
import { emitter } from 'shared/helpers/mitt';
export const useTrack = () => { export const useTrack = () => {
const vm = getCurrentInstance(); const vm = getCurrentInstance();
@@ -8,5 +9,5 @@ export const useTrack = () => {
}; };
export function useAlert(message, action) { export function useAlert(message, action) {
bus.$emit('newToastMessage', message, action); emitter.emit('newToastMessage', message, action);
} }

View File

@@ -1,6 +1,7 @@
import AuthAPI from '../api/auth'; import AuthAPI from '../api/auth';
import BaseActionCableConnector from '../../shared/helpers/BaseActionCableConnector'; import BaseActionCableConnector from '../../shared/helpers/BaseActionCableConnector';
import DashboardAudioNotificationHelper from './AudioAlerts/DashboardAudioNotificationHelper'; import DashboardAudioNotificationHelper from './AudioAlerts/DashboardAudioNotificationHelper';
import { emitter } from 'shared/helpers/mitt';
class ActionCableConnector extends BaseActionCableConnector { class ActionCableConnector extends BaseActionCableConnector {
constructor(app, pubsubToken) { constructor(app, pubsubToken) {
@@ -177,8 +178,8 @@ class ActionCableConnector extends BaseActionCableConnector {
// eslint-disable-next-line class-methods-use-this // eslint-disable-next-line class-methods-use-this
fetchConversationStats = () => { fetchConversationStats = () => {
bus.$emit('fetch_conversation_stats'); emitter.emit('fetch_conversation_stats');
bus.$emit('fetch_overview_reports'); emitter.emit('fetch_overview_reports');
}; };
onContactDelete = data => { onContactDelete = data => {
@@ -207,7 +208,7 @@ class ActionCableConnector extends BaseActionCableConnector {
// eslint-disable-next-line class-methods-use-this // eslint-disable-next-line class-methods-use-this
onFirstReplyCreated = () => { onFirstReplyCreated = () => {
bus.$emit('fetch_overview_reports'); emitter.emit('fetch_overview_reports');
}; };
onCacheInvalidate = data => { onCacheInvalidate = data => {

View File

@@ -1,6 +1,7 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
import NotificationSubscriptions from '../api/notificationSubscription'; import NotificationSubscriptions from '../api/notificationSubscription';
import auth from '../api/auth'; import auth from '../api/auth';
import { emitter } from 'shared/helpers/mitt';
export const verifyServiceWorkerExistence = (callback = () => {}) => { export const verifyServiceWorkerExistence = (callback = () => {}) => {
if (!('serviceWorker' in navigator)) { if (!('serviceWorker' in navigator)) {
@@ -68,7 +69,7 @@ export const registerSubscription = (onSuccess = () => {}) => {
onSuccess(); onSuccess();
}) })
.catch(() => { .catch(() => {
window.bus.$emit( emitter.emit(
'newToastMessage', 'newToastMessage',
'This browser does not support desktop notification' 'This browser does not support desktop notification'
); );
@@ -77,7 +78,7 @@ export const registerSubscription = (onSuccess = () => {}) => {
export const requestPushPermissions = ({ onSuccess }) => { export const requestPushPermissions = ({ onSuccess }) => {
if (!('Notification' in window)) { if (!('Notification' in window)) {
window.bus.$emit( emitter.emit(
'newToastMessage', 'newToastMessage',
'This browser does not support desktop notification' 'This browser does not support desktop notification'
); );

View File

@@ -1,5 +1,6 @@
import AnalyticsHelper from './AnalyticsHelper'; import AnalyticsHelper from './AnalyticsHelper';
import DashboardAudioNotificationHelper from './AudioAlerts/DashboardAudioNotificationHelper'; import DashboardAudioNotificationHelper from './AudioAlerts/DashboardAudioNotificationHelper';
import { emitter } from 'shared/helpers/mitt';
export const CHATWOOT_SET_USER = 'CHATWOOT_SET_USER'; export const CHATWOOT_SET_USER = 'CHATWOOT_SET_USER';
export const CHATWOOT_RESET = 'CHATWOOT_RESET'; export const CHATWOOT_RESET = 'CHATWOOT_RESET';
@@ -8,7 +9,7 @@ export const ANALYTICS_IDENTITY = 'ANALYTICS_IDENTITY';
export const ANALYTICS_RESET = 'ANALYTICS_RESET'; export const ANALYTICS_RESET = 'ANALYTICS_RESET';
export const initializeAnalyticsEvents = () => { export const initializeAnalyticsEvents = () => {
window.bus.$on(ANALYTICS_IDENTITY, ({ user }) => { emitter.on(ANALYTICS_IDENTITY, ({ user }) => {
AnalyticsHelper.identify(user); AnalyticsHelper.identify(user);
}); });
}; };
@@ -34,12 +35,12 @@ const initializeAudioAlerts = user => {
}; };
export const initializeChatwootEvents = () => { export const initializeChatwootEvents = () => {
window.bus.$on(CHATWOOT_RESET, () => { emitter.on(CHATWOOT_RESET, () => {
if (window.$chatwoot) { if (window.$chatwoot) {
window.$chatwoot.reset(); window.$chatwoot.reset();
} }
}); });
window.bus.$on(CHATWOOT_SET_USER, ({ user }) => { emitter.on(CHATWOOT_SET_USER, ({ user }) => {
if (window.$chatwoot) { if (window.$chatwoot) {
window.$chatwoot.setUser(user.email, { window.$chatwoot.setUser(user.email, {
avatar_url: user.avatar_url, avatar_url: user.avatar_url,

View File

@@ -110,11 +110,11 @@ export default {
mounted() { mounted() {
this.handleResize(); this.handleResize();
window.addEventListener('resize', this.handleResize); window.addEventListener('resize', this.handleResize);
bus.$on(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar); this.$emitter.on(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar);
}, },
beforeDestroy() { beforeDestroy() {
window.removeEventListener('resize', this.handleResize); window.removeEventListener('resize', this.handleResize);
bus.$off(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar); this.$emitter.off(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar);
}, },
methods: { methods: {

View File

@@ -11,6 +11,7 @@ import {
ICON_REOPEN_CONVERSATION, ICON_REOPEN_CONVERSATION,
ICON_RESOLVE_CONVERSATION, ICON_RESOLVE_CONVERSATION,
} from './CommandBarIcons'; } from './CommandBarIcons';
import { emitter } from 'shared/helpers/mitt';
import { createSnoozeHandlers } from './commandBarActions'; import { createSnoozeHandlers } from './commandBarActions';
@@ -37,7 +38,7 @@ export const RESOLVED_CONVERSATION_BULK_ACTIONS = [
title: 'COMMAND_BAR.COMMANDS.REOPEN_CONVERSATION', title: 'COMMAND_BAR.COMMANDS.REOPEN_CONVERSATION',
section: 'COMMAND_BAR.SECTIONS.BULK_ACTIONS', section: 'COMMAND_BAR.SECTIONS.BULK_ACTIONS',
icon: ICON_REOPEN_CONVERSATION, icon: ICON_REOPEN_CONVERSATION,
handler: () => bus.$emit(CMD_BULK_ACTION_REOPEN_CONVERSATION), handler: () => emitter.emit(CMD_BULK_ACTION_REOPEN_CONVERSATION),
}, },
]; ];
@@ -47,7 +48,7 @@ export const OPEN_CONVERSATION_BULK_ACTIONS = [
title: 'COMMAND_BAR.COMMANDS.RESOLVE_CONVERSATION', title: 'COMMAND_BAR.COMMANDS.RESOLVE_CONVERSATION',
section: 'COMMAND_BAR.SECTIONS.BULK_ACTIONS', section: 'COMMAND_BAR.SECTIONS.BULK_ACTIONS',
icon: ICON_RESOLVE_CONVERSATION, icon: ICON_RESOLVE_CONVERSATION,
handler: () => bus.$emit(CMD_BULK_ACTION_RESOLVE_CONVERSATION), handler: () => emitter.emit(CMD_BULK_ACTION_RESOLVE_CONVERSATION),
}, },
]; ];

View File

@@ -1,4 +1,5 @@
import wootConstants from 'dashboard/constants/globals'; import wootConstants from 'dashboard/constants/globals';
import { emitter } from 'shared/helpers/mitt';
import { import {
CMD_MUTE_CONVERSATION, CMD_MUTE_CONVERSATION,
@@ -26,7 +27,7 @@ export const OPEN_CONVERSATION_ACTIONS = [
title: 'COMMAND_BAR.COMMANDS.RESOLVE_CONVERSATION', title: 'COMMAND_BAR.COMMANDS.RESOLVE_CONVERSATION',
section: 'COMMAND_BAR.SECTIONS.CONVERSATION', section: 'COMMAND_BAR.SECTIONS.CONVERSATION',
icon: ICON_RESOLVE_CONVERSATION, icon: ICON_RESOLVE_CONVERSATION,
handler: () => bus.$emit(CMD_RESOLVE_CONVERSATION), handler: () => emitter.emit(CMD_RESOLVE_CONVERSATION),
}, },
]; ];
@@ -37,7 +38,7 @@ export const createSnoozeHandlers = (busEventName, parentId, section) => {
parent: parentId, parent: parentId,
section: section, section: section,
icon: ICON_SNOOZE_CONVERSATION, icon: ICON_SNOOZE_CONVERSATION,
handler: () => bus.$emit(busEventName, option), handler: () => emitter.emit(busEventName, option),
})); }));
}; };
@@ -61,7 +62,7 @@ export const RESOLVED_CONVERSATION_ACTIONS = [
title: 'COMMAND_BAR.COMMANDS.REOPEN_CONVERSATION', title: 'COMMAND_BAR.COMMANDS.REOPEN_CONVERSATION',
section: 'COMMAND_BAR.SECTIONS.CONVERSATION', section: 'COMMAND_BAR.SECTIONS.CONVERSATION',
icon: ICON_REOPEN_CONVERSATION, icon: ICON_REOPEN_CONVERSATION,
handler: () => bus.$emit(CMD_REOPEN_CONVERSATION), handler: () => emitter.emit(CMD_REOPEN_CONVERSATION),
}, },
]; ];
@@ -70,7 +71,7 @@ export const SEND_TRANSCRIPT_ACTION = {
title: 'COMMAND_BAR.COMMANDS.SEND_TRANSCRIPT', title: 'COMMAND_BAR.COMMANDS.SEND_TRANSCRIPT',
section: 'COMMAND_BAR.SECTIONS.CONVERSATION', section: 'COMMAND_BAR.SECTIONS.CONVERSATION',
icon: ICON_SEND_TRANSCRIPT, icon: ICON_SEND_TRANSCRIPT,
handler: () => bus.$emit(CMD_SEND_TRANSCRIPT), handler: () => emitter.emit(CMD_SEND_TRANSCRIPT),
}; };
export const UNMUTE_ACTION = { export const UNMUTE_ACTION = {
@@ -78,7 +79,7 @@ export const UNMUTE_ACTION = {
title: 'COMMAND_BAR.COMMANDS.UNMUTE_CONVERSATION', title: 'COMMAND_BAR.COMMANDS.UNMUTE_CONVERSATION',
section: 'COMMAND_BAR.SECTIONS.CONVERSATION', section: 'COMMAND_BAR.SECTIONS.CONVERSATION',
icon: ICON_UNMUTE_CONVERSATION, icon: ICON_UNMUTE_CONVERSATION,
handler: () => bus.$emit(CMD_UNMUTE_CONVERSATION), handler: () => emitter.emit(CMD_UNMUTE_CONVERSATION),
}; };
export const MUTE_ACTION = { export const MUTE_ACTION = {
@@ -86,5 +87,5 @@ export const MUTE_ACTION = {
title: 'COMMAND_BAR.COMMANDS.MUTE_CONVERSATION', title: 'COMMAND_BAR.COMMANDS.MUTE_CONVERSATION',
section: 'COMMAND_BAR.SECTIONS.CONVERSATION', section: 'COMMAND_BAR.SECTIONS.CONVERSATION',
icon: ICON_MUTE_CONVERSATION, icon: ICON_MUTE_CONVERSATION,
handler: () => bus.$emit(CMD_MUTE_CONVERSATION), handler: () => emitter.emit(CMD_MUTE_CONVERSATION),
}; };

View File

@@ -1,5 +1,6 @@
import { mapGetters } from 'vuex'; import { mapGetters } from 'vuex';
import wootConstants from 'dashboard/constants/globals'; import wootConstants from 'dashboard/constants/globals';
import { emitter } from 'shared/helpers/mitt';
import { CMD_AI_ASSIST } from './commandBarBusEvents'; import { CMD_AI_ASSIST } from './commandBarBusEvents';
import { REPLY_EDITOR_MODES } from 'dashboard/components/widgets/WootWriter/constants'; import { REPLY_EDITOR_MODES } from 'dashboard/components/widgets/WootWriter/constants';
@@ -318,7 +319,7 @@ export default {
section: this.$t('COMMAND_BAR.SECTIONS.AI_ASSIST'), section: this.$t('COMMAND_BAR.SECTIONS.AI_ASSIST'),
priority: item, priority: item,
icon: item.icon, icon: item.icon,
handler: () => bus.$emit(CMD_AI_ASSIST, item.key), handler: () => emitter.emit(CMD_AI_ASSIST, item.key),
})); }));
return [ return [
{ {

View File

@@ -2,6 +2,7 @@ import wootConstants from 'dashboard/constants/globals';
import { CMD_SNOOZE_NOTIFICATION } from './commandBarBusEvents'; import { CMD_SNOOZE_NOTIFICATION } from './commandBarBusEvents';
import { ICON_SNOOZE_NOTIFICATION } from './CommandBarIcons'; import { ICON_SNOOZE_NOTIFICATION } from './CommandBarIcons';
import { emitter } from 'shared/helpers/mitt';
import { isAInboxViewRoute } from 'dashboard/helper/routeHelpers'; import { isAInboxViewRoute } from 'dashboard/helper/routeHelpers';
@@ -21,7 +22,7 @@ const INBOX_SNOOZE_EVENTS = [
section: 'COMMAND_BAR.SECTIONS.SNOOZE_NOTIFICATION', section: 'COMMAND_BAR.SECTIONS.SNOOZE_NOTIFICATION',
icon: ICON_SNOOZE_NOTIFICATION, icon: ICON_SNOOZE_NOTIFICATION,
handler: () => handler: () =>
bus.$emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.AN_HOUR_FROM_NOW), emitter.emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.AN_HOUR_FROM_NOW),
}, },
{ {
id: SNOOZE_OPTIONS.UNTIL_TOMORROW, id: SNOOZE_OPTIONS.UNTIL_TOMORROW,
@@ -30,7 +31,7 @@ const INBOX_SNOOZE_EVENTS = [
parent: 'snooze_notification', parent: 'snooze_notification',
icon: ICON_SNOOZE_NOTIFICATION, icon: ICON_SNOOZE_NOTIFICATION,
handler: () => handler: () =>
bus.$emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_TOMORROW), emitter.emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_TOMORROW),
}, },
{ {
id: SNOOZE_OPTIONS.UNTIL_NEXT_WEEK, id: SNOOZE_OPTIONS.UNTIL_NEXT_WEEK,
@@ -39,7 +40,7 @@ const INBOX_SNOOZE_EVENTS = [
parent: 'snooze_notification', parent: 'snooze_notification',
icon: ICON_SNOOZE_NOTIFICATION, icon: ICON_SNOOZE_NOTIFICATION,
handler: () => handler: () =>
bus.$emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_NEXT_WEEK), emitter.emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_NEXT_WEEK),
}, },
{ {
id: SNOOZE_OPTIONS.UNTIL_NEXT_MONTH, id: SNOOZE_OPTIONS.UNTIL_NEXT_MONTH,
@@ -48,7 +49,7 @@ const INBOX_SNOOZE_EVENTS = [
parent: 'snooze_notification', parent: 'snooze_notification',
icon: ICON_SNOOZE_NOTIFICATION, icon: ICON_SNOOZE_NOTIFICATION,
handler: () => handler: () =>
bus.$emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_NEXT_MONTH), emitter.emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_NEXT_MONTH),
}, },
{ {
id: SNOOZE_OPTIONS.UNTIL_CUSTOM_TIME, id: SNOOZE_OPTIONS.UNTIL_CUSTOM_TIME,
@@ -57,7 +58,7 @@ const INBOX_SNOOZE_EVENTS = [
parent: 'snooze_notification', parent: 'snooze_notification',
icon: ICON_SNOOZE_NOTIFICATION, icon: ICON_SNOOZE_NOTIFICATION,
handler: () => handler: () =>
bus.$emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_CUSTOM_TIME), emitter.emit(CMD_SNOOZE_NOTIFICATION, SNOOZE_OPTIONS.UNTIL_CUSTOM_TIME),
}, },
]; ];
export default { export default {

View File

@@ -169,7 +169,7 @@ export default {
after: messageId, after: messageId,
}) })
.then(() => { .then(() => {
bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE, { messageId }); this.$emitter.emit(BUS_EVENTS.SCROLL_TO_MESSAGE, { messageId });
}); });
} else { } else {
this.$store.dispatch('clearSelectedState'); this.$store.dispatch('clearSelectedState');

View File

@@ -271,7 +271,10 @@ export default {
}, },
toggleConversationModal() { toggleConversationModal() {
this.showConversationModal = !this.showConversationModal; this.showConversationModal = !this.showConversationModal;
bus.$emit(BUS_EVENTS.NEW_CONVERSATION_MODAL, this.showConversationModal); this.$emitter.emit(
BUS_EVENTS.NEW_CONVERSATION_MODAL,
this.showConversationModal
);
}, },
toggleDeleteModal() { toggleDeleteModal() {
this.showDeleteModal = !this.showDeleteModal; this.showDeleteModal = !this.showDeleteModal;

View File

@@ -265,7 +265,7 @@ export default {
}, },
mounted() { mounted() {
bus.$on(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar); this.$emitter.on(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar);
const slug = this.$route.params.portalSlug; const slug = this.$route.params.portalSlug;
if (slug) this.lastActivePortalSlug = slug; if (slug) this.lastActivePortalSlug = slug;
@@ -273,7 +273,7 @@ export default {
this.fetchPortalAndItsCategories(); this.fetchPortalAndItsCategories();
}, },
beforeDestroy() { beforeDestroy() {
bus.$off(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar); this.$emitter.off(BUS_EVENTS.TOGGLE_SIDEMENU, this.toggleSidebar);
}, },
updated() { updated() {
const slug = this.$route.params.portalSlug; const slug = this.$route.params.portalSlug;

View File

@@ -140,7 +140,7 @@ export default {
this.$store this.$store
.dispatch('setActiveChat', { data: selectedConversation }) .dispatch('setActiveChat', { data: selectedConversation })
.then(() => { .then(() => {
bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE); this.$emitter.emit(BUS_EVENTS.SCROLL_TO_MESSAGE);
}); });
}, },
findConversation() { findConversation() {

View File

@@ -92,10 +92,10 @@ export default {
...mapGetters({ meta: 'notifications/getMeta' }), ...mapGetters({ meta: 'notifications/getMeta' }),
}, },
mounted() { mounted() {
bus.$on(CMD_SNOOZE_NOTIFICATION, this.onCmdSnoozeNotification); this.$emitter.on(CMD_SNOOZE_NOTIFICATION, this.onCmdSnoozeNotification);
}, },
destroyed() { destroyed() {
bus.$off(CMD_SNOOZE_NOTIFICATION, this.onCmdSnoozeNotification); this.$emitter.off(CMD_SNOOZE_NOTIFICATION, this.onCmdSnoozeNotification);
}, },
methods: { methods: {
openSnoozeNotificationModal() { openSnoozeNotificationModal() {

View File

@@ -69,8 +69,10 @@
<script> <script>
import { required, minLength, email } from 'vuelidate/lib/validators'; import { required, minLength, email } from 'vuelidate/lib/validators';
import { mapGetters } from 'vuex'; import { mapGetters } from 'vuex';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
mixins: [alertMixin],
props: { props: {
onClose: { onClose: {
type: Function, type: Function,
@@ -117,9 +119,6 @@ export default {
}, },
methods: { methods: {
showAlert(message) {
bus.$emit('newToastMessage', message);
},
async addAgent() { async addAgent() {
try { try {
await this.$store.dispatch('agents/create', { await this.$store.dispatch('agents/create', {

View File

@@ -83,6 +83,7 @@ import WootSubmitButton from '../../../../components/buttons/FormSubmitButton.vu
import Modal from '../../../../components/Modal.vue'; import Modal from '../../../../components/Modal.vue';
import Auth from '../../../../api/auth'; import Auth from '../../../../api/auth';
import wootConstants from 'dashboard/constants/globals'; import wootConstants from 'dashboard/constants/globals';
import alertMixin from 'shared/mixins/alertMixin';
const { AVAILABILITY_STATUS_KEYS } = wootConstants; const { AVAILABILITY_STATUS_KEYS } = wootConstants;
@@ -91,6 +92,7 @@ export default {
WootSubmitButton, WootSubmitButton,
Modal, Modal,
}, },
mixins: [alertMixin],
props: { props: {
id: { id: {
type: Number, type: Number,
@@ -169,9 +171,6 @@ export default {
}, },
}, },
methods: { methods: {
showAlert(message) {
bus.$emit('newToastMessage', message);
},
async editAgent() { async editAgent() {
try { try {
await this.$store.dispatch('agents/update', { await this.$store.dispatch('agents/update', {

View File

@@ -130,6 +130,7 @@ import globalConfigMixin from 'shared/mixins/globalConfigMixin';
import Thumbnail from '../../../../components/widgets/Thumbnail.vue'; import Thumbnail from '../../../../components/widgets/Thumbnail.vue';
import AddAgent from './AddAgent.vue'; import AddAgent from './AddAgent.vue';
import EditAgent from './EditAgent.vue'; import EditAgent from './EditAgent.vue';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { components: {
@@ -137,7 +138,7 @@ export default {
EditAgent, EditAgent,
Thumbnail, Thumbnail,
}, },
mixins: [globalConfigMixin], mixins: [globalConfigMixin, alertMixin],
data() { data() {
return { return {
loading: {}, loading: {},
@@ -230,19 +231,19 @@ export default {
async deleteAgent(id) { async deleteAgent(id) {
try { try {
await this.$store.dispatch('agents/delete', id); await this.$store.dispatch('agents/delete', id);
this.showAlert(this.$t('AGENT_MGMT.DELETE.API.SUCCESS_MESSAGE')); this.showAlertMessage(this.$t('AGENT_MGMT.DELETE.API.SUCCESS_MESSAGE'));
} catch (error) { } catch (error) {
this.showAlert(this.$t('AGENT_MGMT.DELETE.API.ERROR_MESSAGE')); this.showAlertMessage(this.$t('AGENT_MGMT.DELETE.API.ERROR_MESSAGE'));
} }
}, },
// Show SnackBar // Show SnackBar
showAlert(message) { showAlertMessage(message) {
// Reset loading, current selected agent // Reset loading, current selected agent
this.loading[this.currentAgent.id] = false; this.loading[this.currentAgent.id] = false;
this.currentAgent = {}; this.currentAgent = {};
// Show message // Show message
this.agentAPI.message = message; this.agentAPI.message = message;
bus.$emit('newToastMessage', message); this.showAlert(message);
}, },
}, },
}; };

View File

@@ -132,12 +132,14 @@
import { mapGetters } from 'vuex'; import { mapGetters } from 'vuex';
import AddCanned from './AddCanned.vue'; import AddCanned from './AddCanned.vue';
import EditCanned from './EditCanned.vue'; import EditCanned from './EditCanned.vue';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { components: {
AddCanned, AddCanned,
EditCanned, EditCanned,
}, },
mixins: [alertMixin],
data() { data() {
return { return {
loading: {}, loading: {},
@@ -187,13 +189,13 @@ export default {
}); });
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'; this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
}, },
showAlert(message) { showAlertMessage(message) {
// Reset loading, current selected agent // Reset loading, current selected agent
this.loading[this.selectedResponse.id] = false; this.loading[this.selectedResponse.id] = false;
this.selectedResponse = {}; this.selectedResponse = {};
// Show message // Show message
this.cannedResponseAPI.message = message; this.cannedResponseAPI.message = message;
bus.$emit('newToastMessage', message); this.showAlert(message);
}, },
// Edit Function // Edit Function
openAddPopup() { openAddPopup() {
@@ -230,12 +232,14 @@ export default {
this.$store this.$store
.dispatch('deleteCannedResponse', id) .dispatch('deleteCannedResponse', id)
.then(() => { .then(() => {
this.showAlert(this.$t('CANNED_MGMT.DELETE.API.SUCCESS_MESSAGE')); this.showAlertMessage(
this.$t('CANNED_MGMT.DELETE.API.SUCCESS_MESSAGE')
);
}) })
.catch(error => { .catch(error => {
const errorMessage = const errorMessage =
error?.message || this.$t('CANNED_MGMT.DELETE.API.ERROR_MESSAGE'); error?.message || this.$t('CANNED_MGMT.DELETE.API.ERROR_MESSAGE');
this.showAlert(errorMessage); this.showAlertMessage(errorMessage);
}); });
}, },
}, },

View File

@@ -51,11 +51,13 @@ import { mapGetters } from 'vuex';
import InboxMembersAPI from '../../../../api/inboxMembers'; import InboxMembersAPI from '../../../../api/inboxMembers';
import router from '../../../index'; import router from '../../../index';
import PageHeader from '../SettingsSubPageHeader.vue'; import PageHeader from '../SettingsSubPageHeader.vue';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { components: {
PageHeader, PageHeader,
}, },
mixins: [alertMixin],
validations: { validations: {
selectedAgents: { selectedAgents: {
@@ -98,7 +100,7 @@ export default {
}, },
}); });
} catch (error) { } catch (error) {
bus.$emit('newToastMessage', error.message); this.showAlert(error.message);
} }
this.isCreating = false; this.isCreating = false;
}, },

View File

@@ -136,12 +136,13 @@ import Settings from './Settings.vue';
import adminMixin from '../../../../mixins/isAdmin'; import adminMixin from '../../../../mixins/isAdmin';
import accountMixin from '../../../../mixins/account'; import accountMixin from '../../../../mixins/account';
import globalConfigMixin from 'shared/mixins/globalConfigMixin'; import globalConfigMixin from 'shared/mixins/globalConfigMixin';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { components: {
Settings, Settings,
}, },
mixins: [adminMixin, accountMixin, globalConfigMixin], mixins: [adminMixin, accountMixin, globalConfigMixin, alertMixin],
data() { data() {
return { return {
loading: {}, loading: {},
@@ -194,15 +195,9 @@ export default {
async deleteInbox({ id }) { async deleteInbox({ id }) {
try { try {
await this.$store.dispatch('inboxes/delete', id); await this.$store.dispatch('inboxes/delete', id);
bus.$emit( this.showAlert(this.$t('INBOX_MGMT.DELETE.API.SUCCESS_MESSAGE'));
'newToastMessage',
this.$t('INBOX_MGMT.DELETE.API.SUCCESS_MESSAGE')
);
} catch (error) { } catch (error) {
bus.$emit( this.showAlert(this.$t('INBOX_MGMT.DELETE.API.ERROR_MESSAGE'));
'newToastMessage',
this.$t('INBOX_MGMT.DELETE.API.ERROR_MESSAGE')
);
} }
}, },

View File

@@ -128,7 +128,7 @@ export default {
this.$store.dispatch('agents/get'); this.$store.dispatch('agents/get');
this.fetchAllData(); this.fetchAllData();
bus.$on('fetch_overview_reports', () => { this.$emitter.on('fetch_overview_reports', () => {
this.fetchAllData(); this.fetchAllData();
}); });
}, },

View File

@@ -6,6 +6,7 @@ import { findPendingMessageIndex } from './helpers';
import { MESSAGE_STATUS } from 'shared/constants/messages'; import { MESSAGE_STATUS } from 'shared/constants/messages';
import wootConstants from 'dashboard/constants/globals'; import wootConstants from 'dashboard/constants/globals';
import { BUS_EVENTS } from '../../../../shared/constants/busEvents'; import { BUS_EVENTS } from '../../../../shared/constants/busEvents';
import { emitter } from 'shared/helpers/mitt';
const state = { const state = {
allConversations: [], allConversations: [],
@@ -195,8 +196,8 @@ export const mutations = {
const { conversation: { unread_count: unreadCount = 0 } = {} } = message; const { conversation: { unread_count: unreadCount = 0 } = {} } = message;
chat.unread_count = unreadCount; chat.unread_count = unreadCount;
if (selectedChatId === conversationId) { if (selectedChatId === conversationId) {
window.bus.$emit(BUS_EVENTS.FETCH_LABEL_SUGGESTIONS); emitter.emit(BUS_EVENTS.FETCH_LABEL_SUGGESTIONS);
window.bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE); emitter.emit(BUS_EVENTS.SCROLL_TO_MESSAGE);
} }
} }
}, },
@@ -218,8 +219,8 @@ export const mutations = {
}; };
Vue.set(allConversations, currentConversationIndex, currentConversation); Vue.set(allConversations, currentConversationIndex, currentConversation);
if (_state.selectedChatId === conversation.id) { if (_state.selectedChatId === conversation.id) {
window.bus.$emit(BUS_EVENTS.FETCH_LABEL_SUGGESTIONS); emitter.emit(BUS_EVENTS.FETCH_LABEL_SUGGESTIONS);
window.bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE); emitter.emit(BUS_EVENTS.SCROLL_TO_MESSAGE);
} }
} else { } else {
_state.allConversations.push(conversation); _state.allConversations.push(conversation);

View File

@@ -1,6 +1,16 @@
import types from '../../../mutation-types'; import types from '../../../mutation-types';
import { mutations } from '../../conversations'; import { mutations } from '../../conversations';
jest.mock('shared/helpers/mitt', () => ({
emitter: {
emit: jest.fn(),
on: jest.fn(),
off: jest.fn(),
},
}));
import { emitter } from 'shared/helpers/mitt';
describe('#mutations', () => { describe('#mutations', () => {
describe('#EMPTY_ALL_CONVERSATION', () => { describe('#EMPTY_ALL_CONVERSATION', () => {
it('empty conversations', () => { it('empty conversations', () => {
@@ -130,7 +140,7 @@ describe('#mutations', () => {
timestamp: 1602256198, timestamp: 1602256198,
}, },
]); ]);
expect(global.bus.$emit).not.toHaveBeenCalled(); expect(emitter.emit).not.toHaveBeenCalled();
}); });
it('add message to the conversation and emit scrollToMessage if it does not exist in the store', () => { it('add message to the conversation and emit scrollToMessage if it does not exist in the store', () => {
@@ -158,7 +168,7 @@ describe('#mutations', () => {
timestamp: 1602256198, timestamp: 1602256198,
}, },
]); ]);
expect(global.bus.$emit).toHaveBeenCalledWith('SCROLL_TO_MESSAGE'); expect(emitter.emit).toHaveBeenCalledWith('SCROLL_TO_MESSAGE');
}); });
it('update message if it exist in the store', () => { it('update message if it exist in the store', () => {
@@ -195,7 +205,7 @@ describe('#mutations', () => {
], ],
}, },
]); ]);
expect(global.bus.$emit).not.toHaveBeenCalled(); expect(emitter.emit).not.toHaveBeenCalled();
}); });
}); });

View File

@@ -9,6 +9,7 @@ import {
} from '../../helper/scriptHelpers'; } from '../../helper/scriptHelpers';
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage'; import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
import { LocalStorage } from 'shared/helpers/localStorage'; import { LocalStorage } from 'shared/helpers/localStorage';
import { emitter } from 'shared/helpers/mitt';
Cookies.defaults = { sameSite: 'Lax' }; Cookies.defaults = { sameSite: 'Lax' };
@@ -18,8 +19,8 @@ export const setLoadingStatus = (state, status) => {
}; };
export const setUser = user => { export const setUser = user => {
window.bus.$emit(CHATWOOT_SET_USER, { user }); emitter.emit(CHATWOOT_SET_USER, { user });
window.bus.$emit(ANALYTICS_IDENTITY, { user }); emitter.emit(ANALYTICS_IDENTITY, { user });
}; };
export const getHeaderExpiry = response => export const getHeaderExpiry = response =>
@@ -70,8 +71,8 @@ export const deleteIndexedDBOnLogout = async () => {
}; };
export const clearCookiesOnLogout = () => { export const clearCookiesOnLogout = () => {
window.bus.$emit(CHATWOOT_RESET); emitter.emit(CHATWOOT_RESET);
window.bus.$emit(ANALYTICS_RESET); emitter.emit(ANALYTICS_RESET);
clearBrowserSessionCookies(); clearBrowserSessionCookies();
clearLocalStorageOnLogout(); clearLocalStorageOnLogout();
const globalConfig = window.globalConfig || {}; const globalConfig = window.globalConfig || {};

View File

@@ -15,6 +15,8 @@ import WootUiKit from '../dashboard/components';
import App from '../dashboard/App'; import App from '../dashboard/App';
import i18n from '../dashboard/i18n'; import i18n from '../dashboard/i18n';
import createAxios from '../dashboard/helper/APIHelper'; import createAxios from '../dashboard/helper/APIHelper';
import { emitter } from '../shared/helpers/mitt';
import commonHelpers, { isJSONValid } from '../dashboard/helper/commons'; import commonHelpers, { isJSONValid } from '../dashboard/helper/commons';
import router, { initalizeRouter } from '../dashboard/routes'; import router, { initalizeRouter } from '../dashboard/routes';
import store from '../dashboard/store'; import store from '../dashboard/store';
@@ -93,7 +95,8 @@ commonHelpers();
window.WootConstants = constants; window.WootConstants = constants;
window.axios = createAxios(axios); window.axios = createAxios(axios);
window.bus = new Vue(); Vue.prototype.$emitter = emitter;
initializeChatwootEvents(); initializeChatwootEvents();
initializeAnalyticsEvents(); initializeAnalyticsEvents();
initalizeRouter(); initalizeRouter();

View File

@@ -4,6 +4,7 @@ import VueI18n from 'vue-i18n';
import App from '../survey/App.vue'; import App from '../survey/App.vue';
import i18n from '../survey/i18n'; import i18n from '../survey/i18n';
import store from '../survey/store'; import store from '../survey/store';
import { emitter } from 'shared/helpers/mitt';
Vue.use(VueI18n); Vue.use(VueI18n);
Vue.use(Vuelidate); Vue.use(Vuelidate);
@@ -14,7 +15,7 @@ const i18nConfig = new VueI18n({
}); });
// Event Bus // Event Bus
window.bus = new Vue(); Vue.prototype.$emitter = emitter;
Vue.config.productionTip = false; Vue.config.productionTip = false;

View File

@@ -13,7 +13,7 @@ import {
} from 'shared/helpers/Validators'; } from 'shared/helpers/Validators';
import router from '../widget/router'; import router from '../widget/router';
import { directive as onClickaway } from 'vue-clickaway'; import { directive as onClickaway } from 'vue-clickaway';
import { emitter } from 'shared/helpers/mitt';
import { domPurifyConfig } from '../shared/helpers/HTMLSanitizer'; import { domPurifyConfig } from '../shared/helpers/HTMLSanitizer';
const PhoneInput = () => import('../widget/components/Form/PhoneInput'); const PhoneInput = () => import('../widget/components/Form/PhoneInput');
@@ -46,7 +46,7 @@ Vue.use(VueFormulate, {
}, },
}); });
// Event Bus // Event Bus
window.bus = new Vue(); Vue.prototype.$emitter = emitter;
Vue.config.productionTip = false; Vue.config.productionTip = false;

View File

@@ -1,5 +1,6 @@
import { createConsumer } from '@rails/actioncable'; import { createConsumer } from '@rails/actioncable';
import { BUS_EVENTS } from 'shared/constants/busEvents'; import { BUS_EVENTS } from 'shared/constants/busEvents';
import { emitter } from 'shared/helpers/mitt';
const PRESENCE_INTERVAL = 20000; const PRESENCE_INTERVAL = 20000;
const RECONNECT_INTERVAL = 1000; const RECONNECT_INTERVAL = 1000;
@@ -28,7 +29,7 @@ class BaseActionCableConnector {
this.onDisconnected(); this.onDisconnected();
this.initReconnectTimer(); this.initReconnectTimer();
// TODO: Remove this after completing the conversation list refetching // TODO: Remove this after completing the conversation list refetching
window.bus.$emit(BUS_EVENTS.WEBSOCKET_DISCONNECT); emitter.emit(BUS_EVENTS.WEBSOCKET_DISCONNECT);
}, },
} }
); );

View File

@@ -0,0 +1,3 @@
import mitt from 'mitt';
const emitter = mitt();
export { emitter };

View File

@@ -0,0 +1,25 @@
import { emitter } from '../mitt';
describe('emitter', () => {
it('should emit and listen to events correctly', () => {
const mockCallback = jest.fn();
// Subscribe to an event
emitter.on('event', mockCallback);
// Emit the event
emitter.emit('event', 'data');
// Expect the callback to be called with the correct data
expect(mockCallback).toHaveBeenCalledWith('data');
// Unsubscribe from the event
emitter.off('event', mockCallback);
// Emit the event again
emitter.emit('event', 'data');
// Expect the callback not to be called again
expect(mockCallback).toHaveBeenCalledTimes(1);
});
});

View File

@@ -1,7 +1,9 @@
import { emitter } from 'shared/helpers/mitt';
export default { export default {
methods: { methods: {
showAlert(message, action) { showAlert(message, action) {
bus.$emit('newToastMessage', message, action); emitter.emit('newToastMessage', message, action);
}, },
}, },
}; };

View File

@@ -53,12 +53,14 @@ import FormInput from '../../../components/Form/Input.vue';
import SubmitButton from '../../../components/Button/SubmitButton.vue'; import SubmitButton from '../../../components/Button/SubmitButton.vue';
import { DEFAULT_REDIRECT_URL } from 'dashboard/constants/globals'; import { DEFAULT_REDIRECT_URL } from 'dashboard/constants/globals';
import { setNewPassword } from '../../../api/auth'; import { setNewPassword } from '../../../api/auth';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { components: {
FormInput, FormInput,
SubmitButton, SubmitButton,
}, },
mixins: [alertMixin],
props: { props: {
resetPasswordToken: { type: String, default: '' }, resetPasswordToken: { type: String, default: '' },
redirectUrl: { type: String, default: '' }, redirectUrl: { type: String, default: '' },
@@ -105,10 +107,10 @@ export default {
}, },
}, },
methods: { methods: {
showAlert(message) { showAlertMessage(message) {
// Reset loading, current selected agent // Reset loading, current selected agent
this.newPasswordAPI.showLoading = false; this.newPasswordAPI.showLoading = false;
bus.$emit('newToastMessage', message); this.showAlert(message);
}, },
submitForm() { submitForm() {
this.newPasswordAPI.showLoading = true; this.newPasswordAPI.showLoading = true;
@@ -122,7 +124,7 @@ export default {
window.location = DEFAULT_REDIRECT_URL; window.location = DEFAULT_REDIRECT_URL;
}) })
.catch(error => { .catch(error => {
this.showAlert( this.showAlertMessage(
error?.message || this.$t('SET_NEW_PASSWORD.API.ERROR_MESSAGE') error?.message || this.$t('SET_NEW_PASSWORD.API.ERROR_MESSAGE')
); );
}); });

View File

@@ -53,10 +53,11 @@ import { mapGetters } from 'vuex';
import FormInput from '../../../../components/Form/Input.vue'; import FormInput from '../../../../components/Form/Input.vue';
import { resetPassword } from '../../../../api/auth'; import { resetPassword } from '../../../../api/auth';
import SubmitButton from '../../../../components/Button/SubmitButton.vue'; import SubmitButton from '../../../../components/Button/SubmitButton.vue';
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { FormInput, SubmitButton }, components: { FormInput, SubmitButton },
mixins: [globalConfigMixin], mixins: [globalConfigMixin, alertMixin],
data() { data() {
return { return {
credentials: { email: '' }, credentials: { email: '' },
@@ -80,10 +81,10 @@ export default {
}, },
}, },
methods: { methods: {
showAlert(message) { showAlertMessage(message) {
// Reset loading, current selected agent // Reset loading, current selected agent
this.resetPassword.showLoading = false; this.resetPassword.showLoading = false;
bus.$emit('newToastMessage', message); this.showAlert(message);
}, },
submit() { submit() {
this.resetPassword.showLoading = true; this.resetPassword.showLoading = true;
@@ -93,7 +94,7 @@ export default {
if (res.data && res.data.message) { if (res.data && res.data.message) {
successMessage = res.data.message; successMessage = res.data.message;
} }
this.showAlert(successMessage); this.showAlertMessage(successMessage);
}) })
.catch(error => { .catch(error => {
let errorMessage = this.$t('RESET_PASSWORD.API.ERROR_MESSAGE'); let errorMessage = this.$t('RESET_PASSWORD.API.ERROR_MESSAGE');

View File

@@ -104,6 +104,7 @@ const ERROR_MESSAGES = {
'no-account-found': 'LOGIN.OAUTH.NO_ACCOUNT_FOUND', 'no-account-found': 'LOGIN.OAUTH.NO_ACCOUNT_FOUND',
'business-account-only': 'LOGIN.OAUTH.BUSINESS_ACCOUNTS_ONLY', 'business-account-only': 'LOGIN.OAUTH.BUSINESS_ACCOUNTS_ONLY',
}; };
import alertMixin from 'shared/mixins/alertMixin';
export default { export default {
components: { components: {
@@ -112,7 +113,7 @@ export default {
Spinner, Spinner,
SubmitButton, SubmitButton,
}, },
mixins: [globalConfigMixin], mixins: [globalConfigMixin, alertMixin],
props: { props: {
ssoAuthToken: { type: String, default: '' }, ssoAuthToken: { type: String, default: '' },
ssoAccountId: { type: String, default: '' }, ssoAccountId: { type: String, default: '' },
@@ -186,15 +187,15 @@ export default {
setTimeout(callback, 0); setTimeout(callback, 0);
} }
}, },
showAlert(message) { showAlertMessage(message) {
// Reset loading, current selected agent // Reset loading, current selected agent
this.loginApi.showLoading = false; this.loginApi.showLoading = false;
this.loginApi.message = message; this.loginApi.message = message;
bus.$emit('newToastMessage', this.loginApi.message); this.showAlert(this.loginApi.message);
}, },
submitLogin() { submitLogin() {
if (this.$v.credentials.email.$invalid && !this.email) { if (this.$v.credentials.email.$invalid && !this.email) {
this.showAlert(this.$t('LOGIN.EMAIL.ERROR')); this.showAlertMessage(this.$t('LOGIN.EMAIL.ERROR'));
return; return;
} }

View File

@@ -43,6 +43,7 @@ import {
} from './constants/widgetBusEvents'; } from './constants/widgetBusEvents';
import darkModeMixin from 'widget/mixins/darkModeMixin'; import darkModeMixin from 'widget/mixins/darkModeMixin';
import { SDK_SET_BUBBLE_VISIBILITY } from '../shared/constants/sharedFrameEvents'; import { SDK_SET_BUBBLE_VISIBILITY } from '../shared/constants/sharedFrameEvents';
import { emitter } from 'shared/helpers/mitt';
export default { export default {
name: 'App', name: 'App',
@@ -157,34 +158,36 @@ export default {
} }
}, },
registerUnreadEvents() { registerUnreadEvents() {
bus.$on(ON_AGENT_MESSAGE_RECEIVED, () => { emitter.on(ON_AGENT_MESSAGE_RECEIVED, () => {
const { name: routeName } = this.$route; const { name: routeName } = this.$route;
if ((this.isWidgetOpen || !this.isIFrame) && routeName === 'messages') { if ((this.isWidgetOpen || !this.isIFrame) && routeName === 'messages') {
this.$store.dispatch('conversation/setUserLastSeen'); this.$store.dispatch('conversation/setUserLastSeen');
} }
this.setUnreadView(); this.setUnreadView();
}); });
bus.$on(ON_UNREAD_MESSAGE_CLICK, () => { emitter.on(ON_UNREAD_MESSAGE_CLICK, () => {
this.replaceRoute('messages').then(() => this.unsetUnreadView()); this.replaceRoute('messages').then(() => this.unsetUnreadView());
}); });
}, },
registerCampaignEvents() { registerCampaignEvents() {
bus.$on(ON_CAMPAIGN_MESSAGE_CLICK, () => { emitter.on(ON_CAMPAIGN_MESSAGE_CLICK, () => {
if (this.shouldShowPreChatForm) { if (this.shouldShowPreChatForm) {
this.replaceRoute('prechat-form'); this.replaceRoute('prechat-form');
} else { } else {
this.replaceRoute('messages'); this.replaceRoute('messages');
bus.$emit('execute-campaign', { campaignId: this.activeCampaign.id }); emitter.emit('execute-campaign', {
campaignId: this.activeCampaign.id,
});
} }
this.unsetUnreadView(); this.unsetUnreadView();
}); });
bus.$on('execute-campaign', campaignDetails => { emitter.on('execute-campaign', campaignDetails => {
const { customAttributes, campaignId } = campaignDetails; const { customAttributes, campaignId } = campaignDetails;
const { websiteToken } = window.chatwootWebChannel; const { websiteToken } = window.chatwootWebChannel;
this.executeCampaign({ campaignId, websiteToken, customAttributes }); this.executeCampaign({ campaignId, websiteToken, customAttributes });
this.replaceRoute('messages'); this.replaceRoute('messages');
}); });
bus.$on('snooze-campaigns', () => { emitter.on('snooze-campaigns', () => {
const expireBy = addHours(new Date(), 1); const expireBy = addHours(new Date(), 1);
this.campaignsSnoozedTill = Number(expireBy); this.campaignsSnoozedTill = Number(expireBy);
}); });

View File

@@ -93,6 +93,7 @@ import { isASubmittedFormMessage } from 'shared/helpers/MessageTypeHelper';
import darkModeMixin from 'widget/mixins/darkModeMixin.js'; import darkModeMixin from 'widget/mixins/darkModeMixin.js';
import ReplyToChip from 'widget/components/ReplyToChip.vue'; import ReplyToChip from 'widget/components/ReplyToChip.vue';
import { BUS_EVENTS } from 'shared/constants/busEvents'; import { BUS_EVENTS } from 'shared/constants/busEvents';
import { emitter } from 'shared/helpers/mitt';
export default { export default {
name: 'AgentMessage', name: 'AgentMessage',
@@ -224,7 +225,7 @@ export default {
this.hasImageError = true; this.hasImageError = true;
}, },
toggleReply() { toggleReply() {
bus.$emit(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE, this.message); emitter.emit(BUS_EVENTS.TOGGLE_REPLY_TO_MESSAGE, this.message);
}, },
}, },
}; };

View File

@@ -8,6 +8,7 @@
<script> <script>
import { BUS_EVENTS } from 'shared/constants/busEvents'; import { BUS_EVENTS } from 'shared/constants/busEvents';
import { emitter } from 'shared/helpers/mitt';
export default { export default {
data() { data() {
@@ -18,7 +19,7 @@ export default {
}; };
}, },
mounted() { mounted() {
bus.$on(BUS_EVENTS.SHOW_ALERT, ({ message, type = 'error' }) => { emitter.on(BUS_EVENTS.SHOW_ALERT, ({ message, type = 'error' }) => {
this.bannerMessage = message; this.bannerMessage = message;
this.bannerType = type; this.bannerType = type;
this.showBannerMessage = true; this.showBannerMessage = true;

View File

@@ -96,7 +96,7 @@ export default {
upload.create((error, blob) => { upload.create((error, blob) => {
if (error) { if (error) {
window.bus.$emit(BUS_EVENTS.SHOW_ALERT, { this.$emitter.emit(BUS_EVENTS.SHOW_ALERT, {
message: error, message: error,
}); });
} else { } else {
@@ -107,7 +107,7 @@ export default {
} }
}); });
} else { } else {
window.bus.$emit(BUS_EVENTS.SHOW_ALERT, { this.$emitter.emit(BUS_EVENTS.SHOW_ALERT, {
message: this.$t('FILE_SIZE_LIMIT', { message: this.$t('FILE_SIZE_LIMIT', {
MAXIMUM_FILE_UPLOAD_SIZE: this.fileUploadSizeLimit, MAXIMUM_FILE_UPLOAD_SIZE: this.fileUploadSizeLimit,
}), }),
@@ -130,7 +130,7 @@ export default {
...this.getLocalFileAttributes(file), ...this.getLocalFileAttributes(file),
}); });
} else { } else {
window.bus.$emit(BUS_EVENTS.SHOW_ALERT, { this.$emitter.emit(BUS_EVENTS.SHOW_ALERT, {
message: this.$t('FILE_SIZE_LIMIT', { message: this.$t('FILE_SIZE_LIMIT', {
MAXIMUM_FILE_UPLOAD_SIZE: this.fileUploadSizeLimit, MAXIMUM_FILE_UPLOAD_SIZE: this.fileUploadSizeLimit,
}), }),

View File

@@ -147,12 +147,12 @@ export default {
if (this.hasEmail) { if (this.hasEmail) {
try { try {
await sendEmailTranscript(); await sendEmailTranscript();
window.bus.$emit(BUS_EVENTS.SHOW_ALERT, { this.$emitter.emit(BUS_EVENTS.SHOW_ALERT, {
message: this.$t('EMAIL_TRANSCRIPT.SEND_EMAIL_SUCCESS'), message: this.$t('EMAIL_TRANSCRIPT.SEND_EMAIL_SUCCESS'),
type: 'success', type: 'success',
}); });
} catch (error) { } catch (error) {
window.bus.$emit(BUS_EVENTS.SHOW_ALERT, { this.$emitter.$emit(BUS_EVENTS.SHOW_ALERT, {
message: this.$t('EMAIL_TRANSCRIPT.SEND_EMAIL_ERROR'), message: this.$t('EMAIL_TRANSCRIPT.SEND_EMAIL_ERROR'),
}); });
} }

View File

@@ -4,6 +4,7 @@ import { ON_AGENT_MESSAGE_RECEIVED } from '../constants/widgetBusEvents';
import { IFrameHelper } from 'widget/helpers/utils'; import { IFrameHelper } from 'widget/helpers/utils';
import { shouldTriggerMessageUpdateEvent } from './IframeEventHelper'; import { shouldTriggerMessageUpdateEvent } from './IframeEventHelper';
import { CHATWOOT_ON_MESSAGE } from '../constants/sdkEvents'; import { CHATWOOT_ON_MESSAGE } from '../constants/sdkEvents';
import { emitter } from '../../shared/helpers/mitt';
const isMessageInActiveConversation = (getters, message) => { const isMessageInActiveConversation = (getters, message) => {
const { conversation_id: conversationId } = message; const { conversation_id: conversationId } = message;
@@ -57,7 +58,7 @@ class ActionCableConnector extends BaseActionCableConnector {
this.app.$store this.app.$store
.dispatch('conversation/addOrUpdateMessage', data) .dispatch('conversation/addOrUpdateMessage', data)
.then(() => window.bus.$emit(ON_AGENT_MESSAGE_RECEIVED)); .then(() => emitter.emit(ON_AGENT_MESSAGE_RECEIVED));
IFrameHelper.sendMessage({ IFrameHelper.sendMessage({
event: 'onEvent', event: 'onEvent',

View File

@@ -31,6 +31,7 @@
], ],
"dependencies": { "dependencies": {
"@braid/vue-formulate": "^2.5.2", "@braid/vue-formulate": "^2.5.2",
"@chatwoot/ninja-keys": "1.2.3",
"@chatwoot/prosemirror-schema": "1.0.9", "@chatwoot/prosemirror-schema": "1.0.9",
"@chatwoot/utils": "^0.0.25", "@chatwoot/utils": "^0.0.25",
"@hcaptcha/vue-hcaptcha": "^0.3.2", "@hcaptcha/vue-hcaptcha": "^0.3.2",
@@ -67,7 +68,7 @@
"markdown-it": "^13.0.2", "markdown-it": "^13.0.2",
"markdown-it-link-attributes": "^4.0.1", "markdown-it-link-attributes": "^4.0.1",
"md5": "^2.3.0", "md5": "^2.3.0",
"@chatwoot/ninja-keys": "1.2.3", "mitt": "^3.0.1",
"opus-recorder": "^8.0.5", "opus-recorder": "^8.0.5",
"postcss": "^8.4.31", "postcss": "^8.4.31",
"postcss-loader": "^4.2.0", "postcss-loader": "^4.2.0",

View File

@@ -14929,6 +14929,11 @@ mississippi@^3.0.0:
stream-each "^1.1.0" stream-each "^1.1.0"
through2 "^2.0.0" through2 "^2.0.0"
mitt@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/mitt/-/mitt-3.0.1.tgz#ea36cf0cc30403601ae074c8f77b7092cdab36d1"
integrity sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==
mixin-deep@^1.2.0: mixin-deep@^1.2.0:
version "1.3.2" version "1.3.2"
resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566"