Skip to content

Commit

Permalink
feat(redlist): add red list option in settings
Browse files Browse the repository at this point in the history
  • Loading branch information
marc.sirisak committed Oct 23, 2024
1 parent 8cbff06 commit 4079105
Show file tree
Hide file tree
Showing 8 changed files with 516 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import SettingsSubsection, { SettingsSubsectionText } from "../../shared/Setting
import { SDKContext } from "../../../../../contexts/SDKContext";
import UserPersonalInfoSettings from "../../UserPersonalInfoSettings";
import { useMatrixClientContext } from "../../../../../contexts/MatrixClientContext";
import TchapRedListSettings from "../../../../../../../../src/tchap/components/views/settings/tabs/user/TchapRedListSettings"; // :TCHAP: red-list-settings

interface IProps {
closeSettingsFn: () => void;
Expand Down Expand Up @@ -194,6 +195,9 @@ const AccountUserSettingsTab: React.FC<IProps> = ({ closeSettingsFn }) => {
onPasswordChanged={onPasswordChanged}
onPasswordChangeError={onPasswordChangeError}
/>
{/* :TCHAP: red-list-settings */}
<TchapRedListSettings />
{/* end :TCHAP: */}
</SettingsSection>
{accountManagementSection}
</SettingsTab>
Expand Down
12 changes: 12 additions & 0 deletions modules/tchap-translations/tchap_translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -877,5 +877,17 @@
"auth|proconnect|error_sso_inactive": {
"en": "ProConnect is disabled for your domain",
"fr": "ProConnect est désactivé pour votre domaine"
},
"settings|general|redlist_description" : {
"en": "The other users won't be able to discover my account during their search",
"fr": "Les autres utilisateurs ne pourront pas découvrir mon compte lors de leurs recherches"
},
"settings|general|redlist_title" : {
"en": "Register my account on the red list",
"fr": "Inscrire mon compte sur la liste rouge"
},
"settings|general|redlist" : {
"en": "Red List",
"fr": "Liste rouge"
}
}
6 changes: 6 additions & 0 deletions patches/subtree-modifications.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,11 @@
"src/components/views/right_panel/RightPanelTabs.tsx",
"src/components/views/settings/tabs/user/SecurityUserSettingsTab.tsx"
]
},
"red-list-settings": {
"issue": "https://github.com/tchapgouv/tchap-web-v4/issues/1134",
"files": [
"src/components/views/settings/tabs/user/AccountUserSettingsTab.tsx"
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React, { useEffect, useState } from 'react';
import LabelledToggleSwitch from 'matrix-react-sdk/src/components/views/elements/LabelledToggleSwitch';
import SettingsSubsection from 'matrix-react-sdk/src/components/views/settings/shared/SettingsSubsection';
import { _t } from "matrix-react-sdk/src/languageHandler";
import TchapUtils from '../../../../../util/TchapUtils';

interface TchapRedListSettingsProps {
}

/**
* A group of settings views to allow the user to set their profile information.
*/
const TchapRedListSettings: React.FC<TchapRedListSettingsProps> = () => {

const [isOnRedList, setIsOnRedList] = useState(false);
const [loading, setLoading] = useState(false);

useEffect(() => {
const fetchInitialRedListValue = async () => {
const initialValue = await TchapUtils.getUserRedListInfo();
console.log("initialRedListValue", initialValue);
setIsOnRedList(initialValue);
}
fetchInitialRedListValue();
}, []);

const _onRedlistOptionChange = async (checked: boolean) => {
try {
if (!loading) {
setLoading(true)
await TchapUtils.setUserRedListInfo(checked);
setIsOnRedList(checked);
}
setLoading(false)
} catch (err) {
console.error("Error setting AccountData 'im.vector.hide_profile': " + err);
setIsOnRedList(!checked); // return to initial state because of error
setLoading(false)
}
}

return <SettingsSubsection
heading={_t("settings|general|redlist")}
stretchContent>
<LabelledToggleSwitch value={isOnRedList}
onChange={(checked: boolean) => _onRedlistOptionChange(checked)}
label={_t('settings|general|redlist_title')}
disabled={loading}
/>
<p className="mx_SettingsTab_subsectionText">
({_t("settings|general|redlist_description")})
</p>
</SettingsSubsection>
}

export default TchapRedListSettings;
12 changes: 12 additions & 0 deletions src/tchap/util/TchapUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,4 +282,16 @@ export default class TchapUtils {
}
}

static async getUserRedListInfo() : Promise<boolean> {
const client = MatrixClientPeg.safeGet();
const accountData = await client.getAccountData('im.vector.hide_profile');
console.log('accountData', accountData?.getContent());
return !!accountData?.getContent().hide_profile;
}

static async setUserRedListInfo(isOnRedList: boolean) : Promise<void> {
const client = MatrixClientPeg.safeGet();
client.setAccountData('im.vector.hide_profile', {hide_profile: isOnRedList});
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { render } from "@testing-library/react";
import React from "react";
import { MatrixClient } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import { MockedObject } from "jest-mock";
import AccountUserSettingsTab from "matrix-react-sdk/src/components/views/settings/tabs/user/AccountUserSettingsTab";
import { SdkContextClass, SDKContext } from "matrix-react-sdk/src/contexts/SDKContext";
import SettingsStore from "matrix-react-sdk/src/settings/SettingsStore";
import { UIFeature } from "matrix-react-sdk/src/settings/UIFeature";
import { OidcClientStore } from "matrix-react-sdk/src/stores/oidc/OidcClientStore";
import MatrixClientContext from "matrix-react-sdk/src/contexts/MatrixClientContext";
import {
getMockClientWithEventEmitter,
mockClientMethodsServer,
mockClientMethodsUser,
mockPlatformPeg,
} from "matrix-react-sdk/test/test-utils";


jest.mock(
"matrix-react-sdk/src/components/views/settings/ChangePassword",
() =>
({ onError, onFinished }: { onError: (e: Error) => void; onFinished: () => void }) => {
return <button>Mock change password</button>;
},
);

describe("<AccountUserSettingsTab />", () => {
const defaultProps = {
closeSettingsFn: jest.fn(),
};

const userId = "@alice:server.org";
let mockClient: MockedObject<MatrixClient>;

let stores: SdkContextClass;

const getComponent = () => (
<MatrixClientContext.Provider value={mockClient}>
<SDKContext.Provider value={stores}>
<AccountUserSettingsTab {...defaultProps} />
</SDKContext.Provider>
</MatrixClientContext.Provider>
);

beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
mockPlatformPeg();
jest.clearAllMocks();
jest.spyOn(SettingsStore, "getValue").mockRestore();
jest.spyOn(logger, "error").mockRestore();

mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
...mockClientMethodsServer(),
getCapabilities: jest.fn(),
getThreePids: jest.fn(),
getIdentityServerUrl: jest.fn(),
deleteThreePid: jest.fn(),
});

mockClient.getCapabilities.mockResolvedValue({});
mockClient.getThreePids.mockResolvedValue({
threepids: [],
});
mockClient.deleteThreePid.mockResolvedValue({
id_server_unbind_result: "success",
});

stores = new SdkContextClass();
stores.client = mockClient;
// stub out this store completely to avoid mocking initialisation
const mockOidcClientStore = {} as unknown as OidcClientStore;
jest.spyOn(stores, "oidcClientStore", "get").mockReturnValue(mockOidcClientStore);
jest.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName: string) => settingName === UIFeature.Deactivate,
);
});

afterEach(() => {
jest.restoreAllMocks();
});


describe("common view snapshot", () => {

it("should render section when account deactivation feature is enabled", () => {
const { container } = render(getComponent());

expect(container).toMatchSnapshot();

Check failure on line 90 in test/unit-tests/tchap/components/views/settings/AccountUserSettingsTab-test.tsx

View workflow job for this annotation

GitHub Actions / Jest

<AccountUserSettingsTab /> › common view snapshot › should render section when account deactivation feature is enabled

expect(received).toMatchSnapshot() Snapshot name: `<AccountUserSettingsTab /> common view snapshot should render section when account deactivation feature is enabled 1` - Snapshot - 2 + Received + 2 @@ -78,16 +78,16 @@ <div class="mx_UserProfileSettings_profile_controls_userId" > <div class="mx_UserProfileSettings_profile_controls_userId_label" - id=":r0.7849031942916656:" + id=":r0.718264254698955:" > Username </div> <div - aria-labelledby=":r0.7849031942916656:" + aria-labelledby=":r0.718264254698955:" class="mx_CopyableText mx_CopyableText_border" > @alice:server.org <div aria-label="Copy" at Object.toMatchSnapshot (test/unit-tests/tchap/components/views/settings/AccountUserSettingsTab-test.tsx:90:31)
});
});


});
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { act, logRoles, render, screen, waitFor } from '@testing-library/react';

Check failure on line 1 in test/unit-tests/tchap/components/views/settings/TchapRedListSettings-test.tsx

View workflow job for this annotation

GitHub Actions / ESLint

'logRoles' is defined but never used
import React from 'react';
import { flushPromises, stubClient } from 'matrix-react-sdk/test/test-utils';
import { Mocked, mocked } from 'jest-mock';

import TchapRedListSettings from '~tchap-web/src/tchap/components/views/settings/tabs/user/TchapRedListSettings';

Check failure on line 6 in test/unit-tests/tchap/components/views/settings/TchapRedListSettings-test.tsx

View workflow job for this annotation

GitHub Actions / ESLint

There should be at least one empty line between import groups
import { MatrixClient } from 'matrix-js-sdk/src/matrix';

Check failure on line 7 in test/unit-tests/tchap/components/views/settings/TchapRedListSettings-test.tsx

View workflow job for this annotation

GitHub Actions / ESLint

There should be at least one empty line between import groups

Check failure on line 7 in test/unit-tests/tchap/components/views/settings/TchapRedListSettings-test.tsx

View workflow job for this annotation

GitHub Actions / ESLint

`matrix-js-sdk/src/matrix` import should occur before import of `~tchap-web/src/tchap/components/views/settings/tabs/user/TchapRedListSettings`
import TchapUtils from '~tchap-web/src/tchap/util/TchapUtils';

Check failure on line 8 in test/unit-tests/tchap/components/views/settings/TchapRedListSettings-test.tsx

View workflow job for this annotation

GitHub Actions / ESLint

There should be at least one empty line between import groups
import userEvent from '@testing-library/user-event';

Check failure on line 9 in test/unit-tests/tchap/components/views/settings/TchapRedListSettings-test.tsx

View workflow job for this annotation

GitHub Actions / ESLint

`@testing-library/user-event` import should occur before import of `~tchap-web/src/tchap/components/views/settings/tabs/user/TchapRedListSettings`

jest.mock("~tchap-web/src/tchap/util/TchapUtils");

describe("TchapRedListSettings", () => {
let client: Mocked<MatrixClient>;

Check failure on line 14 in test/unit-tests/tchap/components/views/settings/TchapRedListSettings-test.tsx

View workflow job for this annotation

GitHub Actions / ESLint

'client' is assigned a value but never used

const renderComponent = () => render(<TchapRedListSettings />);

beforeEach(() => {
client = mocked(stubClient());
});


it("should red list should be activated when initial value is true", async () => {
mocked(TchapUtils.getUserRedListInfo).mockResolvedValue(true);
mocked(TchapUtils.setUserRedListInfo).mockResolvedValue();

renderComponent();

await flushPromises();

const switchElm = screen.getByRole("switch");

expect(switchElm).toHaveAttribute('aria-checked', "true");

});

it("should red list should be desactivated when initial value is false", async () => {
mocked(TchapUtils.getUserRedListInfo).mockResolvedValue(false);
mocked(TchapUtils.setUserRedListInfo).mockResolvedValue();

renderComponent();

await flushPromises();

const switchElm = screen.getByRole("switch");

expect(switchElm).toHaveAttribute('aria-checked', "false");
});


it("should remove user from red list", async () => {
// initial value
mocked(TchapUtils.getUserRedListInfo).mockResolvedValue(true);
mocked(TchapUtils.setUserRedListInfo).mockResolvedValue();

renderComponent();

await flushPromises();

const switchElm = screen.getByRole("switch");

act(() => {
userEvent.click(switchElm);
})

waitFor(() => {
expect(switchElm).toHaveAttribute('aria-checked', "false");
})
});

it("should put user on red list", async () => {
// initial value
mocked(TchapUtils.getUserRedListInfo).mockResolvedValue(false);
mocked(TchapUtils.setUserRedListInfo).mockResolvedValue();

renderComponent();

await flushPromises();

const switchElm = screen.getByRole("switch");

act(() => {
userEvent.click(switchElm);
})

waitFor(() => {
expect(switchElm).toHaveAttribute('aria-checked', "true");
})
});

it("should get back to initial value if throws an error", async () => {
// initial value
mocked(TchapUtils.getUserRedListInfo).mockResolvedValue(false);
mocked(TchapUtils.setUserRedListInfo).mockRejectedValue(new Error("error test"));

renderComponent();

await flushPromises();

const switchElm = screen.getByRole("switch");

act(() => {
userEvent.click(switchElm);
})
waitFor(() => {
expect(switchElm).toHaveAttribute('aria-checked', "false");
});
});
});
Loading

0 comments on commit 4079105

Please sign in to comment.