input: add use & focus utilities
This commit is contained in:
@@ -6,11 +6,14 @@
|
||||
type ValidatorOptions
|
||||
} from '@svelte-toolkit/validate';
|
||||
import { generateIdentifier } from './util';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
type $Props = Omit<HTMLInputAttributes, 'name' | 'value'> & {
|
||||
name?: string;
|
||||
value?: string;
|
||||
validate?: ValidatorOptions;
|
||||
focus?: boolean;
|
||||
use?: (node: HTMLInputElement) => void;
|
||||
ref?: HTMLInputElement | null;
|
||||
onvalidate?: (e: InputValidatorEvent) => void;
|
||||
};
|
||||
@@ -21,6 +24,8 @@
|
||||
value = $bindable(''),
|
||||
placeholder,
|
||||
validate: validateOpts,
|
||||
focus: focusOnMount = false,
|
||||
use,
|
||||
ref = $bindable<HTMLInputElement | null>(null),
|
||||
onvalidate,
|
||||
...others
|
||||
@@ -28,12 +33,24 @@
|
||||
|
||||
let valid: boolean = $state(true);
|
||||
|
||||
export const focus = () => {
|
||||
if (ref) ref.focus();
|
||||
};
|
||||
|
||||
const conditionalUse = $derived(use ? use : () => {});
|
||||
|
||||
$effect(() => {
|
||||
// default autovalOnInvalid to true unless explicitly set to false
|
||||
if (validateOpts !== undefined && validateOpts.autovalOnInvalid === undefined) {
|
||||
validateOpts.autovalOnInvalid = true;
|
||||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
if (focusOnMount && ref) {
|
||||
ref.focus();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<input
|
||||
@@ -52,6 +69,7 @@
|
||||
others.class
|
||||
]}
|
||||
use:validate={validateOpts}
|
||||
use:conditionalUse
|
||||
onvalidate={(e) => {
|
||||
valid = e.detail.valid;
|
||||
if (onvalidate) onvalidate(e);
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
type?: HTMLInputElement['type'];
|
||||
validate?: ValidatorOptions;
|
||||
invalidMessage?: string;
|
||||
focus?: boolean;
|
||||
use?: (node: HTMLInputElement) => void;
|
||||
ref?: HTMLInputElement | null;
|
||||
class?: ClassValue | null | undefined;
|
||||
}
|
||||
@@ -27,11 +29,17 @@
|
||||
type,
|
||||
validate: validateOpts,
|
||||
invalidMessage = 'Field is required',
|
||||
focus: focusOnMount = false,
|
||||
use,
|
||||
ref = $bindable<HTMLInputElement | null>(null),
|
||||
class: classValue
|
||||
}: Props = $props();
|
||||
|
||||
let valid: boolean = $state(true);
|
||||
|
||||
export const focus = () => {
|
||||
if (ref) ref.focus();
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class={['w-full', classValue]}>
|
||||
@@ -50,6 +58,8 @@
|
||||
onvalidate={(e) => {
|
||||
valid = e.detail.valid;
|
||||
}}
|
||||
focus={focusOnMount}
|
||||
{use}
|
||||
/>
|
||||
|
||||
{#if validateOpts}
|
||||
|
||||
Reference in New Issue
Block a user