Skip to content

Commit

Permalink
fix(ControlBar): optimize model saving process in ControlBar component (
Browse files Browse the repository at this point in the history
#177)

Commit ensures that the 'save' function is subscribed only once to
modelSaveSubs - an established change of model state. It guarantees that
the act of subscribing and unsubscribing is done smoothly everytime
modelsave state changes, ensuring optimised performance and logical
clean up. The filename for saved files also now includes '.json'
extension for appropriate categorization.
  • Loading branch information
Lutra-Fs authored Oct 10, 2023
1 parent eb07bdc commit e3cb1c8
Showing 1 changed file with 27 additions and 20 deletions.
47 changes: 27 additions & 20 deletions src/components/ControlBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,30 +51,37 @@ export default function ControlBar(props: ControlBarProps): React.ReactElement {
const { modelSaveSubs, worker, setRestorePopupVisible } = props;

useEffect(() => {
modelSaveSubs.push((sav: ModelSave) => {
save(sav);
});
// take the json and have the user download it
function save(sav: ModelSave): void {
const filename = `${sav.modelType}@${sav.time}`;
const dat = JSON.stringify(sav);
const blob = new Blob([dat], { type: 'application/json' });
const url = URL.createObjectURL(blob);
if (!modelSaveSubs.includes(save)) {
modelSaveSubs.push(save);
}
return () => {
const index = modelSaveSubs.findIndex((value) => value === save);
if (index !== -1) {
modelSaveSubs.splice(index, 1);
}
};
}, [modelSaveSubs]);

const link = document.createElement('a');
link.href = url;
link.download = filename;
link.style.display = 'none';
document.body.appendChild(link);
// take the json and have the user download it
function save(sav: ModelSave): void {
const filename = `${sav.modelType}@${sav.time}.json`;
const dat = JSON.stringify(sav);
const blob = new Blob([dat], { type: 'application/json' });
const url = URL.createObjectURL(blob);

link.click();
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.style.display = 'none';
document.body.appendChild(link);

URL.revokeObjectURL(url);
document.body.removeChild(link);
link.click();

console.log('wrote a save to ' + filename, sav);
}
}, [modelSaveSubs]);
URL.revokeObjectURL(url);
document.body.removeChild(link);

console.log('wrote a save to ' + filename, sav);
}

// take a file and send its contents to the worker

Expand Down

0 comments on commit e3cb1c8

Please sign in to comment.