From e6e58ab1064b02fd440a8df7fd8f063d615c83e8 Mon Sep 17 00:00:00 2001 From: Elijah Duffy Date: Fri, 4 Jul 2025 03:17:38 -0700 Subject: [PATCH] input: add use & focus utilities --- src/lib/StyledRawInput.svelte | 18 ++++++++++++++++++ src/lib/TextInput.svelte | 10 ++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/lib/StyledRawInput.svelte b/src/lib/StyledRawInput.svelte index 810efc0..9d51ae4 100644 --- a/src/lib/StyledRawInput.svelte +++ b/src/lib/StyledRawInput.svelte @@ -6,11 +6,14 @@ type ValidatorOptions } from '@svelte-toolkit/validate'; import { generateIdentifier } from './util'; + import { onMount } from 'svelte'; type $Props = Omit & { 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(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(); + } + }); { valid = e.detail.valid; if (onvalidate) onvalidate(e); diff --git a/src/lib/TextInput.svelte b/src/lib/TextInput.svelte index ad424a1..cfc3a81 100644 --- a/src/lib/TextInput.svelte +++ b/src/lib/TextInput.svelte @@ -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(null), class: classValue }: Props = $props(); let valid: boolean = $state(true); + + export const focus = () => { + if (ref) ref.focus(); + };
@@ -50,6 +58,8 @@ onvalidate={(e) => { valid = e.detail.valid; }} + focus={focusOnMount} + {use} /> {#if validateOpts}