Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Fix: Modify the style of the "Built-in" label in the ParserSelect dropdown menu. (#20669)

balibabu14c2721236d4
diff --git a/web/src/components/document-pipeline-dialog/index.tsx b/web/src/components/document-pipeline-dialog/index.tsx
index 07a0285e89..728c458676 100644
--- a/web/src/components/document-pipeline-dialog/index.tsx
+++ b/web/src/components/document-pipeline-dialog/index.tsx
@@ -31,7 +31,10 @@ import { IChangeParserRequestBody } from '@/interfaces/request/document';
import { useCallback } from 'react';
import { FieldErrors, useFormState, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
-import { buildParserOptionValue } from '@/hooks/use-parser-options';
+import {
+ buildParserOptionValue,
+ ParserOptionKind,
+} from '@/hooks/use-parser-options';
import { useParserSelectHandler } from '@/hooks/use-parser-select-handler';
import {
IDocumentPipelineDialogProps,
@@ -128,10 +131,13 @@ export function DocumentPipelineDialog({
<ParserSelect
value={
parseType === ParseType.BuiltIn
- ? buildParserOptionValue('builtin', selectedParserId)
+ ? buildParserOptionValue(
+ ParserOptionKind.BuiltIn,
+ selectedParserId,
+ )
: selectedPipelineId
? buildParserOptionValue(
- 'pipeline',
+ ParserOptionKind.Pipeline,
selectedPipelineId,
)
: undefined
diff --git a/web/src/components/parser-select/index.test.tsx b/web/src/components/parser-select/index.test.tsx
index aabd5c6324..656a19e6fa 100644
--- a/web/src/components/parser-select/index.test.tsx
+++ b/web/src/components/parser-select/index.test.tsx
@@ -23,7 +23,7 @@ jest.mock('@/hooks/use-parser-options', () => {
{ value: 'pipeline:pipe-1', label: 'My Flow', kind: 'pipeline' },
{
value: 'builtin:general',
- label: 'General (built in)',
+ label: 'General',
kind: 'builtin',
},
],
@@ -33,6 +33,7 @@ jest.mock('@/hooks/use-parser-options', () => {
__setLoading: (v: boolean) => {
parserOptions.loading = v;
},
+ ParserOptionKind: { BuiltIn: 'builtin', Pipeline: 'pipeline' },
useParserOptions: () => parserOptions,
buildParserOptionValue: (kind: string, id: string) => `${kind}:${id}`,
parseParserOptionValue: (v?: string) => {
@@ -68,6 +69,24 @@ describe('ParserSelect', () => {
expect(mockSelectProps.options[0].value).toBe('pipeline:pipe-1');
});
+ it('renders the builtin marker as a tag with searchable keywords', () => {
+ render(<ParserSelect value={undefined} onChange={jest.fn()} />);
+ const pipelineOption = mockSelectProps.options[0];
+ const builtinOption = mockSelectProps.options[1];
+
+ // Pipeline options keep their plain string label.
+ expect(pipelineOption.label).toBe('My Flow');
+
+ // Builtin options get a ReactNode label (label + tag) and explicit
+ // keywords so cmdk search still matches the plain label text.
+ expect(builtinOption.keywords).toEqual(['General']);
+ const { container } = render(<>{builtinOption.label}</>);
+ expect(container.textContent).toContain('General');
+ expect(container.textContent).toContain(
+ 'knowledgeConfiguration.builtInSuffix',
+ );
+ });
+
it('decodes a builtin selection into kind + rawId', () => {
const onChange = jest.fn();
render(<ParserSelect value={undefined} onChange={onChange} />);
diff --git a/web/src/components/parser-select/index.tsx b/web/src/components/parser-select/index.tsx
index dfd5c6cf2e..d023e7799c 100644
--- a/web/src/components/parser-select/index.tsx
+++ b/web/src/components/parser-select/index.tsx
@@ -14,13 +14,16 @@
* limitations under the License.
*/
-import { SelectWithSearch } from '@/components/originui/select-with-search';
+import {
+ SelectWithSearch,
+ type SelectWithSearchFlagOptionType,
+} from '@/components/originui/select-with-search';
import {
parseParserOptionValue,
+ ParserOptionKind,
useParserOptions,
- type ParserOptionKind,
} from '@/hooks/use-parser-options';
-import { useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
interface IProps {
@@ -44,6 +47,45 @@ export function ParserSelect({
const { t } = useTranslation();
const { options, loading } = useParserOptions();
+ // Trim: some locales still define the marker with surrounding whitespace
+ // from when it was appended to the label text.
+ const builtInTag = t('knowledgeConfiguration.builtInSuffix').trim();
+
+ // Render the builtin marker as a tag next to the label instead of baking it
+ // into the label text; keywords keep the plain label searchable via cmdk.
+ const selectOptions = useMemo<SelectWithSearchFlagOptionType[]>(
+ () =>
+ options.map((option) => {
+ if (option.kind !== ParserOptionKind.BuiltIn) {
+ return option;
+ }
+ return {
+ ...option,
+ label: (
+ <>
+ {option.label}
+ <span className="shrink-0 rounded-md bg-bg-card px-1.5 py-0.5 text-xs text-text-secondary">
+ {builtInTag}
+ </span>
+ </>
+ ),
+ keywords: [option.label],
+ };
+ }),
+ [options, builtInTag],
+ );
+
+ // When the saved value references a parser that no longer exists (e.g. a
+ // deleted pipeline) and options have finished loading, render a localized
+ // "unavailable" label instead of the raw internal value.
+ const renderMissingParser = useCallback(
+ () =>
+ t('knowledgeConfiguration.parserOptionUnavailable', {
+ defaultValue: 'unavailable',
+ }),
+ [t],
+ );
+
const handleChange = useCallback(
(v: string) => {
const parsed = parseParserOptionValue(v);
@@ -60,19 +102,12 @@ export function ParserSelect({
<SelectWithSearch
value={value}
loading={loading}
- // When the saved value references a parser that no longer exists (e.g. a
- // deleted pipeline) and options have finished loading, render a localized
- // "unavailable" label instead of the raw internal value.
- renderMissingValue={() =>
- t('knowledgeConfiguration.parserOptionUnavailable', {
- defaultValue: 'unavailable',
- })
- }
+ renderMissingValue={renderMissingParser}
onChange={handleChange}
placeholder={
placeholder ?? t('knowledgeConfiguration.parserSelectPlaceholder')
}
- options={options}
+ options={selectOptions}
disabled={disabled}
/>
);
diff --git a/web/src/hooks/use-agent-request.ts b/web/src/hooks/use-agent-request.ts
index 6074d0d991..e82311ae17 100644
--- a/web/src/hooks/use-agent-request.ts
+++ b/web/src/hooks/use-agent-request.ts
@@ -1016,15 +1016,14 @@ export const BuiltinPipelineKeys = {
[AgentApiAction.FetchBuiltinPipelineDetail, id] as const,
};
-export const useFetchBuiltinPipelines = (type = 'builtin', enabled = true) => {
+export const useFetchBuiltinPipelines = () => {
const { data, isFetching: loading } = useQuery<IBuiltinPipelineListResponse>({
- queryKey: BuiltinPipelineKeys.list(type),
+ queryKey: BuiltinPipelineKeys.list('builtin'),
initialData: { canvas: [], total: 0 },
gcTime: 0,
- enabled,
queryFn: async () => {
const { data } = await agentService.listBuiltinPipelines(
- { params: { type } },
+ { params: { type: 'builtin' } },
true,
);
return data?.data ?? { canvas: [], total: 0 };
diff --git a/web/src/hooks/use-parser-options.test.ts b/web/src/hooks/use-parser-options.test.ts
index 84a7033785..43e508d999 100644
--- a/web/src/hooks/use-parser-options.test.ts
+++ b/web/src/hooks/use-parser-options.test.ts
@@ -3,16 +3,10 @@ import { AgentListItemType } from '@/interfaces/database/agent';
import {
buildParserOptionValue,
parseParserOptionValue,
+ ParserOptionKind,
useParserOptions,
} from '@/hooks/use-parser-options';
-jest.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) =>
- key === 'knowledgeConfiguration.builtInSuffix' ? ' (built in)' : key,
- }),
-}));
-
jest.mock('@/hooks/use-agent-request', () => ({
useFetchBuiltinPipelines: jest.fn(),
useFetchAgentList: jest.fn(),
@@ -34,21 +28,21 @@ beforeEach(() => {
describe('parser option value encoding', () => {
it('prefixes builtin and pipeline ids distinctly', () => {
- expect(buildParserOptionValue('builtin', 'general')).toBe(
+ expect(buildParserOptionValue(ParserOptionKind.BuiltIn, 'general')).toBe(
'builtin:general',
);
- expect(buildParserOptionValue('pipeline', 'abc123')).toBe(
+ expect(buildParserOptionValue(ParserOptionKind.Pipeline, 'abc123')).toBe(
'pipeline:abc123',
);
});
it('round-trips builtin and pipeline values', () => {
expect(parseParserOptionValue('builtin:general')).toEqual({
- kind: 'builtin',
+ kind: ParserOptionKind.BuiltIn,
rawId: 'general',
});
expect(parseParserOptionValue('pipeline:abc123')).toEqual({
- kind: 'pipeline',
+ kind: ParserOptionKind.Pipeline,
rawId: 'abc123',
});
});
@@ -56,18 +50,25 @@ describe('parser option value encoding', () => {
it('keeps builtin and pipeline ids with the same bare value distinct', () => {
// A short builtin id and a pipeline id that happens to share the bare value
// must not collide once prefixed.
- const builtin = buildParserOptionValue('builtin', 'general');
- const pipeline = buildParserOptionValue('pipeline', 'general');
+ const builtin = buildParserOptionValue(ParserOptionKind.BuiltIn, 'general');
+ const pipeline = buildParserOptionValue(
+ ParserOptionKind.Pipeline,
+ 'general',
+ );
expect(builtin).not.toBe(pipeline);
- expect(parseParserOptionValue(builtin)?.kind).toBe('builtin');
- expect(parseParserOptionValue(pipeline)?.kind).toBe('pipeline');
+ expect(parseParserOptionValue(builtin)?.kind).toBe(
+ ParserOptionKind.BuiltIn,
+ );
+ expect(parseParserOptionValue(pipeline)?.kind).toBe(
+ ParserOptionKind.Pipeline,
+ );
});
it('handles ids that themselves contain a colon', () => {
- const value = buildParserOptionValue('pipeline', 'a:b:c');
+ const value = buildParserOptionValue(ParserOptionKind.Pipeline, 'a:b:c');
expect(value).toBe('pipeline:a:b:c');
expect(parseParserOptionValue(value)).toEqual({
- kind: 'pipeline',
+ kind: ParserOptionKind.Pipeline,
rawId: 'a:b:c',
});
});
@@ -81,7 +82,7 @@ describe('parser option value encoding', () => {
});
describe('useParserOptions merged list', () => {
- it('puts pipeline options first, then builtin options with the suffix', () => {
+ it('puts pipeline options first, then builtin options with plain labels', () => {
agentRequest.useFetchBuiltinPipelines.mockReturnValue({
options: [
{ label: 'General', value: 'general' },
@@ -107,16 +108,17 @@ describe('useParserOptions merged list', () => {
expect(opts[0]).toEqual({
value: 'pipeline:pipe-1',
label: 'My Flow',
- kind: 'pipeline',
+ kind: ParserOptionKind.Pipeline,
});
expect(opts[1].value).toBe('pipeline:pipe-2');
- // Builtin appended below with the " (built in)" suffix.
+ // Builtin appended below; the label stays plain and the "built in" tag is
+ // rendered by the select component based on `kind`.
expect(opts[2]).toEqual({
value: 'builtin:general',
- label: 'General (built in)',
- kind: 'builtin',
+ label: 'General',
+ kind: ParserOptionKind.BuiltIn,
});
- expect(opts[3].label).toBe('Book (built in)');
+ expect(opts[3].label).toBe('Book');
});
it('excludes compilation template groups from pipeline options', () => {
@@ -136,7 +138,7 @@ describe('useParserOptions merged list', () => {
const { result } = renderHook(() => useParserOptions());
const pipelineOpts = result.current.options.filter(
- (o) => o.kind === 'pipeline',
+ (o) => o.kind === ParserOptionKind.Pipeline,
);
expect(pipelineOpts).toHaveLength(1);
expect(pipelineOpts[0].value).toBe('pipeline:pipe-1');
diff --git a/web/src/hooks/use-parser-options.ts b/web/src/hooks/use-parser-options.ts
index e904c40404..b9ba9c7e38 100644
--- a/web/src/hooks/use-parser-options.ts
+++ b/web/src/hooks/use-parser-options.ts
@@ -5,9 +5,11 @@ import {
useFetchBuiltinPipelines,
} from '@/hooks/use-agent-request';
import { useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-export type ParserOptionKind = 'builtin' | 'pipeline';
+export enum ParserOptionKind {
+ BuiltIn = 'builtin',
+ Pipeline = 'pipeline',
+}
export interface IParserOption {
value: string;
@@ -15,15 +17,12 @@ export interface IParserOption {
kind: ParserOptionKind;
}
-export const BuiltinPrefix = 'builtin:';
-export const PipelinePrefix = 'pipeline:';
-
// buildParserOptionValue packs the parser kind and the raw backend id into a
// single select value. Prefixing avoids collisions between short builtin ids
// (e.g. "general") and 32-char canvas pipeline ids, and keeps the value safe
// to serialize.
export function buildParserOptionValue(kind: ParserOptionKind, rawId: string) {
- return `${kind === 'builtin' ? BuiltinPrefix : PipelinePrefix}${rawId}`;
+ return `${kind}:${rawId}`;
}
export function parseParserOptionValue(value?: string): {
@@ -31,49 +30,47 @@ export function parseParserOptionValue(value?: string): {
rawId: string;
} | null {
if (!value) return null;
- if (value.startsWith(BuiltinPrefix)) {
- return { kind: 'builtin', rawId: value.slice(BuiltinPrefix.length) };
- }
- if (value.startsWith(PipelinePrefix)) {
- return { kind: 'pipeline', rawId: value.slice(PipelinePrefix.length) };
+ for (const kind of Object.values(ParserOptionKind)) {
+ const prefix = `${kind}:`;
+ if (value.startsWith(prefix)) {
+ return { kind, rawId: value.slice(prefix.length) };
+ }
}
return null;
}
// useParserOptions returns the unified list of parser options shown in the
// merged dataset/document parser dropdown: pipeline (canvas) options first,
-// followed by builtin options each suffixed with the " (built in)" marker.
+// followed by builtin options. Builtin options carry their plain label; the
+// "built in" marker is rendered as a tag by the select component via `kind`.
export function useParserOptions() {
- const { t } = useTranslation();
const { options: builtinOptions, loading: builtinLoading } =
useFetchBuiltinPipelines();
const { data: pipelineData, loading: pipelineLoading } = useFetchAgentList({
canvas_category: AgentCategory.DataflowCanvas,
});
- const suffix = t('knowledgeConfiguration.builtInSuffix');
-
const options = useMemo<IParserOption[]>(() => {
const pipeline = (pipelineData?.canvas ?? [])
.filter(
(item) => item.type !== AgentListItemType.CompilationTemplateGroup,
)
.map((item) => ({
- value: buildParserOptionValue('pipeline', item.id),
+ value: buildParserOptionValue(ParserOptionKind.Pipeline, item.id),
label: item.title,
- kind: 'pipeline' as const,
+ kind: ParserOptionKind.Pipeline,
}));
const builtin = builtinOptions.map((o) => ({
- value: buildParserOptionValue('builtin', o.value),
- label: `${o.label}${suffix}`,
- kind: 'builtin' as const,
+ value: buildParserOptionValue(ParserOptionKind.BuiltIn, o.value),
+ label: o.label,
+ kind: ParserOptionKind.BuiltIn,
}));
// Pipeline options keep their existing order; builtin options are appended
- // below, matching the desired "pipeline first, builtin (built in) below" UI.
+ // below, matching the desired "pipeline first, builtin below" UI.
return [...pipeline, ...builtin];
- }, [pipelineData, builtinOptions, suffix]);
+ }, [pipelineData, builtinOptions]);
return { options, loading: builtinLoading || pipelineLoading };
}
diff --git a/web/src/hooks/use-parser-select-handler.ts b/web/src/hooks/use-parser-select-handler.ts
index 45fa2bcbb8..87197bfff9 100644
--- a/web/src/hooks/use-parser-select-handler.ts
+++ b/web/src/hooks/use-parser-select-handler.ts
@@ -1,26 +1,43 @@
import { useCallback } from 'react';
-import type { UseFormReturn } from 'react-hook-form';
+import type { UseFormReturn, UseFormSetValue } from 'react-hook-form';
import { ParseType } from '@/constants/knowledge';
-import type { ParserOptionKind } from './use-parser-options';
+import { ParserOptionKind } from './use-parser-options';
+
+// The three parser forms (dataset settings, dataset creation, per-document
+// pipeline) all carry this subset of fields. Constraining the handler to it
+// guarantees at the call site that the form actually has these fields.
+interface ParserFormFields {
+ parse_type?: ParseType;
+ parser_id?: string;
+ pipeline_id?: string;
+}
// useParserSelectHandler returns a stable onChange handler for ParserSelect that
// maps the resolved (kind, rawId) pair onto the form's parser fields. Extracting
// it keeps the duplicated logic in one place and avoids a fresh closure on every
// render, which would otherwise defeat SelectWithSearch's memoization.
-export function useParserSelectHandler(form: UseFormReturn<any>) {
+export function useParserSelectHandler<T extends ParserFormFields>(
+ form: UseFormReturn<T>,
+) {
return useCallback(
(kind: ParserOptionKind | null, rawId: string) => {
- if (kind === 'builtin') {
- form.setValue('parse_type', ParseType.BuiltIn);
- form.setValue('parser_id', rawId);
- form.setValue('pipeline_id', '');
- } else if (kind === 'pipeline') {
- form.setValue('parse_type', ParseType.Pipeline);
- form.setValue('pipeline_id', rawId);
- form.setValue('parser_id', '');
+ // UseFormReturn is invariant in its values type, so the full form cannot
+ // be narrowed to ParserFormFields directly. The constraint above
+ // guarantees these fields exist; narrowing setValue once keeps the field
+ // names and value types below checked.
+ const setValue =
+ form.setValue as unknown as UseFormSetValue<ParserFormFields>;
+ if (kind === ParserOptionKind.BuiltIn) {
+ setValue('parse_type', ParseType.BuiltIn);
+ setValue('parser_id', rawId);
+ setValue('pipeline_id', '');
+ } else if (kind === ParserOptionKind.Pipeline) {
+ setValue('parse_type', ParseType.Pipeline);
+ setValue('pipeline_id', rawId);
+ setValue('parser_id', '');
} else {
- form.setValue('parser_id', '');
- form.setValue('pipeline_id', '');
+ setValue('parser_id', '');
+ setValue('pipeline_id', '');
}
},
[form],
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index 02c6e4d9f2..70640d205b 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -665,7 +665,7 @@ Example: A 1 KB message with 1024-dim embedding uses ~9 KB. The 5 MB default lim
reRankModelWaring: 'Re-rank model is very time consuming.',
},
knowledgeConfiguration: {
- builtInSuffix: ' (built in)',
+ builtInSuffix: 'Built in',
parserSelectPlaceholder: 'Select a parser',
parserOptionUnavailable: 'unavailable',
randomSeedTip:
diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts
index 6e1776bc50..b89efbcada 100644
--- a/web/src/locales/zh.ts
+++ b/web/src/locales/zh.ts
@@ -604,7 +604,7 @@ export default {
theDocumentBeingParsedCannotBeDeleted: '正在解析的文档不能被删除',
},
knowledgeConfiguration: {
- builtInSuffix: '(内置)',
+ builtInSuffix: '内置',
parserSelectPlaceholder: '选择解析方式',
parserOptionUnavailable: '不可用',
randomSeedTip:
diff --git a/web/src/pages/dataset/setting/go/index.tsx b/web/src/pages/dataset/setting/go/index.tsx
index 6c765d477d..0300ea51ba 100644
--- a/web/src/pages/dataset/setting/go/index.tsx
+++ b/web/src/pages/dataset/setting/go/index.tsx
@@ -17,7 +17,10 @@ import {
FormMessage,
} from '@/components/ui/form';
import { ParseType } from '@/constants/knowledge';
-import { buildParserOptionValue } from '@/hooks/use-parser-options';
+import {
+ buildParserOptionValue,
+ ParserOptionKind,
+} from '@/hooks/use-parser-options';
import { useParserSelectHandler } from '@/hooks/use-parser-select-handler';
import {
useActiveTab,
@@ -240,12 +243,12 @@ export default function DatasetSetting() {
value={
parseType === ParseType.BuiltIn
? buildParserOptionValue(
- 'builtin',
+ ParserOptionKind.BuiltIn,
builtinPipelineId ?? '',
)
: pipelineId
? buildParserOptionValue(
- 'pipeline',
+ ParserOptionKind.Pipeline,
pipelineId,
)
: undefined
diff --git a/web/src/pages/datasets/dataset-creating-dialog.tsx b/web/src/pages/datasets/dataset-creating-dialog.tsx
index e9ee96696d..dd7f8fda28 100644
--- a/web/src/pages/datasets/dataset-creating-dialog.tsx
+++ b/web/src/pages/datasets/dataset-creating-dialog.tsx
@@ -18,7 +18,10 @@ import {
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { ParseType } from '@/constants/knowledge';
-import { buildParserOptionValue } from '@/hooks/use-parser-options';
+import {
+ buildParserOptionValue,
+ ParserOptionKind,
+} from '@/hooks/use-parser-options';
import { useParserSelectHandler } from '@/hooks/use-parser-select-handler';
import { useFetchDefaultModelDictionary } from '@/hooks/use-llm-request';
import { IModalProps } from '@/interfaces/common';
@@ -150,9 +153,15 @@ export function InputForm({ onOk }: IModalProps<any>) {
<ParserSelect
value={
parseType === ParseType.BuiltIn
- ? buildParserOptionValue('builtin', parserId ?? '')
+ ? buildParserOptionValue(
+ ParserOptionKind.BuiltIn,
+ parserId ?? '',
+ )
: pipelineId
- ? buildParserOptionValue('pipeline', pipelineId)
+ ? buildParserOptionValue(
+ ParserOptionKind.Pipeline,
+ pipelineId,
+ )
: undefined
}
onChange={handleParserSelect}
diff --git a/web/src/pages/user-setting/setting-model/provider-schema/hooks/index.ts b/web/src/pages/user-setting/setting-model/provider-schema/hooks/index.ts
index b42f8112db..0798dc972b 100644
--- a/web/src/pages/user-setting/setting-model/provider-schema/hooks/index.ts
+++ b/web/src/pages/user-setting/setting-model/provider-schema/hooks/index.ts
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-export { useListModelsOptions } from './use-list-models-options';
export { useListModelsPicker } from './use-list-models-picker';
export { useProviderFields } from './use-provider-fields';
export { useProviderModalActions } from './use-provider-modal-actions';
diff --git a/web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-options.tsx b/web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-options.tsx
deleted file mode 100644
index e85a381150..0000000000
--- a/web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-options.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { Checkbox } from '@/components/ui/checkbox';
-import { useTranslate } from '@/hooks/common-hooks';
-import { IProviderModelItem } from '@/interfaces/request/llm';
-import { Pencil } from 'lucide-react';
-import { useMemo } from 'react';
-
-interface UseListModelsOptionsParams {
- models: IProviderModelItem[];
- selectedModelItems: IProviderModelItem[];
- allSelected: boolean;
- handleSelectModel: (model: IProviderModelItem) => void;
- handleToggleAll: () => void;
- onEditModel?: (model: IProviderModelItem) => void;
-}
-
-export const useListModelsOptions = ({
- models,
- selectedModelItems,
- allSelected,
- handleSelectModel,
- handleToggleAll,
- onEditModel,
-}: UseListModelsOptionsParams) => {
- const { t } = useTranslate('setting');
-
- return useMemo(() => {
- const allOption = {
- value: null as string | null,
- label: (
- <div className="flex justify-between items-center gap-2 w-full">
- <div className="flex-1 min-w-0 flex gap-1 items-center">
- <div className="font-medium truncate">{t('allModels')}</div>
- </div>
- <Checkbox
- checked={allSelected}
- onClick={(e) => {
- e.stopPropagation();
- handleToggleAll();
- }}
- />
- </div>
- ),
- onClick: () => handleToggleAll(),
- };
-
- const modelOptions = models.map((m) => {
- const checked = selectedModelItems.some((s) => s.name === m.name);
- return {
- value: m.name,
- label: (
- <div className="flex justify-between items-center gap-2 w-full">
- <div className="flex-1 min-w-0 flex gap-1 items-center">
- <div className="font-medium truncate">{m.name}</div>
- {m.model_types &&
- m.model_types.map((type) => {
- return (
- <div
- key={type}
- className="text-xs text-text-secondary truncate bg-bg-card rounded-md px-2 py-1"
- >
- {type}
- </div>
- );
- })}
- </div>
- <div className="flex items-center gap-1">
- {onEditModel && (
- <button
- type="button"
- aria-label="Edit model"
- title="Edit model"
- className="p-1 rounded hover:bg-bg-card text-text-secondary"
- onClick={(e) => {
- e.stopPropagation();
- onEditModel(m);
- }}
- >
- <Pencil size={12} />
- </button>
- )}
- <Checkbox
- checked={checked}
- onClick={(e) => {
- e.stopPropagation();
- handleSelectModel(m);
- }}
- />
- </div>
- </div>
- ),
- onClick: () => handleSelectModel(m),
- };
- });
- if (modelOptions?.length) {
- return [allOption, ...modelOptions];
- } else {
- return [];
- }
- }, [
- models,
- selectedModelItems,
- handleSelectModel,
- allSelected,
- handleToggleAll,
- onEditModel,
- t,
- ]);
-};