feature/searchbar-enhance #17
@@ -1,5 +1,28 @@
|
||||
import { debounce } from '$shared/lib/utils';
|
||||
|
||||
/**
|
||||
* Creates reactive state with immediate and debounced values.
|
||||
*
|
||||
* Useful for UI inputs that need instant feedback but debounced logic
|
||||
* (e.g., search fields with API calls). The immediate value updates on
|
||||
* every change for UI binding, while debounced updates after a delay.
|
||||
*
|
||||
* @param initialValue - Initial value for both immediate and debounced state
|
||||
* @param wait - Delay in milliseconds before updating debounced value (default: 300)
|
||||
* @returns Object with immediate/debounced getters, immediate setter, and reset method
|
||||
*
|
||||
* @example
|
||||
* ```svelte
|
||||
* <script lang="ts">
|
||||
* const search = createDebouncedState('', 300);
|
||||
* </script>
|
||||
*
|
||||
* <input bind:value={search.immediate} />
|
||||
*
|
||||
* <p>Typing: {search.immediate}</p>
|
||||
* <p>Searching: {search.debounced}</p>
|
||||
* ```
|
||||
*/
|
||||
export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
||||
let immediate = $state(initialValue);
|
||||
let debounced = $state(initialValue);
|
||||
@@ -9,6 +32,7 @@ export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
||||
}, wait);
|
||||
|
||||
return {
|
||||
/** Current value with immediate updates (for UI binding) */
|
||||
get immediate() {
|
||||
return immediate;
|
||||
},
|
||||
@@ -17,9 +41,14 @@ export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
||||
// Manually trigger the debounce on write
|
||||
updateDebounced(value);
|
||||
},
|
||||
/** Current value with debounced updates (for logic/operations) */
|
||||
get debounced() {
|
||||
return debounced;
|
||||
},
|
||||
/**
|
||||
* Resets both values to initial or specified value.
|
||||
* @param value - Optional value to reset to (defaults to initialValue)
|
||||
*/
|
||||
reset(value?: T) {
|
||||
const resetValue = value ?? initialValue;
|
||||
immediate = resetValue;
|
||||
|
||||
Reference in New Issue
Block a user