labyrinth-frontend/src/InputForm.js

104 lines
3.8 KiB
JavaScript
Raw Normal View History

import React, {useState} from 'react';
import ValidatingInputNumberField from "./ValidatingInputNumberField";
export default function InputForm({state, dispatch}) {
const [width, setWidth] = useState(10);
const [height, setHeight] = useState(10);
const [id, setId] = useState(null);
const handleSubmit = (e) => {
e.preventDefault();
dispatch({
type: 'started_loading'
});
2023-04-16 04:04:00 +02:00
const url = `https://manuel.friedli.info/labyrinth/create/json?w=${width}&h=${height}&id=${id || ''}`;
fetch(url)
.then(response => response.json())
2023-04-16 04:04:00 +02:00
// .then(result => new Promise(resolve => setTimeout(resolve, 600, result)))
.then(result => {
dispatch({
type: 'loaded_maze',
maze: result
});
})
.catch(reason => {
console.error("Failed to fetch maze data.", reason);
dispatch({
type: 'loading_failed',
reason
});
});
};
const validateWidthHeightInput = value => {
if (isNaN(value) || "" === value || (Math.floor(value) !== Number(value))) {
return {
valid: false,
message: "Must be an integer greater than 1.",
value
};
}
if (value < 1) {
return {
valid: false,
message: "Must be greater than 1.",
value
};
}
return {
valid: true,
value
};
};
const validateIdInput = value => {
// FIXME doesn't handle strings with characters correctly (e.g. "asdf" yields an empty value, due to "type=number").
if (isNaN(value) || ("" !== value && ((Math.floor(value) !== Number(value))))) {
return {
valid: false,
message: "Must be empty or an integer",
value
};
}
return {
valid: true,
value
}
};
return (
<form onSubmit={handleSubmit}>
<ValidatingInputNumberField id={"width"}
label={"Width"}
2023-04-16 01:01:23 +02:00
value={width}
constraints={{
min: 2
}}
validatorFn={validateWidthHeightInput}
disabled={state.loading}
onChange={setWidth}
/><br/>
<ValidatingInputNumberField id={"height"}
label={"Height"}
2023-04-16 01:01:23 +02:00
value={height}
constraints={{
min: 2
}}
validatorFn={validateWidthHeightInput}
disabled={state.loading}
onChange={setHeight}
/><br/>
<ValidatingInputNumberField id={"id"}
label={"ID (optional)"}
2023-04-16 01:01:23 +02:00
value={id}
validatorFn={validateIdInput}
disabled={state.loading}
onChange={setId}
/><br/>
<button type={"submit"}
disabled={state.loading
|| isNaN(width)
|| isNaN(height)
}>{state.loading ? "Loading ..." : "Create Maze!"}
</button>
</form>
);
}