millis + validation

This commit is contained in:
cv
2021-04-12 22:21:35 +02:00
parent 023c8c446e
commit e56841c8d1
2 changed files with 58 additions and 20 deletions
+42 -20
View File
@@ -1,45 +1,67 @@
import { Editable, EditableInput, EditablePreview } from '@chakra-ui/editable';
import { useEffect, useState } from 'react';
import { addAndFormat, timeToDate, dateToTime } from '../dateConfig';
import {
timeFormat,
stringFromMillis,
timeStringToMillis,
} from '../dateConfig';
import { showErrorToast } from '../helpers/toastManager';
import style from './EditableTimer.module.css';
export default function EditableTimer(props) {
const { name, updateValues, time, delay } = props;
const { name, updateValues, time, delay, validate } = props;
const [value, setValue] = useState('');
const [editing, setEditing] = useState(false);
// prepare time fields
useEffect(() => {
if (time == null) return;
setValue(addAndFormat(time, delay));
try {
setValue(stringFromMillis(time + delay, false));
} catch (error) {
showErrorToast('Error parsing date', error.text);
}
}, [time, delay]);
const handleSubmit = (submitedVal) => {
setValue(addAndFormat(time, delay));
setEditing(false);
const validateValue = (value) => {
const success = handleSubmit(value);
const newTime = timeToDate(submitedVal);
// No need to update if it hasnt changed
if (newTime === value) return;
updateValues(name, newTime);
if (success) setValue(value);
else setValue(stringFromMillis(time + delay, false));
};
const showNormal = () => {
if (!editing) setValue(dateToTime(time));
const handleSubmit = (value) => {
// Check if there is anything there
if (value === '') return false;
// Time now and time submitedVal
const original = stringFromMillis(time, false);
// check if time is different from before
if (value === original) return false;
// conver to millis object
const millis = timeStringToMillis(value, timeFormat);
// validate with parent
if (!validate(name, millis)) return false;
// update entry
updateValues(name, millis);
return true;
};
const handleChange = (submitedVal) => {
setEditing(true);
setValue(submitedVal);
const showOriginal = () => {
setValue(stringFromMillis(time, false));
};
return (
<div className={style.time}>
<Editable
onEdit={() => showNormal}
onSubmit={(v) => handleSubmit(v)}
onChange={(v) => handleChange(v)}
onFocus={() => showOriginal()}
onEdit={() => showOriginal}
onChange={(v) => setValue(v)}
onSubmit={(v) => validateValue(v)}
value={value}
placeholder='--:--'
className={delay > 0 ? style.delayedEditable : style.editable}