Skip to content

Commit

Permalink
partial commit - saving changes to ensure that resetting will not rem…
Browse files Browse the repository at this point in the history
…ove too much progress.
  • Loading branch information
siddheshraze committed Aug 5, 2024
1 parent d47e4a2 commit 8e04600
Show file tree
Hide file tree
Showing 21 changed files with 361 additions and 690 deletions.
421 changes: 97 additions & 324 deletions frontend/app/(hub)/dashboard/page.tsx

Large diffs are not rendered by default.

20 changes: 9 additions & 11 deletions frontend/app/(hub)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { useDataValidityContext } from "../contexts/datavalidityprovider";
import { AcaciaVersionTypography } from "@/styles/versions/acaciaversion";
import GithubFeedbackModal from "@/components/client/githubfeedbackmodal";
import HelpOutlineOutlinedIcon from '@mui/icons-material/HelpOutlineOutlined';
import { useLockAnimation } from "../contexts/lockanimationcontext";

const Sidebar = dynamic(() => import('@/components/sidebar'), { ssr: false });
const Header = dynamic(() => import('@/components/header'), { ssr: false });
Expand Down Expand Up @@ -105,11 +106,9 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
const [isSidebarVisible, setSidebarVisible] = useState(!!session);

const [isFeedbackModalOpen, setIsFeedbackModalOpen] = useState(false);

const pathname = usePathname();

const coreDataLoaded = siteListLoaded && plotListLoaded && censusListLoaded && (quadratListLoaded || subquadratListLoaded);

const { isPulsing } = useLockAnimation();
const loadCensusData = useCallback(async () => {
if (!currentPlot) return { success: false, message: 'Plot must be selected to load census data' };
if (censusListContext !== undefined && censusListContext.length > 0) return { success: true };
Expand Down Expand Up @@ -286,7 +285,7 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
return (
<>
<Box
className={`sidebar ${isSidebarVisible ? 'visible' : 'hidden'}`}
className={`sidebar ${isSidebarVisible ? 'visible' : 'hidden'} ${isPulsing ? `animate-fade-blur-in` : ``}`}
sx={{ position: 'fixed', top: 0, left: 0, height: '100vh', zIndex: 1000 }}
>
<Sidebar
Expand Down Expand Up @@ -326,6 +325,7 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
</Box>
<Divider orientation={"horizontal"} sx={{ my: '5px' }} />
<Box
className={isPulsing ? 'animate-fade-blur-in' : ''}
sx={{
display: 'flex',
flexGrow: 1,
Expand All @@ -334,19 +334,16 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
flexDirection: 'column',
paddingLeft: 2,
}}>
{coreDataLoaded && (
<>
{children}
</>
)}
{children}
</Box>
<Divider orientation={"horizontal"} />
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', mt: 2, position: 'relative' }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', mt: 2, position: 'relative' }} >
<Stack
spacing={1}
direction="row"
sx={{ alignItems: 'center', justifyContent: 'center', width: '100%' }}
divider={<Divider orientation="vertical" />}
className={isPulsing ? 'animate-fade-blur-in' : ''}
>
<Typography level="h1" sx={{ color: 'plum', display: 'inline-block', verticalAlign: 'middle', alignItems: 'center', justifyContent: 'center' }}>
{siteConfig.name}
Expand All @@ -361,6 +358,7 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
</Stack>
<IconButton
onClick={() => setIsFeedbackModalOpen(true)}
className={isPulsing ? 'animate-pulse-no-opacity' : ''}
sx={{
position: 'fixed',
bottom: 20,
Expand All @@ -373,7 +371,7 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
},
}}
>
<HelpOutlineOutlinedIcon />
<HelpOutlineOutlinedIcon fontSize="large" />
</IconButton>
</Box>
</Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,6 @@ export async function GET(request: NextRequest, {params}: {
}

const paginatedResults = await runQuery(conn, format(paginatedQuery, queryParams));
console.log('query: ', format(paginatedQuery, queryParams));

const totalRowsQuery = "SELECT FOUND_ROWS() as totalRows";
const totalRowsResult = await runQuery(conn, totalRowsQuery);
Expand Down
6 changes: 3 additions & 3 deletions frontend/app/contexts/lockanimationcontext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"use client";
import React, {createContext, useContext, useState, ReactNode} from 'react';
import React, { createContext, useContext, useState, ReactNode } from 'react';

interface LockAnimationContextProps {
isPulsing: boolean;
Expand All @@ -8,7 +8,7 @@ interface LockAnimationContextProps {

const LockAnimationContext = createContext<LockAnimationContextProps | undefined>(undefined);

export const LockAnimationProvider: React.FC<{ children: ReactNode }> = ({children}) => {
export const LockAnimationProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [isPulsing, setIsPulsing] = useState(false);

const triggerPulse = () => {
Expand All @@ -19,7 +19,7 @@ export const LockAnimationProvider: React.FC<{ children: ReactNode }> = ({childr
};

return (
<LockAnimationContext.Provider value={{isPulsing, triggerPulse}}>
<LockAnimationContext.Provider value={{ isPulsing, triggerPulse }}>
{children}
</LockAnimationContext.Provider>
);
Expand Down
91 changes: 50 additions & 41 deletions frontend/components/datagrids/datagridcommons.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { GridActionsCellItem, GridColDef, GridEventListener, GridRowEditStopReasons, GridRowId, GridRowModel, GridRowModes, GridRowModesModel, GridToolbar, GridToolbarContainer, GridToolbarProps, ToolbarPropsOverrides, useGridApiRef, GridCellParams, GridFilterModel, } from '@mui/x-data-grid';
import { GridActionsCellItem, GridColDef, GridEventListener, GridRowEditStopReasons, GridRowId, GridRowModel, GridRowModes, GridRowModesModel, GridToolbar, GridToolbarContainer, GridToolbarProps, ToolbarPropsOverrides, useGridApiRef, GridCellParams, GridFilterModel, useGridApiEventHandler, } from '@mui/x-data-grid';
import { Alert, Button, Snackbar, } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
Expand Down Expand Up @@ -95,19 +95,11 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {

const { setLoading } = useLoading();
const { triggerRefresh } = useDataValidityContext();
const { triggerPulse } = useLockAnimation();
const handleLockedClick = () => triggerPulse();

useSession();

const apiRef = useGridApiRef();

useEffect(() => {
if (currentCensus !== undefined) {
setLocked(currentCensus.dateRanges[0].endDate !== undefined);
}
}, [currentCensus]);

useEffect(() => {
if (!isNewRowAdded) {
fetchPaginatedData(paginationModel.page).catch(console.error);
Expand All @@ -128,6 +120,15 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
}
}, [refresh, setRefresh]);

useEffect(() => {
const initialRowModesModel = rows.reduce((acc, row) => {
acc[row.id] = { mode: GridRowModes.View };
return acc;
}, {} as GridRowModesModel);
setRowModesModel(initialRowModesModel);
}, [rows]);


const fetchFullData = async () => {
setLoading(true, "Fetching full dataset...");
let partialQuery = ``;
Expand Down Expand Up @@ -266,6 +267,7 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
};

const handleDeleteClick = (id: GridRowId) => () => {
console.log('handle delete click: ', id);
if (locked) return;
if (gridType === 'census') {
const rowToDelete = rows.find(row => String(row.id) === String(id));
Expand Down Expand Up @@ -392,12 +394,8 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
}), [gridType, currentSite?.schemaName, setSnackbar, setIsNewRowAdded, setShouldAddRowAfterFetch, fetchPaginatedData, paginationModel]);

const handleRowModesModelChange = (newRowModesModel: GridRowModesModel) => {
console.log('new row modes model: ', newRowModesModel);
setRowModesModel(newRowModesModel);

const rowInEditMode = Object.entries(newRowModesModel).find(([, mode]) => mode.mode === GridRowModes.Edit);
if (rowInEditMode) {
const [id] = rowInEditMode;
}
};

const handleCloseSnackbar = () => setSnackbar(null);
Expand Down Expand Up @@ -430,7 +428,7 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
});
};

const handleCancelClick = (id: GridRowId, event?: React.MouseEvent) => {
const handleCancelClick = (id: GridRowId, event?: React.MouseEvent | React.KeyboardEvent) => {
if (locked) return;
event?.preventDefault();
const row = rows.find(row => String(row.id) === String(id));
Expand All @@ -450,6 +448,7 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
if (handleSelectQuadrat) handleSelectQuadrat(null);
};


const getEnhancedCellAction = (type: string, icon: any, onClick: any) => (
<CellItemContainer>
<Tooltip
Expand All @@ -467,34 +466,20 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
arrow
placement="top"
>
<span
onClick={(e) => {
const iconElement = e.currentTarget.querySelector('svg');
if (iconElement) {
iconElement.classList.add('animate-bounce');
setTimeout(() => {
iconElement.classList.remove('animate-bounce');
}, 500);
}
onClick();
}}
>
<GridActionsCellItem icon={icon} label={type} />
</span>
<GridActionsCellItem icon={icon} label={type} onClick={onClick} />
</Tooltip>
</CellItemContainer>
);

function getGridActionsColumn(): GridColDef {
const getGridActionsColumn = useCallback((): GridColDef => {
return {
field: 'actions',
type: 'actions',
headerName: 'Actions',
width: 100,
cellClassName: 'actions',
getActions: ({ id }) => {
const isInEditMode = rowModesModel[id]?.mode === 'edit';

const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;
if (isInEditMode && !locked) {
return [
getEnhancedCellAction('Save', <SaveIcon />, handleSaveClick(id)),
Expand All @@ -508,12 +493,12 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
];
},
};
}
}, [rowModesModel, locked]);

const columns = useMemo(() => {
const commonColumns = gridColumns;
return [...commonColumns, getGridActionsColumn()];
}, [gridColumns, rowModesModel]);
}, [gridColumns, rowModesModel, getGridActionsColumn]);

const filteredColumns = useMemo(() => {
if (gridType !== 'quadratpersonnel') return filterColumns(rows, columns);
Expand Down Expand Up @@ -545,6 +530,33 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
}
};

const handleCellDoubleClick: GridEventListener<'cellDoubleClick'> = (params) => {
if (locked) return;
console.log('params: ', params);
setRowModesModel((prevModel) => ({
...prevModel,
[params.id]: { mode: GridRowModes.Edit },
}));
};

const handleCellKeyDown: GridEventListener<'cellKeyDown'> = (params, event) => {
if (event.key === 'Enter' && !locked) {
console.log('params: ', params);
setRowModesModel((prevModel) => ({
...prevModel,
[params.id]: { mode: GridRowModes.Edit },
}));
}
if (event.key === 'Escape') {
console.log('params: ', params);
setRowModesModel((prevModel) => ({
...prevModel,
[params.id]: { mode: GridRowModes.View, ignoreModifications: true },
}));
handleCancelClick(params.id, event);
}
};

if (!currentSite || !currentPlot || !currentCensus) {
redirect('/dashboard');
} else {
Expand All @@ -569,23 +581,20 @@ export default function DataGridCommons(props: Readonly<DataGridCommonProps>) {
sx={{ width: '100%' }}
rows={rows}
columns={filteredColumns}
editMode='row'
editMode="row"
rowModesModel={rowModesModel}
disableColumnSelector
onRowModesModelChange={handleRowModesModelChange}
onRowEditStop={handleRowEditStop}
onCellDoubleClick={handleCellDoubleClick}
onCellKeyDown={handleCellKeyDown}
processRowUpdate={processRowUpdate}
onProcessRowUpdateError={(error) => {
console.error('Row update error:', error);
setSnackbar({ children: 'Error updating row', severity: 'error' });
}}
onCellKeyDown={(params, event) => {
if (event.key === 'Enter') {
handleEnterKeyNavigation(params, event);
}
}}
loading={refresh}
paginationMode='server'
paginationMode="server"
onPaginationModelChange={setPaginationModel}
paginationModel={paginationModel}
rowCount={rowCount}
Expand Down
9 changes: 1 addition & 8 deletions frontend/components/datagrids/msvdatagrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -473,14 +473,7 @@ export default function MeasurementSummaryGrid(props: Readonly<MeasurementSummar
fetchPaginatedData(paginationModel.page);
}
}, [currentPlot, currentCensus, paginationModel.page, sortModel, isNewRowAdded, fetchPaginatedData]);

// use effect loops, pulled from datagridcommons:
useEffect(() => {
if (currentCensus !== undefined) {
setLocked(currentCensus.dateRanges[0].endDate !== undefined);
}
}, [currentCensus]);


useEffect(() => {
if (errorRowCount > 0) {
setSnackbar({
Expand Down
Loading

0 comments on commit 8e04600

Please sign in to comment.