handle errors on config update

This commit is contained in:
2023-04-28 14:33:23 -07:00
parent 70d71ce14e
commit c5dcc2e50a
5 changed files with 53 additions and 14 deletions

View File

@ -10,19 +10,37 @@
export let max = null;
export let decimal = false;
let error = null;
let localValue = value.toString();
const dispatch = createEventDispatcher();
function validate(event) {
$: localValue = value.toString();
let lastInputTime = null;
function debounce(event) {
lastInputTime = Date.now();
localValue = localValue.replace(/[^-0-9.]/g, '');
const eventTime = lastInputTime;
const pendingValue = localValue;
window.setTimeout(
() => {
// if no other inputs have occured since then
if (eventTime === lastInputTime) {
updateValue(pendingValue);
}
},
500
)
}
let error = null;
function updateValue(newValue) {
// Don't update the value, but also don't error, if it's empty
// or if it could be the start of a negative or decimal number
if (localValue.match(/^$|^-$|^\.$/) !== null) {
if (newValue.match(/^$|^-$|^\.$/) !== null) {
error = null;
return;
}
let num = parseFloat(localValue);
const num = parseFloat(newValue);
if (num % 1 !== 0 && !decimal) {
error = `${num} is not a whole number`;
}
@ -53,7 +71,7 @@
size="{Math.max(5, localValue.length)}"
class:input-error={error}
bind:value={localValue}
on:input="{validate}"
on:input="{debounce}"
/>
</div>
</div>