0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-13 06:32:39 +00:00

"Removed ArchivePage and related files, replaced with VaultPage, updated routes and API endpoints, and made minor changes to theme configuration and error handling."

This commit is contained in:
Víctor Losada Hernández
2024-06-11 00:33:36 +02:00
parent 99b0c2b54e
commit 90431efbc9
8 changed files with 43 additions and 37 deletions

View File

@@ -0,0 +1,410 @@
require('./vaultPage.less');
const React = require('react');
const { useState, useEffect, useRef } = React;
const cx = require('classnames');
const Nav = require('naturalcrit/nav/nav.jsx');
const Navbar = require('../../navbar/navbar.jsx');
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
const Account = require('../../navbar/account.navitem.jsx');
const NewBrew = require('../../navbar/newbrew.navitem.jsx');
const HelpNavItem = require('../../navbar/help.navitem.jsx');
const BrewItem = require('../basePages/listPage/brewItem/brewItem.jsx');
const request = require('../../utils/request-middleware.js');
const VaultPage = (props) => {
const [title, setTitle] = useState(props.query.title || '');
const [legacy, setLegacy] = useState(props.query.legacy !== 'false');
const [v3, setV3] = useState(props.query.v3 !== 'false');
const [count, setCount] = useState(props.query.count || 10);
const [page, setPage] = useState(parseInt(props.query.page) || 1);
const [brewCollection, setBrewCollection] = useState(null);
const [totalBrews, setTotalBrews] = useState(null);
const [searching, setSearching] = useState(false);
const [error, setError] = useState(null);
const titleRef = useRef(null);
const countRef = useRef(null);
const v3Ref = useRef(null);
const legacyRef = useRef(null);
const totalBrewsSpanRef = useRef(null);
useEffect(() => {
validateInput();
if (title) {
loadPage(page, false);
}
!totalBrews && loadTotal();
}, []);
useEffect(() => {
console.log(totalBrewsSpanRef);
console.log(totalBrews);
if (totalBrewsSpanRef.current) {
if (title === '') {
totalBrewsSpanRef.current.innerHTML = '0';
} else {
if (!totalBrews) {
totalBrewsSpanRef.current.innerHTML =
'<span class="searchAnim"></span>';
} else {
totalBrewsSpanRef.current.innerHTML = `${totalBrews}`;
}
}
}
}, [totalBrews, title, () => totalBrewsSpanRef.current]);
const updateStateWithBrews = (brews, page) => {
setBrewCollection(brews || null);
setPage(parseInt(page) || 1);
setSearching(false);
};
const updateUrl = (title, page, count, v3, legacy) => {
const url = new URL(window.location.href);
const urlParams = new URLSearchParams();
Object.entries({ title, page, count, v3, legacy }).forEach(
([key, value]) => urlParams.set(key, value)
);
url.search = urlParams.toString();
window.history.replaceState(null, null, url);
};
const loadPage = async (page, update) => {
setSearching(true);
setError(null);
const performSearch = async ({ title, count, v3, legacy }) => {
updateUrl(title, page, count, v3, legacy);
if (title !== '') {
try {
const response = await request.get(
`/api/vault?title=${title}&page=${page}&count=${count}&v3=${v3}&legacy=${legacy}`
);
if (response.ok) {
updateStateWithBrews(response.body.brews, page);
} else {
throw new Error(`Error: ${response.status}`);
}
} catch (error) {
console.log('error at loadPage: ', error);
setError(
`${
error.response
? error.response.status
: error.message
}`
);
updateStateWithBrews([], 1);
}
} else {
setError('404');
}
};
if (update) {
const title = titleRef.current.value || '';
const count = countRef.current.value || 10;
const v3 = v3Ref.current.checked;
const legacy = legacyRef.current.checked;
setTitle(title);
setCount(count);
setV3(v3);
setLegacy(legacy);
performSearch({ title, count, v3, legacy });
} else {
performSearch({ title, count, v3, legacy });
}
};
const loadTotal = async () => {
setTotalBrews(null);
setError(null);
if (title) {
try {
const response = await request.get(
`/api/vault/total?title=${title}&v3=${v3}&legacy=${legacy}`
);
if (response.ok) {
setTotalBrews(response.body.totalBrews);
} else {
throw new Error(
`Failed to load total brews: ${response.statusText}`
);
}
} catch (error) {
console.log('error at loadTotal: ', error);
setError(`${error.response.status}`);
updateStateWithBrews([], 1);
}
}
};
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 validateInput = () => {
const textInput = titleRef.current;
const submitButton = document.getElementById('searchButton');
if (textInput.validity.valid && textInput.value) {
submitButton.disabled = false;
} else {
submitButton.disabled = true;
}
};
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"
defaultValue={title}
onKeyUp={validateInput}
pattern=".{3,}"
onKeyDown={(e) => {
if (e.key === 'Enter') {
if (e.target.validity.valid && e.target.value) {
loadTotal();
loadPage(1, true);
}
}
}}
placeholder="v3 Reference Document"
/>
</label>
<small>
Tip! you can use <code>-</code> to negate words, and{' '}
<code>"word"</code> to specify an exact string.
</small>
<label>
Results per page
<select ref={countRef} name="count" defaultValue={count}>
<option value="10">10</option>
<option value="20">20</option>
<option value="40">40</option>
<option value="60">60</option>
</select>
</label>
<label>
<input ref={v3Ref} type="checkbox" defaultChecked={v3} />
Search for v3 brews
</label>
<label>
<input
ref={legacyRef}
type="checkbox"
defaultChecked={legacy}
/>
Search for legacy brews
</label>
<button
id="searchButton"
onClick={() => {
loadTotal();
loadPage(1, true);
}}
>
Search
<i
className={cx('fas', {
'fa-search': !searching,
'fa-spin fa-spinner': searching,
})}
/>
</button>
</div>
<small>
Remember, you can only search brews with this tool if they are
published
</small>
</div>
);
const renderPaginationControls = () => {
if (!totalBrews) return null;
const countInt = parseInt(count);
const totalPages = Math.ceil(totalBrews / countInt);
let startPage, endPage;
if (page <= 6) {
startPage = 1;
endPage = Math.min(totalPages, 10);
} else if (page + 4 >= totalPages) {
startPage = Math.max(1, totalPages - 9);
endPage = totalPages;
} else {
startPage = page - 5;
endPage = page + 4;
}
const pagesAroundCurrent = new Array(endPage - startPage + 1)
.fill()
.map((_, index) => (
<a
key={startPage + index}
className={`pageNumber ${
page === startPage + index ? 'currentPage' : ''
}`}
onClick={() => loadPage(startPage + index, false)}
>
{startPage + index}
</a>
));
return (
<div className="paginationControls">
{page > 1 && (
<button
className="previousPage"
onClick={() => loadPage(page - 1, false)}
>
&lt;&lt;
</button>
)}
<ol className="pages">
{startPage > 1 && (
<a
className="firstPage"
onClick={() => loadPage(1, false)}
>
1 ...
</a>
)}
{pagesAroundCurrent}
{endPage < totalPages && (
<a
className="lastPage"
onClick={() => loadPage(totalPages, false)}
>
... {totalPages}
</a>
)}
</ol>
{page < totalPages && (
<button
className="nextPage"
onClick={() => loadPage(page + 1, false)}
>
&gt;&gt;
</button>
)}
</div>
);
};
const renderFoundBrews = () => {
if (searching) {
return (
<div className="foundBrews searching">
<h3 className="searchAnim">Searching</h3>
</div>
);
}
if (title === '') {
return (
<div className="foundBrews noBrews">
<h3>No search yet</h3>
</div>
);
}
if (error) {
console.log('render Error: ', error);
let errorMessage;
switch (error.errorCode) {
case '404':
errorMessage = "404 - We didn't find any brew";
break;
case '503':
errorMessage =
'503 - Service Unavailable, try again later, sorry.';
break;
case '500':
errorMessage =
"500 - We don't know what happened, go ahead and contact the mods or report as a mistake.";
break;
default:
errorMessage = 'An unexpected error occurred';
}
return (
<div className="foundBrews noBrews">
<h3>Error: {errorMessage}</h3>
</div>
);
}
if (!brewCollection || brewCollection.length === 0) {
return (
<div className="foundBrews noBrews">
<h3>No brews found</h3>
</div>
);
}
return (
<div className="foundBrews">
<span className="totalBrews">
{`Brews found: `}
<span ref={totalBrewsSpanRef}></span>
</span>
{brewCollection.map((brew, index) => (
<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" />
{renderNavItems()}
<div className="content">
<div className="form dataGroup">{renderForm()}</div>
<div className="resultsContainer dataGroup">
{renderFoundBrews()}
</div>
</div>
</div>
);
};
module.exports = VaultPage;

View File

@@ -0,0 +1,280 @@
body {
height: 100vh;
.content {
height: 100%;
}
small {
font-size: 10pt;
color: #555;
a {
color: #333;
}
}
code {
background: lightgrey;
border-radius: 5px;
padding-inline: 5px
}
*:not(input) {
user-select: none;
}
}
.vaultPage {
overflow-y: hidden;
height: 100%;
background-color: #2C3E50;
h1,
h2,
h3 {
font-family: 'Open Sans';
color: white;
font-weight: 900;
}
.content {
display: grid;
grid-template-columns: 500px 2fr;
background: #2C3E50;
.dataGroup {
width: 100%;
height: 100%;
background: white;
&.form .brewLookup {
position: relative;
padding: 50px;
.formTitle {
color: black;
font-size: 30px;
border-bottom: 2px solid;
margin: 20px 0;
text-align: center;
}
.formContents {
display: flex;
flex-direction: column;
}
label {
margin: 10px 0;
}
input {
margin: 0 10px;
}
#searchButton {
position: absolute;
right: 10px;
bottom: 20px;
i {
margin-left: 10px;
}
}
}
&.resultsContainer {
display: flex;
flex-direction: column;
border-left: 2px solid;
height: 100%;
font-family: "BookInsanityRemake";
font-size: .34cm;
overflow-y: auto;
.foundBrews {
position: relative;
background-color: #2C3E50;
width: 100%;
max-height: 100%;
height: 100%;
padding: 50px 50px 70px 50px;
overflow-y: scroll;
h3 {
font-size: 25px;
}
&.noBrews {
display: grid;
place-items: center;
color: white;
}
&.searching {
display: grid;
place-items: center;
color: white;
h3 {
position: relative;
}
h3.searchAnim::after {
content: "";
width: max-content;
height: 1em;
position: absolute;
right: 0;
top: 50%;
translate: 100% -50%;
animation: trailingDots 2s ease infinite;
}
}
.totalBrews {
position: fixed;
bottom: 0;
right: 17px;
font-size: 11px;
font-weight: 800;
color: white;
background-color: #333;
padding: 8px 10px;
z-index: 1000;
font-family: 'Open Sans';
.searchAnim {
position: relative;
display: inline-block;
width: 3ch;
height: 1em;
}
.searchAnim::after {
content: "";
width: max-content;
height: 1em;
position: absolute;
right: 0;
top: 50%;
translate: -50% -50%;
animation: trailingDots 2s ease infinite;
}
}
.brewItem {
background-image: url('/assets/parchmentBackground.jpg');
width: 48%;
margin-right: 40px;
color: black;
&:nth-child(even of .brewItem) {
margin-right: 0;
}
h2 {
font-size: 0.75cm;
line-height: 0.988em;
font-family: "MrEavesRemake";
font-weight: 800;
color: var(--HB_Color_HeaderText);
}
.info {
font-family: ScalySansRemake;
font-size: 1.2em;
>span {
margin-right: 12px;
line-height: 1.5em;
}
}
}
.paginationControls {
position: absolute;
left: 50%;
translate: -50%;
width: auto;
display: grid;
place-items: center;
grid-template-areas: "previousPage currentPage nextPage";
grid-template-columns: 50px 1fr 50px;
.pages {
grid-area: currentPage;
height: 100%;
width: 100%;
display: flex;
justify-content: space-evenly;
text-align: center;
padding: 5px 8px;
.pageNumber {
color: white;
font-family: Open Sans;
font-weight: 900;
text-underline-position: under;
margin-inline: 10px;
cursor: pointer;
&.currentPage {
color: gold;
text-decoration: underline;
pointer-events: none;
}
&.firstPage {
margin-right: -5px;
}
&.lastPage {
margin-left: -5px;
}
}
}
button {
width: max-content;
border-radius: 5px;
&.previousPage {
grid-area: previousPage;
}
&.nextPage {
grid-area: nextPage;
}
}
}
hr {
visibility: hidden;
}
}
}
}
}
}
@keyframes trailingDots {
0%,
32% {
content: '.';
}
33%,
65% {
content: '..';
}
66%,
100% {
content: '...';
}
}