0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2025-12-24 14:12:40 +00:00
This commit is contained in:
Trevor Buckner
2024-09-04 01:06:56 -04:00
parent 4f39222724
commit d7d690a9d1
5 changed files with 132 additions and 133 deletions

View File

@@ -5,11 +5,11 @@ const Nav = require('naturalcrit/nav/nav.jsx');
module.exports = function (props) {
return (
<Nav.item
color="purple"
icon="fas fa-dungeon"
href="/vault"
color='purple'
icon='fas fa-dungeon'
href='/vault'
newTab={false}
rel="noopener noreferrer"
rel='noopener noreferrer'
>
Vault
</Nav.item>

View File

@@ -141,7 +141,7 @@ const BrewItem = createClass({
</> : <></>
}
<span title={`Authors:\n${brew.authors?.join('\n')}`}>
<i className='fas fa-user'/> {brew.authors?.map((author, index) => (
<i className='fas fa-user'/> {brew.authors?.map((author, index)=>(
<React.Fragment key={index}>
{author === 'hidden'
? <span title="Username contained an email address; hidden to protect user's privacy">{author}</span>

View File

@@ -174,7 +174,7 @@ const errorIndex = (props)=>{
'90' : dedent` An unexpected error occurred while looking for these brews.
Try again in a few minutes.`,
'91' : dedent` An unexpected error occurred while trying to get the total of brews.`,
};
};

View File

@@ -15,7 +15,7 @@ const ErrorIndex = require('../errorPage/errors/errorIndex.js');
const request = require('../../utils/request-middleware.js');
const VaultPage = (props) => {
const VaultPage = (props)=>{
const [pageState, setPageState] = useState(parseInt(props.query.page) || 1);
//Response state
@@ -32,33 +32,33 @@ const VaultPage = (props) => {
const legacyRef = useRef(null);
const submitButtonRef = useRef(null);
useEffect(() => {
useEffect(()=>{
disableSubmitIfFormInvalid();
loadPage(pageState, true);
}, []);
const updateStateWithBrews = (brews, page) => {
const updateStateWithBrews = (brews, page)=>{
setBrewCollection(brews || null);
setPageState(parseInt(page) || 1);
setSearching(false);
};
const updateUrl = (titleValue, authorValue, countValue, v3Value, legacyValue, page) => {
const updateUrl = (titleValue, authorValue, countValue, v3Value, legacyValue, page)=>{
const url = new URL(window.location.href);
const urlParams = new URLSearchParams(url.search);
urlParams.set('title', titleValue);
urlParams.set('author', authorValue);
urlParams.set('count', countValue);
urlParams.set('v3', v3Value);
urlParams.set('legacy', legacyValue);
urlParams.set('page', page);
url.search = urlParams.toString();
window.history.replaceState(null, '', url.toString());
};
const performSearch = async (title, author, count, v3, legacy, page) => {
const performSearch = async (title, author, count, v3, legacy, page)=>{
updateUrl(title, author, count, v3, legacy, page);
const response = await request.get(
@@ -71,14 +71,14 @@ const VaultPage = (props) => {
);
updateStateWithBrews([], 1);
});
if (response.ok)
if(response.ok)
updateStateWithBrews(response.body.brews, page);
};
const loadTotal = async (title, author, v3, legacy) => {
const loadTotal = async (title, author, v3, legacy)=>{
setTotalBrews(null);
const response = await request.get(
`/api/vault/total?title=${title}&author=${author}&v3=${v3}&legacy=${legacy}`
).catch((error)=>{
@@ -89,13 +89,13 @@ const VaultPage = (props) => {
);
updateStateWithBrews([], 1);
});
if (response.ok)
if(response.ok)
setTotalBrews(response.body.totalBrews);
};
const loadPage = async (page, updateTotal) => {
if (!validateForm())
const loadPage = async (page, updateTotal)=>{
if(!validateForm())
return;
setSearching(true);
@@ -109,14 +109,14 @@ const VaultPage = (props) => {
performSearch(title, author, count, v3, legacy, page);
if (updateTotal)
if(updateTotal)
loadTotal(title, author, v3, legacy);
};
const renderNavItems = () => (
const renderNavItems = ()=>(
<Navbar>
<Nav.section>
<Nav.item className="brewTitle">
<Nav.item className='brewTitle'>
Vault: Search for brews
</Nav.item>
</Nav.section>
@@ -129,7 +129,7 @@ const VaultPage = (props) => {
</Navbar>
);
const validateForm = () => {
const validateForm = ()=>{
//form validity: title or author must be written, and at least one renderer set
const isTitleValid = titleRef.current.validity.valid && titleRef.current.value;
const isAuthorValid = authorRef.current.validity.valid && authorRef.current.value;
@@ -140,29 +140,29 @@ const VaultPage = (props) => {
return isFormValid;
};
const disableSubmitIfFormInvalid = () => {
const disableSubmitIfFormInvalid = ()=>{
submitButtonRef.current.disabled = !validateForm();
};
const renderForm = () => (
<div className="brewLookup">
<h2 className="formTitle">Brew Lookup</h2>
<div className="formContents">
const renderForm = ()=>(
<div className='brewLookup'>
<h2 className='formTitle'>Brew Lookup</h2>
<div className='formContents'>
<label>
Title of the brew
<input
ref={titleRef}
type="text"
name="title"
type='text'
name='title'
defaultValue={props.query.title || ''}
onKeyUp={disableSubmitIfFormInvalid}
pattern=".{3,}"
title="At least 3 characters"
onKeyDown={(e) => {
if (e.key === 'Enter' && !submitButtonRef.current.disabled)
pattern='.{3,}'
title='At least 3 characters'
onKeyDown={(e)=>{
if(e.key === 'Enter' && !submitButtonRef.current.disabled)
loadPage(1, true);
}}
placeholder="v3 Reference Document"
placeholder='v3 Reference Document'
/>
</label>
@@ -170,34 +170,34 @@ const VaultPage = (props) => {
Author of the brew
<input
ref={authorRef}
type="text"
name="author"
pattern=".{1,}"
type='text'
name='author'
pattern='.{1,}'
defaultValue={props.query.author || ''}
onKeyUp={disableSubmitIfFormInvalid}
onKeyDown={(e) => {
if (e.key === 'Enter' && !submitButtonRef.current.disabled)
onKeyDown={(e)=>{
if(e.key === 'Enter' && !submitButtonRef.current.disabled)
loadPage(1, true);
}}
placeholder="Username"
placeholder='Username'
/>
</label>
<label>
Results per page
<select ref={countRef} name="count" defaultValue={props.query.count || 20}>
<option value="10">10</option>
<option value="20">20</option>
<option value="40">40</option>
<option value="60">60</option>
<select ref={countRef} name='count' defaultValue={props.query.count || 20}>
<option value='10'>10</option>
<option value='20'>20</option>
<option value='40'>40</option>
<option value='60'>60</option>
</select>
</label>
<label>
<input
className="renderer"
className='renderer'
ref={v3Ref}
type="checkbox"
type='checkbox'
defaultChecked={props.query.v3 !== 'false'}
onChange={disableSubmitIfFormInvalid}
/>
@@ -206,9 +206,9 @@ const VaultPage = (props) => {
<label>
<input
className="renderer"
className='renderer'
ref={legacyRef}
type="checkbox"
type='checkbox'
defaultChecked={props.query.legacy !== 'false'}
onChange={disableSubmitIfFormInvalid}
/>
@@ -216,9 +216,9 @@ const VaultPage = (props) => {
</label>
<button
id="searchButton"
id='searchButton'
ref={submitButtonRef}
onClick={() => {
onClick={()=>{
loadPage(1, true);
}}
>
@@ -244,7 +244,7 @@ const VaultPage = (props) => {
<li>
Some common words like "a", "after", "through", "itself", "here", etc.,
are ignored in searches. The full list can be found &nbsp;
<a href="https://github.com/mongodb/mongo/blob/0e3b3ca8480ddddf5d0105d11a94bd4698335312/src/mongo/db/fts/stop_words_english.txt">
<a href='https://github.com/mongodb/mongo/blob/0e3b3ca8480ddddf5d0105d11a94bd4698335312/src/mongo/db/fts/stop_words_english.txt'>
here
</a>
</li>
@@ -253,17 +253,17 @@ const VaultPage = (props) => {
</div>
);
const renderPaginationControls = () => {
if (!totalBrews) return null;
const renderPaginationControls = ()=>{
if(!totalBrews) return null;
const countInt = parseInt(props.query.count || 20);
const totalPages = Math.ceil(totalBrews / countInt);
let startPage, endPage;
if (pageState <= 6) {
if(pageState <= 6) {
startPage = 1;
endPage = Math.min(totalPages, 10);
} else if (pageState + 4 >= totalPages) {
} else if(pageState + 4 >= totalPages) {
startPage = Math.max(1, totalPages - 9);
endPage = totalPages;
} else {
@@ -273,32 +273,32 @@ const VaultPage = (props) => {
const pagesAroundCurrent = new Array(endPage - startPage + 1)
.fill()
.map((_, index) => (
.map((_, index)=>(
<a
key={startPage + index}
className={`pageNumber ${
pageState === startPage + index ? 'currentPage' : ''
}`}
onClick={() => loadPage(startPage + index, false)}
onClick={()=>loadPage(startPage + index, false)}
>
{startPage + index}
</a>
));
return (
<div className="paginationControls">
<div className='paginationControls'>
<button
className="previousPage"
onClick={() => loadPage(pageState - 1, false)}
className='previousPage'
onClick={()=>loadPage(pageState - 1, false)}
disabled={pageState === startPage}
>
<i className="fa-solid fa-chevron-left"></i>
<i className='fa-solid fa-chevron-left'></i>
</button>
<ol className="pages">
<ol className='pages'>
{startPage > 1 && (
<a
className="pageNumber firstPage"
onClick={() => loadPage(1, false)}
className='pageNumber firstPage'
onClick={()=>loadPage(1, false)}
>
1 ...
</a>
@@ -306,90 +306,90 @@ const VaultPage = (props) => {
{pagesAroundCurrent}
{endPage < totalPages && (
<a
className="pageNumber lastPage"
onClick={() => loadPage(totalPages, false)}
className='pageNumber lastPage'
onClick={()=>loadPage(totalPages, false)}
>
... {totalPages}
</a>
)}
</ol>
<button
className="nextPage"
onClick={() => loadPage(pageState + 1, false)}
className='nextPage'
onClick={()=>loadPage(pageState + 1, false)}
disabled={pageState === totalPages}
>
<i className="fa-solid fa-chevron-right"></i>
<i className='fa-solid fa-chevron-right'></i>
</button>
</div>
);
};
const renderFoundBrews = () => {
if (searching) {
const renderFoundBrews = ()=>{
if(searching) {
return (
<div className="foundBrews searching">
<h3 className="searchAnim">Searching</h3>
<div className='foundBrews searching'>
<h3 className='searchAnim'>Searching</h3>
</div>
);
}
if (error) {
if(error) {
const errorText = ErrorIndex({ brew })[brew.HBErrorCode.toString()] || '';
console.log('render Error: ', error);
return (
<div className="foundBrews noBrews">
<div className='foundBrews noBrews'>
<h3>Error: {errorText}</h3>
</div>
);
}
if (!brewCollection) {
if(!brewCollection) {
return (
<div className="foundBrews noBrews">
<div className='foundBrews noBrews'>
<h3>No search yet</h3>
</div>
);
}
if (brewCollection.length === 0) {
if(brewCollection.length === 0) {
return (
<div className="foundBrews noBrews">
<div className='foundBrews noBrews'>
<h3>No brews found</h3>
</div>
);
}
return (
<div className="foundBrews">
<span className="totalBrews">
{`Brews found: `}
<span>{totalBrews}</span>
</span>
{brewCollection.map((brew, index) => {
return (
<BrewItem
brew={{...brew}}
key={index}
reportError={props.reportError}
/>
);
})}
{renderPaginationControls()}
</div>
);
};
<div className='foundBrews'>
<span className='totalBrews'>
{`Brews found: `}
<span>{totalBrews}</span>
</span>
{brewCollection.map((brew, index)=>{
return (
<BrewItem
brew={{ ...brew }}
key={index}
reportError={props.reportError}
/>
);
})}
{renderPaginationControls()}
</div>
);
};
return (
<div className="vaultPage">
<link href="/themes/V3/Blank/style.css" rel="stylesheet" />
<link href="/themes/V3/5ePHB/style.css" rel="stylesheet" />
<div className='vaultPage'>
<link href='/themes/V3/Blank/style.css' rel='stylesheet' />
<link href='/themes/V3/5ePHB/style.css' rel='stylesheet' />
{renderNavItems()}
<div className="content">
<div className='content'>
<SplitPane hideMoveArrows>
<div className="form dataGroup">{renderForm()}</div>
<div className='form dataGroup'>{renderForm()}</div>
<div className="resultsContainer dataGroup">
<div className='resultsContainer dataGroup'>
{renderFoundBrews()}
</div>
</SplitPane>

View File

@@ -4,32 +4,32 @@ const HomebrewModel = require('./homebrew.model.js').model;
const router = express.Router();
const titleConditions = (title) => {
if (!title) return {};
const titleConditions = (title)=>{
if(!title) return {};
return {
$text: {
$search: title,
$caseSensitive: false,
$text : {
$search : title,
$caseSensitive : false,
},
};
};
const authorConditions = (author) => {
if (!author) return {};
const authorConditions = (author)=>{
if(!author) return {};
return { authors: author };
};
const rendererConditions = (legacy, v3) => {
if (legacy === 'true' && v3 !== 'true')
return { renderer: 'legacy'};
const rendererConditions = (legacy, v3)=>{
if(legacy === 'true' && v3 !== 'true')
return { renderer: 'legacy' };
if (v3 === 'true' && legacy !== 'true')
return { renderer: 'V3'};
if(v3 === 'true' && legacy !== 'true')
return { renderer: 'V3' };
return {}; // If all renderers selected, renderer field not needed in query for speed
};
const findBrews = async (req, res) => {
const findBrews = async (req, res)=>{
const title = req.query.title || '';
const author = req.query.author || '';
const page = Math.max(parseInt(req.query.page) || 1, 1);
@@ -37,7 +37,7 @@ const findBrews = async (req, res) => {
const skip = (page - 1) * count;
const combinedQuery = {
$and: [
$and : [
{ published: true },
rendererConditions(req.query.legacy, req.query.v3),
titleConditions(title),
@@ -58,28 +58,27 @@ const findBrews = async (req, res) => {
.limit(count)
.maxTimeMS(5000)
.exec()
.then((brews) => {
.then((brews)=>{
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const processedBrews = brews.map((brew) => {
brew.authors = brew.authors.map(author =>
emailRegex.test(author) ? 'hidden' : author
const processedBrews = brews.map((brew)=>{
brew.authors = brew.authors.map((author)=>emailRegex.test(author) ? 'hidden' : author
);
return brew;
});
res.json({ brews: processedBrews, page });
})
.catch((error) => {
throw {...error, message: "Error finding brews in Vault search", HBErrorCode: 90};
.catch((error)=>{
throw { ...error, message: 'Error finding brews in Vault search', HBErrorCode: 90 };
});
};
const findTotal = async (req, res) => {
const findTotal = async (req, res)=>{
const title = req.query.title || '';
const author = req.query.author || '';
const combinedQuery = {
$and: [
$and : [
{ published: true },
rendererConditions(req.query.legacy, req.query.v3),
titleConditions(title),
@@ -88,12 +87,12 @@ const findTotal = async (req, res) => {
};
await HomebrewModel.countDocuments(combinedQuery)
.then((totalBrews) => {
console.log(`when returning, the total of brews is ${totalBrews} for the query ${JSON.stringify(combinedQuery)}`);
.then((totalBrews)=>{
console.log(`when returning, the total of brews is ${totalBrews} for the query ${JSON.stringify(combinedQuery)}`);
res.json({ totalBrews });
})
.catch((error) => {
throw {...error, message: "Error finding brews in Vault search findTotal function", HBErrorCode: 91};
.catch((error)=>{
throw { ...error, message: 'Error finding brews in Vault search findTotal function', HBErrorCode: 91 };
});
};