tag-feature-item.tsx
Overview
The tag-feature-item.tsx file defines a React functional component named TagFeatureItem used within a form context to manage a dynamic list of tags associated with a knowledge base. Each tag can be selected from a list fetched based on configured knowledge base IDs, and each tag has an associated frequency value (a number input).
This component provides an interactive UI allowing users to:
Add new tag-frequency pairs.
Remove existing pairs.
Select tags from filtered options that exclude already selected tags in other list items.
Input frequency values constrained between 0 and 10.
It integrates tightly with a form state managed by react-hook-form and fetches its selectable tag options dynamically based on knowledge base configuration via custom hooks.
Detailed Explanation
Component: TagFeatureItem
This is the default exported React functional component in the file.
Purpose
Render a list of form entries where each entry contains:
A searchable dropdown (
SelectWithSearch) for selecting a tag.A numeric input (
NumberInput) for specifying the frequency of the selected tag.
Enforce uniqueness of selected tags across the list.
Allow adding and removing tag-frequency pairs dynamically.
Fetch tag options by knowledge base IDs and update them reactively.
Dependencies and Hooks Used
React hooks:
useCallback,useEffect,useMemoreact-hook-form:
useFormContext,useFieldArrayi18next: useTranslation for internationalized UI labels.
Custom hooks:
useFetchTagListByKnowledgeIds: Fetches a list of tags based on knowledge base IDs.useFetchKnowledgeBaseConfiguration: Fetches knowledge base configuration including tag-related IDs.
UI Components:
Icons:
CircleMinus, Plus fromlucide-react
Constants
FieldKey: String constant 'tag_feas' used as the form field name for the tag feature list.
Internal Logic and Methods
tagKnowledgeIds
Derived via
useMemofromknowledgeConfiguration.parser_config.tag_kb_ids.An array of knowledge base IDs used to fetch tags.
options
Derived via
useMemofrom the fetchedlistof tags.Transforms the list into an array of { value: string, label: string } objects suitable for the
SelectWithSearchcomponent.
filterOptions
A memoized callback function that filters out tags already selected in other list items.
Parameters:
index: number - the current index of the tag item being rendered.
Returns filtered options excluding tags selected in other indices.
This ensures no duplicate tags can be selected in different list entries.
useEffect
Calls setKnowledgeIds(tagKnowledgeIds) whenever tagKnowledgeIds change.
This triggers the fetching of the tag list based on the updated knowledge base IDs.
useFieldArray
Manages the dynamic array of tag-frequency entries in the form.
Provides:
fields: current list of entries.append: function to add a new empty entry.remove: function to remove an entry by index.
JSX Structure and Rendering
The component uses a
FormFieldwrapper connected toreact-hook-format theFieldKeypath.Inside, it renders a FormItem containing:
A FormLabel with the translated label for "Tags".
A list of current
fieldsmapped to individual UI rows.Each row contains:
A
SelectWithSearchdropdown for the tag, with options filtered byfilterOptions.A
NumberInputfor frequency with min 0 and max 10.A
CircleMinusicon button to remove the current row.
A "Add Tag" button (
Buttoncomponent with Plus icon) to append a new entry to the list.
All input components are controlled by react-hook-form via the FormField component.
Parameters
This component does not accept any props; it relies on the form context and hooks for data and state.
Return Value
Returns the JSX UI for the dynamic tag feature list form section.
Usage Example
import { useForm, FormProvider } from 'react-hook-form';
import { TagFeatureItem } from './tag-feature-item';
const MyFormComponent = () => {
const formMethods = useForm({
defaultValues: {
tag_feas: [{ tag: '', frequency: 0 }],
},
});
const onSubmit = (data) => {
console.log('Form submitted:', data);
};
return (
<FormProvider {...formMethods}>
<form onSubmit={formMethods.handleSubmit(onSubmit)}>
<TagFeatureItem />
<button type="submit">Submit</button>
</form>
</FormProvider>
);
};
Implementation Details and Algorithms
Dynamic Option Filtering: To ensure uniqueness of selected tags, the
filterOptionsfunction filters out tags already present in other list items. It does so by:Extracting the tags from the current form values except the current index.
Filtering the full options list to exclude these tags.
Data Synchronization: The component listens for changes in knowledge base configuration to update the list of valid knowledge IDs, which triggers re-fetching the tag list. This ensures the dropdown options are always up-to-date with backend data.
Form Handling: Uses
react-hook-formwithuseFieldArrayto manage an array of complex inputs efficiently, handling add/remove operations with minimal re-renders.
Integration with the System
Hooks:
useFetchTagListByKnowledgeIdsfetches available tags dynamically based on knowledge base IDs.useFetchKnowledgeBaseConfigurationprovides configuration data including tag knowledge base IDs.
Form Context: Relies on
react-hook-formcontext to manage the tag-frequency list as part of a larger form.UI Components: Uses internal UI primitives (e.g., buttons, inputs) from the project’s component library to maintain consistent styling and behavior.
Internationalization: Uses
react-i18nextfor translation support of labels and placeholders.This component is likely used in a configuration or settings page related to knowledge base/tag management within a larger application.
Mermaid Diagram - Component Structure and Interaction
componentDiagram
TagFeatureItem <.. useFormContext : uses
TagFeatureItem <.. useFieldArray : manages fields array
TagFeatureItem <.. useFetchKnowledgeBaseConfiguration : fetches knowledge config
TagFeatureItem <.. useFetchTagListByKnowledgeIds : fetches tag list
TagFeatureItem --> FormField : renders form field
TagFeatureItem --> SelectWithSearch : tag selector input
TagFeatureItem --> NumberInput : frequency input
TagFeatureItem --> Button : add tag button
TagFeatureItem --> CircleMinus : remove tag button
Summary
tag-feature-item.tsx provides a reusable, dynamic form component for managing a list of tagged features with frequencies. It leverages React hooks, react-hook-form, and custom data-fetching hooks to offer a user-friendly, validated interface for selecting and configuring tags tied to knowledge base data. The component ensures data integrity by filtering out duplicate tags and synchronizing options according to backend configurations. It is a fundamental UI piece in the knowledge configuration domain of the application.