interim commit

This commit is contained in:
oitsjustjose 2020-12-29 09:11:27 -06:00
commit 8d721a88c7
20 changed files with 17329 additions and 152 deletions

View file

@ -1,10 +1,11 @@
import * as bodyParser from 'body-parser' import * as bodyParser from 'body-parser'
import cors from 'cors' import cors from 'cors'
import express from 'express' import express from 'express'
import { configGetHandler, configGetSpecificHandler } from './app/controllers/configGetHandler'
import { configPatchHandler } from './app/controllers/configPatchHandler'
import { configPutHandler } from './app/controllers/configPutHandler'
import { loginPostHandler } from './app/controllers/loginPostHandler' import { loginPostHandler } from './app/controllers/loginPostHandler'
import { registerPostHandler } from './app/controllers/registerPostHandler' import { registerPostHandler } from './app/controllers/registerPostHandler'
import { configGetHandler, configGetSpecificHandler } from './app/controllers/configGetHandler'
import { configPutHandler } from './app/controllers/configPutHandler'
import { UserModel } from './app/db/user.schema' import { UserModel } from './app/db/user.schema'
import { auth, optAuth } from './app/middleware' import { auth, optAuth } from './app/middleware'
@ -28,6 +29,7 @@ app.use(bodyParser.urlencoded({
app.put('/api/configs', optAuth, configPutHandler) app.put('/api/configs', optAuth, configPutHandler)
app.get('/api/configs', auth, configGetHandler) app.get('/api/configs', auth, configGetHandler)
app.patch('/api/configs/:id', auth, configPatchHandler)
app.get('/api/configs/:id', configGetSpecificHandler) app.get('/api/configs/:id', configGetSpecificHandler)
app.post('/api/users/login', loginPostHandler) app.post('/api/users/login', loginPostHandler)
app.post('/api/users/register', registerPostHandler) app.post('/api/users/register', registerPostHandler)

View file

@ -3,7 +3,14 @@ import ConfigSchema from '../db/config.schema'
export const configGetHandler = async (req: Request, res: Response) => { export const configGetHandler = async (req: Request, res: Response) => {
try { try {
return res.json(req.user?.configs) const configs = []
for (const _id of req.user?.configs) {
const { name } = await ConfigSchema.findById(_id)
configs.push({ _id, name })
}
return res.json(configs)
} catch (ex) { } catch (ex) {
console.error(ex) console.error(ex)
return res.status(500).send({ error: ex }) return res.status(500).send({ error: ex })

View file

@ -0,0 +1,22 @@
import { Request, Response } from 'express'
import ConfigSchema from '../db/config.schema'
export const configPatchHandler = async (req: Request, res: Response) => {
try {
const config = await ConfigSchema.findById(req.params.id)
if (!req.user?.configs.includes(config._id)) {
return res.status(403).send()
}
config.json = req.body.json
config.name = req.body.name
await config.save()
return res.status(200).send(config._id)
} catch (ex) {
console.error(ex)
return res.status(500).send({ error: ex })
}
}

View file

@ -5,9 +5,10 @@ export const configPutHandler = async (req: Request, res: Response) => {
try { try {
const config = new ConfigSchema() const config = new ConfigSchema()
config.json = req.body.json config.json = req.body.json
config.name = req.body.name
await config.save() await config.save()
if(req.user) { if (req.user) {
req.user.configs.push(config._id) req.user.configs.push(config._id)
await req.user.save() await req.user.save()
} }

View file

@ -6,11 +6,16 @@ const ConfigSchema = new Schema({
type: String, type: String,
default: shortid.generate default: shortid.generate
}, },
json: Object name: {
type: String,
default: "Unnamed"
},
json: Object,
}) })
export type ConfigModel = Document & { export type ConfigModel = Document & {
_id: string, _id: string,
name: string,
json: object, json: object,
} }

View file

@ -1,5 +1,8 @@
{ {
"[javascriptreact]": { "[javascriptreact]": {
"editor.tabSize": 2 "editor.tabSize": 2
},
"[javascript]": {
"editor.tabSize": 2
} }
} }

17162
frontend/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,7 @@
"react-dom": "^16.13.1", "react-dom": "^16.13.1",
"react-redux": "^7.2.1", "react-redux": "^7.2.1",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "3.4.3", "react-scripts": "^3.4.4",
"react-transition-group": "^4.4.1", "react-transition-group": "^4.4.1",
"redux": "^4.0.5" "redux": "^4.0.5"
}, },

View file

@ -7,6 +7,7 @@ import LoadAuth from './auth/load';
import NavBar from './components/modules/NavBar'; import NavBar from './components/modules/NavBar';
import ConfigBrowse from './components/view/ConfigBrowse'; import ConfigBrowse from './components/view/ConfigBrowse';
import ConfigCreate from './components/view/ConfigCreate'; import ConfigCreate from './components/view/ConfigCreate';
import ConfigRender from './components/view/ConfigRender';
import Login from './components/view/Login'; import Login from './components/view/Login';
import Register from './components/view/Register'; import Register from './components/view/Register';
import store from './redux/store'; import store from './redux/store';
@ -19,7 +20,9 @@ export default () => {
<Router> <Router>
<NavBar /> <NavBar />
<div style={{ paddingTop: `${3.5}em` }} /> <div style={{ paddingTop: `${3.5}em` }} />
<Route exact path="/" component={ConfigCreate} /> <Route exact path="/" component={() => <ConfigCreate editing={false} />} />
<Route exact path="/edit" component={() => <ConfigCreate editing />} />
<Route exact path="/view" component={ConfigRender} />
<Route exact path="/login" component={Login} /> <Route exact path="/login" component={Login} />
<Route exact path="/browse" component={ConfigBrowse} /> <Route exact path="/browse" component={ConfigBrowse} />
<Route exact path="/register" component={Register} /> <Route exact path="/register" component={Register} />

View file

@ -1,4 +1,12 @@
import axios from 'axios'; import axios from 'axios';
import store from '../../redux/store';
export default (id) => axios.get(`/api/configs/${id}`) export default (id) => axios.get(`/api/configs/${id}`)
.then((resp) => resp.data); .then((resp) => resp.data);
export const GetConfigForEdit = (id) => axios.get(`/api/configs/${id}`)
.then(((resp) => {
store.dispatch({
type: 'SET_CONFIG_EDITING', id, json: resp.data.json, name: resp.data.name,
});
}));

View file

@ -0,0 +1,8 @@
import axios from 'axios';
import GetConfigs from './GetConfigs';
export default (id, data) => axios.patch(`/api/configs/${id}`, data)
.then((resp) => {
GetConfigs();
return resp.data;
});

View file

@ -6,10 +6,10 @@ import {
} from 'react-bootstrap'; } from 'react-bootstrap';
export default ({ export default ({
prefix, singular, onChangeSuper, prefix, singular, onChangeSuper, prefill,
}) => { }) => {
const [entries, setEntries] = useState([true]); const [entries, setEntries] = useState(prefill || [true]);
const [state, setState] = useState([{ const [state, setState] = useState(prefill || [{
ore: '', ore: '',
chance: 100, chance: 100,
}]); }]);

Binary file not shown.

Binary file not shown.

View file

@ -40,13 +40,17 @@ const ConfigViewComponent = ({
<tr> <tr>
<th>#</th> <th>#</th>
<th>URL</th> <th>URL</th>
<th>&nbsp;</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{configs.map((slug, idx) => ( {configs.map(({ _id: slug, name }, idx) => (
<tr> <tr>
<td>{idx + 1}</td> <td>{idx + 1}</td>
<td><a href={`/?id=${slug}`}>{slug}</a></td> <td><a href={`/view?id=${slug}`}>{name}</a></td>
<td>
<a href={`/edit?id=${slug}`} className="btn btn-success">Edit</a>
</td>
</tr> </tr>
))} ))}
</tbody> </tbody>

View file

@ -1,21 +1,24 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Accordion, Button, Container } from 'react-bootstrap'; import {
Accordion, Button, Container, Form,
} from 'react-bootstrap';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { CSSTransition } from 'react-transition-group'; import { CSSTransition } from 'react-transition-group';
import { GetConfigForEdit } from '../../axios/Config/GetConfig';
import PutConfig from '../../axios/Config/PutConfig'; import PutConfig from '../../axios/Config/PutConfig';
import GetConfig from '../../axios/Config/GetConfig'; import PatchConfig from '../../axios/Config/PatchConfig';
import ConfigRender from './ConfigRender'; import ConfigCreateOre from './ConfigCreateOre';
import ConfigRenderOre from './ConfigRenderOre'; import ConfigCreateStone from './ConfigCreateStone';
import ConfigRenderStone from './ConfigRenderStone';
const Configurator = ({ const Configurator = ({
mc114, mc114, editing, prefill,
}) => { }) => {
const params = new URLSearchParams(window.location.search); const [name, setName] = useState(prefill && prefill.name);
const [postRender, setPostRender] = useState(null); const [oreConfigs, setOreConfigs] = useState(prefill
? Array(prefill.json.ores.length).fill(true) : [true]);
const [stoneConfigs, setStoneConfigs] = useState(prefill
? Array(prefill.json.stones.length).fill(true) : [true]);
const [oreConfigs, setOreConfigs] = useState([true]);
const [stoneConfigs, setStoneConfigs] = useState([true]);
const [oreState, setOreState] = useState([{ const [oreState, setOreState] = useState([{
name: '', name: '',
type: 'dense', type: 'dense',
@ -29,6 +32,7 @@ const Configurator = ({
dimBlacklist: [], dimBlacklist: [],
blockStateMatchers: [], blockStateMatchers: [],
}]); }]);
const [stoneState, setStoneState] = useState([{ const [stoneState, setStoneState] = useState([{
block: '', block: '',
maxY: -1, maxY: -1,
@ -38,21 +42,6 @@ const Configurator = ({
dimBlacklist: [], dimBlacklist: [],
}]); }]);
if (params.has('id')) {
if (postRender) {
return (<ConfigRender jsonData={postRender} />);
}
GetConfig(params.get('id')).then((data) => (
setPostRender(data)
));
return (
<CSSTransition classNames="react-router" appear in timeout={300}>
<div className="v-center"><h1>Loading...</h1></div>
</CSSTransition>
);
}
const addOreEntry = () => { const addOreEntry = () => {
setOreConfigs([...oreConfigs, true]); setOreConfigs([...oreConfigs, true]);
}; };
@ -69,6 +58,19 @@ const Configurator = ({
setOreState(newState); setOreState(newState);
}; };
const onSubmit = () => {
const body = { name, json: { ores: oreState, stones: stoneState } };
if (editing) {
PatchConfig(prefill.id, body).then((data) => {
window.location.href = `/view?id=${data}`;
});
} else {
PutConfig(body).then((data) => {
window.location.href = `/view?id=${data}`;
});
}
};
const addStoneEntry = () => { const addStoneEntry = () => {
setStoneConfigs([...stoneConfigs, true]); setStoneConfigs([...stoneConfigs, true]);
}; };
@ -85,6 +87,30 @@ const Configurator = ({
setStoneState(newState); setStoneState(newState);
}; };
if (editing && !prefill) {
const params = new URLSearchParams(window.location.search);
if (params.has('id')) {
GetConfigForEdit(params.get('id'));
return (
<CSSTransition classNames="react-router" appear in timeout={300}>
<div className="v-center"><h1>Loading...</h1></div>
</CSSTransition>
);
}
return (
<CSSTransition classNames="react-router" appear in timeout={300}>
<div className="v-center text-danger">
<h3>
Missing Query Param
{' '}
<code>id</code>
</h3>
</div>
</CSSTransition>
);
}
return ( return (
<CSSTransition classNames="react-router" appear in timeout={300}> <CSSTransition classNames="react-router" appear in timeout={300}>
<div> <div>
@ -93,15 +119,27 @@ const Configurator = ({
<h4>Geolosys Deposit Configurator</h4> <h4>Geolosys Deposit Configurator</h4>
</div> </div>
<Container className="w-50">
<Form.Group>
<Form.Label>Config Name:</Form.Label>
<Form.Control
type="text"
name="configName"
value={name}
onChange={(evt) => setName(evt.target.value)}
/>
</Form.Group>
</Container>
<Container> <Container>
<h4>Ores</h4> <h4>Ores</h4>
<Accordion defaultActiveKey="0"> <Accordion defaultActiveKey="0">
{oreConfigs.map((enabled, idx) => enabled && ( {oreConfigs.map((enabled, idx) => enabled && (
<ConfigRenderOre <ConfigCreateOre
mc114={mc114} mc114={mc114}
onEntryCreation={addOreEntry} onEntryCreation={addOreEntry}
onEntryDeletion={removeOreEntry} onEntryDeletion={removeOreEntry}
onConfigChange={onOreConfigChange} onConfigChange={onOreConfigChange}
prefill={editing && prefill.json.ores[idx]}
idx={idx} idx={idx}
/> />
))} ))}
@ -112,11 +150,12 @@ const Configurator = ({
<h4>Stones</h4> <h4>Stones</h4>
<Accordion defaultActiveKey="0"> <Accordion defaultActiveKey="0">
{stoneConfigs.map((enabled, idx) => enabled && ( {stoneConfigs.map((enabled, idx) => enabled && (
<ConfigRenderStone <ConfigCreateStone
mc114={mc114} mc114={mc114}
onEntryCreation={addStoneEntry} onEntryCreation={addStoneEntry}
onEntryDeletion={removeStoneEntry} onEntryDeletion={removeStoneEntry}
onConfigChange={onStoneConfigChange} onConfigChange={onStoneConfigChange}
prefill={editing && prefill.json.stones[idx]}
idx={idx} idx={idx}
/> />
))} ))}
@ -124,17 +163,11 @@ const Configurator = ({
</Container> </Container>
<Button <Button
onClick={() => PutConfig({ onClick={onSubmit}
json: { variant={editing ? 'danger' : 'primary'}
ores: oreState,
stones: stoneState,
},
}).then((data) => {
window.location.href = `/?id=${data}`;
})}
className="d-block mx-auto my-4" className="d-block mx-auto my-4"
> >
Generate! {editing ? 'Save (Overwrites)' : 'Generate!'}
</Button> </Button>
</div> </div>
</CSSTransition> </CSSTransition>
@ -143,6 +176,7 @@ const Configurator = ({
const mapStateToProps = (state) => ({ const mapStateToProps = (state) => ({
mc114: state.mc114, mc114: state.mc114,
prefill: state.editing || null,
}); });
export default connect(mapStateToProps)(Configurator); export default connect(mapStateToProps)(Configurator);

View file

@ -9,9 +9,9 @@ import ExtendableInput from '../modules/Config/ExtendableInput';
import ExtendableBiomeInput from '../modules/Config/ExtendableBiomeInput'; import ExtendableBiomeInput from '../modules/Config/ExtendableBiomeInput';
export default ({ export default ({
mc114, idx, onEntryCreation, onEntryDeletion, onConfigChange, mc114, idx, onEntryCreation, onEntryDeletion, onConfigChange, prefill,
}) => { }) => {
const [state, setState] = useState({ const [state, setState] = useState(prefill || {
name: '', name: '',
depType: 'deposit', depType: 'deposit',
type: 'dense', type: 'dense',
@ -27,16 +27,8 @@ export default ({
}); });
const setStateWithPropogation = (newState) => { const setStateWithPropogation = (newState) => {
const formatted = { ...newState };
if (formatted.oreBlocks) {
formatted.oreBlocks = formatted.oreBlocks.map((x) => [x.ore, x.chance]).flat();
}
if (formatted.sampleBlocks) {
formatted.sampleBlocks = formatted.sampleBlocks.map((x) => [x.ore, x.chance]).flat();
}
delete formatted.depType;
setState(newState); setState(newState);
onConfigChange(idx, formatted); onConfigChange(idx, newState);
}; };
return ( return (
@ -125,6 +117,7 @@ export default ({
<WeightedTextEntry <WeightedTextEntry
singular={!state.depType.toLowerCase().includes('multi')} singular={!state.depType.toLowerCase().includes('multi')}
prefix="ore" prefix="ore"
prefill={prefill && prefill.oreBlocks}
onChangeSuper={(oreBlocks) => { onChangeSuper={(oreBlocks) => {
setStateWithPropogation({ ...state, oreBlocks }); setStateWithPropogation({ ...state, oreBlocks });
}} }}
@ -139,6 +132,7 @@ export default ({
<WeightedTextEntry <WeightedTextEntry
singular={!state.depType.toLowerCase().includes('multi')} singular={!state.depType.toLowerCase().includes('multi')}
prefix="sample" prefix="sample"
prefill={prefill && prefill.sampleBlocks}
onChangeSuper={(sampleBlocks) => { onChangeSuper={(sampleBlocks) => {
setStateWithPropogation({ ...state, sampleBlocks }); setStateWithPropogation({ ...state, sampleBlocks });
}} }}

View file

@ -7,9 +7,9 @@ import {
import ExtendableInput from '../modules/Config/ExtendableInput'; import ExtendableInput from '../modules/Config/ExtendableInput';
export default ({ export default ({
mc114, idx, onEntryCreation, onEntryDeletion, onConfigChange, mc114, idx, onEntryCreation, onEntryDeletion, onConfigChange, prefill,
}) => { }) => {
const [state, setState] = useState({ const [state, setState] = useState(prefill || {
block: '', block: '',
maxY: 1, maxY: 1,
minY: 0, minY: 0,

View file

@ -1,15 +1,61 @@
import React from 'react'; import React, { useState } from 'react';
import { Container } from 'react-bootstrap'; import { Container } from 'react-bootstrap';
import { CSSTransition } from 'react-transition-group';
import GetConfig from '../../axios/Config/GetConfig';
export default ({ const cleanJson = (json) => {
jsonData, const formatted = { ...json.ores };
}) => ( if (formatted.oreBlocks) {
formatted.oreBlocks = formatted.oreBlocks.map((x) => [x.ore, x.chance]).flat();
}
if (formatted.sampleBlocks) {
formatted.sampleBlocks = formatted.sampleBlocks.map((x) => [x.ore, x.chance]).flat();
}
delete formatted.depType;
return {
ores: formatted,
stones: json.stones,
};
};
export default () => {
const [json, setJson] = useState(null);
const params = new URLSearchParams(window.location.search);
if (!json) {
if (params.has('id')) {
GetConfig(params.get('id')).then((data) => (
setJson(data)
));
return (
<CSSTransition classNames="react-router" appear in timeout={300}>
<div className="v-center"><h1>Loading...</h1></div>
</CSSTransition>
);
}
return (
<CSSTransition classNames="react-router" appear in timeout={300}>
<div className="v-center text-danger">
<h3>
Missing Query Param
{' '}
<code>id</code>
</h3>
</div>
</CSSTransition>
);
}
return (
<div> <div>
<h2 className="text-center mt-3">Config View</h2> <h2 className="text-center mt-3">{`Viewing Config ${json.name}`}</h2>
<Container className="shadow mt-5"> <Container className="shadow mt-5">
<pre> <pre>
{JSON.stringify(jsonData.json, null, 2) } {JSON.stringify(cleanJson(json.json), null, 2)}
</pre> </pre>
</Container> </Container>
</div> </div>
); );
};

View file

@ -2,6 +2,7 @@ const defaultState = {
isAuthenticated: false, isAuthenticated: false,
user: null, user: null,
mc114: true, mc114: true,
editing: null,
}; };
export default function reducer( export default function reducer(
@ -33,6 +34,15 @@ export default function reducer(
...state, ...state,
configs: action.configs, configs: action.configs,
}; };
case 'SET_CONFIG_EDITING':
return {
...state,
editing: {
id: action.id,
json: action.json,
name: action.name,
},
};
default: default:
return state; return state;
} }