Skip to content

[CRUD] CRUD UI improvements #4937

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 4 commits into
base: master
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
29 changes: 21 additions & 8 deletions packages/toolpad-core/src/Crud/Edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -201,21 +201,34 @@ function Edit<D extends DataModel>(props: EditProps<D>) {
const { fields, validate, ...methods } = cachedDataSource;
const { getOne, updateOne } = methods;

const [data, setData] = React.useState<D | null>(null);
const [isLoading, setIsLoading] = React.useState(false);
const cachedData = React.useMemo(
() => cache && (cache.get(JSON.stringify(['getOne', id])) as D),
[cache, id],
);

const [data, setData] = React.useState<D | null>(cachedData);
const [isLoading, setIsLoading] = React.useState(!cachedData);
const [error, setError] = React.useState<Error | null>(null);

const loadData = React.useCallback(async () => {
setError(null);
setIsLoading(true);
try {
const showData = await getOne(id);

let showData = cachedData;
if (!showData) {
setIsLoading(true);

try {
showData = await getOne(id);
} catch (showDataError) {
setError(showDataError as Error);
}
}

if (showData) {
setData(showData);
} catch (showDataError) {
setError(showDataError as Error);
}
setIsLoading(false);
}, [getOne, id]);
}, [cachedData, getOne, id]);

React.useEffect(() => {
loadData();
Expand Down
203 changes: 108 additions & 95 deletions packages/toolpad-core/src/Crud/List.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material';
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Stack from '@mui/material/Stack';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import {
DataGrid,
GridToolbar,
Expand Down Expand Up @@ -37,21 +36,6 @@ import { useCachedDataSource } from './useCachedDataSource';
import type { DataModel, DataModelId, DataSource } from './types';
import { CRUD_DEFAULT_LOCALE_TEXT, type CRUDLocaleText } from './localeText';

const ErrorOverlay = styled('div')(({ theme }) => ({
position: 'absolute',
backgroundColor: theme.palette.error.light,
borderRadius: '4px',
top: 0,
height: '100%',
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
p: 1,
zIndex: 10,
}));

export interface ListSlotProps {
dataGrid?: Partial<DataGridProps | DataGridProProps | DataGridPremiumProps>;
}
Expand Down Expand Up @@ -165,11 +149,6 @@ function List<D extends DataModel>(props: ListProps<D>) {
const dialogs = useDialogs();
const notifications = useNotifications();

const [rowsState, setRowsState] = React.useState<{ rows: D[]; rowCount: number }>({
rows: [],
rowCount: 0,
});

const [paginationModel, setPaginationModel] = React.useState<GridPaginationModel>({
page: routerContext?.searchParams.get('page')
? Number(routerContext?.searchParams.get('page'))
Expand All @@ -189,7 +168,30 @@ function List<D extends DataModel>(props: ListProps<D>) {
: [],
);

const [isLoading, setIsLoading] = React.useState(true);
const cachedData = React.useMemo(
() =>
cache &&
(cache.get(
JSON.stringify([
'getMany',
{
paginationModel,
sortModel,
filterModel,
},
]),
) as {
items: D[];
itemCount: number;
}),
[cache, filterModel, paginationModel, sortModel],
);

const [rowsState, setRowsState] = React.useState<{ rows: D[]; rowCount: number }>({
rows: cachedData?.items ?? [],
rowCount: cachedData?.itemCount ?? 0,
});
const [isLoading, setIsLoading] = React.useState(!cachedData);
const [error, setError] = React.useState<Error | null>(null);

React.useEffect(() => {
Expand Down Expand Up @@ -242,26 +244,34 @@ function List<D extends DataModel>(props: ListProps<D>) {

const loadData = React.useCallback(async () => {
setError(null);
setIsLoading(true);
try {
const listData = await getMany({
paginationModel,
sortModel,
filterModel,
});

let listData = cachedData;
if (!listData) {
setIsLoading(true);

try {
listData = await getMany({
paginationModel,
sortModel,
filterModel,
});
} catch (listDataError) {
setError(listDataError as Error);
}
}

if (listData) {
setRowsState({
rows: listData.items,
rowCount: listData.itemCount,
});
} catch (listDataError) {
setError(listDataError as Error);
}
setIsLoading(false);
}, [filterModel, getMany, paginationModel, sortModel]);
}, [cachedData, filterModel, getMany, paginationModel, sortModel]);

React.useEffect(() => {
loadData();
}, [filterModel, getMany, loadData, paginationModel, sortModel]);
}, [loadData]);

const handleRefresh = React.useCallback(() => {
if (!isLoading) {
Expand Down Expand Up @@ -388,68 +398,71 @@ function List<D extends DataModel>(props: ListProps<D>) {

return (
<Stack sx={{ flex: 1, width: '100%' }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 1 }}>
<Tooltip title={localeText.reloadButtonLabel} placement="right" enterDelay={1000}>
<div>
<IconButton aria-label="refresh" onClick={handleRefresh}>
<RefreshIcon />
</IconButton>
</div>
</Tooltip>
{onCreateClick ? (
<Button variant="contained" onClick={onCreateClick} startIcon={<AddIcon />}>
{localeText.createNewButtonLabel}
</Button>
) : null}
</Stack>
<Box sx={{ flex: 1, position: 'relative', width: '100%' }}>
{/* Use NoSsr to prevent issue https://github.com/mui/mui-x/issues/17077 as DataGrid has no SSR support */}
<NoSsr>
<DataGridSlot
rows={rowsState.rows}
rowCount={rowsState.rowCount}
columns={columns}
pagination
sortingMode="server"
filterMode="server"
paginationMode="server"
paginationModel={paginationModel}
onPaginationModelChange={setPaginationModel}
sortModel={sortModel}
onSortModelChange={setSortModel}
filterModel={filterModel}
onFilterModelChange={setFilterModel}
onRowClick={handleRowClick}
loading={isLoading}
initialState={initialState}
slots={{ toolbar: GridToolbar }}
// Prevent type conflicts if slotProps don't match DataGrid used for dataGrid slot
{...(slotProps?.dataGrid as Record<string, unknown>)}
sx={{
[`& .${gridClasses.columnHeader}, & .${gridClasses.cell}`]: {
outline: 'transparent',
},
[`& .${gridClasses.columnHeader}:focus-within, & .${gridClasses.cell}:focus-within`]:
{
outline: 'none',
},
...(onRowClick
? {
[`& .${gridClasses.row}:hover`]: {
cursor: 'pointer',
{error ? (
<Box sx={{ flexGrow: 1 }}>
<Alert severity="error">{error.message}</Alert>
</Box>
) : (
<React.Fragment>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 1 }}>
<Tooltip title={localeText.reloadButtonLabel} placement="right" enterDelay={1000}>
<div>
<IconButton aria-label="refresh" onClick={handleRefresh}>
<RefreshIcon />
</IconButton>
</div>
</Tooltip>
{onCreateClick ? (
<Button variant="contained" onClick={onCreateClick} startIcon={<AddIcon />}>
{localeText.createNewButtonLabel}
</Button>
) : null}
</Stack>
<Box sx={{ flex: 1, position: 'relative', width: '100%' }}>
{/* Use NoSsr to prevent issue https://github.com/mui/mui-x/issues/17077 as DataGrid has no SSR support */}
<NoSsr>
<DataGridSlot
rows={rowsState.rows}
rowCount={rowsState.rowCount}
columns={columns}
pagination
sortingMode="server"
filterMode="server"
paginationMode="server"
paginationModel={paginationModel}
onPaginationModelChange={setPaginationModel}
sortModel={sortModel}
onSortModelChange={setSortModel}
filterModel={filterModel}
onFilterModelChange={setFilterModel}
onRowClick={handleRowClick}
loading={isLoading}
initialState={initialState}
slots={{ toolbar: GridToolbar }}
// Prevent type conflicts if slotProps don't match DataGrid used for dataGrid slot
{...(slotProps?.dataGrid as Record<string, unknown>)}
sx={{
[`& .${gridClasses.columnHeader}, & .${gridClasses.cell}`]: {
outline: 'transparent',
},
[`& .${gridClasses.columnHeader}:focus-within, & .${gridClasses.cell}:focus-within`]:
{
outline: 'none',
},
}
: {}),
...slotProps?.dataGrid?.sx,
}}
/>
</NoSsr>
{error && (
<ErrorOverlay>
<Typography variant="body1">{error.message}</Typography>
</ErrorOverlay>
)}
</Box>
...(onRowClick
? {
[`& .${gridClasses.row}:hover`]: {
cursor: 'pointer',
},
}
: {}),
...slotProps?.dataGrid?.sx,
}}
/>
</NoSsr>
</Box>
</React.Fragment>
)}
</Stack>
);
}
Expand Down
29 changes: 21 additions & 8 deletions packages/toolpad-core/src/Crud/Show.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,23 +85,36 @@ function Show<D extends DataModel>(props: ShowProps<D>) {
const dialogs = useDialogs();
const notifications = useNotifications();

const [data, setData] = React.useState<D | null>(null);
const [isLoading, setIsLoading] = React.useState(false);
const cachedData = React.useMemo(
() => cache && (cache.get(JSON.stringify(['getOne', id])) as D),
[cache, id],
);

const [data, setData] = React.useState<D | null>(cachedData);
const [isLoading, setIsLoading] = React.useState(!cachedData);
const [error, setError] = React.useState<Error | null>(null);

const [hasDeleted, setHasDeleted] = React.useState(false);

const loadData = React.useCallback(async () => {
setError(null);
setIsLoading(true);
try {
const showData = await getOne(id);

let showData = cachedData;
if (!showData) {
setIsLoading(true);

try {
showData = await getOne(id);
} catch (showDataError) {
setError(showDataError as Error);
}
}

if (showData) {
setData(showData);
} catch (showDataError) {
setError(showDataError as Error);
}
setIsLoading(false);
}, [getOne, id]);
}, [cachedData, getOne, id]);

React.useEffect(() => {
loadData();
Expand Down