Skip to content

Commit bab842b

Browse files
committed
Pass existing authenticated status to logUXAction()
1 parent 9f6564b commit bab842b

10 files changed

Lines changed: 89 additions & 68 deletions

File tree

‎translate/src/api/uxaction.test.js‎

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,18 @@ import { vi } from 'vitest';
22

33
vi.mock('./utils/base', () => ({ POST: vi.fn() }));
44
vi.mock('./utils/csrfToken', () => ({ getCSRFToken: () => 'test-csrf-token' }));
5-
vi.mock('./user', () => ({ fetchUserData: vi.fn() }));
65

7-
async function setup({
8-
authenticated: authenticated = true,
9-
postReject = false,
10-
} = {}) {
11-
const { fetchUserData } = await import('./user');
6+
async function setup({ postReject = false } = {}) {
127
const { POST } = await import('./utils/base');
138
const { logUXAction } = await import('./uxaction');
149

15-
fetchUserData.mockResolvedValue({ is_authenticated: authenticated });
16-
1710
if (postReject) {
1811
POST.mockRejectedValue(new Error('err'));
1912
} else {
2013
POST.mockResolvedValue(undefined);
2114
}
2215

23-
return { fetchUserData, POST, logUXAction };
16+
return { POST, logUXAction };
2417
}
2518

2619
describe('logUXAction', () => {
@@ -34,16 +27,8 @@ describe('logUXAction', () => {
3427
document.body.innerHTML = '';
3528
});
3629

37-
it('does nothing when unauthenticated', async () => {
38-
const { POST, logUXAction } = await setup({ authenticated: false });
39-
40-
await logUXAction('Load: X', 'Exp', { a: true });
41-
42-
expect(POST).not.toHaveBeenCalled();
43-
});
44-
45-
it('POSTs when authenticated', async () => {
46-
const { POST, logUXAction } = await setup({ authenticated: true });
30+
it('POSTs when called', async () => {
31+
const { POST, logUXAction } = await setup();
4732

4833
await logUXAction('Load: X', 'Exp', { a: true });
4934

@@ -52,11 +37,25 @@ describe('logUXAction', () => {
5237
});
5338

5439
it('swallows POST errors', async () => {
55-
const { logUXAction } = await setup({
56-
authenticated: true,
57-
postReject: true,
58-
});
40+
const { logUXAction } = await setup({ postReject: true });
5941

6042
await expect(logUXAction('Load: X', null, null)).resolves.toBeUndefined();
6143
});
44+
45+
it('includes CSRF token and payload fields', async () => {
46+
const { POST, logUXAction } = await setup();
47+
48+
await logUXAction('Test Action', 'Test Experiment', { foo: 'bar', num: 1 });
49+
50+
expect(POST).toHaveBeenCalledTimes(1);
51+
52+
const payload = POST.mock.calls[0][1];
53+
expect(payload).toBeInstanceOf(URLSearchParams);
54+
55+
expect(payload.get('csrfmiddlewaretoken')).toBe('test-csrf-token');
56+
expect(payload.get('action_type')).toBe('Test Action');
57+
expect(payload.get('experiment')).toBe('Test Experiment');
58+
59+
expect(JSON.parse(payload.get('data'))).toEqual({ foo: 'bar', num: 1 });
60+
});
6261
});

‎translate/src/api/uxaction.ts‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,11 @@
1-
import { fetchUserData } from './user';
21
import { POST } from './utils/base';
32
import { getCSRFToken } from './utils/csrfToken';
43

5-
let userDataPromise: ReturnType<typeof fetchUserData> | null = null;
6-
7-
async function isAuthenticated(): Promise<boolean> {
8-
if (!userDataPromise) {
9-
userDataPromise = fetchUserData();
10-
}
11-
try {
12-
const userData = await userDataPromise;
13-
return Boolean(userData?.is_authenticated);
14-
} catch {
15-
return false;
16-
}
17-
}
18-
194
export async function logUXAction(
205
action_type: string,
216
experiment: string | null,
227
data: Record<string, string | number | boolean> | null,
238
): Promise<void> {
24-
if (!(await isAuthenticated())) return;
259
const csrfToken = getCSRFToken();
2610

2711
const payload = new URLSearchParams({
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { useAppSelector } from '~/hooks';
2+
import { USER } from '~/modules/user';
3+
import { logUXAction } from '../api/uxaction';
4+
5+
export function useLogUXAction(): (
6+
action_type: string,
7+
experiment: string | null,
8+
data: Record<string, string | number | boolean> | null,
9+
) => Promise<void> | void {
10+
const isAuthenticated = useAppSelector((state) =>
11+
Boolean(state[USER].isAuthenticated),
12+
);
13+
14+
return (action_type, experiment, data) => {
15+
if (!isAuthenticated) return;
16+
return logUXAction(action_type, experiment, data);
17+
};
18+
}

‎translate/src/modules/entities/actions.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ import {
77
import { EntityTranslation } from '~/api/translation';
88
import { logUXAction } from '~/api/uxaction';
99
import { Location } from '~/context/Location';
10+
import { USER } from '~/modules/user';
1011
import { updateStats } from '~/modules/stats/actions';
11-
import type { AppDispatch } from '~/store';
12+
import type { AppDispatch, RootState } from '~/store';
1213

1314
export const RECEIVE_ENTITIES = 'entities/RECEIVE';
1415
export const REQUEST_ENTITIES = 'entities/REQUEST';
@@ -62,7 +63,8 @@ export const updateEntityTranslation = (
6263

6364
/** Fetch entities and their translation. */
6465
export const getEntities =
65-
(location: Location, page: number) => async (dispatch: AppDispatch) => {
66+
(location: Location, page: number) =>
67+
async (dispatch: AppDispatch, getState: () => RootState) => {
6668
dispatch({ type: REQUEST_ENTITIES });
6769

6870
const content = await fetchEntities(location, page);
@@ -74,8 +76,9 @@ export const getEntities =
7476
search_match_whole_word,
7577
search_rejected_translations,
7678
} = location;
79+
const isAuthenticated = Boolean(getState()[USER].isAuthenticated);
7780

78-
if (search) {
81+
if (search && isAuthenticated) {
7982
logUXAction(
8083
'Load: String list with search parameter',
8184
'Search Options Statistics',

‎translate/src/modules/machinery/components/MachineryTranslation.tsx‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import classNames from 'classnames';
33
import React, { useCallback, useContext, useEffect, useRef } from 'react';
44

55
import type { MachineryTranslation, SourceType } from '~/api/machinery';
6-
import { logUXAction } from '~/api/uxaction';
6+
import { useLogUXAction } from '~/hooks/useLogUXAction';
77
import { EditorActions } from '~/context/Editor';
88
import { HelperSelection } from '~/context/HelperSelection';
99
import { Locale } from '~/context/Locale';
@@ -43,6 +43,7 @@ export function MachineryTranslationComponent({
4343
const { llmTranslation } = getLLMTranslationState(translation);
4444

4545
const locale = useContext(Locale);
46+
const log = useLogUXAction();
4647

4748
const copyTranslationIntoEditor = useCallback(() => {
4849
if (window.getSelection()?.isCollapsed !== false) {
@@ -53,13 +54,21 @@ export function MachineryTranslationComponent({
5354
: translation.sources;
5455
setEditorFromHelpers(content, sources, true);
5556
if (llmTranslation) {
56-
logUXAction('LLM Translation Copied', 'LLM Feature Adoption', {
57+
log('LLM Translation Copied', 'LLM Feature Adoption', {
5758
action: 'Copy LLM Translation',
5859
localeCode: locale.code,
5960
});
6061
}
6162
}
62-
}, [index, setEditorFromHelpers, translation, llmTranslation]);
63+
}, [
64+
index,
65+
llmTranslation,
66+
setElement,
67+
setEditorFromHelpers,
68+
translation,
69+
locale.code,
70+
log,
71+
]);
6372

6473
const className = classNames(
6574
'translation',

‎translate/src/modules/machinery/components/source/GoogleTranslation.test.jsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import React from 'react';
22
import { shallow } from 'enzyme';
3+
import { vi } from 'vitest';
4+
5+
vi.mock('~/hooks/useLogUXAction', () => ({
6+
useLogUXAction: () => () => undefined,
7+
}));
38

49
import { GoogleTranslation } from './GoogleTranslation';
510

‎translate/src/modules/machinery/components/source/GoogleTranslation.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import React, { useState, useRef, useContext } from 'react';
22
import { Localized } from '@fluent/react';
33
import type { MachineryTranslation } from '~/api/machinery';
44
import { Locale } from '~/context/Locale';
5-
import { logUXAction } from '~/api/uxaction';
5+
import { useLogUXAction } from '~/hooks/useLogUXAction';
66
import { useLLMTranslation } from '~/context/TranslationContext';
77

88
type Props = {
@@ -26,6 +26,7 @@ export function GoogleTranslation({
2626
const locale = useContext(Locale);
2727

2828
const getLLMTranslationState = useLLMTranslation();
29+
const log = useLogUXAction();
2930

3031
const { transformLLMTranslation, selectedOption, restoreOriginal } =
3132
getLLMTranslationState(translation);
@@ -44,7 +45,7 @@ export function GoogleTranslation({
4445
restoreOriginal(translation);
4546
} else {
4647
await transformLLMTranslation(translation, characteristic, locale.name);
47-
logUXAction('LLM Dropdown Select', 'LLM Feature Adoption', {
48+
log('LLM Dropdown Select', 'LLM Feature Adoption', {
4849
optionSelected: characteristic,
4950
localeCode: locale.code,
5051
});

‎translate/src/modules/translationform/utils/editFieldShortcuts.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { useLLMTranslation } from '~/context/TranslationContext';
1111
import { Locale } from '~/context/Locale';
1212
import { useAppSelector } from '~/hooks';
1313
import { getPlainMessage } from '~/utils/message';
14-
import { logUXAction } from '~/api/uxaction';
14+
import { useLogUXAction } from '~/hooks/useLogUXAction';
1515

1616
import { useExistingTranslationGetter } from '../../editor/hooks/useExistingTranslationGetter';
1717
import { useSendTranslation } from '../../editor/hooks/useSendTranslation';
@@ -96,6 +96,7 @@ export function useHandleCtrlShiftArrow(): (
9696

9797
const getLLMTranslationState = useLLMTranslation();
9898
const locale = useContext(Locale);
99+
const log = useLogUXAction();
99100

100101
return (key) => {
101102
const { tab, element, setElement } = helperSelection;
@@ -126,14 +127,10 @@ export function useHandleCtrlShiftArrow(): (
126127
setEditorFromHelpers(updatedTranslation, translationObj.sources, true);
127128

128129
if (llmState.llmTranslation) {
129-
logUXAction(
130-
'LLM Translation Copied via Shortcut',
131-
'LLM Feature Adoption',
132-
{
133-
action: 'Copy LLM Translation via Shortcut',
134-
localeCode: locale.code,
135-
},
136-
);
130+
log('LLM Translation Copied via Shortcut', 'LLM Feature Adoption', {
131+
action: 'Copy LLM Translation via Shortcut',
132+
localeCode: locale.code,
133+
});
137134
}
138135
} else {
139136
const { translation } = otherLocaleTranslations[nextIdx];

‎translate/src/modules/user/components/UserNotificationsMenu.test.jsx‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
import { mount, shallow } from 'enzyme';
22
import React from 'react';
33

4-
import * as api from '~/api/uxaction';
5-
64
import { UserNotification } from './UserNotification';
75
import {
86
UserNotificationsMenu,
97
UserNotificationsMenuDialog,
108
} from './UserNotificationsMenu';
119
import { vi } from 'vitest';
1210

11+
const logMock = vi.fn();
12+
vi.mock('~/hooks/useLogUXAction', () => ({
13+
useLogUXAction: () => logMock,
14+
}));
15+
1316
describe('<UserNotificationsMenuDialog>', () => {
1417
it('shows empty notifications menu if user has no notifications', () => {
1518
const notifications = [];
@@ -54,7 +57,7 @@ describe('<UserNotificationsMenuDialog>', () => {
5457
});
5558

5659
describe('<UserNotificationsMenu>', () => {
57-
beforeEach(() => vi.spyOn(api, 'logUXAction'));
60+
beforeEach(() => logMock.mockClear());
5861
afterEach(() => vi.restoreAllMocks());
5962

6063
it('hides the notifications icon when the user is logged out', () => {
@@ -93,7 +96,7 @@ describe('<UserNotificationsMenu>', () => {
9396
const wrapper = mount(<UserNotificationsMenu user={user} />);
9497

9598
expect(wrapper.find('.user-notifications-menu .badge').text()).toEqual('5');
96-
expect(api.logUXAction).toHaveBeenCalled();
99+
expect(logMock).toHaveBeenCalled();
97100
});
98101

99102
it('calls the logUxAction function on click on the icon if menu not visible', () => {
@@ -113,12 +116,12 @@ describe('<UserNotificationsMenu>', () => {
113116
);
114117

115118
// shallow() does not handle useEffect()
116-
expect(api.logUXAction).not.toHaveBeenCalled();
119+
expect(logMock).not.toHaveBeenCalled();
117120

118121
wrapper.find('.selector').simulate('click', {});
119-
expect(api.logUXAction).toHaveBeenCalledOnce();
122+
expect(logMock).toHaveBeenCalledOnce();
120123

121124
wrapper.find('.selector').simulate('click', {});
122-
expect(api.logUXAction).toHaveBeenCalledOnce();
125+
expect(logMock).toHaveBeenCalledOnce();
123126
});
124127
});

‎translate/src/modules/user/components/UserNotificationsMenu.tsx‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Localized } from '@fluent/react';
22
import React, { useCallback, useEffect, useRef, useState } from 'react';
33

4-
import { logUXAction } from '~/api/uxaction';
4+
import { useLogUXAction } from '~/hooks/useLogUXAction';
55
import { useOnDiscard } from '~/utils';
66

77
import type { Notification, UserState } from '../index';
@@ -71,30 +71,32 @@ export function UserNotificationsMenu({
7171
const [visible, setVisible] = useState(false);
7272
const handleDiscard = useCallback(() => setVisible(false), []);
7373

74+
const log = useLogUXAction();
75+
7476
const unread = user?.notifications.has_unread;
7577

7678
useEffect(() => {
7779
if (user.isAuthenticated && unread) {
78-
logUXAction('Render: Unread notifications icon', 'Notifications 1.0', {
80+
log('Render: Unread notifications icon', 'Notifications 1.0', {
7981
pathname: window.location.pathname,
8082
});
8183
}
82-
}, []);
84+
}, [user.isAuthenticated, unread, log]);
8385

8486
const handleClick = useCallback(() => {
8587
if (visible) {
8688
setVisible(false);
8789
} else {
8890
setVisible(true);
89-
logUXAction('Click: Notifications icon', 'Notifications 1.0', {
91+
log('Click: Notifications icon', 'Notifications 1.0', {
9092
pathname: window.location.pathname,
9193
unread,
9294
});
9395
}
9496
if (unread) {
9597
markAllNotificationsAsRead();
9698
}
97-
}, [markAllNotificationsAsRead, unread, visible]);
99+
}, [markAllNotificationsAsRead, unread, visible, log]);
98100

99101
return user?.isAuthenticated ? (
100102
<div className='user-notifications-menu'>

0 commit comments

Comments
 (0)