Skip to content

Commit

Permalink
fix: trigger search only when the input value changes
Browse files Browse the repository at this point in the history
  • Loading branch information
zhyian committed May 23, 2024
1 parent d57c8bf commit e5b000a
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions resources/ts/form/input-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { toggleSingleActiveFilter } from '../filters/active-filters';

const INPUT_SELECTOR = '.c-degree-programs-sarchform__input';
const MIN_CHARACTERS = 3;

export const SEARCH_ACTIVE_FILTER_LABEL = _x(
'Keyword',
'frontoffice: degree-programs-overview',
Expand All @@ -19,35 +20,47 @@ const initLiveSearching = () => {

let timeout: ReturnType< typeof setTimeout > | null = null;

input?.addEventListener( 'input', () => {
const handleInput = () => {
if ( timeout ) {
clearTimeout( timeout );
}

const inputValue = input.value.trim();
const inputValue = input?.value.trim() || '';

if ( inputValue.length > MIN_CHARACTERS ) {
timeout = setTimeout( () => {
submitForm();
timeout = null;
}, INPUT_DELAY );
}
} );
};

input?.addEventListener( 'input', handleInput );
};

if ( ! isReducedMotion() ) {
initLiveSearching();
}
let valueOnFocusEvent = '';

input?.addEventListener( 'blur', () => {
const inputValue = input.value.trim();
const handleFocus = () => {
valueOnFocusEvent = input?.value.trim() || '';
};

if ( inputValue.length > MIN_CHARACTERS ) {
return;
const handleBlur = () => {
const inputValue = input?.value.trim() || '';

if (
inputValue.length <= MIN_CHARACTERS &&
valueOnFocusEvent !== inputValue
) {
submitForm();
}
};

submitForm();
} );
if ( ! isReducedMotion() ) {
initLiveSearching();
}

input?.addEventListener( 'focus', handleFocus );
input?.addEventListener( 'blur', handleBlur );
input?.addEventListener( 'search', () => {
submitForm();
} );
Expand All @@ -58,7 +71,6 @@ export const toggleSearchActiveFilter = () => {
}

const inputValue = input.value.trim();

toggleSingleActiveFilter( SEARCH_ACTIVE_FILTER_LABEL, inputValue );
};

Expand Down

0 comments on commit e5b000a

Please sign in to comment.