Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue with link added #43

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions __tests__/components/AppBase/index.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { fireEvent, screen, waitFor } from '@testing-library/react';
import { act } from 'react-dom/test-utils';
import mockio, { serverSocket, cleanup, io } from 'socket.io-client';
import { initialConfig, history as defaultHistory, historyWithLink, historyWithEmailIntent, historyWithPaymentIntent, pd, streamedMessage, streamedMessageWithLink, streamedMessageWithEmailIntent, streamedMessageWithPaymentIntent } from '@/chatMocks';
import { CHAT_SEEN_KEY, STORING_CHECKER_INTERVAL } from '@/config/env';
import { CHAT_SEEN_KEY, LINK_CLICKED_KEY, STORING_CHECKER_INTERVAL } from '@/config/env';
import { intent } from '@/main';
import initialState from '@/store/initialState';

Expand Down Expand Up @@ -88,7 +88,7 @@ describe('AppBase, chat-history event and execute properly', () => {

// Assert
const { chat } = root.store.getState();
expect(localStorage.getItem(CHAT_SEEN_KEY)).toBeTruthy();
expect(localStorage.getItem(LINK_CLICKED_KEY)).toBeTruthy();
expect(document.querySelector).toHaveBeenCalledWith('#chatbot-container');
expect(nodeElem.remove).toHaveBeenCalled();
expect(chat.closed).toBeTruthy();
Expand Down
3 changes: 2 additions & 1 deletion __tests__/components/Layout/base.spec.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-env jest */
import { render } from '@testing-library/react';
import { useAppSelector, useWindowSize } from '@/hooks';
import { useAppDispatch, useAppSelector, useWindowSize } from '@/hooks';
import { LayoutBase } from '@/components/Layout';

const original = console.error;
Expand All @@ -10,6 +10,7 @@ describe('LayoutBase Component', () => {
beforeEach(() => {
jest.clearAllMocks();
console.error = jest.fn();
useAppDispatch.mockReturnValue(() => jest.fn());
useAppSelector.mockReturnValue({ themeId: 'light' });
useWindowSize.mockReturnValue([150, 150]);
});
Expand Down
3,270 changes: 1,638 additions & 1,632 deletions dist/index.es.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.es.js.map

Large diffs are not rendered by default.

24 changes: 12 additions & 12 deletions dist/index.umd.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.umd.js.map

Large diffs are not rendered by default.

9 changes: 4 additions & 5 deletions src/components/Layout/foot.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { track } from '@/services/tracking';
import { customEvents } from '@/config/analytics';
import { getMeta } from '@/store/slices/meta';
import { Ellipsis } from '@/components/Stream/ellipsis';
import { CHAT_SEEN_KEY } from '@/config/env';
import { LINK_CLICKED_KEY } from '@/config/env';

export const LayoutFoot = () => {
const dispatch = useAppDispatch();
Expand Down Expand Up @@ -62,17 +62,16 @@ export const LayoutFoot = () => {
setDisabled(true);
};

const onClickCtaPay = () => {
const onClickCta = (e) => {
localStorage.setItem(LINK_CLICKED_KEY, e.currentTarget.href);
track({
eventType: customEvents.linkClicked,
systemType,
utmParams: marketing.lastUtmParams,
customerUuid: cid,
email: current
});

dispatch(setClosed());
localStorage.setItem(CHAT_SEEN_KEY, true);
};

return (
Expand All @@ -85,7 +84,7 @@ export const LayoutFoot = () => {
<Link
forwardedRef={ ctaAfterPayButton }
text={ ctaText }
onClick={ onClickCtaPay }
onClick={ onClickCta }
href={ ctaHref }
e2e="quiz-trigger-btn"
/>
Expand Down
22 changes: 22 additions & 0 deletions src/components/Stream/modifiers.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
/* eslint-disable react-hooks/rules-of-hooks */
import { customEvents } from '@/config/analytics';
import { LINK_CLICKED_KEY } from '@/config/env';
import { curlyBraces, link } from '@/config/patterns';
import { useAppDispatch, useAppSelector } from '@/hooks';
import { track } from '@/services/tracking';
import { setClosed } from '@/store/slices/chat';
import { getMeta } from '@/store/slices/meta';
import { constructLink } from '@/utils/formatting';
/**
* Replaces all string links with anchor tags.
* @example { replaceLinksWithAnchors('hello nice to see you here is a link to diet http://www.yourketo.diet') }
*/
export const replaceLinksWithAnchors = (val) => {
const dispatch = useAppDispatch();
const { cid, systemType, marketing } = useAppSelector(getMeta);

const parts = val.split(link);

const onClick = (e) => {
localStorage.setItem(LINK_CLICKED_KEY, e.currentTarget.href);
track({
eventType: customEvents.linkClicked,
systemType,
utmParams: marketing.lastUtmParams,
customerUuid: cid,
});
dispatch(setClosed());
};

return parts.map((part) => {
if (link.test(part)) {
const urlWithParams = constructLink(part);
Expand All @@ -15,6 +36,7 @@ export const replaceLinksWithAnchors = (val) => {
key={ `link-idx-${Math.random()}` }
className="tw--underline"
href={ urlWithParams }
onClick={ onClick }
>
{ part }
</a>
Expand Down
4 changes: 3 additions & 1 deletion src/config/env.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// DEV Note: will be depricated, replace with env vars
// DEV Note: will be deprecated, replace with env vars
export const STORAGE_KEY = 'history';
export const CHAT_SEEN_KEY = 'chatSeen';
export const LINK_CLICKED_KEY = 'linkClickedFromChat';
export const CHAT_FINISHED_TIMESTAMP = 'chatConversationFinishedTimeStamp';
export const ALREADY_REGISTERED_KEY = 'showAlreadyRegisteredUser';
export const SHOW_PAYMENT_BUTTON_KEY = 'showPaymentButton';
export const SOCKET_IO_URL = 'http://localhost:5000';
Expand Down
29 changes: 5 additions & 24 deletions src/middleware/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ import {
removeFromQueue,
setQueuedId,
} from '@/store/slices/chat';
import { checkForSpecialPhrases, getQueryParam, isExpired } from '@/utils';
import { checkForSpecialPhrases, getQueryParam } from '@/utils';
import { constructLink, extractOptionSet } from '@/utils/formatting';
import intent from '@/services/intentions';
import { setIsEmailFormVisible, setIsPaymentButtonVisible, setLink, setResponseFormVisibility } from '@/store/slices/intentions';
import { setConfig } from '@/store/slices/config';
import { track } from '@/services/tracking';
import { baseEvents, customEvents } from '@/config/analytics';
import { CHAT_SEEN_KEY } from '@/config/env';
import { setRegion } from '@/store/slices/meta';
import { CHAT_FINISHED_TIMESTAMP } from '@/config/env';

const specialMessages = [intent.type.email, intent.type.payment];
let socket;
Expand Down Expand Up @@ -127,8 +127,9 @@ const chatMiddleware = store => next => action => {
}

if (setClosed.match(action)) {
document.querySelector('#chatbot-container').remove();
document.body.classList.remove('scroll-stop');
document.querySelector('#chatbot-container')?.remove();
document.body.classList?.remove('scroll-stop');
localStorage.setItem(CHAT_FINISHED_TIMESTAMP, new Date().getTime());
socket.close();
}

Expand Down Expand Up @@ -311,32 +312,12 @@ const chatMiddleware = store => next => action => {
next(action);
};

const mustHideChat = ({ time, role }) => {
let hasExpired;

if (role === roles.user && time) {
hasExpired = isExpired(time);
}

if (hasExpired) {
localStorage.removeItem(CHAT_SEEN_KEY);
}

const chatSeen = localStorage.getItem(CHAT_SEEN_KEY);

return chatSeen === 'true';
};

const isFirstUserMessage = (messages) => messages.filter(obj => obj.role === roles.user).length === 1;

const updateForAnySpecialMessage = ({ lastMessage, store }) => {
const { meta, config } = store.getState();
const link = constructLink(lastMessage.content);

if (mustHideChat(lastMessage)) {
store.dispatch(setClosed(true));
}

if (link) {
store.dispatch(setLink({
isVisible: true,
Expand Down
2 changes: 1 addition & 1 deletion src/store/slices/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
bubbleContent = { content: payload.content, groupId: payload.groupId };
}

state.history.push({ ...bubbleContent, role: payload.role, id: payload.id });
state.history.push({ ...bubbleContent, role: payload.role, id: payload.id, time: new Date().getTime() });
},
setLastQuestionId(state, { payload }) {
state.history = state.history.map(item => {
Expand Down Expand Up @@ -135,7 +135,7 @@
setLastGroupPointer(state, { payload }) {
state.lastGroupId = payload;
},
resendMessage(state, { payload }) {

Check warning on line 138 in src/store/slices/chat.js

View workflow job for this annotation

GitHub Actions / post-merge

'payload' is defined but never used
state.history = state.history.map(item => item);
},
setError(state, { payload }) {
Expand Down
16 changes: 0 additions & 16 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,27 +222,11 @@
* @param {string} param
*/
export const getQueryParam = (url, param) => {
const urlParams = new URLSearchParams(url);

Check warning on line 225 in src/utils/index.js

View workflow job for this annotation

GitHub Actions / post-merge

URLSearchParams is not supported in op_mini all

return urlParams.get(param);
};

/**
* Checks if 24 hours have passed since the given date.
*
* @function isExpired
* @param {string} date - The date to compare in ISO 8601 format (e.g., "2023-07-04T14:11:00.097Z").
* @returns {boolean} Returns true if 24 hours have passed since the given date, or false otherwise.
*/
export const isExpired = (date, maxHours = 24) => {
const currentDate = new Date();
const givenDate = new Date(date);
const elapsedMilliseconds = currentDate - givenDate;
const elapsedHours = elapsedMilliseconds / (1000 * 60 * 60); // Convert milliseconds to hours

return elapsedHours >= maxHours;
};

/**
* Formats a date string according to the locale, including the date and time.
*
Expand Down
Loading