feat: Adds support for draft in conversation reply box (#4205)

* Add draft support

* Fixes issue with draft loading

* Adds draft for private notes

* Use localstorage helper

* .remove instead of .clear

* Remove timestamp

* clearLocalStorageOnLogout

* Fix draft save on refresh

* Remove usage of delete operator

* Adds autosave for draft messages

* Remove setinterval and add debounce

* Removes draft redundancy check

* Adds test cases for debouncer

* Update app/javascript/shared/helpers/specs/TimeHelpers.spec.js

Co-authored-by: Nithin David Thomas <1277421+nithindavid@users.noreply.github.com>

* Update app/javascript/shared/helpers/specs/TimeHelpers.spec.js

Co-authored-by: Nithin David Thomas <1277421+nithindavid@users.noreply.github.com>

* Review fixes

* Fixes issue with debouncer

* FIxes debouncer issue

* Fixes issue with draft empty message

* Removes empty keys from local storage drafts

* Fixes error with empty draft

Co-authored-by: Pranav Raj S <pranav@chatwoot.com>
Co-authored-by: Fayaz Ahmed <15716057+fayazara@users.noreply.github.com>
Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
Co-authored-by: iamsivin <iamsivin@gmail.com>
This commit is contained in:
Nithin David Thomas
2022-04-07 22:16:45 +05:30
committed by GitHub
parent dfb56f6bb8
commit 5ea0436051
10 changed files with 202 additions and 24 deletions

View File

@@ -12,12 +12,11 @@
</template>
<script>
import Banner from 'dashboard/components/ui/Banner.vue';
import LocalStorage from '../../helper/localStorage';
import { LocalStorage, LOCAL_STORAGE_KEYS } from '../../helper/localStorage';
import { mapGetters } from 'vuex';
import adminMixin from 'dashboard/mixins/isAdmin';
const semver = require('semver');
const dismissedUpdates = new LocalStorage('dismissedUpdates');
export default {
components: {
@@ -57,16 +56,22 @@ export default {
},
methods: {
isVersionNotificationDismissed(version) {
return dismissedUpdates.get().includes(version);
const dismissedVersions =
LocalStorage.get(LOCAL_STORAGE_KEYS.DISMISSED_UPDATES) || [];
return dismissedVersions.includes(version);
},
dismissUpdateBanner() {
let updatedDismissedItems = dismissedUpdates.get();
let updatedDismissedItems =
LocalStorage.get(LOCAL_STORAGE_KEYS.DISMISSED_UPDATES) || [];
if (updatedDismissedItems instanceof Array) {
updatedDismissedItems.push(this.latestChatwootVersion);
} else {
updatedDismissedItems = [this.latestChatwootVersion];
}
dismissedUpdates.store(updatedDismissedItems);
LocalStorage.set(
LOCAL_STORAGE_KEYS.DISMISSED_UPDATES,
updatedDismissedItems
);
this.latestChatwootVersion = this.globalConfig.appVersion;
},
},

View File

@@ -148,8 +148,8 @@ export default {
showCannedMenu(updatedValue) {
this.$emit('toggle-canned-menu', !this.isPrivate && updatedValue);
},
value(newValue = '') {
if (newValue !== this.lastValue) {
value(newValue = '', oldValue = '') {
if (newValue !== oldValue) {
const { tr } = this.state;
if (this.isFormatMode) {
this.state = createState(

View File

@@ -137,6 +137,7 @@ import messageFormatterMixin from 'shared/mixins/messageFormatterMixin';
import { checkFileSizeLimit } from 'shared/helpers/FileHelper';
import { MAXIMUM_FILE_UPLOAD_SIZE } from 'shared/constants/messages';
import { BUS_EVENTS } from 'shared/constants/busEvents';
import { debounce } from 'shared/helpers/TimeHelpers';
import {
isEscape,
@@ -149,6 +150,8 @@ import inboxMixin from 'shared/mixins/inboxMixin';
import uiSettingsMixin from 'dashboard/mixins/uiSettings';
import { DirectUpload } from 'activestorage';
import { frontendURL } from '../../../helper/URLHelper';
import { LocalStorage, LOCAL_STORAGE_KEYS } from '../../../helper/localStorage';
import { trimMessage } from '../../../store/modules/conversations/helpers';
export default {
components: {
@@ -201,6 +204,7 @@ export default {
hasSlashCommand: false,
bccEmails: '',
ccEmails: '',
doAutoSaveDraft: () => {},
};
},
computed: {
@@ -406,10 +410,19 @@ export default {
profilePath() {
return frontendURL(`accounts/${this.accountId}/profile/settings`);
},
conversationId() {
return this.currentChat.id;
},
},
watch: {
currentChat(conversation) {
currentChat(conversation, oldConversation) {
const { can_reply: canReply } = conversation;
if (oldConversation.id !== conversation.id) {
this.setToDraft(oldConversation.id, this.replyType);
this.getFromDraft();
}
if (this.isOnPrivateNote) {
return;
}
@@ -434,22 +447,87 @@ export default {
this.mentionSearchKey = '';
this.showMentions = false;
}
this.doAutoSaveDraft();
},
replyType(updatedReplyType, oldReplyType) {
this.setToDraft(this.conversationId, oldReplyType);
this.getFromDraft();
},
},
mounted() {
this.getFromDraft();
// Donot use the keyboard listener mixin here as the events here are supposed to be
// working even if input/textarea is focussed.
document.addEventListener('keydown', this.handleKeyEvents);
document.addEventListener('paste', this.onPaste);
this.setCCEmailFromLastChat();
this.doAutoSaveDraft = debounce(
() => {
this.saveDraft(this.conversationId, this.replyType);
},
5000,
false
);
},
destroyed() {
document.removeEventListener('keydown', this.handleKeyEvents);
document.removeEventListener('paste', this.onPaste);
},
methods: {
getSavedDraftMessages() {
return LocalStorage.get(LOCAL_STORAGE_KEYS.DRAFT_MESSAGES) || {};
},
saveDraft(conversationId, replyType) {
if (this.message || this.message === '') {
const savedDraftMessages = this.getSavedDraftMessages();
const key = `draft-${conversationId}-${replyType}`;
const draftToSave = trimMessage(this.message || '');
const {
[key]: currentDraft,
...restOfDraftMessages
} = savedDraftMessages;
const updatedDraftMessages = draftToSave
? {
...restOfDraftMessages,
[key]: draftToSave,
}
: restOfDraftMessages;
LocalStorage.set(
LOCAL_STORAGE_KEYS.DRAFT_MESSAGES,
updatedDraftMessages
);
}
},
setToDraft(conversationId, replyType) {
this.saveDraft(conversationId, replyType);
this.message = '';
},
getFromDraft() {
if (this.conversationId) {
try {
const key = `draft-${this.conversationId}-${this.replyType}`;
const savedDraftMessages = this.getSavedDraftMessages();
this.message = `${savedDraftMessages[key] || ''}`;
} catch (error) {
this.message = '';
}
}
},
removeFromDraft() {
if (this.conversationId) {
const key = `draft-${this.conversationId}-${this.replyType}`;
const draftMessages = this.getSavedDraftMessages();
const { [key]: toBeRemoved, ...updatedDraftMessages } = draftMessages;
LocalStorage.set(
LOCAL_STORAGE_KEYS.DRAFT_MESSAGES,
updatedDraftMessages
);
}
},
onPaste(e) {
const data = e.clipboardData.files;
if (!this.showRichContentEditor && data.length !== 0) {
@@ -537,6 +615,7 @@ export default {
messagePayload
);
bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE);
this.removeFromDraft();
} catch (error) {
const errorMessage =
error?.response?.data?.error ||
@@ -608,6 +687,7 @@ export default {
},
onBlur() {
this.isFocused = false;
this.saveDraft(this.conversationId, this.replyType);
},
onFocus() {
this.isFocused = true;

View File

@@ -1,17 +1,32 @@
class LocalStorage {
constructor(key) {
this.key = key;
}
export const LOCAL_STORAGE_KEYS = {
DISMISSED_UPDATES: 'dismissedUpdates',
DRAFT_MESSAGES: 'draftMessages',
};
store(allItems) {
localStorage.setItem(this.key, JSON.stringify(allItems));
localStorage.setItem(this.key + ':ts', Date.now());
}
export const LocalStorage = {
clearAll() {
window.localStorage.clear();
},
get() {
let stored = localStorage.getItem(this.key);
return JSON.parse(stored) || [];
}
}
get(key) {
const value = window.localStorage.getItem(key);
try {
return typeof value === 'string' ? JSON.parse(value) : value;
} catch (error) {
return value;
}
},
set(key, value) {
if (typeof value === 'object') {
window.localStorage.setItem(key, JSON.stringify(value));
} else {
window.localStorage.setItem(key, value);
}
window.localStorage.setItem(key + ':ts', Date.now());
},
export default LocalStorage;
remove(key) {
window.localStorage.removeItem(key);
window.localStorage.removeItem(key + ':ts');
},
};

View File

@@ -5,7 +5,12 @@ import * as types from '../mutation-types';
import authAPI from '../../api/auth';
import createAxios from '../../helper/APIHelper';
import actionCable from '../../helper/actionCable';
import { setUser, getHeaderExpiry, clearCookiesOnLogout } from '../utils/api';
import {
setUser,
getHeaderExpiry,
clearCookiesOnLogout,
clearLocalStorageOnLogout,
} from '../utils/api';
import { getLoginRedirectURL } from '../../helper/URLHelper';
const state = {
@@ -94,9 +99,9 @@ export const actions = {
.login(credentials)
.then(response => {
commit(types.default.SET_CURRENT_USER);
clearLocalStorageOnLogout();
window.axios = createAxios(axios);
actionCable.init(Vue);
window.location = getLoginRedirectURL(ssoAccountId, response.data);
resolve();
})

View File

@@ -35,3 +35,10 @@ export const applyPageFilters = (conversation, filters) => {
return shouldFilter;
};
export const trimMessage = (content = '', maxLength = 1024) => {
if (content.length > maxLength) {
return content.substring(0, maxLength);
}
return content;
};

View File

@@ -1,6 +1,7 @@
import {
findPendingMessageIndex,
applyPageFilters,
trimMessage,
} from '../../conversations/helpers';
const conversationList = [
@@ -119,3 +120,9 @@ describe('#applyPageFilters', () => {
});
});
});
describe('#trimMessage', () => {
expect(trimMessage('Hello world', 5)).toEqual('Hello');
expect(trimMessage('Hello', 5)).toEqual('Hello');
expect(trimMessage(undefined, 5)).toEqual('');
});

View File

@@ -9,6 +9,7 @@ import {
CHATWOOT_RESET,
CHATWOOT_SET_USER,
} from '../../helper/scriptHelpers';
import { LocalStorage, LOCAL_STORAGE_KEYS } from '../../helper/localStorage';
Cookies.defaults = { sameSite: 'Lax' };
@@ -43,10 +44,15 @@ export const clearBrowserSessionCookies = () => {
Cookies.remove('user');
};
export const clearLocalStorageOnLogout = () => {
LocalStorage.remove(LOCAL_STORAGE_KEYS.DRAFT_MESSAGES);
};
export const clearCookiesOnLogout = () => {
window.bus.$emit(CHATWOOT_RESET);
window.bus.$emit(ANALYTICS_RESET);
clearBrowserSessionCookies();
clearLocalStorageOnLogout();
const globalConfig = window.globalConfig || {};
const logoutRedirectLink =
globalConfig.LOGOUT_REDIRECT_LINK || frontendURL('login');

View File

@@ -0,0 +1,21 @@
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
export const debounce = (func, delay, immediate) => {
let timerId;
return (...args) => {
const boundFunc = func.bind(this, ...args);
clearTimeout(timerId);
if (immediate && !timerId) {
boundFunc();
}
const calleeFunc = immediate
? () => {
timerId = null;
}
: boundFunc;
timerId = setTimeout(calleeFunc, delay);
};
};

View File

@@ -0,0 +1,32 @@
import { debounce } from '../TimeHelpers';
// Tell Jest to mock all timeout functions
jest.useFakeTimers('modern');
describe('debounce', () => {
test('execute just once with immediate false', () => {
let func = jest.fn();
let debouncedFunc = debounce(func, 1000);
for (let i = 0; i < 100; i += 1) {
debouncedFunc();
}
// Fast-forward time
jest.runAllTimers();
expect(func).toBeCalledTimes(1);
});
test('execute just once with immediate true', () => {
let func = jest.fn();
let debouncedFunc = debounce(func, 1000, true);
for (let i = 0; i < 100; i += 1) {
debouncedFunc();
}
jest.runAllTimers();
expect(func).toBeCalledTimes(1);
});
});