From f6920b7a56f5ebfaa841d5907033009438bc8cf2 Mon Sep 17 00:00:00 2001 From: Achraf Mohyeddine Date: Tue, 7 Jan 2025 15:17:14 +0100 Subject: [PATCH] ui-core: clear combobox value when invalid after suggestions Signed-off-by: Achraf Mohyeddine --- .../components/inputs/ComboBox/ComboBox.tsx | 11 ++++++ ui-core/src/stories/ComboBox.stories.tsx | 37 ++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/ui-core/src/components/inputs/ComboBox/ComboBox.tsx b/ui-core/src/components/inputs/ComboBox/ComboBox.tsx index 8b1037093..41f7030ee 100644 --- a/ui-core/src/components/inputs/ComboBox/ComboBox.tsx +++ b/ui-core/src/components/inputs/ComboBox/ComboBox.tsx @@ -119,6 +119,17 @@ const ComboBox = ({ useEffect(() => { setFilteredSuggestions(sortedSuggestions); + + const isInputValid = sortedSuggestions.some( + (suggestion) => + normalizeString(getSuggestionLabel(suggestion)) === normalizeString(inputValue) + ); + + if (!isInputValid) { + setInputValue(''); + setSelectedOption(null); + onSelectSuggestion?.(undefined); + } }, [sortedSuggestions]); const handleInputChange: ChangeEventHandler = (e) => { diff --git a/ui-core/src/stories/ComboBox.stories.tsx b/ui-core/src/stories/ComboBox.stories.tsx index 79e0f391c..c7e70e3b7 100644 --- a/ui-core/src/stories/ComboBox.stories.tsx +++ b/ui-core/src/stories/ComboBox.stories.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useEffect, useState } from 'react'; import type { Meta, StoryObj } from '@storybook/react'; import '@osrd-project/ui-core/dist/theme.css'; @@ -126,3 +126,38 @@ export const DisabledDefaultFilter: Story = { disableDefaultFilter: true, }, }; + +export const DynamicSuggestions: Story = { + render: (args) => { + const [dynamicSuggestions, setDynamicSuggestions] = useState([ + { id: '1', label: 'Manuel' }, + { id: '2', label: 'Manolo' }, + { id: '3', label: 'Maria' }, + { id: '4', label: 'Miguel' }, + ]); + + // Simulate a dynamic update to the suggestions list after 5 seconds + useEffect(() => { + const timeout = setTimeout(() => { + setDynamicSuggestions([ + { id: '1', label: 'Consuela' }, + { id: '2', label: 'Juan' }, + { id: '3', label: 'Jose' }, + { id: '4', label: 'Ana' }, + { id: '5', label: 'Pedro' }, + { id: '6', label: 'Lucia' }, + { id: '7', label: 'Carlos' }, + { id: '8', label: 'Elena' }, + ]); + }, 5000); + + return () => clearTimeout(timeout); + }, []); + + return ; + }, + args: { + label: 'Dynamic Suggestions', + type: 'text', + }, +};