mapcomplete/UI/InputElement/ValidatedInput.svelte

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

56 lines
1.7 KiB
Svelte
Raw Normal View History

<script lang="ts">
2023-03-31 03:28:11 +02:00
import { UIEventSource } from "../../Logic/UIEventSource";
import type { ValidatorType } from "./Validators";
import Validators from "./Validators";
import { ExclamationIcon } from "@rgossiaux/svelte-heroicons/solid";
import { Translation } from "../i18n/Translation";
2023-03-31 03:28:11 +02:00
import { createEventDispatcher } from "svelte";
export let value: UIEventSource<string>;
// Internal state, only copied to 'value' so that no invalid values leak outside
2023-03-31 03:28:11 +02:00
let _value = new UIEventSource(value.data ?? "");
export let type: ValidatorType;
let validator = Validators.get(type);
2023-03-31 03:28:11 +02:00
export let feedback: UIEventSource<Translation> | undefined = undefined;
_value.addCallbackAndRun(v => {
2023-03-31 03:28:11 +02:00
if (validator.isValid(v)) {
feedback?.setData(undefined);
value.setData(v);
return;
}
2023-03-31 03:28:11 +02:00
value.setData(undefined);
feedback?.setData(validator.getFeedback(v));
2023-03-31 03:28:11 +02:00
});
if (validator === undefined) {
throw "Not a valid type for a validator:" + type;
}
const isValid = _value.map(v => validator.isValid(v));
2023-03-31 03:28:11 +02:00
let htmlElem: HTMLInputElement;
let dispatch = createEventDispatcher<{ selected }>();
$: {
console.log(htmlElem)
if (htmlElem !== undefined) {
htmlElem.onfocus = () => {
console.log("Dispatching selected event")
return dispatch("selected");
};
}
}
</script>
{#if validator.textArea}
<textarea bind:value={$_value} inputmode={validator.inputmode ?? "text"}></textarea>
{:else }
<div class="flex">
2023-03-31 03:28:11 +02:00
<input bind:this={htmlElem} bind:value={$_value} inputmode={validator.inputmode ?? "text"}>
{#if !$isValid}
<ExclamationIcon class="h-6 w-6 -ml-6"></ExclamationIcon>
{/if}
</div>
{/if}