Skip to content

Commit

Permalink
Remove unecessary renders after auth refresh.
Browse files Browse the repository at this point in the history
  • Loading branch information
Hyperkid123 committed Sep 24, 2024
1 parent 04ac5c3 commit af10aaa
Show file tree
Hide file tree
Showing 16 changed files with 490 additions and 390 deletions.
20 changes: 5 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@
"@rhds/elements": "^2.0.1",
"@rhds/icons": "^1.1.1",
"@scalprum/core": "^0.8.1",
"@scalprum/react-core": "^0.9.1",
"@scalprum/react-core": "^0.9.3",
"@segment/analytics-next": "^1.70.0",
"@sentry/react": "^7.118.0",
"@sentry/tracing": "^7.118.0",
Expand Down
4 changes: 3 additions & 1 deletion src/auth/ChromeAuthContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { AxiosResponse } from 'axios';
import { createContext } from 'react';
import { OfflineTokenResponse } from './offline';

export type ChromeLogin<LoginResponse = void> = (requiredScopes?: string[]) => Promise<LoginResponse>;

export type ChromeAuthContextValue<LoginResponse = void> = {
ssoUrl: string;
ready: boolean;
Expand All @@ -12,7 +14,7 @@ export type ChromeAuthContextValue<LoginResponse = void> = {
logoutAllTabs: (bounce?: boolean) => void;
loginAllTabs: () => void;
logout: () => void;
login: (requiredScopes?: string[]) => Promise<LoginResponse>;
login: ChromeLogin<LoginResponse>;
tokenExpires: number;
getToken: () => Promise<string>;
getRefreshToken: () => Promise<string>;
Expand Down
13 changes: 12 additions & 1 deletion src/auth/OIDCConnector/OIDCSecured.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,18 @@ export function OIDCSecured({
if (!auth.error) {
startChrome();
}
}, [auth]);
function onRenewError(error: Error) {
console.error('Silent renew error', error);
state.login();
}
auth.events.addSilentRenewError(onRenewError);

return () => {
auth.events.removeSilentRenewError(onRenewError);
};
// to ensure we are not re-initializing the chrome on every auth change
// only on the important events
}, [auth.error, auth.isLoading, auth.isAuthenticated, state.token, state.user?.identity?.account_number]);

useEffect(() => {
authRef.current = auth;
Expand Down
16 changes: 12 additions & 4 deletions src/components/Activation/Activation.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import React, { useContext, useEffect, useState } from 'react';
import { ChromeUser } from '@redhat-cloud-services/types';
import { DeepRequired } from 'utility-types';
import { useNavigate } from 'react-router-dom';
import { Modal, ModalVariant } from '@patternfly/react-core/dist/dynamic/components/Modal';
import { Text, TextContent } from '@patternfly/react-core/dist/dynamic/components/Text';
Expand All @@ -9,7 +7,17 @@ import { useIntl } from 'react-intl';
import messages from '../../locales/Messages';
import InternalChromeContext from '../../utils/internalChromeContext';

const Activation = ({ user, request }: { user: DeepRequired<ChromeUser>; request: string }) => {
const Activation = ({
user,
request,
}: {
user: {
username: string;
accountNumber: string;
email: string;
};
request: string;
}) => {
const intl = useIntl();
const [isModalOpen, setIsModalOpen] = useState(true);
const navigate = useNavigate();
Expand All @@ -29,7 +37,7 @@ const Activation = ({ user, request }: { user: DeepRequired<ChromeUser>; request
'Content-Type': 'application/json',
},
body: JSON.stringify({
description: `Username: ${user.identity.user.username}, Account ID: ${user.identity.account_number}, Email: ${user.identity.user.email}`, //eslint-disable-line
description: `Username: ${user.username}, Account ID: ${user.accountNumber}, Email: ${user.email}`, //eslint-disable-line
summary: `Activation Request - for cloud-marketplace-enablement team`,
labels: [request],
}),
Expand Down
17 changes: 0 additions & 17 deletions src/components/ChromeRoute/ChromeRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@ import LoadingFallback from '../../utils/loading-fallback';
import { batch, useDispatch } from 'react-redux';
import { toggleGlobalFilter } from '../../redux/actions';
import ErrorComponent from '../ErrorComponents/DefaultErrorComponent';
import { getPendoConf } from '../../analytics';
import classNames from 'classnames';
import { HelpTopicContext } from '@patternfly/quickstarts';
import GatewayErrorComponent from '../ErrorComponents/GatewayErrorComponent';
import { DeepRequired } from 'utility-types';
import { ChromeUser } from '@redhat-cloud-services/types';
import ChromeAuthContext from '../../auth/ChromeAuthContext';
import { useAtomValue, useSetAtom } from 'jotai';
import { activeModuleAtom } from '../../state/atoms/activeModuleAtom';
import { gatewayErrorAtom } from '../../state/atoms/gatewayErrorAtom';
Expand All @@ -35,7 +31,6 @@ const ChromeRoute = memo(
const isPreview = useAtomValue(isPreviewAtom);
const dispatch = useDispatch();
const { setActiveHelpTopicByName } = useContext(HelpTopicContext);
const { user } = useContext(ChromeAuthContext);
const gatewayError = useAtomValue(gatewayErrorAtom);
const [isHidden, setIsHidden] = useState<boolean | null>(null);

Expand Down Expand Up @@ -65,18 +60,6 @@ const ChromeRoute = memo(
// should be triggered only once per session
setActiveModule(scope);
});
/**
* update pendo metadata on application change
*/
if (window.pendo) {
try {
window.pendo.updateOptions(getPendoConf(user as DeepRequired<ChromeUser>, isPreview));
} catch (error) {
console.error('Unable to update pendo options');
console.error(error);
}
}

/**
* TODO: Discuss default close feature of topics
* Topics drawer has no close button, therefore there might be an issue with opened topics after user changes route and does not clear the active topic trough the now non existing elements.
Expand Down
22 changes: 11 additions & 11 deletions src/components/ContextSwitcher/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ import {
REQUESTS_COUNT,
REQUESTS_DATA,
} from '../../utils/consts';
import { ChromeUser } from '@redhat-cloud-services/types';
import { useAtom } from 'jotai';
import { contextSwitcherOpenAtom } from '../../state/atoms/contextSwitcher';

export type ContextSwitcherProps = {
user: ChromeUser;
className?: string;
accountNumber?: string;
isInternal?: boolean;
};

// These attributes are present in the response based on the open API spec.
Expand All @@ -41,12 +41,12 @@ type CrossAccountRequestInternal = CrossAccountRequest & {
email: string;
};

const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
const ContextSwitcher = ({ accountNumber, className, isInternal }: ContextSwitcherProps) => {
const intl = useIntl();
const [isOpen, setIsOpen] = useAtom(contextSwitcherOpenAtom);
const [data, setData] = useState<CrossAccountRequestInternal[]>([]);
const [searchValue, setSearchValue] = useState('');
const [selectedAccountNumber, setSelectedAccountNumber] = useState(user.identity.account_number);
const [selectedAccountNumber, setSelectedAccountNumber] = useState(accountNumber);
const onSelect = () => {
setIsOpen((prev) => !prev);
};
Expand Down Expand Up @@ -80,10 +80,10 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
};

const resetAccountRequest = () => {
if (user?.identity?.account_number === selectedAccountNumber) {
if (accountNumber === selectedAccountNumber) {
return;
}
setSelectedAccountNumber(user?.identity?.account_number);
setSelectedAccountNumber(accountNumber);
Cookies.remove(CROSS_ACCESS_ACCOUNT_NUMBER);
Cookies.remove(CROSS_ACCESS_ORG_ID);
localStorage.removeItem(ACTIVE_REMOTE_REQUEST);
Expand All @@ -93,7 +93,7 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
useEffect(() => {
let mounted = true;
// only inernal users have the TAM features enabled
if (user?.identity?.user?.is_internal) {
if (isInternal) {
const initialAccount = localStorage.getItem(ACTIVE_REMOTE_REQUEST);
if (initialAccount) {
try {
Expand Down Expand Up @@ -121,7 +121,7 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
}
return [...acc, curr];
}, [])
.filter(({ target_account }) => target_account !== user.identity.account_number)
.filter(({ target_account }) => target_account !== accountNumber)
);
}
});
Expand Down Expand Up @@ -151,12 +151,12 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
searchInputPlaceholder={intl.formatMessage(messages.searchAccount)}
isFullHeight
>
{user && user?.identity?.account_number?.includes(searchValue) ? (
{accountNumber?.includes(searchValue) ? (
<ContextSelectorItem onClick={resetAccountRequest}>
<TextContent className="chr-c-content-account">
<Text className="account-label pf-v5-u-mb-0 sentry-mask data-hj-suppress">
<span>{user?.identity?.account_number}</span>
{user?.identity?.account_number === `${selectedAccountNumber}` && (
<span>{accountNumber}</span>
{accountNumber === `${selectedAccountNumber}` && (
<Icon size="sm" className="pf-v5-u-ml-auto">
<CheckIcon color="var(--pf-v5-global--primary-color--100)" />
</Icon>
Expand Down
Loading

0 comments on commit af10aaa

Please sign in to comment.