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

Warn unsaved work #59

Merged
merged 14 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
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
122 changes: 113 additions & 9 deletions src/components/notebook-loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
// Component to load a notebook file and initialise the state
import {styled} from '@mui/material/styles';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import {Grid, Button, Typography} from "@mui/material";
import {Grid, Button, Typography, Dialog, DialogActions, DialogTitle, DialogContentText, IconButton} from "@mui/material";
import {initialState, Notebook} from '../state/initial';
import { useAppDispatch } from '../state/hooks';
import { useCallback } from 'react';
import { useAppDispatch, useAppSelector } from '../state/hooks';
import { useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import CloseIcon from '@mui/icons-material/Close';
import { slugify } from '../state/uiSpec-reducer';

const VisuallyHiddenInput = styled('input')({
clip: 'rect(0 0 0 0)',
Expand Down Expand Up @@ -58,20 +60,65 @@ const validateNotebook = (jsonText: string): Notebook => {
export const NotebookLoader = () => {

const dispatch = useAppDispatch();
const notebookModified = useAppSelector((state: Notebook) => state.modifiedStatus.flag);
const state = useAppSelector((state: Notebook) => state);
const resetModifiedStatus = (newStatus: boolean) => {
dispatch({type: "modifiedStatus/resetFlag", payload: {newStatus}});
}

const navigate = useNavigate();

const [open, setOpen] = useState(false);
const [alertTitle, setAlertTitle ] = useState(' ');
const [alertMsgContext, setAlertMsgContext ] = useState(' ');
const [alertBtnLabel, setAlertBtnLabel ] = useState(' ');
const [isUpload, setIsUpload ] = useState(false);

const handleContinue = () => {
setOpen(false);
newNotebook();
}

const handleClose = () => {
setOpen(false);
}

const handleNewNotebook = () => {
if(notebookModified) {
setIsUpload(false)
setAlertTitle("Start a new notebook?")
setAlertMsgContext("You have a notebook currently open. Starting a new notebook will overwrite your work.");
setAlertBtnLabel("Start New Notebook");
setOpen(true);
}
else {
newNotebook();
}
}

const handleUploadFile = () => {
if(notebookModified) {
setIsUpload(true);
setAlertTitle("Upload a notebook file?")
setAlertMsgContext("You have a notebook currently open. Uploading a new file will overwrite your work.");
setAlertBtnLabel("Continue Uploading");
setOpen(true);
}
}

const loadFn = useCallback((notebook: Notebook) => {
dispatch({ type: 'metadata/loaded', payload: notebook.metadata })
dispatch({ type: 'ui-specification/loaded', payload: notebook['ui-specification'] })
resetModifiedStatus(false)
}, [dispatch]);

const afterLoad = () => {
navigate("/info");
}

const newNotebook = () => {
loadFn(initialState);
afterLoad();
loadFn(initialState);
afterLoad();
};

const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
Expand All @@ -89,14 +136,31 @@ export const NotebookLoader = () => {
}
};

const downloadNotebook = () => {
const element = document.createElement("a");
const file = new Blob([JSON.stringify(state, null, 2)], { type: 'application/json' });
element.href = URL.createObjectURL(file);
const name = slugify(state.metadata.name as string);
element.download = `${name}.json`;
document.body.appendChild(element);
element.click();
setOpen(false);
resetModifiedStatus(false);
};

return (
<Grid container spacing={2} pt={3}>
<Grid item xs={12} sm={6}>
<Button component="label"
<Button
component="label"
variant="contained"
startIcon={<CloudUploadIcon />}>
startIcon={<CloudUploadIcon />}
onClick={handleUploadFile}
>
Upload file
<VisuallyHiddenInput type="file" onChange={handleFileChange} />
{!notebookModified ? (
<VisuallyHiddenInput type="file" onChange={handleFileChange} id="file-upload"/>
) : (null)}
</Button>

<Typography variant="body2" color="text.secondary">
Expand All @@ -105,13 +169,53 @@ export const NotebookLoader = () => {
</Grid>

<Grid item xs={12} sm={6}>
<Button variant="contained" onClick={newNotebook}>
<Button variant="contained" onClick={handleNewNotebook}>
New Notebook
</Button>
<Typography variant="body2" color="text.secondary">
Create a new notebook from scratch.
</Typography>
</Grid>
<Dialog
open={open}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description">
<DialogTitle id="draggable-dialog-title">
<Typography sx={{ ml: 0, flex: 1 }} variant="h6" component="div">
{alertTitle}
</Typography>
<IconButton
aria-label="close"
onClick={handleClose}
sx={{
position: 'absolute',
right: 8,
top: 8,
color: (theme) => theme.palette.grey[500],
}}
>
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContentText id="alert-dialog-title" sx={{ p: 3}}>
{alertMsgContext}
</DialogContentText>
<DialogActions sx={{ pb: 3, pr: 1, justifyContent: "center"}}>
<Button onClick={downloadNotebook} variant="outlined" sx={{ mr: 1}}>Save Current Notebook</Button>
{isUpload ? (
<Button autoFocus
component="label"
variant="outlined"
startIcon={<CloudUploadIcon />}>
{alertBtnLabel}
<VisuallyHiddenInput type="file" onChange={handleFileChange} id="file-upload"/>
</Button>
) : (
<Button autoFocus onClick={handleContinue} variant="outlined" >
{alertBtnLabel}
</Button>)}
</DialogActions>
</Dialog>
</Grid>
);
};
12 changes: 10 additions & 2 deletions src/state/initial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,14 @@ export type NotebookUISpec = {
visible_types: string[],
}

export type NotebookModified = {
flag: boolean,
}

export type Notebook = {
metadata: NotebookMetadata,
"ui-specification": NotebookUISpec
"ui-specification": NotebookUISpec,
modifiedStatus: NotebookModified,
}

// an empty notebook
Expand All @@ -127,9 +132,12 @@ export const initialState: Notebook = {
"sections": {}
},
"ui-specification": {
"fields":{},
"fields": {},
"fviews": {},
"viewsets": {},
"visible_types": []
},
"modifiedStatus": {
"flag": false
}
}
90 changes: 90 additions & 0 deletions src/state/modifiedStatus-reducer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright 2023 FAIMS Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { initialState, NotebookModified } from "./initial";
import {propertyUpdated, rolesUpdated} from "./metadata-reducer";
import {fieldAdded, fieldDeleted, fieldMoved, fieldRenamed, fieldUpdated, formVisibilityUpdated, sectionAdded, sectionConditionChanged, sectionDeleted, sectionMoved, sectionRenamed, viewSetAdded, viewSetDeleted, viewSetMoved, viewSetRenamed} from "./uiSpec-reducer";

const modifiedStatusReducer = createSlice({
name: 'modifiedStatus',
initialState: initialState.modifiedStatus,
reducers: {
resetFlag: (state: NotebookModified, action: PayloadAction<{newStatus: boolean}>) => {
const { newStatus } = action.payload;
console.log("Reached modified reducer " + newStatus);
state.flag = newStatus;
},
},
extraReducers: builder => {
//Metadata reducers
builder.addCase(propertyUpdated, (state) => {
state.flag = true;
})
.addCase(rolesUpdated, (state) => {
state.flag = true;
})
//UISpec reducers
.addCase(fieldUpdated, (state) => {
state.flag = true;
})
.addCase(fieldMoved, (state) => {
state.flag = true;
})
.addCase(fieldRenamed, (state) => {
state.flag = true;
})
.addCase(fieldAdded, (state) => {
state.flag = true;
})
.addCase(fieldDeleted, (state) => {
state.flag = true;
})
.addCase(sectionRenamed, (state) => {
state.flag = true;
})
.addCase(sectionAdded, (state) => {
state.flag = true;
})
.addCase(sectionDeleted, (state) => {
state.flag = true;
})
.addCase(sectionMoved, (state) => {
state.flag = true;
})
.addCase(sectionConditionChanged, (state) => {
state.flag = true;
})
.addCase(viewSetAdded, (state) => {
state.flag = true;
})
.addCase(viewSetDeleted, (state) => {
state.flag = true;
})
.addCase(viewSetMoved, (state) => {
state.flag = true;
})
.addCase(viewSetRenamed, (state) => {
state.flag = true;
})
.addCase(formVisibilityUpdated, (state) => {
state.flag = true;
})
}
});

export const { resetFlag } = modifiedStatusReducer.actions;

export default modifiedStatusReducer.reducer;

4 changes: 3 additions & 1 deletion src/state/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import { Middleware, configureStore } from '@reduxjs/toolkit'
import metadataReducer from './metadata-reducer'
import uiSpecificationReducer from './uiSpec-reducer'
import modifiedStatusReducer from './modifiedStatus-reducer';
import { ToolkitStore } from '@reduxjs/toolkit/dist/configureStore';
import { Notebook } from './initial';
import { loadState, saveState } from './localStorage';
Expand All @@ -31,7 +32,8 @@ const loggerMiddleware: Middleware<object, Notebook> = storeAPI => next => actio
export const store: ToolkitStore<Notebook> = configureStore({
reducer: {
metadata: metadataReducer,
"ui-specification": uiSpecificationReducer
"ui-specification": uiSpecificationReducer,
modifiedStatus: modifiedStatusReducer,
},
preloadedState: persistedState,
middleware: (getDefaultMiddleware) =>
Expand Down
7 changes: 2 additions & 5 deletions src/state/uiSpec-reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,9 @@ export const slugify = (str: string) => {
return str;
};



export const uiSpecificationReducer = createSlice({
name: 'ui-specification',
initialState: initialState["ui-specification"],
initialState: initialState['ui-specification'],
reducers: {
loaded: (_state: NotebookUISpec, action: PayloadAction<NotebookUISpec>) => {
return action.payload;
Expand Down Expand Up @@ -185,7 +183,6 @@ export const uiSpecificationReducer = createSlice({
// add to fields and to the fview section
state.fields[fieldLabel] = newField;
state.fviews[viewId].fields.push(fieldLabel);

},
fieldDeleted: (state: NotebookUISpec,
action: PayloadAction<{ fieldName: string, viewId: string }>) => {
Expand Down Expand Up @@ -372,6 +369,6 @@ export const uiSpecificationReducer = createSlice({
}
})

export const { loaded, fieldUpdated } = uiSpecificationReducer.actions;
export const { loaded, fieldUpdated, fieldMoved, fieldRenamed, fieldAdded, fieldDeleted, sectionRenamed, sectionAdded, sectionDeleted, sectionMoved, sectionConditionChanged, viewSetAdded, viewSetDeleted, viewSetMoved, viewSetRenamed, formVisibilityUpdated } = uiSpecificationReducer.actions;

export default uiSpecificationReducer.reducer;
5 changes: 4 additions & 1 deletion src/test-notebook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,5 +330,8 @@ export const sampleNotebook:Notebook = {
"visible_types": [
"Primary"
]
}
},
"modifiedStatus": {
flag: false,
},
}
Loading