0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-10 07:02:39 +00:00

"Refactor ArchivePage component from createClass to functional component with hooks"

This commit is contained in:
Víctor Losada Hernández
2024-06-10 23:23:31 +02:00
parent 609f5a3330
commit 042e217872

View File

@@ -1,7 +1,7 @@
require('./archivePage.less'); require('./archivePage.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const { useState, useEffect, useRef } = React;
const cx = require('classnames'); const cx = require('classnames');
const Nav = require('naturalcrit/nav/nav.jsx'); const Nav = require('naturalcrit/nav/nav.jsx');
@@ -11,270 +11,234 @@ const Account = require('../../navbar/account.navitem.jsx');
const NewBrew = require('../../navbar/newbrew.navitem.jsx'); const NewBrew = require('../../navbar/newbrew.navitem.jsx');
const HelpNavItem = require('../../navbar/help.navitem.jsx'); const HelpNavItem = require('../../navbar/help.navitem.jsx');
const BrewItem = require('../basePages/listPage/brewItem/brewItem.jsx'); const BrewItem = require('../basePages/listPage/brewItem/brewItem.jsx');
//const StringArrayEditor = require('../stringArrayEditor/stringArrayEditor.jsx');
const request = require('../../utils/request-middleware.js'); const request = require('../../utils/request-middleware.js');
const ArchivePage = createClass({ const ArchivePage = (props) => {
displayName: 'ArchivePage', const [title, setTitle] = useState(props.query.title || '');
getDefaultProps: function () { const [legacy, setLegacy] = useState(props.query.legacy !== 'false');
return {}; 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);
getInitialState: function () { const titleRef = useRef(null);
return { const countRef = useRef(null);
//# request const v3Ref = useRef(null);
title: this.props.query.title || '', const legacyRef = useRef(null);
//tags: {},
legacy: this.props.query.legacy !== 'false',
v3: this.props.query.v3 !== 'false',
count: this.props.query.count || 10,
page: parseInt(this.props.query.page) || 1,
//# response useEffect(() => {
brewCollection: null, validateInput();
totalBrews: null, if (title) {
loadPage(page, false);
searching: false,
error: null,
};
},
componentDidMount: function () {
console.log(this.props.query);
console.log(this.state);
this.validateInput();
if (this.state.title) {
this.loadPage(this.state.page, false);
} }
this.state.totalBrews || this.loadTotal(); // Load total if not already loaded !totalBrews && loadTotal();
}, }, []);
updateStateWithBrews: function (brews, page) { const updateStateWithBrews = (brews, page) => {
this.setState({ setBrewCollection(brews || null);
brewCollection: brews || null, setPage(parseInt(page) || 1);
page: parseInt(page) || 1, setSearching(false);
searching: false, };
});
},
updateUrl: function (title, page, count, v3, legacy) { const updateUrl = (title, page, count, v3, legacy) => {
const url = new URL(window.location.href); const url = new URL(window.location.href);
const urlParams = new URLSearchParams(); const urlParams = new URLSearchParams();
Object.entries({ title, page, count, v3, legacy }).forEach(([key, value]) => urlParams.set(key, value)); Object.entries({ title, page, count, v3, legacy }).forEach(
([key, value]) => urlParams.set(key, value)
);
url.search = urlParams.toString(); url.search = urlParams.toString();
window.history.replaceState(null, null, url); window.history.replaceState(null, null, url);
}, };
loadPage: async function (page, update) { const loadPage = async (page, update) => {
this.setState({ searching: true, error: null }); setSearching(true);
setError(null);
const performSearch = async ({ title, count, v3, legacy }) => { const performSearch = async ({ title, count, v3, legacy }) => {
this.updateUrl(title, page, count, v3, legacy); updateUrl(title, page, count, v3, legacy);
if (title !== '') { if (title !== '') {
try { try {
const response = await request.get( const response = await request.get(
`/api/archive?title=${title}&page=${page}&count=${count}&v3=${v3}&legacy=${legacy}` `/api/archive?title=${title}&page=${page}&count=${count}&v3=${v3}&legacy=${legacy}`
); );
if (response.ok) { if (response.ok) {
this.updateStateWithBrews(response.body.brews, page); updateStateWithBrews(response.body.brews, page);
} else { } else {
throw new Error(`Error: ${response.status}`); throw new Error(`Error: ${response.status}`);
} }
} catch (error) { } catch (error) {
console.log('error at loadPage: ', error); console.log('error at loadPage: ', error);
this.setState({ error: `${error.response ? error.response.status : error.message}` }); setError(
this.updateStateWithBrews([], 1); `${
error.response
? error.response.status
: error.message
}`
);
updateStateWithBrews([], 1);
} }
} else { } else {
this.setState({ error: '404' }); setError('404');
} }
}; };
if (update === true) { if (update) {
const title = document.getElementById('title').value || ''; const title = titleRef.current.value || '';
const count = document.getElementById('count').value || 10; const count = countRef.current.value || 10;
const v3 = document.getElementById('v3').checked; const v3 = v3Ref.current.checked;
const legacy = document.getElementById('legacy').checked; const legacy = legacyRef.current.checked;
this.setState( setTitle(title);
{ setCount(count);
title: title, setV3(v3);
count: count, setLegacy(legacy);
v3: v3,
legacy: legacy, performSearch({ title, count, v3, legacy });
},
() => {
// State is updated, now perform the search
performSearch({ title, count, v3, legacy });
}
);
} else { } else {
const { title, count, v3, legacy } = this.state;
performSearch({ title, count, v3, legacy }); performSearch({ title, count, v3, legacy });
} }
}, };
loadTotal: async function () { const loadTotal = async () => {
const {title, v3, legacy} = this.state; setTotalBrews(null);
setError(null);
this.setState({
totalBrews: null,
error: null
});
if (title) { if (title) {
try { try {
const response = await request.get( const response = await request.get(
`/api/archive/total?title=${title}&v3=${v3}&legacy=${legacy}` `/api/archive/total?title=${title}&v3=${v3}&legacy=${legacy}`
); );
if (response.ok) { if (response.ok) {
this.setState({ setTotalBrews(response.body.totalBrews);
totalBrews: response.body.totalBrews,
});
} else { } else {
throw new Error(`Failed to load total brews: ${response.statusText}`); throw new Error(
`Failed to load total brews: ${response.statusText}`
);
} }
} catch (error) { } catch (error) {
console.log('error at loadTotal: ', error); console.log('error at loadTotal: ', error);
this.setState({ error: `${error.response.status}` }); setError(`${error.response.status}`);
this.updateStateWithBrews([], 1); updateStateWithBrews([], 1);
} }
} }
}, };
renderNavItems: function () { const renderNavItems = () => (
return ( <Navbar>
<Navbar> <Nav.section>
<Nav.section> <Nav.item className="brewTitle">
<Nav.item className="brewTitle"> Archive: Search for brews
Archive: Search for brews </Nav.item>
</Nav.item> </Nav.section>
</Nav.section> <Nav.section>
<Nav.section> <NewBrew />
<NewBrew /> <HelpNavItem />
<HelpNavItem /> <RecentNavItem />
<RecentNavItem /> <Account />
<Account /> </Nav.section>
</Nav.section> </Navbar>
</Navbar> );
);
},
validateInput: function () { const validateInput = () => {
const textInput = document.getElementById('title'); const textInput = titleRef.current;
const submitButton = document.getElementById('searchButton'); const submitButton = document.getElementById('searchButton');
if (textInput.validity.valid && textInput.value) { if (textInput.validity.valid && textInput.value) {
submitButton.disabled = false; submitButton.disabled = false;
} else { } else {
submitButton.disabled = true; submitButton.disabled = true;
} }
}, };
renderForm: function () { const renderForm = () => (
return ( <div className="brewLookup">
<div className="brewLookup"> <h2 className="formTitle">Brew Lookup</h2>
<h2 className="formTitle">Brew Lookup</h2> <div className="formContents">
<div className="formContents"> <label>
<label> Title of the brew
Title of the brew <input
<input ref={titleRef}
id="title" type="text"
type="text" name="title"
name="title" defaultValue={title}
defaultValue={this.state.title} onKeyUp={validateInput}
onKeyUp={() => { pattern=".{3,}"
this.validateInput(); onKeyDown={(e) => {
}} if (e.key === 'Enter') {
pattern=".{3,}" if (
onKeyDown={(e) => { e.target.validity.valid &&
if (e.key === 'Enter') { e.target.value
this.loadTotal(); ) {
this.loadPage(1, true); 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 name="count" id="count">
<option value="10" default>10</option>
<option value="20">20</option>
<option value="40">40</option>
<option value="60">60</option>
</select>
</label>
<label>
<input
id="v3"
type="checkbox"
defaultChecked={this.state.v3}
/>
Search for v3 brews
</label>
<label>
<input
id="legacy"
type="checkbox"
defaultChecked={this.state.legacy}
/>
Search for legacy brews
</label>
{/* In the future, we should be able to filter the results by adding tags.
<<StringArrayEditor label='tags' valuePatterns={[/^(?:(?:group|meta|system|type):)?[A-Za-z0-9][A-Za-z0-9 \/.\-]{0,40}$/]}
placeholder='add tag' unique={true}
values={this.state.tags}
onChange={(e)=>this.handleChange('tags', e)}/>
check metadataEditor.jsx L65
*/}
<button
id="searchButton"
onClick={() => {
this.loadTotal();
this.loadPage(1, true);
}} }}
> placeholder="v3 Reference Document"
Search />
<i </label>
className={cx('fas', {
'fa-search': !this.state.searching,
'fa-spin fa-spinner': this.state.searching,
})}
/>
</button>
</div>
<small> <small>
Remember, you can only search brews with this tool if they Tip! you can use <code>-</code> to negate words, and{' '}
are published <code>"word"</code> to specify an exact string.
</small> </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> </div>
); <small>
}, Remember, you can only search brews with this tool if they are
published
</small>
</div>
);
renderPaginationControls: function () { const renderPaginationControls = () => {
if (!this.state.totalBrews) { if (!totalBrews) return null;
return null;
}
const count = parseInt(this.state.count); const countInt = parseInt(count);
const { page, totalBrews } = this.state; const totalPages = Math.ceil(totalBrews / countInt);
const totalPages = Math.ceil(totalBrews / count);
let startPage, endPage; let startPage, endPage;
if (page <= 6) { if (page <= 6) {
@@ -296,7 +260,7 @@ const ArchivePage = createClass({
className={`pageNumber ${ className={`pageNumber ${
page === startPage + index ? 'currentPage' : '' page === startPage + index ? 'currentPage' : ''
}`} }`}
onClick={() => this.loadPage(startPage + index, false)} onClick={() => loadPage(startPage + index, false)}
> >
{startPage + index} {startPage + index}
</a> </a>
@@ -307,7 +271,7 @@ const ArchivePage = createClass({
{page > 1 && ( {page > 1 && (
<button <button
className="previousPage" className="previousPage"
onClick={() => this.loadPage(page - 1, false)} onClick={() => loadPage(page - 1, false)}
> >
&lt;&lt; &lt;&lt;
</button> </button>
@@ -315,8 +279,8 @@ const ArchivePage = createClass({
<ol className="pages"> <ol className="pages">
{startPage > 1 && ( {startPage > 1 && (
<a <a
className="firstPage pageNumber" className="firstPage"
onClick={() => this.loadPage(1, false)} onClick={() => loadPage(1, false)}
> >
1 ... 1 ...
</a> </a>
@@ -324,8 +288,8 @@ const ArchivePage = createClass({
{pagesAroundCurrent} {pagesAroundCurrent}
{endPage < totalPages && ( {endPage < totalPages && (
<a <a
className="lastPage pageNumber" className="lastPage"
onClick={() => this.loadPage(totalPages, false)} onClick={() => loadPage(totalPages, false)}
> >
... {totalPages} ... {totalPages}
</a> </a>
@@ -334,18 +298,16 @@ const ArchivePage = createClass({
{page < totalPages && ( {page < totalPages && (
<button <button
className="nextPage" className="nextPage"
onClick={() => this.loadPage(page + 1, false)} onClick={() => loadPage(page + 1, false)}
> >
&gt;&gt; &gt;&gt;
</button> </button>
)} )}
</div> </div>
); );
}, };
renderFoundBrews() {
const { title, brewCollection, error, searching } = this.state;
const renderFoundBrews = () => {
if (searching) { if (searching) {
return ( return (
<div className="foundBrews searching"> <div className="foundBrews searching">
@@ -395,43 +357,45 @@ const ArchivePage = createClass({
</div> </div>
); );
} }
console.log('state when rendering ');
console.table(this.state);
return ( return (
<div className="foundBrews"> <div className="foundBrews">
<span className="totalBrews"> <span className="totalBrews">
{`Brews found: `} {`Brews found: `}
{title === '' ? '0' : this.state.totalBrews ? this.state.totalBrews : <span className="searchAnim"></span>} {title === '' ? (
'0'
) : totalBrews ? (
totalBrews
) : (
<span className="searchAnim"></span>
)}
</span> </span>
{brewCollection.map((brew, index) => ( {brewCollection.map((brew, index) => (
<BrewItem <BrewItem
brew={brew} brew={brew}
key={index} key={index}
reportError={this.props.reportError} reportError={props.reportError}
/> />
))} ))}
{this.renderPaginationControls()} {renderPaginationControls()}
</div> </div>
); );
};
},
render: function () { return (
return ( <div className="archivePage">
<div className="archivePage"> <link href="/themes/V3/Blank/style.css" rel="stylesheet" />
<link href="/themes/V3/Blank/style.css" rel="stylesheet" /> <link href="/themes/V3/5ePHB/style.css" rel="stylesheet" />
<link href="/themes/V3/5ePHB/style.css" rel="stylesheet" /> {renderNavItems()}
{this.renderNavItems()} <div className="content">
<div className="form dataGroup">{renderForm()}</div>
<div className="content"> <div className="resultsContainer dataGroup">
<div className="form dataGroup">{this.renderForm()}</div> {renderFoundBrews()}
<div className="resultsContainer dataGroup">
{this.renderFoundBrews()}
</div>
</div> </div>
</div> </div>
); </div>
}, );
}); };
module.exports = ArchivePage; module.exports = ArchivePage;