creddy/src/ui/settings/NumericSetting.svelte

81 lines
2.2 KiB
Svelte
Raw Normal View History

2023-04-26 05:10:14 +00:00
<script>
import { createEventDispatcher } from 'svelte';
import Setting from './Setting.svelte';
export let title;
export let value;
export let unit = '';
export let min = null;
export let max = null;
export let decimal = false;
const dispatch = createEventDispatcher();
2023-04-28 21:33:23 +00:00
$: localValue = value.toString();
let lastInputTime = null;
function debounce(event) {
lastInputTime = Date.now();
2023-04-27 21:24:08 +00:00
localValue = localValue.replace(/[^-0-9.]/g, '');
2023-04-28 21:33:23 +00:00
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) {
2023-04-27 21:24:08 +00:00
// 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
2023-04-28 21:33:23 +00:00
if (newValue.match(/^$|^-$|^\.$/) !== null) {
2023-04-26 05:10:14 +00:00
error = null;
return;
}
2023-04-28 21:33:23 +00:00
const num = parseFloat(newValue);
2023-04-27 21:24:08 +00:00
if (num % 1 !== 0 && !decimal) {
2023-04-26 05:10:14 +00:00
error = `${num} is not a whole number`;
}
2023-04-27 21:24:08 +00:00
else if (min !== null && num < min) {
2023-04-26 05:10:14 +00:00
error = `Too low (minimum ${min})`;
}
2023-04-27 21:24:08 +00:00
else if (max !== null && num > max) {
2023-04-26 05:10:14 +00:00
error = `Too large (maximum ${max})`
}
else {
error = null;
value = num;
dispatch('update', {value})
}
}
</script>
<Setting {title}>
2023-04-26 05:10:14 +00:00
<div slot="input">
{#if unit}
<span class="mr-2">{unit}:</span>
{/if}
2023-04-27 21:24:08 +00:00
<div class="tooltip tooltip-error" class:tooltip-open={error !== null} data-tip="{error}">
2023-04-26 05:10:14 +00:00
<input
type="text"
2023-04-27 21:24:08 +00:00
class="input input-sm input-bordered text-right"
size="{Math.max(5, localValue.length)}"
2023-04-26 05:10:14 +00:00
class:input-error={error}
2023-04-27 21:24:08 +00:00
bind:value={localValue}
2023-04-28 21:33:23 +00:00
on:input="{debounce}"
2023-04-26 05:10:14 +00:00
/>
</div>
</div>
<slot name="description" slot="description"></slot>
</Setting>