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

upcoming: [DI-19328] - Added capability to save & retrieve CloudPulse user preferences #10625

Merged
merged 11 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@linode/api-v4": Upcoming Features
---

Add ACLG Config and Widget to CloudPulse types ([#10625](https://github.com/linode/manager/pull/10625))
16 changes: 16 additions & 0 deletions packages/api-v4/src/cloudpulse/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,19 @@ export interface Filters {
operator: string;
value: string;
}

export interface AclpConfig {
dashboardId: number;
interval: string;
region: string;
resources: string[];
timeDuration: string;
widgets: { [label: string]: AclpWidget };
}

export interface AclpWidget {
aggregateFunction: string;
timeGranularity: TimeGranularity;
label: string;
size: number;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@linode/manager": Upcoming Features
---

Add capability to save & retrieve user preferences ([#10625](https://github.com/linode/manager/pull/10625))
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
import { Paper } from '@mui/material';
import * as React from 'react';

import { FiltersObject, GlobalFilters } from '../Overview/GlobalFilters';
import { CircleProgress } from 'src/components/CircleProgress';

import { GlobalFilters } from '../Overview/GlobalFilters';
import { loadUserPreference } from '../Utils/UserPreference';

import type { FiltersObject } from '../Overview/GlobalFilters';

export const DashboardLanding = () => {
const [isPreferenceLoaded, setIsPreferenceLoaded] = React.useState<boolean>(
false
);

// eslint-disable-next-line @typescript-eslint/no-empty-function
const onFilterChange = (_filters: FiltersObject) => {};
const onFilterChange = React.useCallback((_filters: FiltersObject) => { }, []);

// Fetch the saved user preference when this component rendered initially
React.useEffect(() => {
const fetchUserPreference = async () => {
await loadUserPreference();
setIsPreferenceLoaded(true);
};

fetchUserPreference();
}, []);

if (!isPreferenceLoaded) {
return <CircleProgress />;
}

return (
<Paper>
<div style={{ display: 'flex' }}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import { styled } from '@mui/material/styles';
import Grid from '@mui/material/Unstable_Grid2';
import * as React from 'react';

import { CloudPulseDashboardSelect } from '../shared/CloudPulseDashboardSelect';
import { CloudPulseRegionSelect } from '../shared/CloudPulseRegionSelect';
import { CloudPulseResourcesSelect } from '../shared/CloudPulseResourcesSelect';
import { CloudPulseTimeRangeSelect } from '../shared/CloudPulseTimeRangeSelect';

import type { CloudPulseResources } from '../shared/CloudPulseResourcesSelect';
import type { Dashboard } from '@linode/api-v4';
import type { WithStartAndEnd } from 'src/features/Longview/request.types';
import { Dashboard } from '@linode/api-v4';
import { CloudPulseDashboardSelect } from '../shared/CloudPulseDashboardSelect';

export interface GlobalFilterProperties {
handleAnyFilterChange(filters: FiltersObject): undefined | void;
Expand All @@ -32,7 +32,7 @@ export const GlobalFilters = React.memo((props: GlobalFilterProperties) => {
const [selectedDashboard, setSelectedDashboard] = React.useState<
Dashboard | undefined
>();
const [selectedRegion, setRegion] = React.useState<string | undefined>();
const [selectedRegion, setRegion] = React.useState<string>(); // fetch the default region from preference
const [, setResources] = React.useState<CloudPulseResources[]>(); // removed the unused variable, this will be used later point of time

React.useEffect(() => {
Expand Down Expand Up @@ -71,9 +71,12 @@ export const GlobalFilters = React.memo((props: GlobalFilterProperties) => {
);

const handleDashboardChange = React.useCallback(
(dashboard: Dashboard | undefined) => {
(dashboard: Dashboard | undefined, isDefault: boolean = false) => {
setSelectedDashboard(dashboard);
setRegion(undefined);
if (!isDefault) {
// only update the region state when it is not a preference (default) call
setRegion(undefined);
}
},
[]
);
Expand All @@ -90,7 +93,6 @@ export const GlobalFilters = React.memo((props: GlobalFilterProperties) => {
<StyledCloudPulseRegionSelect
handleRegionChange={handleRegionChange}
selectedDashboard={selectedDashboard}
selectedRegion={selectedRegion}
/>
</Grid>

Expand All @@ -103,7 +105,6 @@ export const GlobalFilters = React.memo((props: GlobalFilterProperties) => {
</Grid>
<Grid sx={{ marginLeft: 2, width: 250 }}>
<StyledCloudPulseTimeRangeSelect
defaultValue={'Past 30 Minutes'}
handleStatsChange={handleTimeRangeChange}
hideLabel
label="Select Time Range"
Expand Down
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's rename this file utils.ts to remain consistent with convention in the codebase.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed the case of file name to camel case because in future more util files will be added for different functionalities

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be able to use our React Query data layer for anything related to user preferences. (packages/manager/src/queries/profile/preferences.ts). We try to use that instead of interfacing with @linode/api-v4 functions directly

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

@kmuddapo kmuddapo Jul 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!! for the suggestion. We will take this up as part of enhancements later to use React Query Data layer via https://track.akamai.com/jira/browse/DI-19503 as in Q3 we have a commitment for beta with minimum functionalities. Hope this is fine for now.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kmuddapo Use of React Query is something we'd need to see in this PR to get it merged, rather than later. Using direct api-v4 functions is rare in our codebase, and it may be acceptable on a one-off basis, but our best practice is to use RQ almost all the time -- this offers caching benefits, helps us manage states (loading, errors), as well as provides overall consistency in code. (See here for our section of documentation on this.) In this PR, even with debouncing, we'd be making several requests to /profile/preferences and we should be leveraging the RQ cache.

@nikhagra Please update to use React Query here in place of the api-v4 functions, and let us know if you run into any questions on implementing that switch.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice to have: JSDocs comments are useful to include for custom hooks and utils. useRestrictedGlobalGrantCheck and usePagination are a couple examples of where we do this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure

Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { getUserPreferences, updateUserPreferences } from '@linode/api-v4';

import type { AclpConfig } from '@linode/api-v4';

let userPreference: AclpConfig;
let timerId: ReturnType<typeof setTimeout>;

export const loadUserPreference = async () => {
const data = await getUserPreferences();

if (!data || !data.aclpPreference) {
userPreference = {} as AclpConfig;
} else {
userPreference = { ...data.aclpPreference };
}
return data;
};

export const getUserPreferenceObject = () => {
return { ...userPreference };
};

const updateUserPreference = async (updatedData: AclpConfig) => {
const data = await getUserPreferences();
return await updateUserPreferences({ ...data, aclpPreference: updatedData });
};

export const updateGlobalFilterPreference = (data: {}) => {
if (!userPreference) {
userPreference = {} as AclpConfig;
}
userPreference = { ...userPreference, ...data };

debounce(userPreference);
};
// to avoid frequent preference update calls within 500 ms interval
const debounce = (updatedData: AclpConfig) => {
if (timerId) {
clearTimeout(timerId);
}

timerId = setTimeout(() => updateUserPreference(updatedData), 500);
};
19 changes: 19 additions & 0 deletions packages/manager/src/features/CloudPulse/Utils/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const DASHBOARD_ID = 'dashboardId';

export const REGION = 'region';

export const RESOURCES = 'resources';

export const INTERVAL = 'interval';

export const TIME_DURATION = 'timeDuration';

export const AGGREGATE_FUNCTION = 'aggregateFunction';

export const SIZE = 'size';

export const LABEL = 'label';

export const REFRESH = 'refresh';

export const TIME_GRANULARITY = 'timeGranularity';
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { renderWithTheme } from 'src/utilities/testHelpers';
import {
CloudPulseDashboardSelect,
CloudPulseDashboardSelectProps,
} from './CloudPulseDashboardSelect';
import React from 'react';
import { fireEvent, screen } from '@testing-library/react';
import React from 'react';

import { renderWithTheme } from 'src/utilities/testHelpers';

import { DASHBOARD_ID } from '../Utils/constants';
import * as preferences from '../Utils/UserPreference';
import { CloudPulseDashboardSelect } from './CloudPulseDashboardSelect';

import type { CloudPulseDashboardSelectProps } from './CloudPulseDashboardSelect';
import type { AclpConfig } from '@linode/api-v4';

const dashboardLabel = 'Dashboard 1';
const props: CloudPulseDashboardSelectProps = {
handleDashboardChange: vi.fn(),
};
Expand All @@ -26,23 +31,23 @@ queryMocks.useCloudViewDashboardsQuery.mockReturnValue({
data: {
data: [
{
created: '2024-04-29T17:09:29',
id: 1,
type: 'standard',
label: dashboardLabel,
service_type: 'linode',
label: 'Dashboard 1',
created: '2024-04-29T17:09:29',
type: 'standard',
updated: null,
widgets: {},
},
],
},
isLoading: false,
error: false,
isLoading: false,
});

describe('CloudPulse Dashboard select', () => {
it('Should render dashboard select component', () => {
const { getByTestId, getByPlaceholderText } = renderWithTheme(
const { getByPlaceholderText, getByTestId } = renderWithTheme(
<CloudPulseDashboardSelect {...props} />
);

Expand All @@ -55,18 +60,29 @@ describe('CloudPulse Dashboard select', () => {
fireEvent.click(screen.getByRole('button', { name: 'Open' }));

expect(
screen.getByRole('option', { name: 'Dashboard 1' })
screen.getByRole('option', { name: dashboardLabel })
).toBeInTheDocument();
}),
it('Should select the option on click', () => {
renderWithTheme(<CloudPulseDashboardSelect {...props} />);

fireEvent.click(screen.getByRole('button', { name: 'Open' }));
fireEvent.click(screen.getByRole('option', { name: 'Dashboard 1' }));
fireEvent.click(screen.getByRole('option', { name: dashboardLabel }));

expect(screen.getByRole('combobox')).toHaveAttribute(
'value',
dashboardLabel
);
}),
it('Should select the default value from preferences', () => {
const mockFunction = vi.spyOn(preferences, 'getUserPreferenceObject');
mockFunction.mockReturnValue({ [DASHBOARD_ID]: 1 } as AclpConfig);

renderWithTheme(<CloudPulseDashboardSelect {...props} />);

expect(screen.getByRole('combobox')).toHaveAttribute(
'value',
'Dashboard 1'
dashboardLabel
);
});
});
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import React from 'react';

import { Dashboard } from '@linode/api-v4';
import { Autocomplete } from 'src/components/Autocomplete/Autocomplete';
import { Box } from 'src/components/Box';
import { Typography } from 'src/components/Typography';
import { useCloudViewDashboardsQuery } from 'src/queries/cloudpulse/dashboards';

import { DASHBOARD_ID, REGION, RESOURCES } from '../Utils/constants';
import {
getUserPreferenceObject,
updateGlobalFilterPreference,
} from '../Utils/UserPreference';

import type { Dashboard } from '@linode/api-v4';

export interface CloudPulseDashboardSelectProps {
handleDashboardChange: (dashboard: Dashboard | undefined) => void;
handleDashboardChange: (
dashboard: Dashboard | undefined,
isDefault?: boolean
) => void;
}

export const CloudPulseDashboardSelect = React.memo(
Expand All @@ -16,7 +26,12 @@ export const CloudPulseDashboardSelect = React.memo(
data: dashboardsList,
error,
isLoading,
} = useCloudViewDashboardsQuery(true); //Fetch the list of dashboards
} = useCloudViewDashboardsQuery(true); // Fetch the list of dashboards

const [
selectedDashboard,
setSelectedDashboard,
] = React.useState<Dashboard>();

const errorText: string = error ? 'Error loading dashboards' : '';

Expand All @@ -29,26 +44,35 @@ export const CloudPulseDashboardSelect = React.memo(
);
};

if (!dashboardsList) {
return (
<Autocomplete
options={[]}
label=""
disabled={true}
onChange={() => {}}
data-testid="cloudview-dashboard-select"
placeholder={placeHolder}
errorText={errorText}
/>
);
}
// Once the data is loaded, set the state variable with value stored in preferences
React.useEffect(() => {
if (dashboardsList) {
const dashboardId = getUserPreferenceObject()?.dashboardId;

if (dashboardId) {
const dashboard = dashboardsList.data.find(
(obj) => obj.id === dashboardId
);
setSelectedDashboard(dashboard);
props.handleDashboardChange(dashboard, true);
} else {
props.handleDashboardChange(undefined, true);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dashboardsList]);

return (
<Autocomplete
onChange={(_: any, dashboard: Dashboard) => {
updateGlobalFilterPreference({
[DASHBOARD_ID]: dashboard?.id,
[REGION]: undefined,
[RESOURCES]: undefined,
});
setSelectedDashboard(dashboard);
props.handleDashboardChange(dashboard);
}}
options={getSortedDashboardsList(dashboardsList.data)}
renderGroup={(params) => (
<Box key={params.key}>
<Typography
Expand All @@ -63,14 +87,17 @@ export const CloudPulseDashboardSelect = React.memo(
autoHighlight
clearOnBlur
data-testid="cloudview-dashboard-select"
disabled={!dashboardsList}
errorText={errorText}
fullWidth
groupBy={(option: Dashboard) => option.service_type}
isOptionEqualToValue={(option, value) => option.label === value.label}
isOptionEqualToValue={(option, value) => option.id === value.id}
label=""
loading={isLoading}
noMarginTop
options={getSortedDashboardsList(dashboardsList?.data ?? [])}
placeholder={placeHolder}
value={selectedDashboard ?? null} // Undefined is not allowed for uncontrolled component
/>
);
}
Expand Down
Loading
Loading