refactor snippetbar into functional component

This commit is contained in:
Víctor Losada Hernández
2026-09-30 21:40:37 +02:00
parent ec7828dc65
commit 8bfa373da9
+134 -165
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,147 +30,122 @@ 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 [showHistory, setShowHistory] = useState(false);
}; 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 toggleHistoryMenu = ()=>setShowHistory(!showHistory);
this.setState({
showHistory : !this.state.showHistory
});
},
renderHistoryItems : function() { const renderHistoryItems = ()=>{
if(!this.state.historyExists) return; if(!historyExists) return;
return <div className='dropdown'> return <div className='dropdown'>
{_.map(this.state.historyItems, (item, index)=>{ {_.map(historyItems, (item, index)=>{
if(item.noData || !item.savedAt) return; if(item.noData || !item.savedAt) return;
const saveTime = new Date(item.savedAt); const saveTime = new Date(item.savedAt);
@@ -185,106 +159,103 @@ const Snippetbar = createReactClass({
if(diffSecs > (24 * 60 * 60)) diffString = `about ${Math.floor(diffSecs / (24 * 60 * 60))} days 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`; 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);}} > return <div className='snippet' key={index} onClick={()=>{replaceContent(item);}} >
<i className={`fas fa-${index+1}`} /> <i className={`fas fa-${index+1}`} />
<span className='name' title={saveTime.toISOString()}>v{item.version} : {diffString}</span> <span className='name' title={saveTime.toISOString()}>v{item.version} : {diffString}</span>
</div>; </div>;
})} })}
</div>; </div>;
}, };
renderEditorButtons : function(){
if(!this.props.showEditButtons) return; const renderEditorButtons =()=>{
if(!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' : ''}`} <button className={`editorTool snippetGroup history ${historyExists ? 'active' : ''}`}
onClick={this.toggleHistoryMenu} > onClick={toggleHistoryMenu} >
<i className='fas fa-clock-rotate-left' /> <i className='fas fa-clock-rotate-left' />
{ this.state.showHistory && this.renderHistoryItems() } { showHistory && renderHistoryItems() }
</button> </button>
<button className={`editorTool undo ${this.props.historySize.done ? 'active' : ''}`} <button className={`editorTool undo ${historySize.done ? 'active' : ''}`}
onClick={this.props.undo} > onClick={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 +266,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>; };
},
});