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

Use Session Storage to hold temp state for DataGrid #1618

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
66 changes: 48 additions & 18 deletions src/components/Grid/useDataGridSource.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
useGridApiContext,
useGridApiRef,
} from '@mui/x-data-grid-pro';
import { GridInitialStatePro } from '@mui/x-data-grid-pro/models/gridStatePro';
import { groupBy, Nil, setOf } from '@seedcompany/common';
import {
useDebounceFn,
Expand All @@ -39,6 +40,7 @@ import type { Get, Paths, SetNonNullable } from 'type-fest';
import { type PaginatedListInput, type SortableListInput } from '~/api';
import type { Order } from '~/api/schema/schema.graphql';
import { lowerCase, upperCase } from '~/common';
import { usePersistedGridState } from '~/hooks/usePersistedGridState';
import { convertMuiFiltersToApi, FilterShape } from './convertMuiFiltersToApi';

type ListInput = SetNonNullable<
Expand All @@ -52,6 +54,11 @@ interface PaginatedListOutput<T> {
total: number;
}

interface SessionStorageProps {
key: string;
defaultValue: GridInitialStatePro;
}

type PathsMatching<T, List> = {
[K in Paths<T>]: K extends string
? Get<T, K> extends List
Expand Down Expand Up @@ -99,13 +106,15 @@ export const useDataGridSource = <
initialInput,
keyArgs = defaultKeyArgs,
apiRef: apiRefInput,
sessionStorageProps: sessionStateProps,
}: {
query: DocumentNode<Output, Vars>;
variables: NoInfer<Vars & { input?: Input }>;
listAt: Path;
initialInput?: Partial<Omit<NoInfer<Input>, 'page'>>;
keyArgs?: string[];
apiRef?: MutableRefObject<GridApiPro>;
sessionStorageProps: SessionStorageProps;
}) => {
const initialInputRef = useLatest(initialInput);
// eslint-disable-next-line react-hooks/rules-of-hooks -- we'll assume this doesn't change between renders
Expand Down Expand Up @@ -198,6 +207,13 @@ export const useDataGridSource = <
);
};

const [savedGridState = {}, onStateChange, persistedFilterModel] =
usePersistedGridState({
key: sessionStateProps.key,
apiRef: apiRef,
defaultValue: sessionStateProps.defaultValue,
});

// State for current sorting & filtering
const [initialSort] = useState((): ViewState['sortModel'] => [
{
Expand All @@ -215,6 +231,7 @@ export const useDataGridSource = <
}),
}
);

const persist = useDebounceFn((next: ViewState) => {
const filterModel = {
// Strip out filters for columns that shouldn't be persisted
Expand All @@ -234,9 +251,14 @@ export const useDataGridSource = <
});
});
const [view, reallySetView] = useState((): ViewState => {
const { apiFilterModel: _, ...rest } = storedView!; // not null because we give a default value
const { apiFilterModel, ...rest } = storedView!; // not null because we give a default value
return {
...rest,
filterModel: merge(
{},
rest.filterModel,
savedGridState.filter?.filterModel
),
apiSortModel: rest.sortModel,
};
});
Expand All @@ -253,23 +275,29 @@ export const useDataGridSource = <

// Convert the view state to the input for the GQL query
const input = useMemo(
() => ({
...defaultInitialInput,
...initialInputRef.current,
count: initialInputRef.current?.count ?? defaultInitialInput.count,
...(view.apiSortModel?.[0] && {
sort: view.apiSortModel[0].field,
order: upperCase(view.apiSortModel[0].sort!),
}),
// eslint-disable-next-line no-extra-boolean-cast
filter: Boolean(apiRef.current.instanceId)
? convertMuiFiltersToApi(
apiRef.current,
view.filterModel,
initialInputRef.current?.filter
)
: storedView?.apiFilterModel,
}),
() => {
const initialFilterModel = {
...storedView?.apiFilterModel,
...persistedFilterModel,
};
return {
...defaultInitialInput,
...initialInputRef.current,
count: initialInputRef.current?.count ?? defaultInitialInput.count,
...(view.apiSortModel?.[0] && {
sort: view.apiSortModel[0].field,
order: upperCase(view.apiSortModel[0].sort!),
}),
// eslint-disable-next-line no-extra-boolean-cast
filter: Boolean(apiRef.current.instanceId)
? convertMuiFiltersToApi(
apiRef.current,
view.filterModel,
initialInputRef.current?.filter
)
: initialFilterModel,
Comment on lines +292 to +298
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove redundant Boolean cast

As flagged by static analysis, the Boolean cast is redundant since the expression will already be coerced to a boolean.

Apply this change:

-       filter: Boolean(apiRef.current.instanceId)
+       filter: !!apiRef.current.instanceId
          ? convertMuiFiltersToApi(
              apiRef.current,
              view.filterModel,
              initialInputRef.current?.filter
            )
          : initialFilterModel,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
filter: Boolean(apiRef.current.instanceId)
? convertMuiFiltersToApi(
apiRef.current,
view.filterModel,
initialInputRef.current?.filter
)
: initialFilterModel,
filter: !!apiRef.current.instanceId
? convertMuiFiltersToApi(
apiRef.current,
view.filterModel,
initialInputRef.current?.filter
)
: initialFilterModel,
🧰 Tools
🪛 Biome

[error] 292-292: Avoid redundant Boolean call

It is not necessary to use Boolean call when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant Boolean call

(lint/complexity/noExtraBooleanCast)

};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[apiRef, initialInputRef, view.apiSortModel, view.filterModel]
);
Expand Down Expand Up @@ -427,10 +455,12 @@ export const useDataGridSource = <
rows,
loading,
rowCount: total,
initialState: savedGridState,
sortModel: view.sortModel,
filterModel: view.filterModel,
hideFooterPagination: true,
onFetchRows: onFetchRows.run,
onStateChange,
onSortModelChange,
onFilterModelChange,
paginationMode: total != null ? 'server' : 'client', // Not used, but prevents row count warning.
Expand Down
65 changes: 65 additions & 0 deletions src/hooks/usePersistedGridState.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { GridApiPro, GridEventListener } from '@mui/x-data-grid-pro';
import { GridInitialStatePro } from '@mui/x-data-grid-pro/models/gridStatePro';
import { useDebounceFn, usePrevious, useSessionStorageState } from 'ahooks';
import { isEqual } from 'lodash';
import { MutableRefObject, useEffect, useRef } from 'react';
import { convertMuiFiltersToApi } from '~/components/Grid/convertMuiFiltersToApi';

interface UsePersistedGridStateOptions {
key: string;
apiRef: MutableRefObject<GridApiPro>;
defaultValue: GridInitialStatePro;
}

export const usePersistedGridState = ({
key,
apiRef,
defaultValue,
}: UsePersistedGridStateOptions) => {
const isRestoringState = useRef(true);

const [savedGridState, setSavedGridState] = useSessionStorageState(key, {
defaultValue,
});

const [persistedFilterModel, setPersistedFilterModel] =
useSessionStorageState<Record<string, any>>(`${key}-api-filter`, {});

const prevGridState = usePrevious(
savedGridState,
(prev, next) => !isEqual(prev, next)
);
Comment on lines +28 to +31
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect usage of the compare function in usePrevious

The compare function in usePrevious should return true to keep the previous value unchanged when the values are equal. Currently, it returns true when the values are not equal, which prevents prevGridState from updating correctly. Adjust the compare function to isEqual(prev, next) to ensure that prevGridState updates only when the values differ.


const { run: handleStateChange } = useDebounceFn(
() => {
const gridState = apiRef.current.exportState();

setPersistedFilterModel((prev) =>
isEqual(prev, gridState)
? prev
: convertMuiFiltersToApi(
apiRef.current,
gridState.filter?.filterModel
)
);
setSavedGridState((prev) =>
isEqual(prev, gridState) ? prev || defaultValue : gridState
);
},
{ wait: 500, maxWait: 500 }
);

const onStateChange: GridEventListener<'stateChange'> = () => {
handleStateChange();
};

useEffect(() => {
if (isRestoringState.current) {
isRestoringState.current = false;
} else if (savedGridState && !isEqual(savedGridState, prevGridState)) {
apiRef.current.restoreState(savedGridState);
}
}, [savedGridState, apiRef, prevGridState]);

return [savedGridState, onStateChange, persistedFilterModel] as const;
};
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ export const ProgressReportsExpandedGrid = (
}),
[onMouseDown]
);

return (
<ExpansionContext.Provider value={expanded}>
<ProgressReportsGrid
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export interface ProgressReportsGridProps extends DataGridProps {

export const ProgressReportsGrid = ({
quarter,
initialState = {},
...props
}: ProgressReportsGridProps) => {
const source = useMemo(() => {
Expand Down Expand Up @@ -210,9 +211,14 @@ export const ProgressReportsGrid = ({
},
} as const;
}, [quarter]);

const [dataGridProps] = useDataGridSource({
...source,
apiRef: props.apiRef,
sessionStorageProps: {
key: 'progress-reports-grid',
defaultValue: initialState,
},
});

const slots = useMemo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ export const PartnerDetailEngagements = () => {
initialInput: {
sort: EngagementColumns[0]!.field,
},
sessionStorageProps: {
key: `partners-engagements-grid-state-${partnerId}`,
defaultValue: EngagementInitialState,
},
});

const slots = useMemo(
Expand All @@ -53,7 +57,6 @@ export const PartnerDetailEngagements = () => {
slots={slots}
slotProps={slotProps}
columns={EngagementColumns}
initialState={EngagementInitialState}
headerFilters
hideFooter
sx={[flexLayout, noHeaderFilterButtons, noFooter]}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,17 @@ import {

export const PartnerDetailProjects = () => {
const { partnerId = '' } = useParams();

const [props] = useDataGridSource({
query: PartnerProjectsDocument,
variables: { partnerId },
listAt: 'partner.projects',
initialInput: {
sort: 'name',
},
sessionStorageProps: {
key: `partners-projects-grid-state-${partnerId}`,
defaultValue: ProjectInitialState,
},
});

const slots = useMemo(
Expand All @@ -60,7 +63,6 @@ export const PartnerDetailProjects = () => {
slots={slots}
slotProps={slotProps}
columns={PartnerProjectColumns}
initialState={ProjectInitialState}
headerFilters
hideFooter
sx={[flexLayout, noHeaderFilterButtons, noFooter]}
Expand Down
5 changes: 4 additions & 1 deletion src/scenes/Projects/List/EngagementsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export const EngagementsPanel = () => {
initialInput: {
sort: EngagementColumns[0]!.field,
},
sessionStorageProps: {
key: 'engagements-grid',
defaultValue: EngagementInitialState,
},
});

const slots = useMemo(
Expand All @@ -49,7 +53,6 @@ export const EngagementsPanel = () => {
slots={slots}
slotProps={slotProps}
columns={EngagementColumns}
initialState={EngagementInitialState}
headerFilters
hideFooter
sx={[flexLayout, noHeaderFilterButtons, noFooter]}
Expand Down
5 changes: 4 additions & 1 deletion src/scenes/Projects/List/ProjectsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export const ProjectsPanel = () => {
initialInput: {
sort: 'name',
},
sessionStorageProps: {
key: 'projects-grid',
defaultValue: ProjectInitialState,
},
});

const slots = useMemo(
Expand All @@ -49,7 +53,6 @@ export const ProjectsPanel = () => {
slots={slots}
slotProps={slotProps}
columns={ProjectColumns}
initialState={ProjectInitialState}
headerFilters
hideFooter
sx={[flexLayout, noHeaderFilterButtons, noFooter]}
Expand Down
Loading