mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-11-04 22:38:43 +00:00
614 lines
17 KiB
React
614 lines
17 KiB
React
/*eslint max-lines: ["warn", {"max": 400, "skipBlankLines": true, "skipComments": true}]*/
|
|
/*eslint max-params:["warn", { max: 10 }], */
|
|
import './vaultPage.less';
|
|
import React, { useState, useEffect, useRef } from 'react';
|
|
|
|
import Nav from '@navbar/nav.jsx';
|
|
import Navbar from '@navbar/navbar.jsx';
|
|
import RecentNavItems from '@navbar/recent.navitem.jsx';
|
|
const { both: RecentNavItem } = RecentNavItems;
|
|
import Account from '@navbar/account.navitem.jsx';
|
|
import NewBrew from '@navbar/newbrew.navitem.jsx';
|
|
import HelpNavItem from '@navbar/help.navitem.jsx';
|
|
import BrewItem from '../basePages/listPage/brewItem/brewItem.jsx';
|
|
import SplitPane from '@components/splitPane/splitPane.jsx';
|
|
import ErrorIndex from '../errorPage/errors/errorIndex.js';
|
|
|
|
import TagInput from '../../editor/tagInput/tagInput.jsx';
|
|
|
|
import request from '../../utils/request-middleware.js';
|
|
|
|
const DEFAULT_SORT_TYPE = 'alpha';
|
|
const DEFAULT_SORT_DIR = 'asc';
|
|
const DEFAULT_LAYOUT_MODE = 'grid';
|
|
const DEFAULT_THEME_MODE = 'light';
|
|
const USERPAGE_LAYOUT_MODE = 'HB_listPage_layout_mode';
|
|
const USERPAGE_THEME_MODE = 'HB_listPage_theme_mode';
|
|
|
|
const VaultPage = (props)=>{
|
|
const [pageState, setPageState] = useState(parseInt(props.query.page) || 1);
|
|
|
|
const [sortState, setSort] = useState(props.query.sort || 'title');
|
|
const [dirState, setdir] = useState(props.query.dir || 'asc');
|
|
|
|
//Response state
|
|
const [brewCollection, setBrewCollection] = useState(null);
|
|
const [totalBrews, setTotalBrews] = useState(null);
|
|
const [searching, setSearching] = useState(false);
|
|
const [error, setError] = useState(null);
|
|
const [layoutMode, setLayoutMode] = useState(DEFAULT_LAYOUT_MODE);
|
|
const [themeMode, setThemeMode] = useState(DEFAULT_THEME_MODE);
|
|
|
|
const titleRef = useRef(null);
|
|
const authorRef = useRef(null);
|
|
const countRef = useRef(null);
|
|
const v3Ref = useRef(null);
|
|
const legacyRef = useRef(null);
|
|
const submitButtonRef = useRef(null);
|
|
|
|
const parseTags = (value)=>value?.split(',').filter(Boolean) || [];
|
|
|
|
const [tagsListAnd, setTagListAnd] = useState(parseTags(props.query.tagsAnd));
|
|
const [tagsListOr, setTagListOr] = useState(parseTags(props.query.tagsOr));
|
|
const [tagsListNot, setTagListNot] = useState(parseTags(props.query.tagsNot));
|
|
|
|
useEffect(()=>{
|
|
disableSubmitIfFormInvalid();
|
|
|
|
const newLayoutMode = localStorage.getItem(USERPAGE_LAYOUT_MODE) || DEFAULT_LAYOUT_MODE;
|
|
const newThemeMode = localStorage.getItem(USERPAGE_THEME_MODE) || DEFAULT_THEME_MODE;
|
|
|
|
setLayoutMode(newLayoutMode);
|
|
setThemeMode(newThemeMode);
|
|
|
|
loadPage(pageState, true, props.query.sort, props.query.dir);
|
|
}, []);
|
|
|
|
useEffect(()=>{disableSubmitIfFormInvalid()},[tagsListAnd, tagsListOr, tagsListNot])
|
|
|
|
const updateStateWithBrews = (brews, page)=>{
|
|
setBrewCollection(brews || null);
|
|
setPageState(parseInt(page) || 1);
|
|
setSearching(false);
|
|
};
|
|
|
|
const buildQueryParams = (entries)=>{
|
|
const params = new URLSearchParams();
|
|
|
|
entries.forEach(([key, value])=>{
|
|
if(value === undefined || value === null || value === '') return;
|
|
if(Array.isArray(value) && value.length === 0) return;
|
|
|
|
params.set(key, Array.isArray(value) ? value.join(',') : value);
|
|
});
|
|
|
|
return params.toString();
|
|
};
|
|
|
|
const performSearch = async (formContents, page, sort, dir)=>{
|
|
const { title, author, count, v3, legacy, tagsAnd, tagsOr, tagsNot } = formContents;
|
|
|
|
const params = buildQueryParams([
|
|
['title', title],
|
|
['author', author],
|
|
['v3', v3],
|
|
['legacy', legacy],
|
|
['tagsAnd', tagsAnd],
|
|
['tagsOr', tagsOr],
|
|
['tagsNot', tagsNot],
|
|
['count', count],
|
|
['page', page],
|
|
['sort', sort],
|
|
['dir', dir]
|
|
]);
|
|
|
|
const url = new URL(window.location.href);
|
|
url.search = params;
|
|
window.history.replaceState(null, '', url.toString());
|
|
|
|
const response = await request.get(`/api/vault?${params}`)
|
|
.catch((error)=>{
|
|
console.log('error at loadPage: ', error);
|
|
setError(error);
|
|
updateStateWithBrews([], 1);
|
|
});
|
|
|
|
if(response?.ok) {
|
|
updateStateWithBrews(response.body.brews, page);
|
|
}
|
|
};
|
|
|
|
const loadTotal = async (formContents)=>{
|
|
const { title, author, v3, legacy, tagsAnd, tagsOr, tagsNot } = formContents;
|
|
|
|
setTotalBrews(null);
|
|
|
|
const params = buildQueryParams([
|
|
['title', title],
|
|
['author', author],
|
|
['v3', v3],
|
|
['legacy', legacy],
|
|
['tagsAnd', tagsAnd],
|
|
['tagsOr', tagsOr],
|
|
['tagsNot', tagsNot]
|
|
]);
|
|
|
|
const response = await request.get(`/api/vault/total?${params}`)
|
|
.catch((error)=>{
|
|
console.log('error at loadTotal: ');
|
|
console.error(error);
|
|
setError(error);
|
|
updateStateWithBrews([], 1);
|
|
});
|
|
|
|
if(response?.ok) {
|
|
setTotalBrews(response.body.totalBrews);
|
|
}
|
|
};
|
|
|
|
const loadPage = async (page, updateTotal, sort, dir)=>{
|
|
if(!validateForm()) return;
|
|
|
|
setSearching(true);
|
|
setError(null);
|
|
|
|
const title = titleRef.current.value || '';
|
|
const author = authorRef.current.value || '';
|
|
const count = countRef.current.value || 20;
|
|
const v3 = v3Ref.current.checked != false;
|
|
const legacy = legacyRef.current.checked != false;
|
|
const tagsAnd = tagsListAnd;
|
|
const tagsOr = tagsListOr;
|
|
const tagsNot = tagsListNot;
|
|
|
|
const formContents = {
|
|
title, author, count, v3, legacy, tagsAnd, tagsOr, tagsNot
|
|
};
|
|
|
|
const sortOption = sort || 'title';
|
|
const dirOption = dir || 'asc';
|
|
const pageProp = page || 1;
|
|
|
|
setSort(sortOption);
|
|
setdir(dirOption);
|
|
|
|
performSearch(formContents, pageProp, sortOption, dirOption);
|
|
|
|
if(updateTotal)
|
|
loadTotal(formContents);
|
|
};
|
|
|
|
const renderNavItems = ()=>(
|
|
<Navbar>
|
|
<Nav.section>
|
|
<Nav.item className='brewTitle'>
|
|
Vault: Search for brews
|
|
</Nav.item>
|
|
</Nav.section>
|
|
<Nav.section>
|
|
<NewBrew />
|
|
<HelpNavItem />
|
|
<RecentNavItem />
|
|
<Account />
|
|
</Nav.section>
|
|
</Navbar>
|
|
);
|
|
|
|
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;
|
|
const isCheckboxChecked = legacyRef.current.checked || v3Ref.current.checked;
|
|
const isTagsValid = tagsListAnd.length >= 1 || tagsListOr.length >= 1;
|
|
//if a search is done with only negative tags, the planner crashes
|
|
|
|
const isFormValid = (isTitleValid || isAuthorValid || isTagsValid) && isCheckboxChecked;
|
|
|
|
return isFormValid;
|
|
};
|
|
|
|
const disableSubmitIfFormInvalid = ()=>{
|
|
submitButtonRef.current.disabled = !validateForm();
|
|
};
|
|
|
|
const renderForm = ()=>(
|
|
<div className='brewLookup'>
|
|
<h1 className='formTitle'>Brew Lookup</h1>
|
|
<div className='formContents'>
|
|
<label>
|
|
Title of the brew
|
|
<input
|
|
ref={titleRef}
|
|
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)
|
|
loadPage(1, true);
|
|
}}
|
|
placeholder='v3 Reference Document'
|
|
/>
|
|
</label>
|
|
|
|
<label>
|
|
Author of the brew
|
|
<input
|
|
ref={authorRef}
|
|
type='text'
|
|
name='author'
|
|
pattern='.{1,}'
|
|
defaultValue={props.query.author || ''}
|
|
onKeyUp={disableSubmitIfFormInvalid}
|
|
onKeyDown={(e)=>{
|
|
if(e.key === 'Enter' && !submitButtonRef.current.disabled)
|
|
loadPage(1, true);
|
|
}}
|
|
placeholder='Username'
|
|
/>
|
|
</label>
|
|
|
|
<h3>Tag Search</h3>
|
|
<fieldset className='tags'>
|
|
<label>
|
|
Must include
|
|
<TagInput
|
|
id='combobox-tags-and'
|
|
label='tags'
|
|
valuePatterns={/^\s*(?:(?:group|meta|system|type)\s*:\s*)?[A-Za-z0-9][A-Za-z0-9 \/\\.&_\-]{0,40}\s*$/}
|
|
placeholder='add tag'
|
|
unique={true}
|
|
values={tagsListAnd}
|
|
onChange={(e)=>setTagListAnd(e.target.value)}
|
|
tooltip='You may start tags with "type", "system", "group" or "meta" followed by a colon ":", these will be colored in your userpage.'
|
|
/>
|
|
</label>
|
|
|
|
<label>
|
|
Match any
|
|
<TagInput
|
|
id='combobox-tags-or'
|
|
label='tags'
|
|
valuePatterns={/^\s*(?:(?:group|meta|system|type)\s*:\s*)?[A-Za-z0-9][A-Za-z0-9 \/\\.&_\-]{0,40}\s*$/}
|
|
placeholder='add tag'
|
|
unique={true}
|
|
values={tagsListOr}
|
|
onChange={(e)=>setTagListOr(e.target.value)}
|
|
tooltip='You may start tags with "type", "system", "group" or "meta" followed by a colon ":", these will be colored in your userpage.'
|
|
/>
|
|
</label>
|
|
|
|
<label>
|
|
Must exclude
|
|
<TagInput
|
|
id='combobox-tags-not'
|
|
label='tags'
|
|
valuePatterns={/^\s*(?:(?:group|meta|system|type)\s*:\s*)?[A-Za-z0-9][A-Za-z0-9 \/\\.&_\-]{0,40}\s*$/}
|
|
placeholder='add tag'
|
|
unique={true}
|
|
values={tagsListNot}
|
|
onChange={(e)=>setTagListNot(e.target.value)}
|
|
tooltip='You may start tags with "type", "system", "group" or "meta" followed by a colon ":", these will be colored in your userpage.'
|
|
/>
|
|
</label>
|
|
</fieldset>
|
|
|
|
<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>
|
|
</label>
|
|
|
|
<label>
|
|
<input
|
|
className='renderer'
|
|
ref={v3Ref}
|
|
type='checkbox'
|
|
defaultChecked={props.query.v3 !== 'false'}
|
|
onChange={disableSubmitIfFormInvalid}
|
|
/>
|
|
Search for v3 brews
|
|
</label>
|
|
|
|
<label>
|
|
<input
|
|
className='renderer'
|
|
ref={legacyRef}
|
|
type='checkbox'
|
|
defaultChecked={props.query.legacy !== 'false'}
|
|
onChange={disableSubmitIfFormInvalid}
|
|
/>
|
|
Search for legacy brews
|
|
</label>
|
|
|
|
<button
|
|
id='searchButton'
|
|
ref={submitButtonRef}
|
|
onClick={()=>{
|
|
loadPage(1, true);
|
|
}}
|
|
>
|
|
Search
|
|
<i
|
|
className={searching ? 'fas fa-spin fa-spinner': 'fas fa-search'}
|
|
/>
|
|
</button>
|
|
</div>
|
|
<legend>
|
|
<h2>Tips and tricks</h2>
|
|
<ul>
|
|
<li>
|
|
Only <b>published</b> brews are searchable via this tool
|
|
</li>
|
|
<li>
|
|
Usernames are case-sensitive
|
|
</li>
|
|
<li>
|
|
Use <code>"word"</code> to match an exact string,
|
|
and <code>-</code> to exclude words (at least one word must not be negated)
|
|
</li>
|
|
<li>
|
|
Some common words like "a", "after", "through", "itself", "here", etc.,
|
|
are ignored in searches. The full list can be found
|
|
<a href='https://github.com/mongodb/mongo/blob/0e3b3ca8480ddddf5d0105d11a94bd4698335312/src/mongo/db/fts/stop_words_english.txt'>
|
|
here
|
|
</a>
|
|
</li>
|
|
</ul>
|
|
<small>New features will be coming, such as filters and search by tags.</small>
|
|
</legend>
|
|
</div>
|
|
);
|
|
|
|
const renderSortOption = (optionTitle, optionValue)=>{
|
|
const oppositeDir = dirState === 'asc' ? 'desc' : 'asc';
|
|
|
|
return (
|
|
<div className={`option ${sortState === optionValue ? `active` : ''}`}>
|
|
<button onClick={()=>loadPage(1, false, optionValue, oppositeDir)}>
|
|
{optionTitle}
|
|
</button>
|
|
{sortState === optionValue && (
|
|
<i className={`sortDir fas ${dirState === 'asc' ? 'fa-sort-up' : 'fa-sort-down'}`} />
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const renderSortOptions = ()=>{
|
|
|
|
return (
|
|
<div className='radio-toggle sort-container'>
|
|
{renderSortOption('Title', 'title', props.query.dir)}
|
|
{renderSortOption('Created Date', 'createdAt', props.query.dir)}
|
|
{renderSortOption('Updated Date', 'updatedAt', props.query.dir)}
|
|
{renderSortOption('Views', 'views', props.query.dir)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const handleLayoutChange = (e, mode)=>{
|
|
setLayoutMode(e.target.checked ? mode : DEFAULT_LAYOUT_MODE);
|
|
localStorage.setItem(USERPAGE_LAYOUT_MODE, e.target.checked ? mode : DEFAULT_LAYOUT_MODE);
|
|
return;
|
|
};
|
|
const renderLayoutModeOptions = ()=>{
|
|
return (
|
|
<div className='radio-toggle layout-container'>
|
|
<h6>View:</h6>
|
|
<label className='option' title='grid'>
|
|
<input name='layout-mode' type='radio' onChange={(e)=>handleLayoutChange(e, 'grid')} checked={layoutMode === 'grid'} />
|
|
<i className='fac compressed-grid'></i>
|
|
</label>
|
|
<label className='option' title='list'>
|
|
<input name='layout-mode' type='radio' onChange={(e)=>handleLayoutChange(e, 'list')} checked={layoutMode === 'list'} />
|
|
<i className='fas fa-bars'></i>
|
|
</label>
|
|
<label className='option' title='card'>
|
|
<input name='layout-mode' type='radio' onChange={(e)=>handleLayoutChange(e, 'card')} checked={layoutMode === 'card'} />
|
|
<i className='fac format-card'></i>
|
|
</label>
|
|
</div>
|
|
);
|
|
};
|
|
const handleThemeChange = (e, mode)=>{
|
|
setThemeMode(e.target.checked ? mode : DEFAULT_THEME_MODE);
|
|
localStorage.setItem(USERPAGE_THEME_MODE, e.target.checked ? mode : DEFAULT_THEME_MODE);
|
|
return;
|
|
};
|
|
|
|
const renderThemePicker = ()=>{
|
|
return (
|
|
<div className='radio-toggle theme-container'>
|
|
<h6>Theme:</h6>
|
|
<label className='option'>
|
|
<input type='radio' name='theme' onChange={(e)=>handleThemeChange(e, 'light')} checked={themeMode === 'light'}/>
|
|
<i className='fas fa-sun'/>
|
|
</label>
|
|
<label className='option'>
|
|
<input type='radio' name='theme' onChange={(e)=>handleThemeChange(e, 'dark')} checked={themeMode === 'dark'}/>
|
|
<i className='fas fa-moon'/>
|
|
</label>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
|
|
const renderNav = ()=>{
|
|
return (
|
|
<div className='listPageNav'>
|
|
{renderLayoutModeOptions()}
|
|
{renderThemePicker()}
|
|
{renderSortOptions()}
|
|
</div>
|
|
);
|
|
|
|
};
|
|
|
|
const renderPaginationControls = ()=>{
|
|
if(!totalBrews || totalBrews < 10) return null;
|
|
|
|
|
|
const countInt = parseInt(countRef.current.value || 20);
|
|
const totalPages = Math.ceil(totalBrews / countInt);
|
|
|
|
let startPage, endPage;
|
|
if(pageState <= 6) {
|
|
startPage = 1;
|
|
endPage = Math.min(totalPages, 10);
|
|
} else if(pageState + 4 >= totalPages) {
|
|
startPage = Math.max(1, totalPages - 9);
|
|
endPage = totalPages;
|
|
} else {
|
|
startPage = pageState - 5;
|
|
endPage = pageState + 4;
|
|
}
|
|
|
|
const pagesAroundCurrent = new Array(endPage - startPage + 1)
|
|
.fill()
|
|
.map((_, index)=>(
|
|
<a
|
|
key={startPage + index}
|
|
className={`pageNumber ${pageState === startPage + index ? 'currentPage' : ''}`}
|
|
onClick={()=>loadPage(startPage + index, false, sortState, dirState)}
|
|
>
|
|
{startPage + index}
|
|
</a>
|
|
));
|
|
|
|
return (
|
|
<div className='paginationControls'>
|
|
<button
|
|
className='previousPage'
|
|
onClick={()=>loadPage(pageState - 1, false, sortState, dirState)}
|
|
disabled={pageState === startPage}
|
|
>
|
|
<i className='fa-solid fa-chevron-left'></i>
|
|
</button>
|
|
<ol className='pages'>
|
|
{startPage > 1 && (
|
|
<a
|
|
className='pageNumber firstPage'
|
|
onClick={()=>loadPage(1, false, sortState, dirState)}
|
|
>
|
|
1 ...
|
|
</a>
|
|
)}
|
|
{pagesAroundCurrent}
|
|
{endPage < totalPages && (
|
|
<a
|
|
className='pageNumber lastPage'
|
|
onClick={()=>loadPage(totalPages, false, sortState, dirState)}
|
|
>
|
|
... {totalPages}
|
|
</a>
|
|
)}
|
|
</ol>
|
|
<button
|
|
className='nextPage'
|
|
onClick={()=>loadPage(pageState + 1, false, sortState, dirState)}
|
|
disabled={pageState === totalPages}
|
|
>
|
|
<i className='fa-solid fa-chevron-right'></i>
|
|
</button>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const renderFoundBrews = ()=>{
|
|
if(searching && !brewCollection) {
|
|
return (
|
|
<div className='foundBrews searching'>
|
|
<h3 className='searchAnim'>Searching</h3>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if(error) {
|
|
if(error.HBErrorCode === undefined) {
|
|
return (
|
|
<div className='foundBrews noBrews'>
|
|
<h3>Error: Unknown error</h3>
|
|
</div>
|
|
);
|
|
} else {
|
|
|
|
const errorText = ErrorIndex()[error.HBErrorCode.toString()] || '';
|
|
|
|
return (
|
|
<div className='foundBrews noBrews'>
|
|
<h3>Error: {errorText}</h3>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
}
|
|
|
|
if(!brewCollection) {
|
|
return (
|
|
<div className='foundBrews noBrews'>
|
|
<h3>No search yet</h3>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if(brewCollection.length === 0) {
|
|
return (
|
|
<div className='foundBrews noBrews'>
|
|
<h3>No brews found</h3>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className={`foundBrews ${`${themeMode}Mode`}`}>
|
|
<span className='totalBrews'>
|
|
{`Brews found: `}
|
|
<span>{totalBrews}</span>
|
|
</span>
|
|
{brewCollection.length > 10 && renderPaginationControls()}
|
|
<div className='brewCollection'>
|
|
<div className={`brewGroup ${layoutMode}`}>
|
|
{brewCollection.map((brew, index)=>{
|
|
return (
|
|
<BrewItem
|
|
brew={{ ...brew }}
|
|
key={index}
|
|
reportError={props.reportError}
|
|
renderStorage={false}
|
|
/>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
{renderPaginationControls()}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div className='sitePage vaultPage'>
|
|
<link href='/themes/V3/Blank/style.css' rel='stylesheet' />
|
|
<link href='/themes/V3/5ePHB/style.css' rel='stylesheet' />
|
|
{renderNavItems()}
|
|
<div className='content'>
|
|
<SplitPane showDividerButtons={false}>
|
|
<div className='form dataGroup'>{renderForm()}</div>
|
|
<div className='resultsContainer dataGroup'>
|
|
{renderNav()}
|
|
{renderFoundBrews()}
|
|
</div>
|
|
</SplitPane>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default VaultPage;
|