Merge branch 'master' of https://github.com/naturalcrit/homebrewery into fit-listpage-into-vault

This commit is contained in:
Víctor Losada Hernández
2026-10-06 20:11:28 +02:00
8 changed files with 304 additions and 302 deletions
+18 -3
View File
@@ -22,7 +22,7 @@ import _ from 'lodash';
// use react context to keep track of the menu depth (menus in menus) // use react context to keep track of the menu depth (menus in menus)
const MenuDepthContext = React.createContext(0); const MenuDepthContext = React.createContext(0);
const Dropdown = ({ groupName, className = null, icon, children, color = null, customTrigger, ...props })=>{ const Dropdown = ({ groupName, className = null, icon, children, color = null, customTrigger, disabled = false, ...props })=>{
const reactId = useId(); const reactId = useId();
const safeId = reactId.replace(/[^a-zA-Z0-9_-]/g, ''); const safeId = reactId.replace(/[^a-zA-Z0-9_-]/g, '');
const menuId = `${_.kebabCase(groupName)}-${safeId}-menu`; const menuId = `${_.kebabCase(groupName)}-${safeId}-menu`;
@@ -41,7 +41,7 @@ const Dropdown = ({ groupName, className = null, icon, children, color = null, c
useEffect(()=>{ useEffect(()=>{
triggerRef.current?.setAttribute('style', `anchor-name: ${anchorName}`); triggerRef.current?.setAttribute('style', `anchor-name: ${anchorName}`);
menuRef.current?.setAttribute('style', `position-anchor: ${anchorName}`); menuRef.current?.setAttribute('style', `position-anchor: ${anchorName}`);
}, [anchorName]); }, [anchorName, disabled]);
// hide popover with click inside iframe (not supported by light dismiss) // hide popover with click inside iframe (not supported by light dismiss)
useEffect(()=>{ useEffect(()=>{
@@ -91,8 +91,23 @@ const Dropdown = ({ groupName, className = null, icon, children, color = null, c
document.querySelectorAll('.menu-list:popover-open').forEach((openMenu)=>openMenu.hidePopover()); document.querySelectorAll('.menu-list:popover-open').forEach((openMenu)=>openMenu.hidePopover());
}; };
if(disabled){
return (
<li className={['menu-wrapper', className].filter(Boolean).join(' ')} role='none'>
<button
className={['menu-item', color].filter(Boolean).join(' ')}
aria-label={groupName}
role='menuitem'
disabled
>
{trigger(groupName, icon)}
</button>
</li>
);
}
return ( return (
<li className='menu-wrapper' role='none'> <li className={['menu-wrapper', className].filter(Boolean).join(' ')} role='none'>
<button <button
id={`${menuId}-trigger`} id={`${menuId}-trigger`}
className={['menu-item', color].join(' ')} className={['menu-item', color].join(' ')}
+3
View File
@@ -11,6 +11,9 @@
} }
:root { --activeTriggerColor : var(--activeTriggerColor); } :root { --activeTriggerColor : var(--activeTriggerColor); }
.menu-wrapper {
list-style: none;
}
.menu-list { .menu-list {
position : fixed; position : fixed;
top : anchor(bottom); top : anchor(bottom);
+168 -184
View File
@@ -1,7 +1,6 @@
/*eslint max-lines: ["warn", {"max": 350, "skipBlankLines": true, "skipComments": true}]*/ /*eslint max-lines: ["warn", {"max": 350, "skipBlankLines": true, "skipComments": true}]*/
import './snippetbar.less'; import './snippetbar.less';
import React from 'react'; import React, { useState, useEffect } from 'react';
import createReactClass from 'create-react-class';
import { Dropdown } from '@components/dropdown/dropdown.jsx'; import { Dropdown } from '@components/dropdown/dropdown.jsx';
import _ from 'lodash'; import _ from 'lodash';
@@ -31,260 +30,247 @@ const execute = function(val, props){
return val; return val;
}; };
const Snippetbar = createReactClass({ const SnippetBar = ({
displayName : 'SnippetBar', brew = {},
getDefaultProps : function() { view = 'text',
return { onViewChange = ()=>{},
brew : {}, onInject = ()=>{},
view : 'text', onToggle = ()=>{},
onViewChange : ()=>{}, showEditButtons = true,
onInject : ()=>{}, renderer = 'legacy',
onToggle : ()=>{}, undo = ()=>{},
showEditButtons : true, redo = ()=>{},
renderer : 'legacy', historySize = ()=>{},
undo : ()=>{}, foldCode = ()=>{},
redo : ()=>{}, unfoldCode = ()=>{},
historySize : ()=>{}, formatCode = ()=>{},
foldCode : ()=>{}, cursorPos = {},
unfoldCode : ()=>{}, themeBundle = [],
formatCode : ()=>{}, updateBrew = ()=>{}
cursorPos : {}, })=>{
themeBundle : [], const [snippets, setSnippets] = useState([]);
updateBrew : ()=>{} const [historyExists, setHistoryExists] = useState(false);
}; const [historyItems, setHistoryItems] = useState([]);
},
getInitialState : function() { useEffect(()=>{
return { setSnippets(compileSnippets());
renderer : this.props.renderer, }, []);
snippets : [],
showHistory : false,
historyExists : false,
historyItems : []
};
},
componentDidMount : async function(prevState) { const mergeCustomizer = (oldValue, newValue, key)=>{
const snippets = this.compileSnippets(); if(key == 'snippets') {
this.setState({
snippets : snippets
});
},
componentDidUpdate : async function(prevProps, prevState) {
if(prevProps.renderer != this.props.renderer ||
prevProps.themeBundle != this.props.themeBundle ||
prevProps.brew.snippets != this.props.brew.snippets) {
this.setState({
snippets : this.compileSnippets()
});
};
// Update history list if it has changed
const checkHistoryItems = await loadHistory(this.props.brew);
// If all items have the noData property, there is no saved data
const checkHistoryExists = !checkHistoryItems.every((historyItem)=>{
return historyItem?.noData;
});
if(prevState.historyExists != checkHistoryExists){
this.setState({
historyExists : checkHistoryExists
});
}
// If any history items have changed, update the list
if(checkHistoryExists && checkHistoryItems.some((historyItem, index)=>{
return index >= prevState.historyItems.length || !_.isEqual(historyItem, prevState.historyItems[index]);
})){
this.setState({
historyItems : checkHistoryItems
});
}
},
mergeCustomizer : function(oldValue, newValue, key) {
if(key == 'snippets') {
const result = _.reverse(_.unionBy(_.reverse(newValue), _.reverse(oldValue), 'name')); // Join snippets together, with preference for the child theme over the parent theme const result = _.reverse(_.unionBy(_.reverse(newValue), _.reverse(oldValue), 'name')); // Join snippets together, with preference for the child theme over the parent theme
return result.filter((snip)=>snip.gen || snip.subsnippets); return result.filter((snip)=>snip.gen || snip.subsnippets);
}; };
}, };
const compileSnippets = ()=>{
compileSnippets : function() {
let compiledSnippets = []; let compiledSnippets = [];
let oldSnippets = _.keyBy(compiledSnippets, 'groupName'); let oldSnippets = _.keyBy(compiledSnippets, 'groupName');
if(this.props.themeBundle.snippets) { if(themeBundle.snippets) {
for (let snippets of this.props.themeBundle.snippets) { for (let snippets of themeBundle.snippets) {
if(typeof(snippets) == 'string') // load staticThemes as needed; they were sent as just a file name if(typeof(snippets) == 'string') // load staticThemes as needed; they were sent as just a file name
snippets = ThemeSnippets[snippets]; snippets = ThemeSnippets[snippets];
const newSnippets = _.keyBy(_.cloneDeep(snippets), 'groupName'); const newSnippets = _.keyBy(_.cloneDeep(snippets), 'groupName');
compiledSnippets = _.values(_.mergeWith(oldSnippets, newSnippets, this.mergeCustomizer)); compiledSnippets = _.values(_.mergeWith(oldSnippets, newSnippets, mergeCustomizer));
oldSnippets = _.keyBy(compiledSnippets, 'groupName'); oldSnippets = _.keyBy(compiledSnippets, 'groupName');
} }
} }
const userSnippetsasJSON = brewSnippetsToJSON(this.props.brew.title || 'New Document', this.props.brew.snippets, this.props.themeBundle.snippets); const userSnippetsasJSON = brewSnippetsToJSON(brew.title || 'New Document', brew.snippets, themeBundle.snippets);
compiledSnippets.push(userSnippetsasJSON); compiledSnippets.push(userSnippetsasJSON);
return compiledSnippets; return compiledSnippets;
}, };
handleSnippetClick : function(injectedText){ useEffect(()=>{
this.props.onInject(injectedText); setSnippets(compileSnippets());
}, }, [renderer, themeBundle, brew.snippets]);
renderSnippetGroups : function(){ useEffect(()=>{
const snippets = this.state.snippets.filter((snippetGroup)=>snippetGroup.view === this.props.view); const updateHistory = async ()=>{
if(snippets.length === 0) return null; // Update history list if it has changed
const checkHistoryItems = await loadHistory(brew);
// If all items have the noData property, there is no saved data
const checkHistoryExists = !checkHistoryItems.every(
(historyItem)=>historyItem?.noData
);
if(historyExists !== checkHistoryExists) {
setHistoryExists(checkHistoryExists);
}
// If any history items have changed, update the list
if(!_.isEqual(checkHistoryItems, historyItems)) {
setHistoryItems(checkHistoryItems);
}
};
updateHistory();
}, [brew]);
const handleSnippetClick = (injectedText)=>onInject(injectedText);
const renderSnippetGroups = ()=>{
const currentSnippets = snippets.filter((snippetGroup)=>snippetGroup.view === view);
if(currentSnippets.length === 0) return null;
return <ul className='snippets' role='menubar' aria-label='Snippets Menubar'> return <ul className='snippets' role='menubar' aria-label='Snippets Menubar'>
{_.map(snippets, (snippetGroup)=>{ {_.map(currentSnippets, (snippetGroup)=>{
return <SnippetGroup return <SnippetGroup
brew={this.props.brew} brew={brew}
groupName={snippetGroup.groupName} groupName={snippetGroup.groupName}
icon={snippetGroup.icon} icon={snippetGroup.icon}
snippets={snippetGroup.snippets} snippets={snippetGroup.snippets}
key={snippetGroup.groupName} key={snippetGroup.groupName}
onSnippetClick={this.handleSnippetClick} onSnippetClick={handleSnippetClick}
cursorPos={this.props.cursorPos} cursorPos={cursorPos}
/>; />;
}) })
} }
</ul>; </ul>;
}, };
replaceContent : function(item){ const replaceContent = (item)=>{
return this.props.updateBrew(item); return updateBrew(item);
}, };
toggleHistoryMenu : function(){ const renderHistoryMenu = ()=>{
this.setState({ return (
showHistory : !this.state.showHistory <Dropdown
}); groupName='History'
}, icon='fas fa-clock-rotate-left'
className='history'
customTrigger={<><i className='fas fa-clock-rotate-left' /></>}
disabled={!historyExists}
>
{historyExists && _.map(historyItems, (item, index)=>{
if(item.noData || !item.savedAt) return null;
renderHistoryItems : function() { const saveTime = new Date(item.savedAt);
if(!this.state.historyExists) return; const diffMs = new Date() - saveTime;
const diffSecs = Math.floor(diffMs / 1000);
return <div className='dropdown'> let diffString = `about ${diffSecs} seconds ago`;
{_.map(this.state.historyItems, (item, index)=>{
if(item.noData || !item.savedAt) return;
const saveTime = new Date(item.savedAt); if(diffSecs > 60)
const diffMs = new Date() - saveTime; diffString = `about ${Math.floor(diffSecs / 60)} minutes ago`;
const diffSecs = Math.floor(diffMs / 1000); if(diffSecs > (60 * 60))
diffString = `about ${Math.floor(diffSecs / (60 * 60))} hours ago`;
if(diffSecs > (24 * 60 * 60))
diffString = `about ${Math.floor(diffSecs / (24 * 60 * 60))} days ago`;
if(diffSecs > (7 * 24 * 60 * 60))
diffString = `about ${Math.floor(diffSecs / (7 * 24 * 60 * 60))} weeks ago`;
let diffString = `about ${diffSecs} seconds ago`; return (
<li key={index} role='none'>
<button
className='menu-item'
onClick={()=>replaceContent(item)}
role='menuitem'
>
<i className={`fas fa-${index + 1}`} />
<span
className='name'
title={saveTime.toISOString()}
>
v{item.version} : {diffString}
</span>
</button>
</li>
);
})}
</Dropdown>
);
};
if(diffSecs > 60) diffString = `about ${Math.floor(diffSecs / 60)} minutes ago`; const renderEditorButtons =()=>{
if(diffSecs > (60 * 60)) diffString = `about ${Math.floor(diffSecs / (60 * 60))} hours ago`; if(!showEditButtons) return;
if(diffSecs > (24 * 60 * 60)) diffString = `about ${Math.floor(diffSecs / (24 * 60 * 60))} days ago`;
if(diffSecs > (7 * 24 * 60 * 60)) diffString = `about ${Math.floor(diffSecs / (7 * 24 * 60 * 60))} weeks ago`;
return <div className='snippet' key={index} onClick={()=>{this.replaceContent(item);}} >
<i className={`fas fa-${index+1}`} />
<span className='name' title={saveTime.toISOString()}>v{item.version} : {diffString}</span>
</div>;
})}
</div>;
},
renderEditorButtons : function(){
if(!this.props.showEditButtons) return;
return ( return (
<div className='editors'> <div className='editors'>
{this.props.view !== 'meta' && this.props.view !== 'settings' && <><div className='historyTools'> {view !== 'meta' && view !== 'settings' && <><div className='historyTools'>
<button className={`editorTool snippetGroup history ${this.state.historyExists ? 'active' : ''}`} {renderHistoryMenu()}
onClick={this.toggleHistoryMenu} > <button className={`editorTool undo ${historySize.done ? 'active' : ''}`}
<i className='fas fa-clock-rotate-left' /> onClick={undo} >
{ this.state.showHistory && this.renderHistoryItems() }
</button>
<button className={`editorTool undo ${this.props.historySize.done ? 'active' : ''}`}
onClick={this.props.undo} >
<i className='fas fa-undo' /> <i className='fas fa-undo' />
</button> </button>
<button className={`editorTool redo ${this.props.historySize.undone ? 'active' : ''}`} <button className={`editorTool redo ${historySize.undone ? 'active' : ''}`}
onClick={this.props.redo} > onClick={redo} >
<i className='fas fa-redo' /> <i className='fas fa-redo' />
</button> </button>
</div> </div>
<div className='codeTools'> <div className='codeTools'>
<button className={`editorTool foldAll ${this.props.foldCode ? 'active' : ''}`} <button className={`editorTool foldAll ${foldCode ? 'active' : ''}`}
onClick={this.props.foldCode} > onClick={foldCode} >
<i className='fas fa-compress-alt' /> <i className='fas fa-compress-alt' />
</button> </button>
<button className={`editorTool unfoldAll ${this.props.unfoldCode ? 'active' : ''}`} <button className={`editorTool unfoldAll ${unfoldCode ? 'active' : ''}`}
onClick={this.props.unfoldCode} > onClick={unfoldCode} >
<i className='fas fa-expand-alt' /> <i className='fas fa-expand-alt' />
</button> </button>
<button className={`editorTool formatCode ${this.props.formatCode ? 'active' : ''}`} <button className={`editorTool formatCode ${formatCode ? 'active' : ''}`}
onClick={this.props.formatCode} > onClick={formatCode} >
<i className='fas fa-wand-magic-sparkles' /> <i className='fas fa-wand-magic-sparkles' />
</button> </button>
</div></>} </div></>}
<div className='tabs'> <div className='tabs'>
<button className={cx('text', { selected: this.props.view === 'text' })} <button className={cx('text', { selected: view === 'text' })}
onClick={()=>this.props.onViewChange('text')}> onClick={()=>onViewChange('text')}>
<i className='fa fa-beer' /> <i className='fa fa-beer' />
</button> </button>
<button className={cx('style', { selected: this.props.view === 'style' })} <button className={cx('style', { selected: view === 'style' })}
onClick={()=>this.props.onViewChange('style')}> onClick={()=>onViewChange('style')}>
<i className='fa fa-paint-brush' /> <i className='fa fa-paint-brush' />
</button> </button>
<button className={cx('snippet', { selected: this.props.view === 'snippet' })} <button className={cx('snippet', { selected: view === 'snippet' })}
onClick={()=>this.props.onViewChange('snippet')}> onClick={()=>onViewChange('snippet')}>
<i className='fas fa-th-list' /> <i className='fas fa-th-list' />
</button> </button>
<button className={cx('meta', { selected: this.props.view === 'meta' })} <button className={cx('meta', { selected: view === 'meta' })}
onClick={()=>this.props.onViewChange('meta')}> onClick={()=>onViewChange('meta')}>
<i className='fas fa-info-circle' /> <i className='fas fa-info-circle' />
</button> </button>
<button className={cx('settings', { selected: this.props.view === 'settings' })} <button className={cx('settings', { selected: view === 'settings' })}
onClick={()=>this.props.onViewChange('settings')}> onClick={()=>onViewChange('settings')}>
<i className='fas fa-gear' /> <i className='fas fa-gear' />
</button> </button>
</div> </div>
</div> </div>
); );
}, };
render : function(){ return <div className='snippetBar'>
return <div className='snippetBar'> {renderSnippetGroups()}
{this.renderSnippetGroups()} {renderEditorButtons()}
{this.renderEditorButtons()} </div>;
</div>; };
}
});
export default Snippetbar; export default SnippetBar;
const SnippetGroup = createReactClass({ const SnippetGroup = (props)=>{
displayName : 'SnippetGroup', const {
getDefaultProps : function() { brew = {},
return { groupName = '',
brew : {}, icon = 'fas fa-rocket',
groupName : '', snippets = [],
icon : 'fas fa-rocket', onSnippetClick = function(){},
snippets : [], } = props;
onSnippetClick : function(){},
}; const handleSnippetClick = (e, snippet)=>{
}, onSnippetClick(execute(snippet.gen, props));
handleSnippetClick : function(e, snippet){ };
this.props.onSnippetClick(execute(snippet.gen, this.props)); const renderSnippets = (snippets)=>{
},
renderSnippets : function(snippets){
return _.map(snippets, (snippet)=>{ return _.map(snippets, (snippet)=>{
if(!snippet.subsnippets){ if(!snippet.subsnippets){
return ( return (
<li key={snippet.name} role='none'> <li key={snippet.name} role='none'>
<button className='menu-item' onClick={(e)=>this.handleSnippetClick(e, snippet)} role='menuitem' aria-label={snippet.name} disabled={snippet.disabled}> <button className='menu-item' onClick={(e)=>handleSnippetClick(e, snippet)} role='menuitem' aria-label={snippet.name} disabled={snippet.disabled}>
<i className={snippet.icon} /> <i className={snippet.icon} />
<span className={`name${snippet.disabled ? ' disabled' : ''}`} title={snippet.name}>{snippet.name}</span> <span className={`name${snippet.disabled ? ' disabled' : ''}`} title={snippet.name}>{snippet.name}</span>
{snippet.experimental && <span className='status'>beta</span>} {snippet.experimental && <span className='status'>beta</span>}
@@ -295,17 +281,15 @@ const SnippetGroup = createReactClass({
} else if(snippet.subsnippets){ } else if(snippet.subsnippets){
return ( return (
<Dropdown groupName={snippet.name} icon={snippet.icon} key={snippet.name}> <Dropdown groupName={snippet.name} icon={snippet.icon} key={snippet.name}>
{this.renderSnippets(snippet.subsnippets)} {renderSnippets(snippet.subsnippets)}
</Dropdown> </Dropdown>
); );
} }
}); });
}, };
render : function(){ return <Dropdown groupName={groupName} id={groupName} icon={icon}>
return <Dropdown groupName={this.props.groupName} id={this.props.groupName} icon={this.props.icon}> {renderSnippets(snippets)}
{this.renderSnippets(this.props.snippets)} </Dropdown>;
</Dropdown>; };
},
});
@@ -25,7 +25,7 @@
display : flex; display : flex;
justify-content : flex-end; justify-content : flex-end;
min-width : 275px; //must be controlled every time an item is added, must be hardcoded for the wrapping as it is applied min-width : 275px; //must be controlled every time an item is added, must be hardcoded for the wrapping as it is applied
font-size : 0.85rem; font-size:0.85rem;
&:only-child {min-width : unset; margin-left : auto;} &:only-child {min-width : unset; margin-left : auto;}
reading-order : 2; reading-order : 2;
@@ -36,7 +36,7 @@
&:first-child { border-left : none; } &:first-child { border-left : none; }
& > button { & > button, & > li {
position : relative; position : relative;
width : @menuHeight; width : @menuHeight;
height : @menuHeight; height : @menuHeight;
@@ -44,7 +44,7 @@
text-align : center; text-align : center;
cursor : pointer; cursor : pointer;
&.editorTool:not(.active) { cursor : not-allowed; } &.editorTool:not(.active),&.editorTool:disabled { cursor : not-allowed; }
&:hover,&.selected { background-color : var(--hoverMenuColor); } &:hover,&.selected { background-color : var(--hoverMenuColor); }
&.text { &.text {
@@ -59,6 +59,9 @@
&.snippet { &.snippet {
.tooltipLeft('Snippets'); .tooltipLeft('Snippets');
} }
&.settings {
.tooltipLeft('Settings');
}
&.undo { &.undo {
.tooltipLeft('Undo'); .tooltipLeft('Undo');
color : grey; color : grey;
@@ -85,11 +88,16 @@
&.active { color : inherit; } &.active { color : inherit; }
} }
&.history { &.history {
font-size:.70rem;
i {
min-width:auto;
}
.tooltipLeft('History'); .tooltipLeft('History');
position : relative; position : relative;
color : grey; color : grey;
border : none; border : none;
&.active { color : inherit; } &:not(:disabled) { color : inherit; }
& > .dropdown { & > .dropdown {
right : -1px; right : -1px;
& > .snippet { padding-right : 10px; } & > .snippet { padding-right : 10px; }
+12 -26
View File
@@ -3,7 +3,7 @@ import './editPage.less';
// Common imports // Common imports
import React, { useState, useEffect, useRef, useEffectEvent } from 'react'; import React, { useState, useEffect, useRef, useEffectEvent } from 'react';
import request from '../../utils/request-middleware.js'; import request from '../../utils/request-middleware.js';
import { hbfm } from 'marked-hbfm';
import _ from 'lodash'; import _ from 'lodash';
import { DEFAULT_BREW_LOAD } from '../../../../server/brewDefaults.js'; import { DEFAULT_BREW_LOAD } from '../../../../server/brewDefaults.js';
@@ -20,16 +20,11 @@ import { makePatches, stringifyPatches } from '@sanity/diff-match-patch';
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 BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'HB_newPage_style';
const SNIPKEY = 'HB_newPage_snippets';
const METAKEY = 'HB_newPage_meta';
const useLocalStorage = false; const useLocalStorage = false;
const sandbox = false; const sandbox = false;
const showFloatingButtons = false; const showFloatingButtons = false;
const showEditorButtons = true; const showEditorButtons = true;
const pageName = "editPage"; const pageName = 'editPage';
const EditPage = (props)=>{ const EditPage = (props)=>{
props = { props = {
@@ -108,23 +103,17 @@ const EditPage = (props)=>{
if(!res) return; if(!res) return;
const updatedFields = { const updatedFields = {
googleId : res.body.googleId ?? null, googleId : res.body.googleId ?? null, //TODO: investigate if we can set googleId:null in server/update instead of undefined
editId : res.body.editId, editId : res.body.editId, //then, editPage can just apply res.body instead of breaking out these fields.
shareId : res.body.shareId, shareId : res.body.shareId,
version : res.body.version version : res.body.version
}; };
lastSavedBrew.current = { return updatedFields;
...brew, };
...updatedFields
};
setCurrentBrew((prevBrew)=>({ const onSaveSuccess = (savedBrew)=>{
...prevBrew, history.replaceState(null, null, `/edit/${savedBrew.editId}`);;
...updatedFields
}));
history.replaceState(null, null, `/edit/${res.body.editId}`);
}; };
const renderGoogleDriveIcon = ()=>( const renderGoogleDriveIcon = ()=>(
@@ -176,24 +165,21 @@ const EditPage = (props)=>{
trySave, trySave,
} = useCommonEditPageFunctions({ } = useCommonEditPageFunctions({
saveGoogle, saveGoogle,
setSaveGoogle,
error, error,
setError, setError,
currentBrew, currentBrew,
setCurrentBrew, setCurrentBrew,
useLocalStorage, useLocalStorage,
BREWKEY,
STYLEKEY,
SNIPKEY,
METAKEY,
hbfm,
sandbox, sandbox,
showFloatingButtons, showFloatingButtons,
lastSavedBrew, lastSavedBrew,
save, save,
onSaveSuccess,
pageName, pageName,
showEditorButtons, showEditorButtons,
renderGoogleDriveIcon, renderGoogleDriveIcon,
userThemes: props.userThemes userThemes : props.userThemes
}); });
return renderPanels(); return renderPanels();
+12 -18
View File
@@ -3,7 +3,6 @@ import './homePage.less';
// Common imports // Common imports
import React, { useState, useEffect, useRef, useEffectEvent } from 'react'; import React, { useState, useEffect, useRef, useEffectEvent } from 'react';
import request from '../../utils/request-middleware.js'; import request from '../../utils/request-middleware.js';
import { hbfm } from 'marked-hbfm';
import _ from 'lodash'; import _ from 'lodash';
import { DEFAULT_BREW } from '../../../../server/brewDefaults.js'; import { DEFAULT_BREW } from '../../../../server/brewDefaults.js';
@@ -11,16 +10,11 @@ import { DEFAULT_BREW } from '../../../../server/brewDefau
import useCommonEditPageFunctions from '../../utils/commonEditPageFunctions.jsx'; import useCommonEditPageFunctions from '../../utils/commonEditPageFunctions.jsx';
// Page specific imports // Page specific imports
const BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'HB_newPage_style';
const SNIPKEY = 'HB_newPage_snippets';
const METAKEY = 'HB_newPage_meta';
const useLocalStorage = false; const useLocalStorage = false;
const sandbox = true; const sandbox = true;
const showFloatingButtons = true; const showFloatingButtons = true;
const showEditorButtons = false; const showEditorButtons = false;
const pageName = "homePage"; const pageName = 'homePage';
const HomePage =(props)=>{ const HomePage =(props)=>{
props = { props = {
@@ -28,9 +22,9 @@ const HomePage =(props)=>{
...props ...props
}; };
const [currentBrew, setCurrentBrew] = useState(props.brew); const [currentBrew, setCurrentBrew] = useState(props.brew);
const [saveGoogle, setSaveGoogle] = useState(global.account?.googleId ? true : false); const [saveGoogle, setSaveGoogle] = useState(global.account?.googleId ? true : false);
const [error, setError] = useState(undefined); const [error, setError] = useState(undefined);
const lastSavedBrew = useRef(_.cloneDeep(props.brew)); const lastSavedBrew = useRef(_.cloneDeep(props.brew));
@@ -44,32 +38,32 @@ const HomePage =(props)=>{
}); });
if(!res) return; if(!res) return;
const saved = res.body; return res.body;
};
const onSaveSuccess = (savedBrew)=>{
window.onbeforeunload = null; window.onbeforeunload = null;
window.location = `/edit/${saved.editId}`; window.location = `/edit/${savedBrew.editId}`;
}; };
const { const {
renderPanels renderPanels
} = useCommonEditPageFunctions({ } = useCommonEditPageFunctions({
saveGoogle, saveGoogle,
setSaveGoogle,
error, error,
setError, setError,
currentBrew, currentBrew,
setCurrentBrew, setCurrentBrew,
useLocalStorage, useLocalStorage,
BREWKEY,
STYLEKEY,
SNIPKEY,
METAKEY,
hbfm,
sandbox, sandbox,
showFloatingButtons, showFloatingButtons,
lastSavedBrew, lastSavedBrew,
save, save,
onSaveSuccess,
pageName, pageName,
showEditorButtons, showEditorButtons,
userThemes: {} userThemes : {}
}); });
return renderPanels(); return renderPanels();
+9 -54
View File
@@ -3,7 +3,6 @@ import './newPage.less';
// Common imports // Common imports
import React, { useState, useEffect, useRef, useEffectEvent } from 'react'; import React, { useState, useEffect, useRef, useEffectEvent } from 'react';
import request from '../../utils/request-middleware.js'; import request from '../../utils/request-middleware.js';
import { hbfm } from 'marked-hbfm';
import _ from 'lodash'; import _ from 'lodash';
import { DEFAULT_BREW } from '../../../../server/brewDefaults.js'; import { DEFAULT_BREW } from '../../../../server/brewDefaults.js';
@@ -11,18 +10,11 @@ import { DEFAULT_BREW } from '../../../../server/brewDefau
import useCommonEditPageFunctions from '../../utils/commonEditPageFunctions.jsx'; import useCommonEditPageFunctions from '../../utils/commonEditPageFunctions.jsx';
// Page specific imports // Page specific imports
const BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'HB_newPage_style';
const SNIPKEY = 'HB_newPage_snippets';
const METAKEY = 'HB_newPage_meta';
const SAVEKEYPREFIX = 'HB_editor_defaultSave_';
const useLocalStorage = true; const useLocalStorage = true;
const sandbox = true; const sandbox = true;
const showFloatingButtons = false; const showFloatingButtons = false;
const showEditorButtons = true; const showEditorButtons = true;
const pageName = "newPage"; const pageName = 'newPage';
const NewPage = (props)=>{ const NewPage = (props)=>{
props = { props = {
@@ -31,44 +23,11 @@ const NewPage = (props)=>{
}; };
const [currentBrew, setCurrentBrew] = useState(props.brew); const [currentBrew, setCurrentBrew] = useState(props.brew);
const [saveGoogle, setSaveGoogle] = useState(global.account?.googleId ? true : false); const [saveGoogle, setSaveGoogle] = useState(global.account?.googleId ? true : false);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const lastSavedBrew = useRef(_.cloneDeep(props.brew)); const lastSavedBrew = useRef(_.cloneDeep(props.brew));
useEffect(()=>{
loadBrew();
}, []);
const loadBrew = ()=>{
const brew = { ...currentBrew };
if(!brew.shareId && typeof window !== 'undefined') { //Load from localStorage if in client browser
const brewStorage = localStorage.getItem(BREWKEY);
const styleStorage = localStorage.getItem(STYLEKEY);
const metaStorage = JSON.parse(localStorage.getItem(METAKEY));
brew.text = brewStorage ?? brew.text;
brew.style = styleStorage ?? brew.style;
brew.renderer = metaStorage?.renderer ?? brew.renderer;
brew.theme = metaStorage?.theme ?? brew.theme;
brew.lang = metaStorage?.lang ?? brew.lang;
}
const SAVEKEY = `${SAVEKEYPREFIX}${global.account?.username}`;
const saveStorage = localStorage.getItem(SAVEKEY) || 'HOMEBREWERY';
setCurrentBrew(brew);
lastSavedBrew.current = brew;
setSaveGoogle(saveStorage == 'GOOGLE-DRIVE' && saveGoogle);
localStorage.setItem(BREWKEY, brew.text);
if(brew.style)
localStorage.setItem(STYLEKEY, brew.style);
localStorage.setItem(METAKEY, JSON.stringify({ renderer: brew.renderer, theme: brew.theme, lang: brew.lang }));
if(window.location.pathname !== '/new')
window.history.replaceState({}, window.location.title, '/new/');
};
const save = async (brew, saveToGoogle)=>{ const save = async (brew, saveToGoogle)=>{
//Prepare content to send to server //Prepare content to send to server
const brewToSave = { const brewToSave = {
@@ -87,11 +46,10 @@ const NewPage = (props)=>{
}); });
if(!res) return; if(!res) return;
const savedBrew = res.body; return res.body;
};
localStorage.removeItem(BREWKEY); const onSaveSuccess = (savedBrew)=>{
localStorage.removeItem(STYLEKEY);
localStorage.removeItem(METAKEY);
window.onbeforeunload = null; window.onbeforeunload = null;
window.location = `/edit/${savedBrew.editId}`; window.location = `/edit/${savedBrew.editId}`;
}; };
@@ -100,23 +58,20 @@ const NewPage = (props)=>{
renderPanels renderPanels
} = useCommonEditPageFunctions({ } = useCommonEditPageFunctions({
saveGoogle, saveGoogle,
setSaveGoogle,
error, error,
setError, setError,
currentBrew, currentBrew,
setCurrentBrew, setCurrentBrew,
useLocalStorage, useLocalStorage,
BREWKEY,
STYLEKEY,
SNIPKEY,
METAKEY,
hbfm,
sandbox, sandbox,
showFloatingButtons, showFloatingButtons,
lastSavedBrew, lastSavedBrew,
save, save,
onSaveSuccess,
pageName, pageName,
showEditorButtons, showEditorButtons,
userThemes: props.userThemes userThemes : props.userThemes
}); });
return renderPanels(); return renderPanels();
@@ -1,6 +1,7 @@
import React, { useState, useEffect, useEffectEvent, 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';
import { hbfm } from 'marked-hbfm';
import Headtags from '@vitreum/headtags.js'; import Headtags from '@vitreum/headtags.js';
import SplitPane from '@components/splitPane/splitPane.jsx'; import SplitPane from '@components/splitPane/splitPane.jsx';
@@ -22,7 +23,12 @@ import ShareNavItem from '@navbar/share.navitem.jsx';
import RecentNavItems from '@navbar/recent.navitem.jsx'; import RecentNavItems from '@navbar/recent.navitem.jsx';
const { both: RecentNavItem } = RecentNavItems; const { both: RecentNavItem } = RecentNavItems;
const AUTOSAVE_KEY = 'HB_editor_autoSaveOn'; const AUTOSAVE_KEY = 'HB_editor_autoSaveOn';
const BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'HB_newPage_style';
const SNIPKEY = 'HB_newPage_snippets';
const METAKEY = 'HB_newPage_meta';
const SAVEKEY_PREFIX = 'HB_editor_defaultSave_';
const SAVE_TIMEOUT = 10000; //Autosave 10 seconds after last change 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
@@ -31,20 +37,17 @@ 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, saveGoogle,
setSaveGoogle,
error, error,
setError, setError,
currentBrew, currentBrew,
setCurrentBrew, setCurrentBrew,
useLocalStorage, useLocalStorage,
BREWKEY,
STYLEKEY,
SNIPKEY,
METAKEY,
hbfm,
sandbox, sandbox,
showFloatingButtons, showFloatingButtons,
lastSavedBrew, lastSavedBrew,
save, save,
onSaveSuccess,
pageName, pageName,
renderGoogleDriveIcon = ()=>{}, renderGoogleDriveIcon = ()=>{},
showEditorButtons, showEditorButtons,
@@ -70,6 +73,7 @@ export default function useCommonEditPageFunctions(dependencies) {
//==--------- Page setup ----------==// //==--------- Page setup ----------==//
useEffect(()=>{ useEffect(()=>{
if(useLocalStorage) loadBrewFromLocalStorage();
const autoSavePref = !sandbox && JSON.parse(localStorage.getItem(AUTOSAVE_KEY) ?? true); const autoSavePref = !sandbox && JSON.parse(localStorage.getItem(AUTOSAVE_KEY) ?? true);
setAutoSaveEnabled(autoSavePref); setAutoSaveEnabled(autoSavePref);
setWarnUnsavedChanges(!autoSavePref); setWarnUnsavedChanges(!autoSavePref);
@@ -95,6 +99,44 @@ export default function useCommonEditPageFunctions(dependencies) {
}; };
}, []); }, []);
const loadBrewFromLocalStorage = ()=>{
const brew = { ...currentBrew };
if(!brew.shareId && typeof window !== 'undefined') { //Load from localStorage if in client browser
const brewStorage = localStorage.getItem(BREWKEY);
const styleStorage = localStorage.getItem(STYLEKEY);
const snipStorage = localStorage.getItem(SNIPKEY);
const metaStorage = JSON.parse(localStorage.getItem(METAKEY));
brew.text = brewStorage ?? brew.text;
brew.style = styleStorage ?? brew.style;
brew.snippets = snipStorage ?? brew.snippets;
brew.renderer = metaStorage?.renderer ?? brew.renderer;
brew.theme = metaStorage?.theme ?? brew.theme;
brew.lang = metaStorage?.lang ?? brew.lang;
}
const SAVEKEY = `${SAVEKEY_PREFIX}${global.account?.username}`;
const saveStorage = localStorage.getItem(SAVEKEY) || 'HOMEBREWERY';
setCurrentBrew(brew);
lastSavedBrew.current = brew;
setSaveGoogle(saveStorage == 'GOOGLE-DRIVE' && saveGoogle);
localStorage.setItem(BREWKEY, brew.text);
if(brew.style) localStorage.setItem(STYLEKEY, brew.style);
if(brew.snippets) localStorage.setItem(SNIPKEY, brew.snippets);
localStorage.setItem(METAKEY, JSON.stringify({ renderer: brew.renderer, theme: brew.theme, lang: brew.lang }));
if(window.location.pathname !== '/new')
window.history.replaceState({}, window.location.title, '/new/');
};
const clearLocalStorage = ()=>{
localStorage.removeItem(BREWKEY);
localStorage.removeItem(STYLEKEY);
localStorage.removeItem(SNIPKEY);
localStorage.removeItem(METAKEY);
};
//======----- Check for unsaved changes and autosave if enabled -----====== //======----- Check for unsaved changes and autosave if enabled -----======
useEffect(()=>{ useEffect(()=>{
const hasChange = !_.isEqual(currentBrew, lastSavedBrew.current); const hasChange = !_.isEqual(currentBrew, lastSavedBrew.current);
@@ -127,12 +169,12 @@ export default function useCommonEditPageFunctions(dependencies) {
if(useLocalStorage) { if(useLocalStorage) {
if(field == 'text') localStorage.setItem(BREWKEY, value); if(field == 'text') localStorage.setItem(BREWKEY, value);
if(field == 'style') localStorage.setItem(STYLEKEY, value); if(field == 'style') localStorage.setItem(STYLEKEY, value);
if(field == 'snippets') localStorage.setItem(SNIPKEY, value); if(field == 'snippets') localStorage.setItem(SNIPKEY, value);
if(field == 'metadata') localStorage.setItem(METAKEY, JSON.stringify({ if(field == 'metadata') localStorage.setItem(METAKEY, JSON.stringify({
renderer : value.renderer, renderer : value.renderer,
theme : value.theme, theme : value.theme,
lang : value.lang lang : value.lang
})); }));
} }
}; };
@@ -160,8 +202,23 @@ export default function useCommonEditPageFunctions(dependencies) {
setIsSaving(true); setIsSaving(true);
setError(null); setError(null);
setHTMLErrors(hbfm.validate(currentBrew.text)); setHTMLErrors(hbfm.validate(currentBrew.text));
await save(currentBrew, saveToGoogle) const brewToSave = currentBrew;
let savedBrew = await save(brewToSave, saveToGoogle)
.catch((err)=>{setError(err);}); .catch((err)=>{setError(err);});
if(savedBrew) {
lastSavedBrew.current = {
...brewToSave,
...savedBrew
};
setCurrentBrew((prevBrew)=>({
...prevBrew,
...savedBrew
}));
if(useLocalStorage) clearLocalStorage();
onSaveSuccess(savedBrew);
}
setIsSaving(false); setIsSaving(false);
setLastSavedTime(new Date()); setLastSavedTime(new Date());
if(!autoSaveEnabled) resetWarnUnsavedTimer(); if(!autoSaveEnabled) resetWarnUnsavedTimer();
@@ -216,14 +273,14 @@ export default function useCommonEditPageFunctions(dependencies) {
? <ErrorNavItem error={error} clearError={clearError} /> ? <ErrorNavItem error={error} clearError={clearError} />
: <Nav.dropdown className='save-menu'> : <Nav.dropdown className='save-menu'>
{renderSaveButton()} {renderSaveButton()}
{pageName == "editPage" && renderAutoSaveButton()} {pageName == 'editPage' && renderAutoSaveButton()}
</Nav.dropdown>} </Nav.dropdown>}
<NewBrewItem /> <NewBrewItem />
<PrintNavItem /> <PrintNavItem />
<HelpNavItem /> <HelpNavItem />
<VaultNavItem /> <VaultNavItem />
{(pageName == "editPage") && <ShareNavItem brew={currentBrew} currentPage={currentBrewRendererPageNum} />} {(pageName == 'editPage') && <ShareNavItem brew={currentBrew} currentPage={currentBrewRendererPageNum} />}
<RecentNavItem brew={currentBrew} storageKey={(pageName == "editPage") ? 'edit' : undefined} /> <RecentNavItem brew={currentBrew} storageKey={(pageName == 'editPage') ? 'edit' : undefined} />
<AccountNavItem /> <AccountNavItem />
</Nav.section> </Nav.section>
</Navbar> </Navbar>