Skip to content

feat: Generalize user preferences as per resource kind #793

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

Open
wants to merge 15 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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 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
@@ -1,6 +1,6 @@
{
"name": "@devtron-labs/devtron-fe-common-lib",
"version": "1.15.3-pre-4",
"version": "1.15.3-beta-3",
"description": "Supporting common component library",
"type": "module",
"main": "dist/index.js",
Expand Down
41 changes: 41 additions & 0 deletions src/Shared/Components/ContextSwitcher/ContextSwitcher.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { getNoMatchingResultText, SelectPicker, SelectPickerVariantType } from '@Shared/Components'
import { ComponentSizeType } from '@Shared/constants'

import { ContextSwitcherTypes } from './types'
import { customSelect, getDisabledOptions } from './utils'

export const ContextSwitcher = ({
inputId,
options = [],
inputValue,
onInputChange,
isLoading,
value,
onChange,
placeholder,
filterOption,
formatOptionLabel,
}: ContextSwitcherTypes) => {
const selectedOptions = options?.map((section) => ({
...section,
options: section?.label === 'Recently Visited' ? section.options?.slice(1) : section.options,
}))
return (
<SelectPicker
inputId={inputId}
options={selectedOptions || []}
inputValue={inputValue}
onInputChange={onInputChange}
isLoading={isLoading}
noOptionsMessage={getNoMatchingResultText}
onChange={onChange}
value={value}
variant={SelectPickerVariantType.BORDER_LESS}
placeholder={placeholder}
isOptionDisabled={getDisabledOptions}
size={ComponentSizeType.xl}
filterOption={filterOption || customSelect}
formatOptionLabel={formatOptionLabel}
/>
)
}
3 changes: 3 additions & 0 deletions src/Shared/Components/ContextSwitcher/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { ContextSwitcher } from './ContextSwitcher'
export type { ContextSwitcherTypes, RecentlyVisitedGroupedOptionsType, RecentlyVisitedOptions } from './types'
export { getMinCharSearchPlaceholderGroup } from './utils'
30 changes: 30 additions & 0 deletions src/Shared/Components/ContextSwitcher/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { GroupBase } from 'react-select'

import { SelectPickerOptionType, SelectPickerProps } from '../SelectPicker'

export interface ContextSwitcherTypes
extends Pick<
SelectPickerProps,
| 'placeholder'
| 'onChange'
| 'value'
| 'isLoading'
| 'onInputChange'
| 'inputValue'
| 'inputId'
| 'formatOptionLabel'
| 'filterOption'
> {
options: GroupBase<SelectPickerOptionType<string | number>>[]
isAppDataAvailable?: boolean
}

export interface RecentlyVisitedOptions extends SelectPickerOptionType<number> {
isDisabled?: boolean
isRecentlyVisited?: boolean
}

export interface RecentlyVisitedGroupedOptionsType extends GroupBase<SelectPickerOptionType<number>> {
label: string
options: RecentlyVisitedOptions[]
}
14 changes: 14 additions & 0 deletions src/Shared/Components/ContextSwitcher/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { SelectPickerProps } from '../SelectPicker'
import { RecentlyVisitedGroupedOptionsType, RecentlyVisitedOptions } from './types'

export const getDisabledOptions = (option: RecentlyVisitedOptions): SelectPickerProps['isDisabled'] => option.isDisabled

export const customSelect: SelectPickerProps['filterOption'] = (option, searchText: string) => {
const label = option.data.label as string
return option.data.value === 0 || label.toLowerCase().includes(searchText.toLowerCase())
}

export const getMinCharSearchPlaceholderGroup = (resourceKind: string): RecentlyVisitedGroupedOptionsType => ({
label: `All ${resourceKind}`,
options: [{ value: 0, label: 'Type 3 characters to search', isDisabled: true }],
})
1 change: 1 addition & 0 deletions src/Shared/Components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export * from './CollapsibleList'
export * from './CommitChipCell'
export * from './Confetti'
export * from './ConfirmationModal'
export * from './ContextSwitcher'
export * from './CountrySelect'
export * from './CustomInput'
export * from './DatePicker'
Expand Down
55 changes: 41 additions & 14 deletions src/Shared/Hooks/useUserPreferences/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@
import { ROUTES } from '@Common/Constants'
import { get, getUrlWithSearchParams, patch, showError } from '@Common/index'
import { THEME_PREFERENCE_MAP } from '@Shared/Providers/ThemeProvider/types'
import { BaseAppMetaData } from '@Shared/Services'
import { ResourceKindType } from '@Shared/types'

import { USER_PREFERENCES_ATTRIBUTE_KEY } from './constants'
import {
BaseRecentlyVisitedEntitiesTypes,
GetUserPreferencesParsedDTO,
GetUserPreferencesQueryParamsType,
UpdateUserPreferencesPayloadType,
Expand All @@ -34,6 +33,17 @@ import {
} from './types'
import { getUserPreferenceResourcesMetadata } from './utils'

export const getParsedResourcesMap = (resources: GetUserPreferencesParsedDTO['resources']) => {
const resourcesMap = resources || {}
const parsedResourcesMap: UserPreferencesType['resources'] = {}

Object.entries(resourcesMap).forEach(([resourceKind, resourceActions]) => {
parsedResourcesMap[resourceKind] = resourceActions
})

return parsedResourcesMap
}

/**
* @returns UserPreferencesType
* @description This function fetches the user preferences from the server. It uses the `get` method to make a request to the server and retrieves the user preferences based on the `USER_PREFERENCES_ATTRIBUTE_KEY`. The result is parsed and returned as a `UserPreferencesType` object.
Expand Down Expand Up @@ -64,17 +74,9 @@ export const getUserPreferences = async (): Promise<UserPreferencesType> => {
parsedResult.computedAppTheme === 'system-dark' || parsedResult.computedAppTheme === 'system-light'
? THEME_PREFERENCE_MAP.auto
: parsedResult.computedAppTheme,
resources: {
[ResourceKindType.devtronApplication]: {
[UserPreferenceResourceActions.RECENTLY_VISITED]:
parsedResult.resources?.[ResourceKindType.devtronApplication]?.[
UserPreferenceResourceActions.RECENTLY_VISITED
] || ([] as BaseAppMetaData[]),
},
},
resources: getParsedResourcesMap(parsedResult.resources),
}
}

/**
* @description This function updates the user preferences in the server. It constructs a payload with the updated user preferences and sends a PATCH request to the server. If the request is successful, it returns true. If an error occurs, it shows an error message and returns false.
* @param updatedUserPreferences - The updated user preferences to be sent to the server.
Copy link
Member

Choose a reason for hiding this comment

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

Pls fix the comment

Expand All @@ -87,6 +89,8 @@ export const getUserPreferences = async (): Promise<UserPreferencesType> => {
const getUserPreferencePayload = async ({
path,
value,
resourceKind,
userPreferencesResponse,
}: UserPathValueMapType): Promise<Partial<UserPreferencesPayloadValueType>> => {
switch (path) {
case 'themePreference':
Expand All @@ -100,10 +104,24 @@ const getUserPreferencePayload = async ({
value.pipelineRBACViewSelectedTab === ViewIsPipelineRBACConfiguredRadioTabs.ACCESS_ONLY,
}

case 'resources':
case 'resources': {
const existingResources = userPreferencesResponse?.resources || {}

const updatedResources = {
...existingResources,
[resourceKind]: {
...existingResources[resourceKind],
[UserPreferenceResourceActions.RECENTLY_VISITED]:
getUserPreferenceResourcesMetadata(value as BaseRecentlyVisitedEntitiesTypes[], resourceKind)[
resourceKind
]?.[UserPreferenceResourceActions.RECENTLY_VISITED] || [],
},
}

return {
resources: getUserPreferenceResourcesMetadata(value as BaseAppMetaData[]),
resources: updatedResources,
}
}
default:
return {}
}
Expand All @@ -112,12 +130,21 @@ const getUserPreferencePayload = async ({
export const updateUserPreferences = async ({
path,
value,
resourceKind,
shouldThrowError = false,
userPreferencesResponse,
}: UserPreferenceResourceProps): Promise<boolean> => {
try {
const payload: UpdateUserPreferencesPayloadType = {
key: USER_PREFERENCES_ATTRIBUTE_KEY,
value: JSON.stringify(await getUserPreferencePayload({ path, value } as UserPathValueMapType)),
value: JSON.stringify(
await getUserPreferencePayload({
path,
value,
resourceKind,
userPreferencesResponse,
} as UserPathValueMapType),
),
}

await patch(`${ROUTES.ATTRIBUTES_USER}/${ROUTES.PATCH}`, payload)
Expand Down
41 changes: 30 additions & 11 deletions src/Shared/Hooks/useUserPreferences/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

import { USER_PREFERENCES_ATTRIBUTE_KEY } from '@Shared/Hooks/useUserPreferences/constants'
import { AppThemeType, ThemeConfigType, ThemePreferenceType } from '@Shared/Providers/ThemeProvider/types'
import { BaseAppMetaData } from '@Shared/Services'
import { ResourceKindType } from '@Shared/types'

export interface GetUserPreferencesQueryParamsType {
Expand All @@ -31,12 +30,24 @@ export enum ViewIsPipelineRBACConfiguredRadioTabs {
export enum UserPreferenceResourceActions {
RECENTLY_VISITED = 'recently-visited',
}
export interface UserResourceKindActionType {
[UserPreferenceResourceActions.RECENTLY_VISITED]: BaseAppMetaData[]
export type PreferredResourceKindType =
| ResourceKindType.devtronApplication
| ResourceKindType.job
| 'app-group'
| ResourceKindType.cluster

export interface BaseRecentlyVisitedEntitiesTypes {
id: number
name: string
}
export interface UserPreferenceRecentlyVisitedAppsTypes extends BaseRecentlyVisitedEntitiesTypes {
resourceKind: PreferredResourceKindType
}
export interface UserPreferenceResourceType {
[ResourceKindType.devtronApplication]: UserResourceKindActionType

export interface UserResourceKindActionType {
[UserPreferenceResourceActions.RECENTLY_VISITED]: BaseRecentlyVisitedEntitiesTypes[]
}
export type UserPreferenceResourceType = Partial<Record<PreferredResourceKindType, UserResourceKindActionType>>
export interface GetUserPreferencesParsedDTO {
viewPermittedEnvOnly?: boolean
/**
Expand Down Expand Up @@ -75,31 +86,39 @@ export interface UserPreferencesType {

export interface UpdatedUserPreferencesType extends UserPreferencesType, Pick<ThemeConfigType, 'appTheme'> {}

export interface RecentlyVisitedFetchConfigType extends UserPreferenceRecentlyVisitedAppsTypes {
isDataAvailable?: boolean
}

export interface UseUserPreferencesProps {
userPreferenceResourceKind?: PreferredResourceKindType
migrateUserPreferences?: (userPreferencesResponse: UserPreferencesType) => Promise<UserPreferencesType>
recentlyVisitedFetchConfig?: RecentlyVisitedFetchConfigType
}

export type UserPathValueMapType =
| {
path: 'themePreference'
value: Required<Pick<UpdatedUserPreferencesType, 'themePreference' | 'appTheme'>>
resourceKind?: never
userPreferencesResponse?: never
}
| {
path: 'pipelineRBACViewSelectedTab'
value: Required<Pick<UserPreferencesType, 'pipelineRBACViewSelectedTab'>>
resourceKind?: never
userPreferencesResponse?: never
}
| {
path: 'resources'
value: Required<BaseAppMetaData[]>
value: Required<BaseRecentlyVisitedEntitiesTypes[]>
resourceKind: PreferredResourceKindType
userPreferencesResponse?: UserPreferencesType
}

export type UserPreferenceResourceProps = UserPathValueMapType & {
shouldThrowError?: boolean
}

export interface UserPreferenceRecentlyVisitedAppsTypes {
appId: number
appName: string
userPreferencesResponse?: UserPreferencesType
}

export interface UserPreferenceFilteredListTypes extends UserPreferenceRecentlyVisitedAppsTypes {
Expand Down
Loading