diff --git a/src/components/textinput.js b/src/components/textinput.js index a06283109..8907a1878 100644 --- a/src/components/textinput.js +++ b/src/components/textinput.js @@ -37,6 +37,7 @@ validationAboveMaximum = [''], value, hideLabel, + debounceDelay, dataComponentAttribute = ['TextField'], required, } = options; @@ -64,6 +65,7 @@ const [currentValue, setCurrentValue] = usePageState(useText(value)); const parsedLabel = useText(label); const labelText = parsedLabel; + const debouncedOnChangeRef = useRef(null); const validPattern = pattern || null; const validMinlength = minLength || null; @@ -140,6 +142,20 @@ }; }; + const debounce = + (func, delay) => + (...args) => { + clearTimeout(debounce.timeoutId); + debounce.timeoutId = setTimeout(() => func(...args), delay); + }; + debounce.timeoutId = null; + + if (!debouncedOnChangeRef.current) { + debouncedOnChangeRef.current = debounce((newValue) => { + B.triggerEvent('onChange', newValue); + }, debounceDelay); + } + const changeHandler = (event) => { const { target } = event; let { validity: validation } = target; @@ -156,7 +172,7 @@ } const newValue = isNumberType ? numberValue : eventValue; setCurrentValue(newValue); - B.triggerEvent('onChange', newValue); + debouncedOnChangeRef.current(newValue); }; const blurHandler = (event) => { diff --git a/src/prefabs/structures/TextInput/index.ts b/src/prefabs/structures/TextInput/index.ts index e14c2f701..0f0147624 100644 --- a/src/prefabs/structures/TextInput/index.ts +++ b/src/prefabs/structures/TextInput/index.ts @@ -44,7 +44,7 @@ export const TextInput = ( { label: 'Advanced Options', expanded: false, - members: ['dataComponentAttribute'], + members: ['debounceDelay', 'dataComponentAttribute'], }, ]; diff --git a/src/prefabs/structures/TextInput/options/advanced.ts b/src/prefabs/structures/TextInput/options/advanced.ts index e4e158839..4ee8286f7 100644 --- a/src/prefabs/structures/TextInput/options/advanced.ts +++ b/src/prefabs/structures/TextInput/options/advanced.ts @@ -1,6 +1,7 @@ -import { variable } from '@betty-blocks/component-sdk'; +import { number, variable } from '@betty-blocks/component-sdk'; export const advanced = { + debounceDelay: number('Debounce delay (in ms)'), dataComponentAttribute: variable('Test attribute', { value: [], }),