Make trySave common and move to useCommonEditorFunctions

Also makes "save()" more common between the pages, but they still have some differences
This commit is contained in:
Trevor Buckner
2026-09-13 16:24:45 -04:00
parent aaf1a718a5
commit 3e2ac93424
4 changed files with 82 additions and 65 deletions
+7 -25
View File
@@ -38,8 +38,6 @@ import LockNotification from './lockNotification/lockNotification.jsx';
import { updateHistory, versionHistoryGarbageCollection } from '../../utils/versionHistory.js'; import { updateHistory, versionHistoryGarbageCollection } from '../../utils/versionHistory.js';
import googleDriveIcon from '../../googleDrive.svg'; import googleDriveIcon from '../../googleDrive.svg';
const SAVE_TIMEOUT = 10000;
const BREWKEY = 'HB_newPage_content'; const BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'HB_newPage_style'; const STYLEKEY = 'HB_newPage_style';
const SNIPKEY = 'HB_newPage_snippets'; const SNIPKEY = 'HB_newPage_snippets';
@@ -74,7 +72,6 @@ const EditPage = (props)=>{
const editorRef = useRef(null); const editorRef = useRef(null);
const lastSavedBrew = useRef(_.cloneDeep(props.brew)); const lastSavedBrew = useRef(_.cloneDeep(props.brew));
const saveTimeout = useRef(null);
const updateBrew = (newData)=>setCurrentBrew((prevBrew)=>({ const updateBrew = (newData)=>setCurrentBrew((prevBrew)=>({
...prevBrew, ...prevBrew,
@@ -113,25 +110,6 @@ const EditPage = (props)=>{
trySave(true, true, newSaveGoogle); trySave(true, true, newSaveGoogle);
}; };
const trySave = useEffectEvent((immediate = false, hasChanges = true, saveToGoogle = false)=>{
clearTimeout(saveTimeout.current);
if(isSaving) return;
if(!hasChanges && !immediate) return;
const newTimeout = immediate ? 0 : SAVE_TIMEOUT;
saveTimeout.current = setTimeout(async ()=>{
setIsSaving(true);
setError(null);
await save(currentBrew, saveToGoogle)
.catch((err)=>{
setError(err);
});
setIsSaving(false);
setLastSavedTime(new Date());
if(!autoSaveEnabled) resetWarnUnsavedTimer();
}, newTimeout);
});
const save = async (brew, saveToGoogle)=>{ const save = async (brew, saveToGoogle)=>{
setHTMLErrors(hbfm.validate(brew.text)); setHTMLErrors(hbfm.validate(brew.text));
@@ -303,7 +281,8 @@ const EditPage = (props)=>{
resetWarnUnsavedTimer, resetWarnUnsavedTimer,
handleSplitMove, handleSplitMove,
handleBrewChange, handleBrewChange,
toggleAutoSave toggleAutoSave,
trySave
} = useCommonEditPageFunctions({ } = useCommonEditPageFunctions({
saveGoogle, saveGoogle,
setError, setError,
@@ -323,11 +302,14 @@ const EditPage = (props)=>{
setWarnUnsavedChanges, setWarnUnsavedChanges,
unsavedChanges, unsavedChanges,
setUnsavedChanges, setUnsavedChanges,
trySave,
sandbox, sandbox,
lastSavedBrew, lastSavedBrew,
editorRef, editorRef,
saveTimeout isSaving,
setIsSaving,
save,
lastSavedTime,
setLastSavedTime
}); });
return ( return (
+24 -16
View File
@@ -31,8 +31,6 @@ const { both: RecentNavItem } = RecentNavItems;
import Headtags from '@vitreum/headtags.js'; import Headtags from '@vitreum/headtags.js';
const Meta = Headtags.Meta; const Meta = Headtags.Meta;
const SAVE_TIMEOUT = 10000;
const BREWKEY = 'HB_newPage_content'; const BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'HB_newPage_style'; const STYLEKEY = 'HB_newPage_style';
const SNIPKEY = 'HB_newPage_snippets'; const SNIPKEY = 'HB_newPage_snippets';
@@ -48,6 +46,7 @@ const HomePage =(props)=>{
}; };
const [currentBrew, setCurrentBrew] = useState(props.brew); const [currentBrew, setCurrentBrew] = useState(props.brew);
const [saveGoogle, setSaveGoogle] = useState(global.account?.googleId ? true : false);
const [error, setError] = useState(undefined); const [error, setError] = useState(undefined);
const [HTMLErrors, setHTMLErrors] = useState(hbfm.validate(props.brew.text)); const [HTMLErrors, setHTMLErrors] = useState(hbfm.validate(props.brew.text));
const [currentEditorViewPageNum, setCurrentEditorViewPageNum] = useState(1); const [currentEditorViewPageNum, setCurrentEditorViewPageNum] = useState(1);
@@ -63,17 +62,19 @@ const HomePage =(props)=>{
const editorRef = useRef(null); const editorRef = useRef(null);
const lastSavedBrew = useRef(_.cloneDeep(props.brew)); const lastSavedBrew = useRef(_.cloneDeep(props.brew));
const save = ()=>{ const save = async (brew, saveToGoogle)=>{
request.post('/api') const res = await request
.send(currentBrew) .post(`/api${saveGoogle ? '?saveToGoogle=true' : ''}`)
.end((err, res)=>{ .send(brew)
if(err) { .catch((err)=>{
setError(err); console.error('Error Updating Local Brew');
return; setError(err);
}
const saved = res.body;
window.location = `/edit/${saved.editId}`;
}); });
if(!res) return;
const saved = res.body;
window.onbeforeunload = null;
window.location = `/edit/${saved.editId}`;
}; };
const renderSaveButton = ()=>{ const renderSaveButton = ()=>{
@@ -97,7 +98,7 @@ const HomePage =(props)=>{
// #3 - Unsaved changes exist, click to save, show SAVE NOW // #3 - Unsaved changes exist, click to save, show SAVE NOW
if(unsavedChanges) if(unsavedChanges)
return <Nav.item className='save' onClick={save} color='blue' icon='fas fa-save'>save now</Nav.item>; return <Nav.item className='save' onClick={()=>trySave(true, true, saveGoogle)} color='blue' icon='fas fa-save'>save now</Nav.item>;
// #4 - No unsaved changes, autosave is ON, show AUTO-SAVED // #4 - No unsaved changes, autosave is ON, show AUTO-SAVED
if(autoSaveEnabled) if(autoSaveEnabled)
@@ -135,8 +136,10 @@ const HomePage =(props)=>{
const { const {
resetWarnUnsavedTimer, resetWarnUnsavedTimer,
handleSplitMove, handleSplitMove,
handleBrewChange handleBrewChange,
trySave
} = useCommonEditPageFunctions({ } = useCommonEditPageFunctions({
saveGoogle,
setError, setError,
setThemeBundle, setThemeBundle,
HTMLErrors, HTMLErrors,
@@ -156,7 +159,12 @@ const HomePage =(props)=>{
setUnsavedChanges, setUnsavedChanges,
sandbox, sandbox,
lastSavedBrew, lastSavedBrew,
editorRef editorRef,
isSaving,
setIsSaving,
save,
lastSavedTime,
setLastSavedTime
}); });
return ( return (
@@ -190,7 +198,7 @@ const HomePage =(props)=>{
/> />
</SplitPane> </SplitPane>
</div> </div>
<div className={`floatingSaveButton${unsavedChanges ? ' show' : ''}`} onClick={save}> <div className={`floatingSaveButton${unsavedChanges ? ' show' : ''}`} onClick={()=>trySave(true, true, saveGoogle)}>
Save current <i className='fas fa-save' /> Save current <i className='fas fa-save' />
</div> </div>
+21 -19
View File
@@ -28,8 +28,6 @@ import RecentNavItems from '@navbar/recent.navitem.jsx';
const { both: RecentNavItem } = RecentNavItems; const { both: RecentNavItem } = RecentNavItems;
// Page specific imports // Page specific imports
const SAVE_TIMEOUT = 10000;
const BREWKEY = 'HB_newPage_content'; const BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'HB_newPage_style'; const STYLEKEY = 'HB_newPage_style';
const SNIPKEY = 'HB_newPage_snippets'; const SNIPKEY = 'HB_newPage_snippets';
@@ -96,24 +94,22 @@ const NewPage = (props)=>{
window.history.replaceState({}, window.location.title, '/new/'); window.history.replaceState({}, window.location.title, '/new/');
}; };
const trySave = useEffectEvent(async ()=>{ const save = async (brew, saveToGoogle)=>{
setIsSaving(true); //Prepare content to send to server
const brewToSave = {
const updatedBrew = { ...currentBrew }; ...brew,
splitTextStyleAndMetadata(updatedBrew); text : brew.text.normalize('NFC'),
pageCount : ((brew.renderer === 'legacy' ? brew.text.match(/\\page/g) : brew.text.match(/^(?=\\page(?:break)?(?: *{[^\n{}]*})?$)/gm)) || []).length + 1,
const pageRegex = updatedBrew.renderer === 'legacy' ? /\\page/g : /^(?=\\page(?:break)?(?: *{[^\n{}]*})?$)/gm; textBin : undefined
updatedBrew.pageCount = (updatedBrew.text.match(pageRegex) || []).length + 1; };
const res = await request const res = await request
.post(`/api${saveGoogle ? '?saveToGoogle=true' : ''}`) .post(`/api${saveGoogle ? '?saveToGoogle=true' : ''}`)
.send(updatedBrew) .send(brewToSave)
.catch((err)=>{ .catch((err)=>{
setIsSaving(false); console.error('Error Updating Local Brew');
setError(err); setError(err);
}); });
setIsSaving(false);
if(!res) return; if(!res) return;
const savedBrew = res.body; const savedBrew = res.body;
@@ -123,7 +119,7 @@ const NewPage = (props)=>{
localStorage.removeItem(METAKEY); localStorage.removeItem(METAKEY);
window.onbeforeunload = null; window.onbeforeunload = null;
window.location = `/edit/${savedBrew.editId}`; window.location = `/edit/${savedBrew.editId}`;
}); };
const renderSaveButton = ()=>{ const renderSaveButton = ()=>{
// #1 - Currently saving, show SAVING // #1 - Currently saving, show SAVING
@@ -146,7 +142,7 @@ const NewPage = (props)=>{
// #3 - Unsaved changes exist, click to save, show SAVE NOW // #3 - Unsaved changes exist, click to save, show SAVE NOW
if(unsavedChanges) if(unsavedChanges)
return <Nav.item className='save' onClick={trySave} color='blue' icon='fas fa-save'>save now</Nav.item>; return <Nav.item className='save' onClick={()=>trySave(true, true, saveGoogle)} color='blue' icon='fas fa-save'>save now</Nav.item>;
// #4 - No unsaved changes, autosave is ON, show AUTO-SAVED // #4 - No unsaved changes, autosave is ON, show AUTO-SAVED
if(autoSaveEnabled) if(autoSaveEnabled)
@@ -188,8 +184,10 @@ const NewPage = (props)=>{
const { const {
resetWarnUnsavedTimer, resetWarnUnsavedTimer,
handleSplitMove, handleSplitMove,
handleBrewChange handleBrewChange,
trySave
} = useCommonEditPageFunctions({ } = useCommonEditPageFunctions({
saveGoogle,
setError, setError,
setThemeBundle, setThemeBundle,
HTMLErrors, HTMLErrors,
@@ -207,10 +205,14 @@ const NewPage = (props)=>{
setWarnUnsavedChanges, setWarnUnsavedChanges,
unsavedChanges, unsavedChanges,
setUnsavedChanges, setUnsavedChanges,
trySave,
sandbox, sandbox,
lastSavedBrew, lastSavedBrew,
editorRef editorRef,
isSaving,
setIsSaving,
save,
lastSavedTime,
setLastSavedTime
}); });
return ( return (
@@ -1,14 +1,16 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useEffectEvent, useRef } from 'react';
import { printCurrentBrew, fetchThemeBundle } from '@shared/helpers.js'; import { printCurrentBrew, fetchThemeBundle } from '@shared/helpers.js';
import _ from 'lodash'; import _ from 'lodash';
const AUTOSAVE_KEY = 'HB_editor_autoSaveOn'; const AUTOSAVE_KEY = 'HB_editor_autoSaveOn';
const SAVE_TIMEOUT = 10000; //Autosave 10 seconds after last change
const UNSAVED_WARNING_TIMEOUT = 900000; //Warn user afer 15 minutes of unsaved changes const UNSAVED_WARNING_TIMEOUT = 900000; //Warn user afer 15 minutes of unsaved changes
const UNSAVED_WARNING_POPUP_TIMEOUT = 4000; //Show the warning for 4 seconds const UNSAVED_WARNING_POPUP_TIMEOUT = 4000; //Show the warning for 4 seconds
export default function useCommonEditPageFunctions(dependencies) { export default function useCommonEditPageFunctions(dependencies) {
const { const {
saveGoogle,
setError, setError,
setThemeBundle, setThemeBundle,
HTMLErrors, HTMLErrors,
@@ -24,18 +26,21 @@ export default function useCommonEditPageFunctions(dependencies) {
autoSaveEnabled, autoSaveEnabled,
setAutoSaveEnabled, setAutoSaveEnabled,
setWarnUnsavedChanges, setWarnUnsavedChanges,
trySave = ()=>{},
sandbox, sandbox,
saveGoogle = false,
unsavedChanges, unsavedChanges,
setUnsavedChanges, setUnsavedChanges,
lastSavedBrew, lastSavedBrew,
editorRef, editorRef,
saveTimeout = undefined isSaving,
setIsSaving,
save,
lastSavedTime,
setLastSavedTime
} = dependencies; } = dependencies;
const unsavedChangesRef = useRef(unsavedChanges); // onBeforeUnload lives outside React and needs ref to unsavedChanges const unsavedChangesRef = useRef(unsavedChanges); // onBeforeUnload lives outside React and needs ref to unsavedChanges
const warnUnsavedTimeout = useRef(null); // timers live outside React and need ref to consistently track time const warnUnsavedTimeout = useRef(null); // timers live outside React and need ref to consistently track time
const saveTimeout = useRef(null);
//==--------- Page setup ----------==// //==--------- Page setup ----------==//
useEffect(()=>{ useEffect(()=>{
@@ -116,10 +121,30 @@ export default function useCommonEditPageFunctions(dependencies) {
setWarnUnsavedChanges(autoSaveEnabled); setWarnUnsavedChanges(autoSaveEnabled);
}; };
const trySave = useEffectEvent((forceSave = false, hasChanges = true, saveToGoogle = false)=>{
clearTimeout(saveTimeout.current);
if(isSaving) return;
if(!forceSave && !hasChanges) return;
const newTimeout = forceSave ? 0 : SAVE_TIMEOUT;
saveTimeout.current = setTimeout(async ()=>{
setIsSaving(true);
setError(null);
await save(currentBrew, saveToGoogle)
.catch((err)=>{
setError(err);
});
setIsSaving(false);
setLastSavedTime(new Date());
if(!autoSaveEnabled) resetWarnUnsavedTimer();
}, newTimeout);
});
return { return {
resetWarnUnsavedTimer, resetWarnUnsavedTimer,
handleSplitMove, handleSplitMove,
handleBrewChange, handleBrewChange,
toggleAutoSave toggleAutoSave,
trySave,
} }
} }