Skip to content

Commit

Permalink
JNG-5899 save state
Browse files Browse the repository at this point in the history
  • Loading branch information
noherczeg committed Sep 2, 2024
1 parent 6fc9c68 commit b9e057e
Show file tree
Hide file tree
Showing 16 changed files with 161 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,13 @@ export default function GodGodGalaxiesAccessTablePage() {
await refresh();
}
};
const applyRowEdit = async (rowData: ViewGalaxyStored): Promise<any> => {
setIsLoading(true);
alert(JSON.stringify(rowData, null, 2));
setTimeout(() => {
setIsLoading(false);
}, 500);
};

const actions: ViewGalaxyTablePageActions = {
getPageTitle,
Expand All @@ -263,6 +270,7 @@ export default function GodGodGalaxiesAccessTablePage() {
createIntergalacticDustAction,
createInterstellarMediumAction,
getMask,
applyRowEdit,
...(customActions ?? {}),
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,9 +381,9 @@ public static String tableButtonVisibilityConditions(Button button, Table table,
public static String tableRowButtonDisabledConditions(Button button, Table table, PageContainer container) {
if (table.getIsRelationType() && table.getRelationType().isIsInlineCreatable() && (button.getActionDefinition().getIsRemoveAction()) || button.getActionDefinition().getIsBulkRemoveAction()) {
if (button.getActionDefinition().getIsRemoveAction()) {
return "isLoading";
return "isLoading || isRowInEditMode";
} else if (button.getActionDefinition().getIsBulkRemoveAction()) {
return "getSelectedRows && getSelectedRows().length > 0 || isLoading";
return "(getSelectedRows && getSelectedRows().length > 0) || isLoading || isRowInEditMode";
}
}
String result = "getSelectedRows && getSelectedRows().length > 0 ||";
Expand Down Expand Up @@ -421,7 +421,7 @@ public static String tableRowButtonDisabledConditions(Button button, Table table
result += "!row." + button.getEnabledBy().getName() + " || ";
}

return result + "isLoading";
return result + "isLoading || isRowInEditMode";
}

public static String checkboxLabelPlacement(Checkbox checkbox) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ interface EagerTableProps<T extends GridValidRowModel, TStored extends GridValid
relationName: string;
filtersSerializer: FiltersSerializer;
navigable?: boolean;
editable?: boolean;
rowModesModel?: GridRowModesModel;
handleRowModesModelChange?: (newRowModesModel: GridRowModesModel) => void;
handleRowEditStop?: GridEventListener<'rowEditStop'>;
Expand Down Expand Up @@ -132,6 +133,7 @@ export function EagerTable<T extends GridValidRowModel, TStored extends T, S ext
checkboxSelection,
filtersSerializer,
navigable = true,
editable = false,
rowModesModel = {},
handleRowModesModelChange,
handleRowEditStop,
Expand Down Expand Up @@ -212,7 +214,7 @@ export function EagerTable<T extends GridValidRowModel, TStored extends T, S ext
const effectiveTableColumns = useMemo(() => {
const cols = [
...columns,
...columnsActionCalculator(dataElementId, tableRowActions, t, isLoading, getSelectedRows, ownerData, { crudOperationsDisplayed: crudOperationsDisplayed, transferOperationsDisplayed: transferOperationsDisplayed })
...columnsActionCalculator(dataElementId, tableRowActions, t, isLoading, editable, rowModesModel, getSelectedRows, ownerData, { crudOperationsDisplayed: crudOperationsDisplayed, transferOperationsDisplayed: transferOperationsDisplayed })
];
{{# if isMUILicensePlanPro }}
if (columnState.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ interface LazyTableProps<T extends GridValidRowModel, TStored extends GridValidR
filtersSerializer: FiltersSerializer;
navigable?: boolean;
editable?: boolean;
applyRowEdit?: (rowData: TStored) => Promise<any>;
}

export function LazyTable<T extends GridValidRowModel, TStored extends T, S extends QueryCustomizer<T>>(props: LazyTableProps<T, TStored>) {
Expand Down Expand Up @@ -150,6 +151,7 @@ export function LazyTable<T extends GridValidRowModel, TStored extends T, S exte
filtersSerializer,
navigable = true,
editable = false,
applyRowEdit,
} = props;

const apiRef = useGridApiRef();
Expand Down Expand Up @@ -210,7 +212,6 @@ export function LazyTable<T extends GridValidRowModel, TStored extends T, S exte
const [firstItem, setFirstItem] = useState<TStored>();
const [isNextButtonEnabled, setIsNextButtonEnabled] = useState<boolean>(true);
const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});
const [rowEditingData, setRowEditingData] = useState<Record<string, TStored>>({});

const isLoading = useMemo(() => isInternalLoading || !!isOwnerLoading, [isInternalLoading, isOwnerLoading]);

Expand Down Expand Up @@ -242,60 +243,46 @@ export function LazyTable<T extends GridValidRowModel, TStored extends T, S exte
id: `${uniqueId}-row-edit`,
icon: <MdiIcon path="pencil" />,
isCRUD: true,
forceKeep: true,
isEditAction: true,
hidden: (row: any) => rowModesModel[row.__identifier]?.mode === GridRowModes.Edit,
disabled: () => false,
action: async (rowData: any) => {
setRowEditingData({
...rowEditingData,
[rowData.__identifier]: simpleCloneDeep(rowData),
});
action: async (rowData: TStored) => {
setRowModesModel({ ...rowModesModel, [rowData.__identifier!]: { mode: GridRowModes.Edit } });
},
},
{
id: `${uniqueId}-row-save`,
icon: <MdiIcon path="content-save" />,
isCRUD: true,
forceKeep: true,
isEditAction: true,
hidden: (row: any) => !(rowModesModel[row.__identifier]?.mode === GridRowModes.Edit),
disabled: () => false,
action: async (rowData: any) => {

action: async (rowData: TStored) => {
setRowModesModel({ ...rowModesModel, [rowData.__identifier!]: { mode: GridRowModes.View } });
/*try {
const validationResult = await applyRowEdit!(rowData);
} catch(e) {
console.error(e);
}*/
},
},
{
id: `${uniqueId}-row-cancel`,
icon: <MdiIcon path="close" />,
isCRUD: true,
forceKeep: true,
isEditAction: true,
hidden: (row: any) => !(rowModesModel[row.__identifier]?.mode === GridRowModes.Edit),
disabled: () => false,
action: async (rowData: any) => {
setRowModesModel({
...rowModesModel,
[rowData.__identifier!]: { mode: GridRowModes.View, ignoreModifications: true }
});
const tmp = {
...rowEditingData,
};
const original = tmp[rowData.__identifier];
delete rowEditingData[rowData.__identifier];
setData((prevData) => {
const ttt = [...prevData];
const idx = ttt.findIndex(d => d.__identifier === rowData.__identifier);
ttt[idx] = original;
// debugger;
return [...ttt];
});
action: async (rowData: TStored) => {
setRowModesModel({ ...rowModesModel, [rowData.__identifier!]: { mode: GridRowModes.View, ignoreModifications: true } });
},
},
], [rowEditingData, tableRowActions, rowModesModel]);
], [tableRowActions, rowModesModel, applyRowEdit]);

const effectiveTableColumns = useMemo(() => {
const cols = [
...columns,
...columnsActionCalculator(dataElementId, [...(editable ? editActions: []), ...tableRowActions], t, isLoading, getSelectedRows, ownerData, { crudOperationsDisplayed: crudOperationsDisplayed, transferOperationsDisplayed: transferOperationsDisplayed })
...columnsActionCalculator(dataElementId, [...(editable ? editActions: []), ...tableRowActions], t, isLoading, editable, rowModesModel, getSelectedRows, ownerData, { crudOperationsDisplayed, transferOperationsDisplayed })
];
{{# if isMUILicensePlanPro }}
if (columnState.length) {
Expand All @@ -313,7 +300,7 @@ export function LazyTable<T extends GridValidRowModel, TStored extends T, S exte
}
{{/ if }}
return cols;
}, [columns, editActions, tableRowActions, getSelectedRows, ownerData, isLoading, editable{{# if isMUILicensePlanPro }}, columnState{{/ if }}]);
}, [columns, editActions, tableRowActions, getSelectedRows, ownerData, isLoading, editable, rowModesModel{{# if isMUILicensePlanPro }}, columnState{{/ if }}]);

{{# if isMUILicensePlanPro }}
const onColumnsChanged = () => {
Expand Down Expand Up @@ -600,25 +587,14 @@ export function LazyTable<T extends GridValidRowModel, TStored extends T, S exte
{{/ if }}
}

const processRowUpdate = (newRow: GridRowModel) => {
console.warn(newRow);
//const updatedRow = { ...newRow, isNew: false };
//setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
//return updatedRow;
};

const handleRowModesModelChange = (newRowModesModel: GridRowModesModel) => {
// setRowModesModel(newRowModesModel);
};

const handleRowEditStop: GridEventListener<'rowEditStop'> = (params, event) => {
if (params.reason === GridRowEditStopReasons.rowFocusOut) {
event.defaultMuiPrevented = true;
}
};
const processRowUpdate = useCallback(async (newRow: GridRowModel) => {
await applyRowEdit!(newRow as TStored);
throw new Error('lmao');
}, [applyRowEdit]);

const handleProcessRowUpdateError = useCallback((error: Error) => {
console.error(error);
setRowModesModel({ ...rowModesModel, [error.message]: { mode: GridRowModes.Edit } });
}, []);

return (
Expand Down Expand Up @@ -651,10 +627,8 @@ export function LazyTable<T extends GridValidRowModel, TStored extends T, S exte
{{/ if }}
} }
editMode="row"
rowModesModel={rowModesModel}
onRowModesModelChange={handleRowModesModelChange}
onRowEditStop={handleRowEditStop}
processRowUpdate={processRowUpdate}
rowModesModel={rowModesModel}
onProcessRowUpdateError={handleProcessRowUpdateError}
slotProps={ {
{{# if (stringValueIsTrue useTableContextMenus) }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,13 @@ export const StripedDataGrid: typeof {{ muiDataGridComponent }} = styled({{ muiD
},
},
},
'& .Mui-error': {
backgroundColor: 'rgb(126,10,15, 0.1)',
color: '#750f0f',
...theme.applyStyles('dark', {
backgroundColor: 'rgb(126,10,15, 0)',
color: '#ff4343',
}),
},
},
})) as typeof {{ muiDataGridComponent }};
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export * from './StripedDataGrid';
export * from './EagerTable';
export * from './LazyTable';
export * from './table-column-operators';
export * from './table-editor';
export * from './table-row-actions';
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { styled } from '@mui/material/styles';
import Tooltip, { tooltipClasses, type TooltipProps } from '@mui/material/Tooltip';
import {
GridEditInputCell,
type GridRenderEditCellParams,
} from '@mui/x-data-grid{{ getMUIDataGridPlanSuffix }}';

const StyledTooltip = styled(({ className, ...props }: TooltipProps) => (
<Tooltip {...props} classes={ { popper: className } } />
))(({ theme }) => ({
[`& .${tooltipClasses.tooltip}`]: {
backgroundColor: theme.palette.error.main,
color: theme.palette.error.contrastText,
},
}));

export function NameEditInputCell(props: GridRenderEditCellParams & { error?: string }) {
const { error } = props;

return (
<StyledTooltip open={!!error} title={error}>
<GridEditInputCell {...props} />
</StyledTooltip>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@

import Button from '@mui/material/Button';
import ButtonGroup from '@mui/material/ButtonGroup';
import type { GridActionsColDef, GridRowParams } from '@mui/x-data-grid{{ getMUIDataGridPlanSuffix }}';
import { type GridActionsColDef, type GridRowParams, type GridRowModesModel, GridRowModes } from '@mui/x-data-grid{{ getMUIDataGridPlanSuffix }}';
import type { TFunction } from 'i18next';
import type { JudoIdentifiable } from '~/services/data-api/common/JudoIdentifiable';
import { baseColumnConfig, characterMultiplier, iconAndDropdownIconExtra, onlyDropdownWidth } from '../../config';
import type { ColumnActionsProvider, ColumnsActionsOptions, TableRowAction } from '../../utilities';
import { DropdownButton } from '../DropdownButton';
import { MdiIcon } from '../MdiIcon';

export const calculateMinWidth = (entry: TableRowAction<any, any>[]) => entry.length ? ((entry.map(a => (a.label ?? '').length).reduce((p, c) => p + c, 0) * characterMultiplier) + iconAndDropdownIconExtra) : onlyDropdownWidth;
export const calculateMinWidth = (entry: TableRowAction<any, any>[], editable = false) => {
const baseWidth = entry.length ? ((entry.map(a => (a.label ?? '').length).reduce((p, c) => p + c, 0) * characterMultiplier) + iconAndDropdownIconExtra) : onlyDropdownWidth;
return baseWidth + (editable ? 90 : 0);
};

const findLastIndex = <T,>(array: T[], predicate: (e: T) => boolean): number => {
for (let i = array.length - 1; i >= 0; i--) {
Expand All @@ -20,11 +24,18 @@ const findLastIndex = <T,>(array: T[], predicate: (e: T) => boolean): number =>
return -1;
};

const isRowInEditMode = <T extends JudoIdentifiable<any>,>(row: T, gridRowModesModel: GridRowModesModel): boolean => {
const rowData = gridRowModesModel[row.__identifier!];
return rowData?.mode === GridRowModes.Edit;
};

export const columnsActionCalculator: ColumnActionsProvider<any, any> = (
id: string,
actions: TableRowAction<any, any>[],
t: TFunction<string, any>,
isLoading: boolean,
editable: boolean,
rowModesModel: GridRowModesModel,
getSelectedRows: () => any[],
ownerData?: any,
options?: ColumnsActionsOptions,
Expand All @@ -35,7 +46,7 @@ export const columnsActionCalculator: ColumnActionsProvider<any, any> = (
};
const originalCrudActions = actions.filter((a) => !!a.action && a.isCRUD);
const originalOperationActions = actions.filter((a) => !!a.action && !a.isCRUD);
const keptCrudActions = originalCrudActions.splice(0, (findLastIndex<TableRowAction<any, any>>(actions, a => !!a.forceKeep) + 1) + (safeOptions.crudOperationsDisplayed || 0));
const keptCrudActions = originalCrudActions.splice(0, (findLastIndex<TableRowAction<any, any>>(actions, a => !!a.isEditAction) + 1) + (safeOptions.crudOperationsDisplayed || 0));
const keptOperationActions = originalOperationActions.splice(0, safeOptions.transferOperationsDisplayed);
const splitActions = [...keptCrudActions, ...keptOperationActions];
const dropdownActions = [...originalCrudActions, ...originalOperationActions];
Expand All @@ -50,7 +61,7 @@ export const columnsActionCalculator: ColumnActionsProvider<any, any> = (
field: 'actions',
sortable: false,
disableColumnMenu: true,
minWidth: calculateMinWidth(splitActions),
minWidth: calculateMinWidth(splitActions, editable),
headerName: t('judo.pages.table.column.actions', { defaultValue: 'Actions' }) as string,
type: 'actions',
getActions: (params: GridRowParams) => [
Expand All @@ -61,7 +72,7 @@ export const columnsActionCalculator: ColumnActionsProvider<any, any> = (
key={a.id}
variant="text"
startIcon={a.icon}
disabled={a.disabled ? a.disabled(params.row, isLoading, getSelectedRows, ownerData) : false}
disabled={a.disabled ? a.disabled(params.row, isLoading, isRowInEditMode(params.row, rowModesModel), getSelectedRows, ownerData) : false}
onClick={() => a.action!(params.row)}
>
{a.label ?? ''}
Expand All @@ -76,7 +87,7 @@ export const columnsActionCalculator: ColumnActionsProvider<any, any> = (
label: action.label,
startIcon: action.icon,
onClick: () => action.action!(params.row),
disabled: action.disabled ? action.disabled(params.row, isLoading, getSelectedRows, ownerData) : false,
disabled: action.disabled ? action.disabled(params.row, isLoading, isRowInEditMode(params.row, rowModesModel), getSelectedRows, ownerData) : false,
}))}
>
<MdiIcon path="menu-down" />
Expand Down
Loading

0 comments on commit b9e057e

Please sign in to comment.