chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,738 @@
|
||||
import type {
|
||||
DatasetDetailWithPartialMembersResponse,
|
||||
DatasetRetrievalModelResponse,
|
||||
DocumentDetailResponse,
|
||||
} from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { StepTwoProps } from '../types'
|
||||
import { act, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { assert } from 'vite-plus/test'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { AppToaster } from '@/app/notifications/app-toaster'
|
||||
import DatasetDetailContext from '@/context/dataset-detail'
|
||||
import { DataSourceProvider } from '@/models/common'
|
||||
import { ChunkingMode, DataSourceType } from '@/models/datasets'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import {
|
||||
createCatalogModelFixture,
|
||||
createDefaultModelFixture,
|
||||
createModelCatalogFixture,
|
||||
seedModelProviderQueries,
|
||||
} from '@/test/console/model-provider'
|
||||
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createDatasetFixture } from '@/test/fixtures/dataset'
|
||||
import { createNuqsTestRenderer } from '@/test/nuqs-testing'
|
||||
import StepTwo from '../index'
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
create: vi.fn<typeof import('@/service/console').consoleClient.datasets.init.post>(),
|
||||
save: vi.fn<
|
||||
typeof import('@/service/console').consoleClient.datasets.byDatasetId.documents.post
|
||||
>(),
|
||||
estimate:
|
||||
vi.fn<typeof import('@/service/console').consoleClient.datasets.indexingEstimate.post>(),
|
||||
rules: vi.fn<typeof import('@/service/console').consoleClient.datasets.processRule.get>(),
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'datasets.processRule.get': api.rules,
|
||||
'datasets.indexingEstimate.post': api.estimate,
|
||||
'datasets.init.post': api.create,
|
||||
'datasets.byDatasetId.documents.post': api.save,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const document: DocumentDetailResponse = {
|
||||
id: 'doc-1',
|
||||
name: 'Handbook',
|
||||
doc_form: ChunkingMode.text,
|
||||
doc_language: 'English',
|
||||
dataset_process_rule: {
|
||||
mode: 'custom',
|
||||
rules: {
|
||||
segmentation: { separator: '\\n\\n', max_tokens: 1024, chunk_overlap: 50 },
|
||||
pre_processing_rules: [{ id: 'remove_extra_spaces', enabled: true }],
|
||||
},
|
||||
},
|
||||
}
|
||||
const saved = { batch: 'batch-1', dataset: { id: 'dataset-1', name: 'Handbook' }, documents: [] }
|
||||
const render = createNuqsTestRenderer(renderWithConsoleQuery)
|
||||
|
||||
async function setup(
|
||||
props: Partial<StepTwoProps> = {},
|
||||
dataset?: DatasetDetailWithPartialMembersResponse,
|
||||
defaultModels: { embedding?: boolean; rerank?: boolean } = {},
|
||||
) {
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedModelProviderQueries(queryClient, [
|
||||
createModelCatalogFixture({
|
||||
models: [
|
||||
createCatalogModelFixture({
|
||||
model: 'text-embedding-ada-002',
|
||||
model_type: 'text-embedding',
|
||||
label: { en_US: 'Ada Embedding' },
|
||||
}),
|
||||
createCatalogModelFixture({ model: 'gpt-4', model_type: 'llm', label: { en_US: 'GPT-4' } }),
|
||||
],
|
||||
}),
|
||||
createModelCatalogFixture({
|
||||
provider: 'cohere',
|
||||
models: [createCatalogModelFixture({ model: 'rerank-english-v3.0', model_type: 'rerank' })],
|
||||
}),
|
||||
])
|
||||
for (const model_type of ['text-embedding', 'rerank'] as const) {
|
||||
queryClient.setQueryData(
|
||||
consoleQuery.workspaces.current.defaultModel.get.queryKey({
|
||||
input: { query: { model_type } },
|
||||
}),
|
||||
{
|
||||
data:
|
||||
defaultModels[model_type === 'text-embedding' ? 'embedding' : 'rerank'] === false
|
||||
? null
|
||||
: createDefaultModelFixture({
|
||||
model_type,
|
||||
model:
|
||||
model_type === 'text-embedding'
|
||||
? 'text-embedding-ada-002'
|
||||
: 'rerank-english-v3.0',
|
||||
provider: { provider: model_type === 'text-embedding' ? 'openai' : 'cohere' },
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
queryClient.setQueryData(consoleQuery.datasets.retrievalSetting.get.queryKey(), {
|
||||
retrieval_method: ['semantic_search', 'full_text_search', 'hybrid_search'],
|
||||
})
|
||||
const onSave = vi.fn()
|
||||
const onCancel = vi.fn()
|
||||
const tree = (
|
||||
// oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector contexts require their Provider rather than React 19 context rendering.
|
||||
<DatasetDetailContext.Provider value={{ dataset }}>
|
||||
<AppToaster timeout={0} />
|
||||
<StepTwo
|
||||
dataSourceType={DataSourceType.FILE}
|
||||
files={[{ id: 'file-1', name: 'handbook.pdf', extension: 'pdf' }]}
|
||||
isAPIKeySet
|
||||
onSetting={vi.fn()}
|
||||
notionCredentialId=""
|
||||
onSave={onSave}
|
||||
onCancel={onCancel}
|
||||
datasetId={dataset?.id}
|
||||
{...props}
|
||||
/>
|
||||
</DatasetDetailContext.Provider>
|
||||
)
|
||||
const view = await act(async () =>
|
||||
render(tree, { queryClient, systemFeatures: { deployment_edition: 'COMMUNITY' } }),
|
||||
)
|
||||
return {
|
||||
...view,
|
||||
user: userEvent.setup(),
|
||||
onSave,
|
||||
onCancel,
|
||||
}
|
||||
}
|
||||
|
||||
const defaultRules: Awaited<ReturnType<typeof api.rules>> = {
|
||||
mode: 'custom',
|
||||
rules: {
|
||||
segmentation: { separator: '\\n', max_tokens: 500, chunk_overlap: 50 },
|
||||
pre_processing_rules: [
|
||||
{ id: 'remove_extra_spaces', enabled: true },
|
||||
{ id: 'remove_urls_emails', enabled: false },
|
||||
],
|
||||
parent_mode: 'paragraph',
|
||||
subchunk_segmentation: { separator: '\\n', max_tokens: 256, chunk_overlap: 0 },
|
||||
},
|
||||
limits: { indexing_max_segmentation_tokens_length: 4000 },
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
toast.dismiss()
|
||||
api.create.mockReset().mockResolvedValue(saved)
|
||||
api.save.mockReset().mockResolvedValue(saved)
|
||||
api.estimate.mockReset().mockResolvedValue({
|
||||
total_segments: 1,
|
||||
tokens: 100,
|
||||
total_price: 0.01,
|
||||
currency: 'USD',
|
||||
qa_preview: [{ question: 'Question', answer: 'Answer' }],
|
||||
preview: [{ content: 'Previewed chunk', child_chunks: ['Child chunk'] }],
|
||||
})
|
||||
api.rules.mockReset().mockResolvedValue(defaultRules)
|
||||
})
|
||||
afterEach(() => {
|
||||
act(() => toast.dismiss())
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('keeps the chunk mode and preview while editing its delimiter with an arrow key', async () => {
|
||||
const { user } = await setup()
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' }))
|
||||
expect(await screen.findByText('Previewed chunk')).toBeInTheDocument()
|
||||
const input = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.separator' })
|
||||
await user.click(input)
|
||||
await user.keyboard('{End}{ArrowDown}')
|
||||
expect(input).toHaveFocus()
|
||||
expect(screen.getByRole('radio', { name: 'datasetCreation.stepTwo.general' })).toBeChecked()
|
||||
expect(
|
||||
screen.getByRole('radio', { name: 'datasetCreation.stepTwo.parentChild' }),
|
||||
).not.toBeChecked()
|
||||
expect(screen.getByText('Previewed chunk')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the mobile preview with fetched chunks and restores its trigger after closing', async () => {
|
||||
vi.stubGlobal('innerWidth', 480)
|
||||
const { user } = await setup()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
const trigger = screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' })
|
||||
await user.click(trigger)
|
||||
const drawer = await screen.findByRole('dialog', { name: 'datasetCreation.stepTwo.preview' })
|
||||
expect(await within(drawer).findByText('Previewed chunk')).toBeInTheDocument()
|
||||
await user.click(within(drawer).getByRole('button', { name: 'common.operation.close' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(trigger).toHaveFocus()
|
||||
})
|
||||
|
||||
it('initializes document settings from saved rules and saves edits before notifying the owner', async () => {
|
||||
const pending = createDeferred<Awaited<ReturnType<typeof api.save>>>()
|
||||
api.save.mockReturnValue(pending.promise)
|
||||
const { user, onSave } = await setup(
|
||||
{ isSetting: true, documentDetail: document },
|
||||
createDatasetFixture(),
|
||||
)
|
||||
const length = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.maxLength' })
|
||||
expect(length).toHaveValue('1,024')
|
||||
await user.clear(length)
|
||||
await user.type(length, '800')
|
||||
const save = screen.getByRole('button', { name: 'datasetCreation.stepTwo.save' })
|
||||
await user.click(save)
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
expect(save).toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(save)
|
||||
expect(api.save).toHaveBeenCalledExactlyOnceWith({
|
||||
params: { dataset_id: 'dataset-1' },
|
||||
body: expect.objectContaining({
|
||||
original_document_id: 'doc-1',
|
||||
doc_form: ChunkingMode.text,
|
||||
process_rule: expect.objectContaining({
|
||||
rules: expect.objectContaining({
|
||||
segmentation: { separator: '\n\n', max_tokens: 800, chunk_overlap: 50 },
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
await act(async () => pending.resolve(saved))
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('retains failed document edits for retry', async () => {
|
||||
api.save.mockRejectedValueOnce(new Error('Save failed'))
|
||||
const { user, onSave } = await setup(
|
||||
{ isSetting: true, documentDetail: document },
|
||||
createDatasetFixture(),
|
||||
)
|
||||
const length = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.maxLength' })
|
||||
await user.clear(length)
|
||||
await user.type(length, '700')
|
||||
const save = screen.getByRole('button', { name: 'datasetCreation.stepTwo.save' })
|
||||
await user.click(save)
|
||||
await waitFor(() => expect(save).not.toHaveAttribute('aria-disabled', 'true'))
|
||||
expect(length).toHaveValue('700')
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
await user.click(save)
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledOnce())
|
||||
expect(api.save.mock.calls[1]).toEqual(api.save.mock.calls[0])
|
||||
expect(api.save).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
form: ChunkingMode.parentChild,
|
||||
visible: 'datasetCreation.stepTwo.parentChild',
|
||||
hidden: 'datasetCreation.stepTwo.general',
|
||||
},
|
||||
{
|
||||
form: ChunkingMode.text,
|
||||
visible: 'datasetCreation.stepTwo.general',
|
||||
hidden: 'datasetCreation.stepTwo.parentChild',
|
||||
},
|
||||
])(
|
||||
'uses the existing dataset chunk format $form and locks its model and retrieval settings',
|
||||
async ({ form, visible, hidden }) => {
|
||||
await setup({}, createDatasetFixture({ doc_form: form }))
|
||||
expect(screen.getByText(visible)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('radio', { name: hidden })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /Ada Embedding/ })).toBeDisabled()
|
||||
expect(
|
||||
screen.getByRole('radio', { name: 'dataset.retrieval.semantic_search.title' }),
|
||||
).toBeDisabled()
|
||||
},
|
||||
)
|
||||
|
||||
it('lets an empty dataset choose chunking format before its first document', async () => {
|
||||
const { user } = await setup({}, createDatasetFixture({ doc_form: null, data_source_type: null }))
|
||||
const general = screen.getByRole('radio', { name: 'datasetCreation.stepTwo.general' })
|
||||
const parentChild = screen.getByRole('radio', { name: 'datasetCreation.stepTwo.parentChild' })
|
||||
expect(general).toBeChecked()
|
||||
await user.click(parentChild)
|
||||
expect(parentChild).toBeChecked()
|
||||
expect(general).not.toBeChecked()
|
||||
expect(screen.getByRole('button', { name: /Ada Embedding/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('switches economical indexing to high quality when parent-child chunking is selected', async () => {
|
||||
const { user } = await setup()
|
||||
await user.click(screen.getByRole('radio', { name: 'datasetCreation.stepTwo.economical' }))
|
||||
await user.click(screen.getByRole('radio', { name: 'datasetCreation.stepTwo.parentChild' }))
|
||||
expect(screen.getByRole('radio', { name: /stepTwo.qualified/ })).toBeChecked()
|
||||
expect(screen.getByRole('radio', { name: 'datasetCreation.stepTwo.parentChild' })).toBeChecked()
|
||||
})
|
||||
|
||||
it('keeps economical indexing when Q&A conversion is canceled and switches only after confirmation', async () => {
|
||||
const { user } = await setup()
|
||||
const economy = screen.getByRole('radio', { name: 'datasetCreation.stepTwo.economical' })
|
||||
await user.click(economy)
|
||||
const qa = screen.getByRole('checkbox', { name: /stepTwo.useQALanguage/ })
|
||||
await user.click(qa)
|
||||
let dialog = await screen.findByRole('alertdialog')
|
||||
await user.click(within(dialog).getByRole('button', { name: 'datasetCreation.stepTwo.cancel' }))
|
||||
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
|
||||
expect(economy).toBeChecked()
|
||||
expect(qa).not.toBeChecked()
|
||||
await user.click(qa)
|
||||
dialog = await screen.findByRole('alertdialog')
|
||||
await user.click(within(dialog).getByRole('button', { name: 'datasetCreation.stepTwo.switch' }))
|
||||
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
|
||||
expect(screen.getByRole('radio', { name: /stepTwo.qualified/ })).toBeChecked()
|
||||
expect(qa).toBeChecked()
|
||||
})
|
||||
|
||||
it('cancels document rule edits without submitting them', async () => {
|
||||
const { user, onCancel } = await setup(
|
||||
{ isSetting: true, documentDetail: document },
|
||||
createDatasetFixture(),
|
||||
)
|
||||
const length = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.maxLength' })
|
||||
await user.clear(length)
|
||||
await user.type(length, '700')
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.cancel' }))
|
||||
expect(onCancel).toHaveBeenCalledOnce()
|
||||
expect(api.save).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
source: 'files with the same name',
|
||||
props: {
|
||||
files: [
|
||||
{ id: 'file-1', name: 'handbook.pdf', extension: 'pdf' },
|
||||
{ id: 'file-2', name: 'handbook.pdf', extension: 'pdf' },
|
||||
],
|
||||
},
|
||||
firstName: 'handbook.pdf',
|
||||
nextName: 'handbook.pdf',
|
||||
optionIndex: 1,
|
||||
info: { data_source_type: DataSourceType.FILE, file_info_list: { file_ids: ['file-2'] } },
|
||||
},
|
||||
{
|
||||
source: 'Notion pages',
|
||||
props: {
|
||||
dataSourceType: DataSourceType.NOTION,
|
||||
files: [],
|
||||
notionCredentialId: 'credential-1',
|
||||
notionPages: [
|
||||
{
|
||||
page_id: 'page-1',
|
||||
page_name: 'Guide',
|
||||
page_icon: null,
|
||||
type: 'page',
|
||||
workspace_id: 'workspace-1',
|
||||
},
|
||||
{
|
||||
page_id: 'page-2',
|
||||
page_name: 'Reference',
|
||||
page_icon: null,
|
||||
type: 'page',
|
||||
workspace_id: 'workspace-1',
|
||||
},
|
||||
],
|
||||
},
|
||||
firstName: 'Guide',
|
||||
nextName: 'Reference',
|
||||
optionIndex: 0,
|
||||
info: {
|
||||
data_source_type: DataSourceType.NOTION,
|
||||
notion_info_list: [
|
||||
{
|
||||
credential_id: 'credential-1',
|
||||
workspace_id: 'workspace-1',
|
||||
pages: [expect.objectContaining({ page_id: 'page-2' })],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
source: 'crawled pages',
|
||||
props: {
|
||||
dataSourceType: DataSourceType.WEB,
|
||||
files: [],
|
||||
websiteCrawlProvider: DataSourceProvider.jinaReader,
|
||||
websiteCrawlJobId: 'job-1',
|
||||
websitePages: [
|
||||
{
|
||||
source_url: 'https://example.com/guide',
|
||||
title: 'Guide',
|
||||
markdown: 'Guide content',
|
||||
description: '',
|
||||
},
|
||||
{
|
||||
source_url: 'https://example.com/reference',
|
||||
title: 'Reference',
|
||||
markdown: 'Reference content',
|
||||
description: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
firstName: 'Guide',
|
||||
nextName: 'Reference',
|
||||
optionIndex: 0,
|
||||
info: {
|
||||
data_source_type: DataSourceType.WEB,
|
||||
website_info_list: expect.objectContaining({
|
||||
provider: DataSourceProvider.jinaReader,
|
||||
job_id: 'job-1',
|
||||
urls: ['https://example.com/reference'],
|
||||
}),
|
||||
},
|
||||
},
|
||||
])(
|
||||
'previews the newly selected document among $source',
|
||||
async ({ props, firstName, nextName, optionIndex, info }) => {
|
||||
const { user } = await setup(props)
|
||||
expect(screen.getByText('datasetCreation.stepTwo.previewChunkTip')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' }))
|
||||
expect(await screen.findByText('Previewed chunk')).toBeInTheDocument()
|
||||
|
||||
const pending = createDeferred<Awaited<ReturnType<typeof api.estimate>>>()
|
||||
api.estimate.mockReturnValueOnce(pending.promise)
|
||||
await user.click(screen.getByRole('button', { name: firstName }))
|
||||
const picker = await screen.findByRole('dialog')
|
||||
const option = within(picker).getAllByRole('button', { name: nextName })[optionIndex]
|
||||
assert(option)
|
||||
await user.click(option)
|
||||
await waitFor(() =>
|
||||
expect(api.estimate).toHaveBeenLastCalledWith({
|
||||
body: expect.objectContaining({ info_list: info }),
|
||||
}),
|
||||
)
|
||||
expect(screen.getByRole('button', { name: nextName })).toBeInTheDocument()
|
||||
expect(screen.getByText('common.loading').closest('[role="status"]')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Previewed chunk')).not.toBeInTheDocument()
|
||||
await act(async () =>
|
||||
pending.resolve({
|
||||
total_segments: 1,
|
||||
tokens: 200,
|
||||
total_price: 0.02,
|
||||
currency: 'USD',
|
||||
preview: [{ content: 'Selected document chunk' }],
|
||||
}),
|
||||
)
|
||||
expect(await screen.findByText('Selected document chunk')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' }))
|
||||
expect(api.estimate).toHaveBeenLastCalledWith({
|
||||
body: expect.objectContaining({ info_list: info }),
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'overlap beyond the chunk length',
|
||||
field: 'overlap',
|
||||
value: '600',
|
||||
message: 'overlapCheck',
|
||||
corrected: '40',
|
||||
},
|
||||
{
|
||||
name: 'chunk length beyond the server limit',
|
||||
field: 'maxLength',
|
||||
value: '900',
|
||||
message: 'maxLengthCheck:{"limit":800}',
|
||||
corrected: '700',
|
||||
},
|
||||
])('rejects $name and submits after correction', async ({ field, value, message, corrected }) => {
|
||||
api.rules.mockResolvedValue({
|
||||
...defaultRules,
|
||||
limits: { indexing_max_segmentation_tokens_length: 800 },
|
||||
})
|
||||
const { user } = await setup()
|
||||
const input = screen.getByRole('textbox', { name: `datasetCreation.stepTwo.${field}` })
|
||||
await user.clear(input)
|
||||
await user.type(input, value)
|
||||
const next = screen.getByRole('button', { name: 'datasetCreation.stepTwo.nextStep' })
|
||||
await user.click(next)
|
||||
expect(await screen.findByText(`datasetCreation.stepTwo.${message}`)).toBeInTheDocument()
|
||||
expect(api.create).not.toHaveBeenCalled()
|
||||
await user.clear(input)
|
||||
await user.type(input, corrected)
|
||||
await user.click(next)
|
||||
await waitFor(() => expect(api.create).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('requires an embedding model for high-quality indexing but permits economical indexing', async () => {
|
||||
const { user } = await setup({ isAPIKeySet: false }, undefined, { embedding: false })
|
||||
await user.click(screen.getByRole('radio', { name: /stepTwo.qualified/ }))
|
||||
const next = screen.getByRole('button', { name: 'datasetCreation.stepTwo.nextStep' })
|
||||
await user.click(next)
|
||||
expect(
|
||||
await screen.findByText('appDebug.datasetConfig.embeddingModelRequired'),
|
||||
).toBeInTheDocument()
|
||||
expect(api.create).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole('radio', { name: 'datasetCreation.stepTwo.economical' }))
|
||||
await user.click(next)
|
||||
await waitFor(() => expect(api.create).toHaveBeenCalledOnce())
|
||||
expect(api.create).toHaveBeenCalledWith({
|
||||
body: expect.objectContaining({ indexing_technique: 'economy' }),
|
||||
})
|
||||
})
|
||||
|
||||
it('requires a rerank model when hybrid search uses model reranking', async () => {
|
||||
const { user } = await setup({}, undefined, { rerank: false })
|
||||
await user.click(screen.getByRole('radio', { name: 'dataset.retrieval.hybrid_search.title' }))
|
||||
await user.click(
|
||||
screen.getByRole('radio', { name: /^modelProvider.modelProvider.rerankModel.key/ }),
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.nextStep' }))
|
||||
expect(await screen.findByText('appDebug.datasetConfig.rerankModelRequired')).toBeInTheDocument()
|
||||
expect(api.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('serializes edited delimiters and cleaning rules, then restores server defaults on reset', async () => {
|
||||
const { user } = await setup()
|
||||
const delimiter = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.separator' })
|
||||
await user.clear(delimiter)
|
||||
await user.type(delimiter, String.raw`\n---\n`)
|
||||
const removeSpaces = screen.getByRole('checkbox', {
|
||||
name: 'datasetCreation.stepTwo.removeExtraSpaces',
|
||||
})
|
||||
const removeUrls = screen.getByRole('checkbox', {
|
||||
name: 'datasetCreation.stepTwo.removeUrlEmails',
|
||||
})
|
||||
await user.click(removeSpaces)
|
||||
await user.click(removeUrls)
|
||||
const preview = screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' })
|
||||
await user.click(preview)
|
||||
expect(api.estimate).toHaveBeenLastCalledWith({
|
||||
body: expect.objectContaining({
|
||||
process_rule: expect.objectContaining({
|
||||
rules: {
|
||||
segmentation: { separator: '\n---\n', max_tokens: 500, chunk_overlap: 50 },
|
||||
pre_processing_rules: [
|
||||
{ id: 'remove_extra_spaces', enabled: false },
|
||||
{ id: 'remove_urls_emails', enabled: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.reset' }))
|
||||
expect(delimiter).toHaveValue(String.raw`\n`)
|
||||
expect(removeSpaces).toBeChecked()
|
||||
expect(removeUrls).not.toBeChecked()
|
||||
await user.click(preview)
|
||||
expect(api.estimate).toHaveBeenLastCalledWith({
|
||||
body: expect.objectContaining({
|
||||
process_rule: expect.objectContaining({
|
||||
rules: expect.objectContaining({
|
||||
segmentation: { separator: '\n', max_tokens: 500, chunk_overlap: 50 },
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
await user.click(screen.getByRole('radio', { name: 'datasetCreation.stepTwo.parentChild' }))
|
||||
expect(screen.queryByText('Previewed chunk')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('datasetCreation.stepTwo.previewChunkTip')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the existing dataset retrieval configuration when saving document chunking rules', async () => {
|
||||
const retrieval: DatasetRetrievalModelResponse = {
|
||||
search_method: 'full_text_search',
|
||||
reranking_enable: false,
|
||||
reranking_model: { reranking_provider_name: '', reranking_model_name: '' },
|
||||
top_k: 5,
|
||||
score_threshold_enabled: true,
|
||||
score_threshold: 0.8,
|
||||
}
|
||||
const { user } = await setup(
|
||||
{ isSetting: true, documentDetail: document, indexingType: 'economy' },
|
||||
createDatasetFixture({ indexing_technique: 'economy', retrieval_model_dict: retrieval }),
|
||||
)
|
||||
expect(screen.queryByRole('radio', { name: /stepTwo.qualified/ })).not.toBeInTheDocument()
|
||||
const length = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.maxLength' })
|
||||
await user.clear(length)
|
||||
await user.type(length, '700')
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.save' }))
|
||||
await waitFor(() => expect(api.save).toHaveBeenCalledOnce())
|
||||
expect(api.save).toHaveBeenCalledWith({
|
||||
params: { dataset_id: 'dataset-1' },
|
||||
body: expect.objectContaining({ indexing_technique: 'economy', retrieval_model: retrieval }),
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes parent and child chunk edits and restores both configurations on reset', async () => {
|
||||
const { user } = await setup()
|
||||
await user.click(screen.getByRole('radio', { name: 'datasetCreation.stepTwo.parentChild' }))
|
||||
const [parentDelimiter, childDelimiter] = screen.getAllByRole('textbox', {
|
||||
name: 'datasetCreation.stepTwo.separator',
|
||||
})
|
||||
assert(parentDelimiter && childDelimiter)
|
||||
await user.clear(parentDelimiter)
|
||||
await user.type(parentDelimiter, String.raw`\n---\n`)
|
||||
await user.clear(childDelimiter)
|
||||
await user.type(childDelimiter, ';')
|
||||
const [parentLength, childLength] = screen.getAllByRole('textbox', {
|
||||
name: 'datasetCreation.stepTwo.maxLength',
|
||||
})
|
||||
assert(parentLength && childLength)
|
||||
await user.clear(parentLength)
|
||||
await user.type(parentLength, '900')
|
||||
await user.clear(childLength)
|
||||
await user.type(childLength, '200')
|
||||
await user.click(
|
||||
screen.getByRole('checkbox', { name: 'datasetCreation.stepTwo.removeUrlEmails' }),
|
||||
)
|
||||
const preview = screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' })
|
||||
await user.click(preview)
|
||||
expect(api.estimate).toHaveBeenLastCalledWith({
|
||||
body: expect.objectContaining({
|
||||
doc_form: ChunkingMode.parentChild,
|
||||
process_rule: expect.objectContaining({
|
||||
mode: 'hierarchical',
|
||||
rules: {
|
||||
parent_mode: 'paragraph',
|
||||
segmentation: { separator: '\n---\n', max_tokens: 900 },
|
||||
subchunk_segmentation: { separator: ';', max_tokens: 200 },
|
||||
pre_processing_rules: [
|
||||
{ id: 'remove_extra_spaces', enabled: true },
|
||||
{ id: 'remove_urls_emails', enabled: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
})
|
||||
await user.click(screen.getByRole('radio', { name: /^datasetCreation.stepTwo.fullDoc/ }))
|
||||
await user.click(preview)
|
||||
expect(api.estimate).toHaveBeenLastCalledWith({
|
||||
body: expect.objectContaining({
|
||||
process_rule: expect.objectContaining({
|
||||
rules: expect.objectContaining({ parent_mode: 'full-doc' }),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.reset' }))
|
||||
expect(screen.getByRole('radio', { name: /^datasetCreation.stepTwo.paragraph/ })).toBeChecked()
|
||||
const resetLengths = screen.getAllByRole('textbox', { name: 'datasetCreation.stepTwo.maxLength' })
|
||||
expect(resetLengths[0]).toHaveValue('1,024')
|
||||
expect(resetLengths[1]).toHaveValue('512')
|
||||
await user.click(preview)
|
||||
expect(api.estimate).toHaveBeenLastCalledWith({
|
||||
body: expect.objectContaining({
|
||||
process_rule: expect.objectContaining({
|
||||
rules: expect.objectContaining({
|
||||
parent_mode: 'paragraph',
|
||||
segmentation: { separator: '\n\n', max_tokens: 1024 },
|
||||
subchunk_segmentation: { separator: '\n', max_tokens: 512 },
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
it('includes the chosen summary model and instructions in preview and creation requests', async () => {
|
||||
const { user } = await setup()
|
||||
await user.click(screen.getByRole('switch', { name: 'datasetSettings.form.summaryAutoGen' }))
|
||||
await user.click(
|
||||
screen.getByRole('button', {
|
||||
name: 'datasetSettings.form.summaryModel plugin.detailPanel.configureModel',
|
||||
}),
|
||||
)
|
||||
const picker = await screen.findByRole('dialog', { name: 'plugin.detailPanel.configureModel' })
|
||||
await user.click(within(picker).getByText('GPT-4'))
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'datasetSettings.form.summaryInstructions' }),
|
||||
'Summarize key decisions',
|
||||
)
|
||||
const summary = {
|
||||
enable: true,
|
||||
model_provider_name: 'openai',
|
||||
model_name: 'gpt-4',
|
||||
summary_prompt: 'Summarize key decisions',
|
||||
}
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' }))
|
||||
expect(api.estimate).toHaveBeenCalledWith({
|
||||
body: expect.objectContaining({
|
||||
process_rule: expect.objectContaining({ summary_index_setting: summary }),
|
||||
}),
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.nextStep' }))
|
||||
await waitFor(() => expect(api.create).toHaveBeenCalledOnce())
|
||||
expect(api.create).toHaveBeenCalledWith({
|
||||
body: expect.objectContaining({ summary_index_setting: summary }),
|
||||
})
|
||||
})
|
||||
|
||||
it('restores stored parent-child rules and saves edited child chunking', async () => {
|
||||
const { user } = await setup(
|
||||
{
|
||||
isSetting: true,
|
||||
documentDetail: {
|
||||
...document,
|
||||
doc_form: ChunkingMode.parentChild,
|
||||
dataset_process_rule: {
|
||||
mode: 'hierarchical',
|
||||
rules: {
|
||||
parent_mode: 'paragraph',
|
||||
segmentation: { separator: String.raw`\n---\n`, max_tokens: 900 },
|
||||
subchunk_segmentation: { separator: ';', max_tokens: 200 },
|
||||
pre_processing_rules: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
createDatasetFixture({ doc_form: ChunkingMode.parentChild }),
|
||||
)
|
||||
const delimiters = screen.getAllByRole('textbox', { name: 'datasetCreation.stepTwo.separator' })
|
||||
expect(delimiters[0]).toHaveValue(String.raw`\n---\n`)
|
||||
expect(delimiters[1]).toHaveValue(';')
|
||||
const [parentLength, childLength] = screen.getAllByRole('textbox', {
|
||||
name: 'datasetCreation.stepTwo.maxLength',
|
||||
})
|
||||
assert(childLength)
|
||||
expect(parentLength).toHaveValue('900')
|
||||
expect(childLength).toHaveValue('200')
|
||||
await user.clear(childLength)
|
||||
await user.type(childLength, '180')
|
||||
await user.click(screen.getByRole('button', { name: 'datasetCreation.stepTwo.save' }))
|
||||
await waitFor(() => expect(api.save).toHaveBeenCalledOnce())
|
||||
expect(api.save).toHaveBeenCalledWith({
|
||||
params: { dataset_id: 'dataset-1' },
|
||||
body: expect.objectContaining({
|
||||
original_document_id: 'doc-1',
|
||||
doc_form: ChunkingMode.parentChild,
|
||||
process_rule: expect.objectContaining({
|
||||
mode: 'hierarchical',
|
||||
rules: expect.objectContaining({
|
||||
segmentation: { separator: '\n---\n', max_tokens: 900 },
|
||||
subchunk_segmentation: { separator: ';', max_tokens: 180 },
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
})
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import { isProcessMode, toSegmentationRules } from '../process-rule'
|
||||
|
||||
describe('toSegmentationRules', () => {
|
||||
it('should restore stored segmentation with the backend defaults', () => {
|
||||
expect(
|
||||
toSegmentationRules({
|
||||
pre_processing_rules: [
|
||||
{ id: 'remove_extra_spaces', enabled: true },
|
||||
{ id: 'legacy_rule', enabled: true },
|
||||
],
|
||||
segmentation: { max_tokens: 500 },
|
||||
parent_mode: 'paragraph',
|
||||
subchunk_segmentation: { separator: '\n', max_tokens: 200, chunk_overlap: 10 },
|
||||
}),
|
||||
).toEqual({
|
||||
pre_processing_rules: [{ id: 'remove_extra_spaces', enabled: true }],
|
||||
segmentation: { separator: '\n', max_tokens: 500, chunk_overlap: 0 },
|
||||
parent_mode: 'paragraph',
|
||||
subchunk_segmentation: { separator: '\n', max_tokens: 200, chunk_overlap: 10 },
|
||||
})
|
||||
})
|
||||
|
||||
it('should restore nothing for automatic rules without segmentation', () => {
|
||||
expect(toSegmentationRules({ pre_processing_rules: null })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isProcessMode', () => {
|
||||
it('should accept only the editable process modes', () => {
|
||||
expect(isProcessMode('custom')).toBe(true)
|
||||
expect(isProcessMode('hierarchical')).toBe(true)
|
||||
expect(isProcessMode('automatic')).toBe(false)
|
||||
})
|
||||
})
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { DelimiterInput, MaxLengthInput, OverlapInput } from '../inputs'
|
||||
|
||||
describe('DelimiterInput', () => {
|
||||
it('commits the delimiter only after IME composition ends', () => {
|
||||
const onValueChange = vi.fn()
|
||||
render(<DelimiterInput value="" onValueChange={onValueChange} />)
|
||||
const input = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.separator' })
|
||||
|
||||
fireEvent.compositionStart(input)
|
||||
fireEvent.change(input, { target: { value: 'w' } })
|
||||
fireEvent.change(input, { target: { value: '文' } })
|
||||
expect(onValueChange).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.compositionEnd(input)
|
||||
expect(onValueChange).toHaveBeenCalledExactlyOnceWith('文')
|
||||
})
|
||||
})
|
||||
|
||||
describe.each([
|
||||
{ Component: MaxLengthInput, label: 'datasetCreation.stepTwo.maxLength' },
|
||||
{ Component: OverlapInput, label: 'datasetCreation.stepTwo.overlap' },
|
||||
])('$label', ({ Component, label }) => {
|
||||
it('resets to the minimum when users clear the value', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<Component value={50} onChange={onChange} />)
|
||||
|
||||
await user.clear(screen.getByRole('textbox', { name: label }))
|
||||
expect(onChange).toHaveBeenLastCalledWith(1)
|
||||
})
|
||||
})
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import type { IndexingEstimateResponse } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useRef, useState } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { ChunkingMode, DataSourceType } from '@/models/datasets'
|
||||
import { PreviewPanel } from '../preview-panel'
|
||||
|
||||
const estimateBase: IndexingEstimateResponse = {
|
||||
currency: 'USD',
|
||||
tokens: 0,
|
||||
total_price: 0,
|
||||
total_segments: 0,
|
||||
preview: [],
|
||||
}
|
||||
|
||||
describe('PreviewPanel', () => {
|
||||
const defaultProps = {
|
||||
isMobile: false,
|
||||
isOpen: false,
|
||||
onClose: vi.fn(),
|
||||
dataSourceType: DataSourceType.FILE,
|
||||
currentDocForm: ChunkingMode.text,
|
||||
parentChildConfig: {
|
||||
chunkForContext: 'paragraph' as const,
|
||||
parent: { delimiter: '\\n\\n', maxLength: 2000 },
|
||||
child: { delimiter: '\\n', maxLength: 500 },
|
||||
},
|
||||
pickerFiles: [{ id: '1', name: 'file.pdf', extension: 'pdf' }],
|
||||
pickerValue: { id: '1', name: 'file.pdf', extension: 'pdf' },
|
||||
isIdle: false,
|
||||
isPending: false,
|
||||
onPickerChange: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('announces preview loading and completed chunk count through a persistent status', () => {
|
||||
const { rerender } = render(<PreviewPanel {...defaultProps} isPending />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('common.loading')
|
||||
rerender(<PreviewPanel {...defaultProps} estimate={{ ...estimateBase, total_segments: 3 }} />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent(
|
||||
'datasetCreation.stepTwo.previewChunkCount',
|
||||
)
|
||||
})
|
||||
|
||||
it('allows mobile preview to close, restore focus, and reopen', async () => {
|
||||
const user = userEvent.setup()
|
||||
const MobilePreview = () => {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
return (
|
||||
<>
|
||||
<button ref={triggerRef} type="button" onClick={() => setIsOpen(true)}>
|
||||
Preview chunks
|
||||
</button>
|
||||
<PreviewPanel
|
||||
{...defaultProps}
|
||||
isMobile
|
||||
isOpen={isOpen}
|
||||
onClose={() => setIsOpen(false)}
|
||||
finalFocus={triggerRef}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(<MobilePreview />)
|
||||
const trigger = screen.getByRole('button', { name: 'Preview chunks' })
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(trigger)
|
||||
const dialog = await screen.findByRole('dialog', { name: 'datasetCreation.stepTwo.preview' })
|
||||
await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
await waitFor(() => expect(trigger).toHaveFocus())
|
||||
|
||||
await user.keyboard('{Enter}')
|
||||
expect(
|
||||
await screen.findByRole('dialog', { name: 'datasetCreation.stepTwo.preview' }),
|
||||
).toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
await waitFor(() => expect(trigger).toHaveFocus())
|
||||
})
|
||||
|
||||
it('should show idle state when isIdle is true', () => {
|
||||
render(<PreviewPanel {...defaultProps} isIdle={true} />)
|
||||
expect(screen.getByText('datasetCreation.stepTwo.previewChunkTip')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render text preview chunks', () => {
|
||||
const estimate: IndexingEstimateResponse = {
|
||||
...estimateBase,
|
||||
total_segments: 2,
|
||||
preview: [
|
||||
{ content: 'chunk 1 text', child_chunks: [], summary: '' },
|
||||
{ content: 'chunk 2 text', child_chunks: [], summary: 'summary text' },
|
||||
],
|
||||
}
|
||||
render(<PreviewPanel {...defaultProps} estimate={estimate} />)
|
||||
expect(screen.getByText('chunk 1 text')).toBeInTheDocument()
|
||||
expect(screen.getByText('chunk 2 text')).toBeInTheDocument()
|
||||
expect(screen.getByText('summary text')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render QA preview', () => {
|
||||
const estimate: IndexingEstimateResponse = {
|
||||
...estimateBase,
|
||||
qa_preview: [{ question: 'Q1', answer: 'A1' }],
|
||||
}
|
||||
render(<PreviewPanel {...defaultProps} currentDocForm={ChunkingMode.qa} estimate={estimate} />)
|
||||
expect(screen.getByText('Q1')).toBeInTheDocument()
|
||||
expect(screen.getByText('A1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render parent-child preview', () => {
|
||||
const estimate: IndexingEstimateResponse = {
|
||||
...estimateBase,
|
||||
preview: [{ content: 'parent chunk', child_chunks: ['child1', 'child2'], summary: '' }],
|
||||
}
|
||||
render(
|
||||
<PreviewPanel
|
||||
{...defaultProps}
|
||||
currentDocForm={ChunkingMode.parentChild}
|
||||
estimate={estimate}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('child1')).toBeInTheDocument()
|
||||
expect(screen.getByText('child2')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
'use client'
|
||||
|
||||
import type { PreProcessingRule } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { FC, MouseEventHandler } from 'react'
|
||||
import type { SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets'
|
||||
import { Alert, AlertTitle } from '@langgenius/dify-ui/alert'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Checkbox } from '@langgenius/dify-ui/checkbox'
|
||||
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { RiSearchEyeLine } from '@remixicon/react'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useId } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import SummaryIndexSetting from '@/app/components/datasets/settings/summary-index-setting'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
import { ChunkingMode } from '@/models/datasets'
|
||||
import SettingCog from '../../assets/setting-gear-mod.svg'
|
||||
import s from '../index.module.css'
|
||||
import LanguageSelect from '../language-select'
|
||||
import { DelimiterInput, MaxLengthInput, OverlapInput } from './inputs'
|
||||
import { OptionCard } from './option-card'
|
||||
|
||||
type TextLabelProps = {
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
const TextLabel: FC<TextLabelProps> = ({ children }) => {
|
||||
return <label className="system-sm-semibold text-text-secondary">{children}</label>
|
||||
}
|
||||
|
||||
type GeneralChunkingOptionsProps = {
|
||||
// State
|
||||
segmentIdentifier: string
|
||||
maxChunkLength: number
|
||||
overlap: number
|
||||
rules: PreProcessingRule[]
|
||||
currentDocForm: ChunkingMode
|
||||
docLanguage: string
|
||||
// Flags
|
||||
isActive: boolean
|
||||
isInUpload: boolean
|
||||
isNotUploadInEmptyDataset: boolean
|
||||
hasCurrentDatasetDocForm: boolean
|
||||
// Actions
|
||||
onSegmentIdentifierChange: (value: string) => void
|
||||
onMaxChunkLengthChange: (value: number) => void
|
||||
onOverlapChange: (value: number) => void
|
||||
onRuleToggle: (id: string) => void
|
||||
onDocFormChange: (form: ChunkingMode) => void
|
||||
onDocLanguageChange: (lang: string) => void
|
||||
onPreview: MouseEventHandler<HTMLButtonElement>
|
||||
onReset: () => void
|
||||
// Locale
|
||||
locale: string
|
||||
showSummaryIndexSetting?: boolean
|
||||
summaryIndexSetting?: SummaryIndexSettingType
|
||||
onSummaryIndexSettingChange?: (payload: SummaryIndexSettingType) => void
|
||||
}
|
||||
|
||||
export const GeneralChunkingOptions: FC<GeneralChunkingOptionsProps> = ({
|
||||
segmentIdentifier,
|
||||
maxChunkLength,
|
||||
overlap,
|
||||
rules,
|
||||
currentDocForm,
|
||||
docLanguage,
|
||||
isActive,
|
||||
isInUpload,
|
||||
isNotUploadInEmptyDataset,
|
||||
hasCurrentDatasetDocForm,
|
||||
onSegmentIdentifierChange,
|
||||
onMaxChunkLengthChange,
|
||||
onOverlapChange,
|
||||
onRuleToggle,
|
||||
onDocFormChange,
|
||||
onDocLanguageChange,
|
||||
onPreview,
|
||||
onReset,
|
||||
locale,
|
||||
showSummaryIndexSetting,
|
||||
summaryIndexSetting,
|
||||
onSummaryIndexSettingChange,
|
||||
}) => {
|
||||
const qaLabelId = useId()
|
||||
|
||||
const { t } = useTranslation(['datasetCreation'])
|
||||
const { data: deploymentEdition } = useSuspenseQuery({
|
||||
...systemFeaturesQueryOptions(),
|
||||
select: ({ deployment_edition }) => deployment_edition,
|
||||
})
|
||||
const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'
|
||||
|
||||
const getRuleName = (key: string): string => {
|
||||
const ruleNameMap: Record<string, string> = {
|
||||
remove_extra_spaces: t(($) => $['stepTwo.removeExtraSpaces'], { ns: 'datasetCreation' }),
|
||||
remove_urls_emails: t(($) => $['stepTwo.removeUrlEmails'], { ns: 'datasetCreation' }),
|
||||
remove_stopwords: t(($) => $['stepTwo.removeStopwords'], { ns: 'datasetCreation' }),
|
||||
}
|
||||
return ruleNameMap[key] ?? key
|
||||
}
|
||||
|
||||
return (
|
||||
<OptionCard
|
||||
className="mb-2 bg-background-section"
|
||||
title={t(($) => $['stepTwo.general'], { ns: 'datasetCreation' })}
|
||||
icon={
|
||||
<img
|
||||
width={20}
|
||||
height={20}
|
||||
src={SettingCog.src}
|
||||
alt={t(($) => $['stepTwo.general'], { ns: 'datasetCreation' })}
|
||||
/>
|
||||
}
|
||||
activeHeaderClassName="bg-dataset-option-card-blue-gradient"
|
||||
description={t(($) => $['stepTwo.generalTip'], { ns: 'datasetCreation' })}
|
||||
isActive={isActive}
|
||||
value={ChunkingMode.text}
|
||||
actions={
|
||||
<>
|
||||
<Button variant="secondary-accent" onClick={onPreview}>
|
||||
<RiSearchEyeLine className="size-4" />
|
||||
{t(($) => $['stepTwo.previewChunk'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onReset}>
|
||||
{t(($) => $['stepTwo.reset'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
noHighlight={isInUpload && isNotUploadInEmptyDataset}
|
||||
>
|
||||
<div className="@container/chunkfields flex flex-col gap-y-4">
|
||||
{/* Container query, not a viewport breakpoint: three across at/above a
|
||||
552px container, stacked one-per-row below (see inputs.tsx FormField). */}
|
||||
<div className="flex flex-col gap-3 @min-[552px]/chunkfields:flex-row">
|
||||
<DelimiterInput value={segmentIdentifier} onValueChange={onSegmentIdentifierChange} />
|
||||
<MaxLengthInput
|
||||
unit="characters"
|
||||
value={maxChunkLength}
|
||||
onChange={onMaxChunkLengthChange}
|
||||
/>
|
||||
<OverlapInput unit="characters" value={overlap} min={1} onChange={onOverlapChange} />
|
||||
</div>
|
||||
<div className="flex w-full flex-col">
|
||||
<div className="flex items-center gap-x-2">
|
||||
<div className="inline-flex shrink-0">
|
||||
<TextLabel>{t(($) => $['stepTwo.rules'], { ns: 'datasetCreation' })}</TextLabel>
|
||||
</div>
|
||||
<Separator decorative className="my-2 h-[0.5px] grow" variant="gradient" />
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
{rules.map((rule) => (
|
||||
<label key={rule.id} className={`${s.ruleItem} cursor-pointer`}>
|
||||
<Checkbox checked={rule.enabled} onCheckedChange={() => onRuleToggle(rule.id)} />
|
||||
<span className="ml-2 system-sm-regular text-text-secondary">
|
||||
{getRuleName(rule.id)}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
{showSummaryIndexSetting && isNonCloudEdition && (
|
||||
<div className="mt-3">
|
||||
<SummaryIndexSetting
|
||||
entry="create-document"
|
||||
summaryIndexSetting={summaryIndexSetting}
|
||||
onSummaryIndexSettingChange={onSummaryIndexSettingChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{isNonCloudEdition && (
|
||||
<>
|
||||
<Separator orientation="horizontal" className="my-4 h-[0.5px] bg-divider-subtle" />
|
||||
<div className="flex flex-wrap items-center gap-y-2 py-0.5">
|
||||
<label
|
||||
className={`flex items-center ${hasCurrentDatasetDocForm ? '' : 'cursor-pointer'}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={currentDocForm === ChunkingMode.qa}
|
||||
disabled={hasCurrentDatasetDocForm}
|
||||
onCheckedChange={() => {
|
||||
if (hasCurrentDatasetDocForm) return
|
||||
if (currentDocForm === ChunkingMode.qa) onDocFormChange(ChunkingMode.text)
|
||||
else onDocFormChange(ChunkingMode.qa)
|
||||
}}
|
||||
/>
|
||||
<span id={qaLabelId} className="ml-2 system-sm-regular text-text-secondary">
|
||||
{t(($) => $['stepTwo.useQALanguage'], { ns: 'datasetCreation' })}
|
||||
</span>
|
||||
</label>
|
||||
<LanguageSelect
|
||||
currentLanguage={docLanguage || locale}
|
||||
onSelect={onDocLanguageChange}
|
||||
disabled={currentDocForm !== ChunkingMode.qa}
|
||||
/>
|
||||
<Infotip>
|
||||
<InfotipTrigger aria-labelledby={qaLabelId} className="size-3.5" />
|
||||
<InfotipContent aria-labelledby={qaLabelId}>
|
||||
{t(($) => $['stepTwo.QATip'], { ns: 'datasetCreation' })}
|
||||
</InfotipContent>
|
||||
</Infotip>
|
||||
</div>
|
||||
{currentDocForm === ChunkingMode.qa && (
|
||||
<Alert type="warning" className="mt-2">
|
||||
<AlertTitle>
|
||||
{t(($) => $['stepTwo.QATip'], { ns: 'datasetCreation' })}
|
||||
</AlertTitle>
|
||||
</Alert>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</OptionCard>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { GeneralChunkingOptions } from './general-chunking-options'
|
||||
export { IndexingModeSection } from './indexing-mode-section'
|
||||
export { ParentChildOptions } from './parent-child-options'
|
||||
export { PreviewPanel } from './preview-panel'
|
||||
export { StepTwoFooter } from './step-two-footer'
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
'use client'
|
||||
import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { FC } from 'react'
|
||||
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { RetrievalConfig } from '@/types/app'
|
||||
import { Alert, AlertTitle } from '@langgenius/dify-ui/alert'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancelButton,
|
||||
AlertDialogConfirmButton,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@langgenius/dify-ui/alert-dialog'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RadioGroup } from '@langgenius/dify-ui/radio-group'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Badge from '@/app/components/base/badge'
|
||||
import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/economical-retrieval-method-config'
|
||||
import {
|
||||
MultimodalRetrievalGuidance,
|
||||
MultimodalRetrievalGuidanceLearnMore,
|
||||
} from '@/app/components/datasets/common/multimodal-retrieval-guidance'
|
||||
import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'
|
||||
import { ModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector'
|
||||
import { useDocLink } from '@/context/i18n'
|
||||
import { ChunkingMode } from '@/models/datasets'
|
||||
import Link from '@/next/link'
|
||||
import { indexMethodIcon } from '../../icons'
|
||||
import { IndexingType } from '../hooks'
|
||||
import s from '../index.module.css'
|
||||
import { OptionCard } from './option-card'
|
||||
|
||||
type IndexingModeSectionProps = {
|
||||
// State
|
||||
indexType: IndexingType
|
||||
hasSetIndexType: boolean
|
||||
docForm: ChunkingMode
|
||||
embeddingModel: DefaultModel
|
||||
embeddingModelList?: ProviderWithModelsResponse[]
|
||||
retrievalConfig: RetrievalConfig
|
||||
showMultiModalTip: boolean
|
||||
// Flags
|
||||
isModelAndRetrievalConfigDisabled: boolean
|
||||
datasetId?: string
|
||||
// Modal state
|
||||
isQAConfirmDialogOpen: boolean
|
||||
// Actions
|
||||
onIndexTypeChange: (type: IndexingType) => void
|
||||
onEmbeddingModelChange: (model: DefaultModel) => void
|
||||
onRetrievalConfigChange: (config: RetrievalConfig) => void
|
||||
onQAConfirmDialogClose: () => void
|
||||
onQAConfirmDialogConfirm: () => void
|
||||
}
|
||||
|
||||
export const IndexingModeSection: FC<IndexingModeSectionProps> = ({
|
||||
indexType,
|
||||
hasSetIndexType,
|
||||
docForm,
|
||||
embeddingModel,
|
||||
embeddingModelList,
|
||||
retrievalConfig,
|
||||
showMultiModalTip,
|
||||
isModelAndRetrievalConfigDisabled,
|
||||
datasetId,
|
||||
isQAConfirmDialogOpen,
|
||||
onIndexTypeChange,
|
||||
onEmbeddingModelChange,
|
||||
onRetrievalConfigChange,
|
||||
onQAConfirmDialogClose,
|
||||
onQAConfirmDialogConfirm,
|
||||
}) => {
|
||||
const { t } = useTranslation(['datasetCreation', 'datasetSettings'])
|
||||
const docLink = useDocLink()
|
||||
|
||||
const getIndexingTechnique = () => indexType
|
||||
const economicalDisabledReason = (() => {
|
||||
if (docForm === ChunkingMode.qa)
|
||||
return t(($) => $['stepTwo.notAvailableForQA'], { ns: 'datasetCreation' })
|
||||
|
||||
if (docForm !== ChunkingMode.text)
|
||||
return t(($) => $['stepTwo.notAvailableForParentChild'], { ns: 'datasetCreation' })
|
||||
})()
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Index Mode */}
|
||||
<h2 className="mb-1 system-md-semibold text-text-secondary">
|
||||
{t(($) => $['stepTwo.indexMode'], { ns: 'datasetCreation' })}
|
||||
</h2>
|
||||
<AlertDialog
|
||||
open={isQAConfirmDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onQAConfirmDialogClose()
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t(($) => $['stepTwo.qaSwitchHighQualityTipTitle'], { ns: 'datasetCreation' })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t(($) => $['stepTwo.qaSwitchHighQualityTipContent'], { ns: 'datasetCreation' })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancelButton>
|
||||
{t(($) => $['stepTwo.cancel'], { ns: 'datasetCreation' })}
|
||||
</AlertDialogCancelButton>
|
||||
<AlertDialogConfirmButton tone="default" onClick={onQAConfirmDialogConfirm}>
|
||||
{t(($) => $['stepTwo.switch'], { ns: 'datasetCreation' })}
|
||||
</AlertDialogConfirmButton>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<RadioGroup<IndexingType>
|
||||
aria-label={t(($) => $['stepTwo.indexMode'], { ns: 'datasetCreation' })}
|
||||
value={indexType}
|
||||
onValueChange={onIndexTypeChange}
|
||||
className="flex flex-col items-stretch gap-2 @min-[552px]/chunkfields:flex-row"
|
||||
>
|
||||
{/* Qualified option */}
|
||||
{(!hasSetIndexType || (hasSetIndexType && indexType === IndexingType.QUALIFIED)) && (
|
||||
<OptionCard
|
||||
className="flex-1 self-stretch"
|
||||
title={
|
||||
<div className="flex flex-wrap items-center gap-y-1">
|
||||
{t(($) => $['stepTwo.qualified'], { ns: 'datasetCreation' })}
|
||||
<Badge
|
||||
className={cn(
|
||||
'ml-1 h-4.5',
|
||||
!hasSetIndexType && indexType === IndexingType.QUALIFIED
|
||||
? 'border-text-accent-secondary text-text-accent-secondary'
|
||||
: '',
|
||||
)}
|
||||
uppercase
|
||||
>
|
||||
{t(($) => $['stepTwo.recommend'], { ns: 'datasetCreation' })}
|
||||
</Badge>
|
||||
<span className="ml-auto">
|
||||
{!hasSetIndexType && <span className={cn(s.radio)} />}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
description={t(($) => $['stepTwo.qualifiedTip'], { ns: 'datasetCreation' })}
|
||||
icon={<img src={indexMethodIcon.high_quality} alt="" />}
|
||||
isActive={!hasSetIndexType && indexType === IndexingType.QUALIFIED}
|
||||
disabled={hasSetIndexType}
|
||||
value={IndexingType.QUALIFIED}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Economical option */}
|
||||
{(!hasSetIndexType || (hasSetIndexType && indexType === IndexingType.ECONOMICAL)) && (
|
||||
<OptionCard
|
||||
className="flex-1 self-stretch"
|
||||
title={t(($) => $['stepTwo.economical'], { ns: 'datasetCreation' })}
|
||||
description={
|
||||
economicalDisabledReason ||
|
||||
t(($) => $['stepTwo.economicalTip'], { ns: 'datasetCreation' })
|
||||
}
|
||||
icon={<img src={indexMethodIcon.economical} alt="" />}
|
||||
isActive={!hasSetIndexType && indexType === IndexingType.ECONOMICAL}
|
||||
disabled={hasSetIndexType || !!economicalDisabledReason}
|
||||
value={IndexingType.ECONOMICAL}
|
||||
/>
|
||||
)}
|
||||
</RadioGroup>
|
||||
|
||||
{/* High quality tip */}
|
||||
{!hasSetIndexType && indexType === IndexingType.QUALIFIED && (
|
||||
<Alert type="warning" className="mt-2">
|
||||
<AlertTitle>
|
||||
{t(($) => $['stepTwo.highQualityTip'], { ns: 'datasetCreation' })}
|
||||
</AlertTitle>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Economical index setting tip */}
|
||||
{hasSetIndexType && indexType === IndexingType.ECONOMICAL && (
|
||||
<div className="mt-2 system-xs-medium text-text-tertiary">
|
||||
{t(($) => $['stepTwo.indexSettingTip'], { ns: 'datasetCreation' })}
|
||||
<Link className="text-text-accent" href={`/datasets/${datasetId}/settings`}>
|
||||
{t(($) => $['stepTwo.datasetSettingLink'], { ns: 'datasetCreation' })}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Embedding model */}
|
||||
{indexType === IndexingType.QUALIFIED && (
|
||||
<div className="mt-5">
|
||||
<h2
|
||||
className={cn(
|
||||
'mb-1 system-md-semibold text-text-secondary',
|
||||
datasetId && 'flex items-center justify-between',
|
||||
)}
|
||||
>
|
||||
{t(($) => $['form.embeddingModel'], { ns: 'datasetSettings' })}
|
||||
</h2>
|
||||
<MultimodalRetrievalGuidanceLearnMore className="mb-2" />
|
||||
<MultimodalRetrievalGuidance
|
||||
variant="create"
|
||||
embeddingModel={embeddingModel}
|
||||
embeddingModelList={embeddingModelList}
|
||||
className="mb-2"
|
||||
/>
|
||||
<ModelSelector
|
||||
disabled={isModelAndRetrievalConfigDisabled}
|
||||
value={embeddingModel}
|
||||
models={embeddingModelList ?? []}
|
||||
onValueChange={onEmbeddingModelChange}
|
||||
/>
|
||||
{isModelAndRetrievalConfigDisabled && (
|
||||
<div className="mt-2 system-xs-medium text-text-tertiary">
|
||||
{t(($) => $['stepTwo.indexSettingTip'], { ns: 'datasetCreation' })}
|
||||
<Link className="text-text-accent" href={`/datasets/${datasetId}/settings`}>
|
||||
{t(($) => $['stepTwo.datasetSettingLink'], { ns: 'datasetCreation' })}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator className="my-5 h-[0.5px]" />
|
||||
|
||||
{/* Retrieval Method Config */}
|
||||
<div>
|
||||
{!isModelAndRetrievalConfigDisabled ? (
|
||||
<div className="mb-1">
|
||||
<h2 className="mb-0.5 system-md-semibold text-text-secondary">
|
||||
{t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}
|
||||
</h2>
|
||||
<div className="body-xs-regular text-text-tertiary">
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')}
|
||||
className="text-text-accent"
|
||||
>
|
||||
{t(($) => $['form.retrievalSetting.learnMore'], { ns: 'datasetSettings' })}
|
||||
</a>
|
||||
{t(($) => $['form.retrievalSetting.longDescription'], { ns: 'datasetSettings' })}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
'mb-0.5 system-md-semibold text-text-secondary',
|
||||
'flex items-center justify-between',
|
||||
)}
|
||||
>
|
||||
<div>{t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
{getIndexingTechnique() === IndexingType.QUALIFIED ? (
|
||||
<RetrievalMethodConfig
|
||||
disabled={isModelAndRetrievalConfigDisabled}
|
||||
value={retrievalConfig}
|
||||
onChange={onRetrievalConfigChange}
|
||||
showMultiModalTip={showMultiModalTip}
|
||||
/>
|
||||
) : (
|
||||
<EconomicalRetrievalMethodConfig
|
||||
disabled={isModelAndRetrievalConfigDisabled}
|
||||
value={retrievalConfig}
|
||||
onChange={onRetrievalConfigChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { InputProps } from '@langgenius/dify-ui/input'
|
||||
import type {
|
||||
NumberFieldInputProps,
|
||||
NumberFieldProps,
|
||||
NumberFieldSize,
|
||||
} from '@langgenius/dify-ui/number-field'
|
||||
import type { FC, PropsWithChildren, ReactNode } from 'react'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
|
||||
import { Input } from '@langgenius/dify-ui/input'
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldControls,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldGroup,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
NumberFieldUnit,
|
||||
} from '@langgenius/dify-ui/number-field'
|
||||
import { useId, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { env } from '@/env'
|
||||
|
||||
const FormField: FC<PropsWithChildren<{ label: ReactNode }>> = (props) => {
|
||||
return (
|
||||
// Reflow on the container (a @container/chunkfields ancestor), not the
|
||||
// viewport. Below 552px the fields stack one per row, each capped at
|
||||
// max-w-[288px] so the input reads as a form field, not a full-bleed bar.
|
||||
// At/above 552px this restores flex-1 with no cap, so three columns resolve
|
||||
// to (container - gaps)/3 — pixel-identical to the stock flex-1 layout.
|
||||
<div className="max-w-[288px] space-y-2 @min-[552px]/chunkfields:max-w-none @min-[552px]/chunkfields:flex-1">
|
||||
<div className="text-xs leading-none font-semibold text-text-secondary">{props.label}</div>
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const DelimiterInput: FC<
|
||||
Omit<InputProps, 'onChange' | 'onValueChange'> & {
|
||||
tooltip?: string
|
||||
onValueChange?: (value: string) => void
|
||||
}
|
||||
> = ({ tooltip, onValueChange, value, ...rest }) => {
|
||||
const labelId = useId()
|
||||
|
||||
const { t } = useTranslation(['datasetCreation'])
|
||||
const generatedInputId = useId()
|
||||
const inputId = rest.id ?? generatedInputId
|
||||
const isComposing = useRef(false)
|
||||
const [compositionValue, setCompositionValue] = useState('')
|
||||
|
||||
return (
|
||||
<FormField
|
||||
label={
|
||||
<div className="mb-1 flex items-center">
|
||||
<label id={labelId} htmlFor={inputId} className="mr-0.5 system-sm-semibold">
|
||||
{t(($) => $['stepTwo.separator'], { ns: 'datasetCreation' })}
|
||||
</label>
|
||||
<Infotip>
|
||||
<InfotipTrigger aria-labelledby={labelId} />
|
||||
<InfotipContent aria-labelledby={labelId} className="max-w-50">
|
||||
{tooltip || t(($) => $['stepTwo.separatorTip'], { ns: 'datasetCreation' })}
|
||||
</InfotipContent>
|
||||
</Infotip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Input
|
||||
id={inputId}
|
||||
type="text"
|
||||
className="h-9"
|
||||
placeholder={t(($) => $['stepTwo.separatorPlaceholder'], { ns: 'datasetCreation' })!}
|
||||
value={isComposing.current ? compositionValue : value}
|
||||
onValueChange={(value) => {
|
||||
if (isComposing.current) setCompositionValue(value)
|
||||
else onValueChange?.(value)
|
||||
}}
|
||||
onCompositionStart={() => {
|
||||
isComposing.current = true
|
||||
setCompositionValue(String(value ?? ''))
|
||||
}}
|
||||
onCompositionEnd={(e) => {
|
||||
const committed = e.currentTarget.value
|
||||
isComposing.current = false
|
||||
setCompositionValue('')
|
||||
onValueChange?.(committed)
|
||||
}}
|
||||
{...rest}
|
||||
/>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
type CompoundNumberInputProps = Omit<NumberFieldProps, 'children' | 'className' | 'onValueChange'> &
|
||||
Omit<NumberFieldInputProps, 'children' | 'size' | 'onChange'> & {
|
||||
label: string
|
||||
unit?: ReactNode
|
||||
size?: NumberFieldSize
|
||||
onChange: (value: number) => void
|
||||
}
|
||||
|
||||
function CompoundNumberInput({
|
||||
label,
|
||||
onChange,
|
||||
unit,
|
||||
size = 'large',
|
||||
className,
|
||||
...props
|
||||
}: CompoundNumberInputProps) {
|
||||
const {
|
||||
value,
|
||||
defaultValue,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
id,
|
||||
name,
|
||||
onBlur,
|
||||
...inputProps
|
||||
} = props
|
||||
const emptyValue = defaultValue ?? min ?? 0
|
||||
|
||||
return (
|
||||
<NumberField
|
||||
value={value}
|
||||
defaultValue={defaultValue}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
required={required}
|
||||
id={id}
|
||||
name={name}
|
||||
onValueChange={(value) => onChange(value ?? emptyValue)}
|
||||
>
|
||||
<NumberFieldGroup size={size}>
|
||||
<NumberFieldInput
|
||||
{...inputProps}
|
||||
aria-label={label}
|
||||
size={size}
|
||||
// min-w-[64px] overrides the component's default min-w-0 so the input
|
||||
// can never collapse to an unusable sliver, even in an unforeseen
|
||||
// container; belt to the row's flex-wrap braces.
|
||||
className={cn('min-w-16', className)}
|
||||
onBlur={onBlur}
|
||||
/>
|
||||
{Boolean(unit) && <NumberFieldUnit size={size}>{unit}</NumberFieldUnit>}
|
||||
<NumberFieldControls>
|
||||
<NumberFieldIncrement size={size} />
|
||||
<NumberFieldDecrement size={size} />
|
||||
</NumberFieldControls>
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
)
|
||||
}
|
||||
|
||||
type LabeledCompoundNumberInputProps = Omit<CompoundNumberInputProps, 'label'>
|
||||
|
||||
export const MaxLengthInput: FC<LabeledCompoundNumberInputProps> = (props) => {
|
||||
const maxValue = env.NEXT_PUBLIC_INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH
|
||||
|
||||
const { t } = useTranslation(['datasetCreation'])
|
||||
const label = t(($) => $['stepTwo.maxLength'], { ns: 'datasetCreation' })
|
||||
return (
|
||||
<FormField label={<div className="mb-1 system-sm-semibold">{label}</div>}>
|
||||
<CompoundNumberInput
|
||||
label={label}
|
||||
size="large"
|
||||
placeholder={`≤ ${maxValue}`}
|
||||
max={maxValue}
|
||||
min={1}
|
||||
{...props}
|
||||
/>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
export const OverlapInput: FC<LabeledCompoundNumberInputProps> = (props) => {
|
||||
const labelId = useId()
|
||||
|
||||
const { t } = useTranslation(['datasetCreation'])
|
||||
const label = t(($) => $['stepTwo.overlap'], { ns: 'datasetCreation' })
|
||||
return (
|
||||
<FormField
|
||||
label={
|
||||
<div className="mb-1 flex items-center">
|
||||
<span id={labelId} className="system-sm-semibold">
|
||||
{label}
|
||||
</span>
|
||||
<Infotip>
|
||||
<InfotipTrigger aria-labelledby={labelId} />
|
||||
<InfotipContent aria-labelledby={labelId} className="max-w-50">
|
||||
{t(($) => $['stepTwo.overlapTip'], { ns: 'datasetCreation' })}
|
||||
</InfotipContent>
|
||||
</Infotip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<CompoundNumberInput
|
||||
label={label}
|
||||
size="large"
|
||||
placeholder={label || ''}
|
||||
min={1}
|
||||
{...props}
|
||||
/>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
import type { ComponentProps, FC, ReactNode } from 'react'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RadioItem } from '@langgenius/dify-ui/radio-group'
|
||||
import { useId } from 'react'
|
||||
|
||||
const TriangleArrow: FC<ComponentProps<'svg'>> = (props) => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="11"
|
||||
viewBox="0 0 24 11"
|
||||
fill="none"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M9.87868 1.12132C11.0503 -0.0502525 12.9497 -0.0502525 14.1213 1.12132L23.3137 10.3137H0.686292L9.87868 1.12132Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
|
||||
type OptionCardHeaderProps = {
|
||||
icon: ReactNode
|
||||
title: ReactNode
|
||||
description: string
|
||||
isActive?: boolean
|
||||
activeClassName?: string
|
||||
effectImg?: string
|
||||
disabled?: boolean
|
||||
titleId?: string
|
||||
descriptionId?: string
|
||||
}
|
||||
|
||||
const OptionCardHeader: FC<OptionCardHeaderProps> = (props) => {
|
||||
const {
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
isActive,
|
||||
activeClassName,
|
||||
effectImg,
|
||||
disabled,
|
||||
titleId,
|
||||
descriptionId,
|
||||
} = props
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex min-w-0 flex-1 overflow-hidden rounded-t-xl',
|
||||
isActive && activeClassName,
|
||||
!disabled && 'cursor-pointer',
|
||||
)}
|
||||
>
|
||||
<div className="relative flex size-14 shrink-0 items-center justify-center overflow-hidden">
|
||||
{isActive && effectImg && (
|
||||
<img
|
||||
src={effectImg}
|
||||
className="absolute top-0 left-0 size-full"
|
||||
alt=""
|
||||
width={56}
|
||||
height={56}
|
||||
/>
|
||||
)}
|
||||
<div className="p-1">
|
||||
<div className="flex size-8 items-center justify-center rounded-lg border border-components-panel-border-subtle bg-background-default-dodge p-1.5 shadow-md">
|
||||
{icon}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<TriangleArrow
|
||||
className={cn(
|
||||
'absolute -bottom-1.5 left-4 text-transparent',
|
||||
isActive && 'text-components-panel-bg',
|
||||
)}
|
||||
/>
|
||||
<div className="min-w-0 flex-1 space-y-0.5 py-3 pr-4">
|
||||
<div id={titleId} className="system-md-semibold text-text-secondary">
|
||||
{title}
|
||||
</div>
|
||||
<div id={descriptionId} className="system-xs-regular text-text-tertiary">
|
||||
{description}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type OptionCardProps<Value> = {
|
||||
value: Value
|
||||
icon: ReactNode
|
||||
className?: string
|
||||
activeHeaderClassName?: string
|
||||
title: ReactNode
|
||||
description: string
|
||||
isActive?: boolean
|
||||
actions?: ReactNode
|
||||
effectImg?: string
|
||||
noHighlight?: boolean
|
||||
disabled?: boolean
|
||||
} & Omit<ComponentProps<'div'>, 'title' | 'onClick'>
|
||||
|
||||
export const OptionCard = <Value,>({ ref, ...props }: OptionCardProps<Value>) => {
|
||||
const {
|
||||
icon,
|
||||
className,
|
||||
title,
|
||||
description,
|
||||
isActive,
|
||||
children,
|
||||
actions,
|
||||
activeHeaderClassName,
|
||||
style,
|
||||
effectImg,
|
||||
value,
|
||||
noHighlight,
|
||||
disabled,
|
||||
...rest
|
||||
} = props
|
||||
const titleId = useId()
|
||||
const descriptionId = useId()
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex min-w-0 flex-col rounded-xl bg-components-option-card-option-bg shadow-xs',
|
||||
isActive && !noHighlight
|
||||
? 'border-[1.5px] border-components-option-card-option-selected-border'
|
||||
: 'border border-components-option-card-option-border',
|
||||
disabled && 'opacity-50',
|
||||
className,
|
||||
)}
|
||||
style={{
|
||||
...style,
|
||||
}}
|
||||
{...rest}
|
||||
ref={ref}
|
||||
>
|
||||
<RadioItem<Value>
|
||||
value={value}
|
||||
nativeButton
|
||||
render={<button type="button" />}
|
||||
disabled={disabled}
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={descriptionId}
|
||||
className="flex w-full min-w-0 rounded-t-xl border-0 bg-transparent p-0 text-left outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset"
|
||||
>
|
||||
<OptionCardHeader
|
||||
titleId={titleId}
|
||||
descriptionId={descriptionId}
|
||||
icon={icon}
|
||||
title={title}
|
||||
description={description}
|
||||
isActive={isActive && !noHighlight}
|
||||
activeClassName={activeHeaderClassName}
|
||||
effectImg={effectImg}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</RadioItem>
|
||||
{/** Body */}
|
||||
{!!(isActive && (children || actions)) && (
|
||||
<div
|
||||
role="presentation"
|
||||
className="rounded-b-xl bg-components-panel-bg px-4 py-3"
|
||||
onKeyDown={(event) => {
|
||||
// Keep parameter arrow keys from navigating the enclosing radio group.
|
||||
if (event.key.startsWith('Arrow')) event.stopPropagation()
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
{!!actions && <div className="mt-4 flex flex-wrap gap-2">{actions}</div>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
OptionCard.displayName = 'OptionCard'
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
'use client'
|
||||
|
||||
import type { PreProcessingRule } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { FC, MouseEventHandler } from 'react'
|
||||
import type { ParentChildConfig } from '../hooks'
|
||||
import type { ParentMode, SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Checkbox } from '@langgenius/dify-ui/checkbox'
|
||||
import { RadioGroup } from '@langgenius/dify-ui/radio-group'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { RiSearchEyeLine } from '@remixicon/react'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import RadioCard from '@/app/components/base/radio-card'
|
||||
import SummaryIndexSetting from '@/app/components/datasets/settings/summary-index-setting'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
import { ChunkingMode } from '@/models/datasets'
|
||||
import FileList from '../../assets/file-list-3-fill.svg'
|
||||
import Note from '../../assets/note-mod.svg'
|
||||
import BlueEffect from '../../assets/option-card-effect-blue.svg'
|
||||
import s from '../index.module.css'
|
||||
import { DelimiterInput, MaxLengthInput } from './inputs'
|
||||
import { OptionCard } from './option-card'
|
||||
|
||||
type TextLabelProps = {
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
const TextLabel: FC<TextLabelProps> = ({ children }) => {
|
||||
return <label className="system-sm-semibold text-text-secondary">{children}</label>
|
||||
}
|
||||
|
||||
type ParentChildOptionsProps = {
|
||||
// State
|
||||
parentChildConfig: ParentChildConfig
|
||||
rules: PreProcessingRule[]
|
||||
summaryIndexSetting?: SummaryIndexSettingType
|
||||
onSummaryIndexSettingChange?: (payload: SummaryIndexSettingType) => void
|
||||
currentDocForm: ChunkingMode
|
||||
// Flags
|
||||
isActive: boolean
|
||||
isInUpload: boolean
|
||||
isNotUploadInEmptyDataset: boolean
|
||||
// Actions
|
||||
onChunkForContextChange: (mode: ParentMode) => void
|
||||
onParentDelimiterChange: (value: string) => void
|
||||
onParentMaxLengthChange: (value: number) => void
|
||||
onChildDelimiterChange: (value: string) => void
|
||||
onChildMaxLengthChange: (value: number) => void
|
||||
onRuleToggle: (id: string) => void
|
||||
onPreview: MouseEventHandler<HTMLButtonElement>
|
||||
onReset: () => void
|
||||
showSummaryIndexSetting?: boolean
|
||||
}
|
||||
|
||||
export const ParentChildOptions: FC<ParentChildOptionsProps> = ({
|
||||
parentChildConfig,
|
||||
rules,
|
||||
summaryIndexSetting,
|
||||
currentDocForm: _currentDocForm,
|
||||
isActive,
|
||||
isInUpload,
|
||||
isNotUploadInEmptyDataset,
|
||||
onChunkForContextChange,
|
||||
onParentDelimiterChange,
|
||||
onParentMaxLengthChange,
|
||||
onChildDelimiterChange,
|
||||
onChildMaxLengthChange,
|
||||
onRuleToggle,
|
||||
onSummaryIndexSettingChange,
|
||||
onPreview,
|
||||
onReset,
|
||||
showSummaryIndexSetting,
|
||||
}) => {
|
||||
const { t } = useTranslation(['datasetCreation'])
|
||||
const { data: deploymentEdition } = useSuspenseQuery({
|
||||
...systemFeaturesQueryOptions(),
|
||||
select: ({ deployment_edition }) => deployment_edition,
|
||||
})
|
||||
const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'
|
||||
|
||||
const getRuleName = (key: string): string => {
|
||||
const ruleNameMap: Record<string, string> = {
|
||||
remove_extra_spaces: t(($) => $['stepTwo.removeExtraSpaces'], { ns: 'datasetCreation' }),
|
||||
remove_urls_emails: t(($) => $['stepTwo.removeUrlEmails'], { ns: 'datasetCreation' }),
|
||||
remove_stopwords: t(($) => $['stepTwo.removeStopwords'], { ns: 'datasetCreation' }),
|
||||
}
|
||||
return ruleNameMap[key] ?? key
|
||||
}
|
||||
|
||||
return (
|
||||
<OptionCard
|
||||
title={t(($) => $['stepTwo.parentChild'], { ns: 'datasetCreation' })}
|
||||
icon={<span aria-hidden className="i-custom-vender-knowledge-parent-child-chunk h-5 w-5" />}
|
||||
effectImg={BlueEffect.src}
|
||||
className="text-util-colors-blue-light-blue-light-500"
|
||||
activeHeaderClassName="bg-dataset-option-card-blue-gradient"
|
||||
description={t(($) => $['stepTwo.parentChildTip'], { ns: 'datasetCreation' })}
|
||||
isActive={isActive}
|
||||
value={ChunkingMode.parentChild}
|
||||
actions={
|
||||
<>
|
||||
<Button variant="secondary-accent" onClick={onPreview}>
|
||||
<RiSearchEyeLine className="size-4" />
|
||||
{t(($) => $['stepTwo.previewChunk'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onReset}>
|
||||
{t(($) => $['stepTwo.reset'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
noHighlight={isInUpload && isNotUploadInEmptyDataset}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Parent chunk for context */}
|
||||
<div>
|
||||
<div className="flex items-center gap-x-2">
|
||||
<div className="inline-flex shrink-0">
|
||||
<TextLabel>
|
||||
{t(($) => $['stepTwo.parentChunkForContext'], { ns: 'datasetCreation' })}
|
||||
</TextLabel>
|
||||
</div>
|
||||
<Separator decorative className="my-2 h-[0.5px] grow" variant="gradient" />
|
||||
</div>
|
||||
<RadioGroup<ParentMode>
|
||||
aria-label={t(($) => $['stepTwo.parentChunkForContext'], { ns: 'datasetCreation' })}
|
||||
value={parentChildConfig.chunkForContext}
|
||||
onValueChange={(value) => onChunkForContextChange(value)}
|
||||
className="mt-1 flex-col items-stretch gap-2"
|
||||
>
|
||||
<RadioCard<ParentMode>
|
||||
value="paragraph"
|
||||
icon={<img src={Note.src} alt="" />}
|
||||
title={t(($) => $['stepTwo.paragraph'], { ns: 'datasetCreation' })}
|
||||
description={t(($) => $['stepTwo.paragraphTip'], { ns: 'datasetCreation' })}
|
||||
chosenConfig={
|
||||
<div className="flex flex-col gap-3 @min-[552px]/chunkfields:flex-row">
|
||||
<DelimiterInput
|
||||
value={parentChildConfig.parent.delimiter}
|
||||
tooltip={t(($) => $['stepTwo.parentChildDelimiterTip'], {
|
||||
ns: 'datasetCreation',
|
||||
})!}
|
||||
onValueChange={onParentDelimiterChange}
|
||||
/>
|
||||
<MaxLengthInput
|
||||
unit="characters"
|
||||
value={parentChildConfig.parent.maxLength}
|
||||
onChange={onParentMaxLengthChange}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<RadioCard<ParentMode>
|
||||
value="full-doc"
|
||||
icon={<img src={FileList.src} alt="" />}
|
||||
title={t(($) => $['stepTwo.fullDoc'], { ns: 'datasetCreation' })}
|
||||
description={t(($) => $['stepTwo.fullDocTip'], { ns: 'datasetCreation' })}
|
||||
/>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{/* Child chunk for retrieval */}
|
||||
<div>
|
||||
<div className="flex items-center gap-x-2">
|
||||
<div className="inline-flex shrink-0">
|
||||
<TextLabel>
|
||||
{t(($) => $['stepTwo.childChunkForRetrieval'], { ns: 'datasetCreation' })}
|
||||
</TextLabel>
|
||||
</div>
|
||||
<Separator decorative className="my-2 h-[0.5px] grow" variant="gradient" />
|
||||
</div>
|
||||
<div className="mt-1 flex flex-col gap-3 @min-[552px]/chunkfields:flex-row">
|
||||
<DelimiterInput
|
||||
value={parentChildConfig.child.delimiter}
|
||||
tooltip={t(($) => $['stepTwo.parentChildChunkDelimiterTip'], {
|
||||
ns: 'datasetCreation',
|
||||
})!}
|
||||
onValueChange={onChildDelimiterChange}
|
||||
/>
|
||||
<MaxLengthInput
|
||||
unit="characters"
|
||||
value={parentChildConfig.child.maxLength}
|
||||
onChange={onChildMaxLengthChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rules */}
|
||||
<div>
|
||||
<div className="flex items-center gap-x-2">
|
||||
<div className="inline-flex shrink-0">
|
||||
<TextLabel>{t(($) => $['stepTwo.rules'], { ns: 'datasetCreation' })}</TextLabel>
|
||||
</div>
|
||||
<Separator decorative className="my-2 h-[0.5px] grow" variant="gradient" />
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
{rules.map((rule) => (
|
||||
<label key={rule.id} className={`${s.ruleItem} cursor-pointer`}>
|
||||
<Checkbox checked={rule.enabled} onCheckedChange={() => onRuleToggle(rule.id)} />
|
||||
<span className="ml-2 system-sm-regular text-text-secondary">
|
||||
{getRuleName(rule.id)}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
{showSummaryIndexSetting && isNonCloudEdition && (
|
||||
<div className="mt-3">
|
||||
<SummaryIndexSetting
|
||||
entry="create-document"
|
||||
summaryIndexSetting={summaryIndexSetting}
|
||||
onSummaryIndexSettingChange={onSummaryIndexSettingChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</OptionCard>
|
||||
)
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
'use client'
|
||||
|
||||
import type { IndexingEstimateResponse } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { ComponentProps, FC } from 'react'
|
||||
import type { ParentChildConfig } from '../hooks'
|
||||
import type { DataSourceType } from '@/models/datasets'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RiSearchEyeLine } from '@remixicon/react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Badge from '@/app/components/base/badge'
|
||||
import FloatRightContainer from '@/app/components/base/float-right-container'
|
||||
import {
|
||||
SkeletonContainer,
|
||||
SkeletonPoint,
|
||||
SkeletonRectangle,
|
||||
SkeletonRow,
|
||||
} from '@/app/components/base/skeleton'
|
||||
import { FULL_DOC_PREVIEW_LENGTH } from '@/config'
|
||||
import { ChunkingMode } from '@/models/datasets'
|
||||
import { ChunkContainer, QAPreview } from '../../../chunk'
|
||||
import PreviewDocumentPicker from '../../../common/document-picker/preview-document-picker'
|
||||
import SummaryLabel from '../../../documents/detail/completed/common/summary-label'
|
||||
import { PreviewSlice } from '../../../formatted-text/flavours/preview-slice'
|
||||
import { FormattedText } from '../../../formatted-text/formatted'
|
||||
import PreviewContainer from '../../../preview/container'
|
||||
|
||||
type PreviewPanelProps = {
|
||||
// State
|
||||
isMobile: boolean
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
finalFocus?: ComponentProps<typeof FloatRightContainer>['finalFocus']
|
||||
dataSourceType: DataSourceType
|
||||
currentDocForm: ChunkingMode
|
||||
estimate?: IndexingEstimateResponse
|
||||
parentChildConfig: ParentChildConfig
|
||||
isSetting?: boolean
|
||||
// Picker
|
||||
pickerFiles: Array<{ id: string; name: string; extension: string }>
|
||||
pickerValue?: { id: string; name: string; extension: string }
|
||||
// Mutation state
|
||||
isIdle: boolean
|
||||
isPending: boolean
|
||||
// Actions
|
||||
onPickerChange: (selected: { id: string; name: string }) => void
|
||||
}
|
||||
|
||||
export const PreviewPanel: FC<PreviewPanelProps> = ({
|
||||
isMobile,
|
||||
isOpen,
|
||||
onClose,
|
||||
finalFocus,
|
||||
dataSourceType: _dataSourceType,
|
||||
currentDocForm,
|
||||
estimate,
|
||||
parentChildConfig,
|
||||
isSetting,
|
||||
pickerFiles,
|
||||
pickerValue,
|
||||
isIdle,
|
||||
isPending,
|
||||
onPickerChange,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'datasetCreation'])
|
||||
|
||||
return (
|
||||
<FloatRightContainer
|
||||
isMobile={isMobile}
|
||||
isOpen={!isMobile || isOpen}
|
||||
onClose={onClose}
|
||||
showClose
|
||||
title={t(($) => $['stepTwo.preview'], { ns: 'datasetCreation' })}
|
||||
finalFocus={finalFocus}
|
||||
>
|
||||
<div role="status" aria-atomic="true" className="sr-only">
|
||||
{isPending
|
||||
? t(($) => $.loading, { ns: 'common' })
|
||||
: estimate
|
||||
? t(($) => $['stepTwo.previewChunkCount'], {
|
||||
ns: 'datasetCreation',
|
||||
count: estimate.total_segments ?? estimate.qa_preview?.length ?? 0,
|
||||
})
|
||||
: ''}
|
||||
</div>
|
||||
<PreviewContainer
|
||||
header={
|
||||
<div>
|
||||
{!isMobile && (
|
||||
<h2 className="mb-1 px-1 system-2xs-semibold-uppercase text-text-accent uppercase">
|
||||
{t(($) => $['stepTwo.preview'], { ns: 'datasetCreation' })}
|
||||
</h2>
|
||||
)}
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-1">
|
||||
<PreviewDocumentPicker
|
||||
files={
|
||||
pickerFiles as Array<Required<{ id: string; name: string; extension: string }>>
|
||||
}
|
||||
onChange={onPickerChange}
|
||||
value={isSetting ? pickerFiles[0] : pickerValue}
|
||||
/>
|
||||
{currentDocForm !== ChunkingMode.qa && (
|
||||
<Badge>
|
||||
{t(($) => $['stepTwo.previewChunkCount'], {
|
||||
ns: 'datasetCreation',
|
||||
count: estimate?.total_segments || 0,
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
className={cn(
|
||||
'relative flex min-w-0 shrink-0 p-4',
|
||||
isMobile ? 'min-h-0 w-full flex-1' : 'h-full w-1/2 pr-0',
|
||||
)}
|
||||
mainClassName="space-y-6 wrap-break-word"
|
||||
>
|
||||
{/* QA Preview */}
|
||||
{currentDocForm === ChunkingMode.qa &&
|
||||
estimate?.qa_preview &&
|
||||
estimate.qa_preview.map((item, index) => (
|
||||
<ChunkContainer
|
||||
key={item.question}
|
||||
label={`Chunk-${index + 1}`}
|
||||
characterCount={item.question.length + item.answer.length}
|
||||
>
|
||||
<QAPreview qa={item} />
|
||||
</ChunkContainer>
|
||||
))}
|
||||
|
||||
{/* Text Preview */}
|
||||
{currentDocForm === ChunkingMode.text &&
|
||||
estimate?.preview &&
|
||||
estimate.preview.map((item, index) => (
|
||||
<ChunkContainer
|
||||
key={item.content}
|
||||
label={`Chunk-${index + 1}`}
|
||||
characterCount={item.content.length}
|
||||
>
|
||||
{item.content}
|
||||
{item.summary && <SummaryLabel summary={item.summary} />}
|
||||
</ChunkContainer>
|
||||
))}
|
||||
|
||||
{/* Parent-Child Preview */}
|
||||
{currentDocForm === ChunkingMode.parentChild &&
|
||||
estimate?.preview &&
|
||||
estimate.preview.map((item, index) => {
|
||||
const indexForLabel = index + 1
|
||||
const childChunks =
|
||||
parentChildConfig.chunkForContext === 'full-doc'
|
||||
? (item.child_chunks ?? []).slice(0, FULL_DOC_PREVIEW_LENGTH)
|
||||
: (item.child_chunks ?? [])
|
||||
return (
|
||||
<ChunkContainer
|
||||
key={item.content}
|
||||
label={`Chunk-${indexForLabel}`}
|
||||
characterCount={item.content.length}
|
||||
>
|
||||
<FormattedText>
|
||||
{childChunks.map((child, childIndex) => {
|
||||
const childIndexForLabel = childIndex + 1
|
||||
return (
|
||||
<PreviewSlice
|
||||
key={`C-${childIndexForLabel}-${child}`}
|
||||
label={`C-${childIndexForLabel}`}
|
||||
text={child}
|
||||
tooltip={`Child-chunk-${childIndexForLabel} · ${child.length} Characters`}
|
||||
labelInnerClassName="text-[10px] font-semibold align-bottom leading-7"
|
||||
dividerClassName="leading-7"
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</FormattedText>
|
||||
{item.summary && <SummaryLabel summary={item.summary} />}
|
||||
</ChunkContainer>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Idle State */}
|
||||
{isIdle && (
|
||||
<div className="flex size-full items-center justify-center">
|
||||
<div className="flex flex-col items-center justify-center gap-3">
|
||||
<RiSearchEyeLine className="size-10 text-text-empty-state-icon" />
|
||||
<p className="text-sm text-text-tertiary">
|
||||
{t(($) => $['stepTwo.previewChunkTip'], { ns: 'datasetCreation' })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Loading State */}
|
||||
{isPending && (
|
||||
<div className="space-y-6">
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<SkeletonContainer key={i}>
|
||||
<SkeletonRow>
|
||||
<SkeletonRectangle className="w-20" />
|
||||
<SkeletonPoint />
|
||||
<SkeletonRectangle className="w-24" />
|
||||
</SkeletonRow>
|
||||
<SkeletonRectangle className="w-full" />
|
||||
<SkeletonRectangle className="w-full" />
|
||||
<SkeletonRectangle className="w-full max-w-105.5" />
|
||||
</SkeletonContainer>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</PreviewContainer>
|
||||
</FloatRightContainer>
|
||||
)
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
'use client'
|
||||
|
||||
import type { FC } from 'react'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { RiArrowLeftLine } from '@remixicon/react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type StepTwoFooterProps = {
|
||||
isSetting?: boolean
|
||||
isCreating: boolean
|
||||
onPrevious: () => void
|
||||
onCreate: () => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
export const StepTwoFooter: FC<StepTwoFooterProps> = ({
|
||||
isSetting,
|
||||
isCreating,
|
||||
onPrevious,
|
||||
onCreate,
|
||||
onCancel,
|
||||
}) => {
|
||||
const { t } = useTranslation(['datasetCreation'])
|
||||
|
||||
if (!isSetting) {
|
||||
return (
|
||||
<div className="mt-8 flex flex-wrap items-center gap-y-2 py-2">
|
||||
<Button onClick={onPrevious}>
|
||||
<RiArrowLeftLine className="size-4" />
|
||||
{t(($) => $['stepTwo.previousStep'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
<Button className="ml-auto" loading={isCreating} variant="primary" onClick={onCreate}>
|
||||
{t(($) => $['stepTwo.nextStep'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-8 flex flex-wrap items-center gap-y-2 py-2">
|
||||
<Button loading={isCreating} variant="primary" onClick={onCreate}>
|
||||
{t(($) => $['stepTwo.save'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
<Button className="ml-2" onClick={onCancel}>
|
||||
{t(($) => $['stepTwo.cancel'], { ns: 'datasetCreation' })}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import type {
|
||||
IndexingEstimatePayload,
|
||||
NotionInfo,
|
||||
} from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { IndexingType } from './hooks/use-indexing-config'
|
||||
import type { StepTwoFile, StepTwoNotionPage } from './types'
|
||||
import type { DataSourceProvider } from '@/models/common'
|
||||
import type {
|
||||
ChunkingMode,
|
||||
CrawlOptions,
|
||||
CrawlResultItem,
|
||||
DataSourceType,
|
||||
ProcessRule,
|
||||
} from '@/models/datasets'
|
||||
import { groupBy } from 'es-toolkit/compat'
|
||||
|
||||
export const getNotionInfo = (
|
||||
notionPages: StepTwoNotionPage[],
|
||||
credentialId: string,
|
||||
): NotionInfo[] => {
|
||||
const workspacesMap = groupBy(notionPages, 'workspace_id')
|
||||
const workspaces = Object.keys(workspacesMap).map((workspaceId) => {
|
||||
return {
|
||||
workspaceId,
|
||||
pages: workspacesMap[workspaceId],
|
||||
}
|
||||
})
|
||||
return workspaces.map((workspace) => {
|
||||
return {
|
||||
credential_id: credentialId,
|
||||
workspace_id: workspace.workspaceId,
|
||||
pages: workspace.pages!.map((page) => {
|
||||
const { page_id, page_name, page_icon, type } = page
|
||||
return {
|
||||
page_id,
|
||||
page_name,
|
||||
// The backend requires an icon type; an icon without one carries nothing to render.
|
||||
page_icon: page_icon?.type ? { ...page_icon, type: page_icon.type } : null,
|
||||
type,
|
||||
}
|
||||
}),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const getWebsiteInfo = (opts: {
|
||||
websiteCrawlProvider: DataSourceProvider
|
||||
websiteCrawlJobId: string
|
||||
websitePages: CrawlResultItem[]
|
||||
crawlOptions?: CrawlOptions
|
||||
}) => {
|
||||
const { websiteCrawlProvider, websiteCrawlJobId, websitePages, crawlOptions } = opts
|
||||
return {
|
||||
provider: websiteCrawlProvider,
|
||||
job_id: websiteCrawlJobId,
|
||||
urls: websitePages.map((page) => page.source_url),
|
||||
only_main_content: crawlOptions?.only_main_content,
|
||||
}
|
||||
}
|
||||
|
||||
type GetFileIndexingEstimateParamsOptionBase = {
|
||||
docForm: ChunkingMode
|
||||
docLanguage: string
|
||||
indexingTechnique: IndexingType
|
||||
processRule: ProcessRule
|
||||
dataset_id: string
|
||||
}
|
||||
|
||||
type GetFileIndexingEstimateParamsOptionFile = GetFileIndexingEstimateParamsOptionBase & {
|
||||
dataSourceType: typeof DataSourceType.FILE
|
||||
files: StepTwoFile[]
|
||||
}
|
||||
|
||||
export const getFileIndexingEstimateParamsForFile = ({
|
||||
docForm,
|
||||
docLanguage,
|
||||
dataSourceType,
|
||||
files,
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
dataset_id,
|
||||
}: GetFileIndexingEstimateParamsOptionFile): IndexingEstimatePayload => {
|
||||
const fileIds = files.map((file) => file.id).filter((id): id is string => Boolean(id))
|
||||
|
||||
return {
|
||||
info_list: {
|
||||
data_source_type: dataSourceType,
|
||||
file_info_list: {
|
||||
file_ids: fileIds,
|
||||
},
|
||||
},
|
||||
indexing_technique: indexingTechnique,
|
||||
process_rule: processRule,
|
||||
doc_form: docForm,
|
||||
doc_language: docLanguage,
|
||||
dataset_id,
|
||||
}
|
||||
}
|
||||
|
||||
type GetFileIndexingEstimateParamsOptionNotion = GetFileIndexingEstimateParamsOptionBase & {
|
||||
dataSourceType: typeof DataSourceType.NOTION
|
||||
notionPages: StepTwoNotionPage[]
|
||||
credential_id: string
|
||||
}
|
||||
|
||||
export const getFileIndexingEstimateParamsForNotion = ({
|
||||
docForm,
|
||||
docLanguage,
|
||||
dataSourceType,
|
||||
notionPages,
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
dataset_id,
|
||||
credential_id,
|
||||
}: GetFileIndexingEstimateParamsOptionNotion): IndexingEstimatePayload => {
|
||||
return {
|
||||
info_list: {
|
||||
data_source_type: dataSourceType,
|
||||
notion_info_list: getNotionInfo(notionPages, credential_id),
|
||||
},
|
||||
indexing_technique: indexingTechnique,
|
||||
process_rule: processRule,
|
||||
doc_form: docForm,
|
||||
doc_language: docLanguage,
|
||||
dataset_id,
|
||||
}
|
||||
}
|
||||
|
||||
type GetFileIndexingEstimateParamsOptionWeb = GetFileIndexingEstimateParamsOptionBase & {
|
||||
dataSourceType: typeof DataSourceType.WEB
|
||||
websitePages: CrawlResultItem[]
|
||||
crawlOptions?: CrawlOptions
|
||||
websiteCrawlProvider: DataSourceProvider
|
||||
websiteCrawlJobId: string
|
||||
}
|
||||
|
||||
export const getFileIndexingEstimateParamsForWeb = ({
|
||||
docForm,
|
||||
docLanguage,
|
||||
dataSourceType,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
dataset_id,
|
||||
}: GetFileIndexingEstimateParamsOptionWeb): IndexingEstimatePayload => {
|
||||
return {
|
||||
info_list: {
|
||||
data_source_type: dataSourceType,
|
||||
website_info_list: getWebsiteInfo({
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
}),
|
||||
},
|
||||
indexing_technique: indexingTechnique,
|
||||
process_rule: processRule,
|
||||
doc_form: docForm,
|
||||
doc_language: docLanguage,
|
||||
dataset_id,
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import escape from '../escape'
|
||||
|
||||
describe('escape', () => {
|
||||
// Basic special character escaping
|
||||
it('should escape null character', () => {
|
||||
expect(escape('\0')).toBe('\\0')
|
||||
})
|
||||
|
||||
it('should escape backspace', () => {
|
||||
expect(escape('\b')).toBe('\\b')
|
||||
})
|
||||
|
||||
it('should escape form feed', () => {
|
||||
expect(escape('\f')).toBe('\\f')
|
||||
})
|
||||
|
||||
it('should escape newline', () => {
|
||||
expect(escape('\n')).toBe('\\n')
|
||||
})
|
||||
|
||||
it('should escape carriage return', () => {
|
||||
expect(escape('\r')).toBe('\\r')
|
||||
})
|
||||
|
||||
it('should escape tab', () => {
|
||||
expect(escape('\t')).toBe('\\t')
|
||||
})
|
||||
|
||||
it('should escape vertical tab', () => {
|
||||
expect(escape('\v')).toBe('\\v')
|
||||
})
|
||||
|
||||
it('should escape single quote', () => {
|
||||
expect(escape("'")).toBe("\\'")
|
||||
})
|
||||
|
||||
// Multiple special characters in one string
|
||||
it('should escape multiple special characters', () => {
|
||||
expect(escape('line1\nline2\ttab')).toBe('line1\\nline2\\ttab')
|
||||
})
|
||||
|
||||
it('should return empty string for empty string input', () => {
|
||||
expect(escape('')).toBe('')
|
||||
})
|
||||
|
||||
// Pass-through for normal strings
|
||||
it('should leave normal text unchanged', () => {
|
||||
expect(escape('hello world')).toBe('hello world')
|
||||
})
|
||||
|
||||
it('should leave special regex characters unchanged', () => {
|
||||
expect(escape('a.b*c+d')).toBe('a.b*c+d')
|
||||
})
|
||||
})
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import unescape from '../unescape'
|
||||
|
||||
describe('unescape', () => {
|
||||
// Basic escape sequences
|
||||
it('should unescape \\n to newline', () => {
|
||||
expect(unescape('\\n')).toBe('\n')
|
||||
})
|
||||
|
||||
it('should unescape \\t to tab', () => {
|
||||
expect(unescape('\\t')).toBe('\t')
|
||||
})
|
||||
|
||||
it('should unescape \\r to carriage return', () => {
|
||||
expect(unescape('\\r')).toBe('\r')
|
||||
})
|
||||
|
||||
it('should unescape \\b to backspace', () => {
|
||||
expect(unescape('\\b')).toBe('\b')
|
||||
})
|
||||
|
||||
it('should unescape \\f to form feed', () => {
|
||||
expect(unescape('\\f')).toBe('\f')
|
||||
})
|
||||
|
||||
it('should unescape \\v to vertical tab', () => {
|
||||
expect(unescape('\\v')).toBe('\v')
|
||||
})
|
||||
|
||||
it('should unescape \\0 to null character', () => {
|
||||
expect(unescape('\\0')).toBe('\0')
|
||||
})
|
||||
|
||||
it('should unescape \\\\ to backslash', () => {
|
||||
expect(unescape('\\\\')).toBe('\\')
|
||||
})
|
||||
|
||||
it("should unescape \\' to single quote", () => {
|
||||
expect(unescape("\\'")).toBe("'")
|
||||
})
|
||||
|
||||
it('should unescape \\" to double quote', () => {
|
||||
expect(unescape('\\"')).toBe('"')
|
||||
})
|
||||
|
||||
// Hex escape sequences (\\xNN)
|
||||
it('should unescape 2-digit hex sequences', () => {
|
||||
expect(unescape('\\x41')).toBe('A')
|
||||
expect(unescape('\\x61')).toBe('a')
|
||||
})
|
||||
|
||||
// Unicode escape sequences (\\uNNNN)
|
||||
it('should unescape 4-digit unicode sequences', () => {
|
||||
expect(unescape('\\u0041')).toBe('A')
|
||||
expect(unescape('\\u4e2d')).toBe('中')
|
||||
})
|
||||
|
||||
// Variable-length unicode (\\u{NNNN})
|
||||
it('should unescape variable-length unicode sequences', () => {
|
||||
expect(unescape('\\u{41}')).toBe('A')
|
||||
expect(unescape('\\u{1F600}')).toBe('😀')
|
||||
})
|
||||
|
||||
// Octal escape sequences
|
||||
it('should unescape octal sequences', () => {
|
||||
expect(unescape('\\101')).toBe('A') // 0o101 = 65 = 'A'
|
||||
expect(unescape('\\12')).toBe('\n') // 0o12 = 10 = '\n'
|
||||
})
|
||||
|
||||
// Python-style 8-digit unicode (\\UNNNNNNNN)
|
||||
it('should unescape Python-style 8-digit unicode', () => {
|
||||
expect(unescape('\\U0001F3B5')).toBe('🎵')
|
||||
})
|
||||
|
||||
// Multiple escape sequences
|
||||
it('should unescape multiple sequences in one string', () => {
|
||||
expect(unescape('line1\\nline2\\ttab')).toBe('line1\nline2\ttab')
|
||||
})
|
||||
|
||||
// Mixed content
|
||||
it('should leave non-escape content unchanged', () => {
|
||||
expect(unescape('hello world')).toBe('hello world')
|
||||
})
|
||||
|
||||
it('should handle empty string', () => {
|
||||
expect(unescape('')).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
function escape(input: string): string {
|
||||
if (!input || typeof input !== 'string') return ''
|
||||
|
||||
const res = input
|
||||
// .replaceAll('\\', '\\\\') // This would add too many backslashes
|
||||
.replaceAll('\0', '\\0')
|
||||
.replaceAll('\b', '\\b')
|
||||
.replaceAll('\f', '\\f')
|
||||
.replaceAll('\n', '\\n')
|
||||
.replaceAll('\r', '\\r')
|
||||
.replaceAll('\t', '\\t')
|
||||
.replaceAll('\v', '\\v')
|
||||
.replaceAll("'", "\\'")
|
||||
return res
|
||||
}
|
||||
|
||||
export default escape
|
||||
@@ -0,0 +1,10 @@
|
||||
export { useDocumentCreation } from './use-document-creation'
|
||||
|
||||
export { IndexingType, useIndexingConfig } from './use-indexing-config'
|
||||
|
||||
export { useIndexingEstimate } from './use-indexing-estimate'
|
||||
|
||||
export { usePreviewState } from './use-preview-state'
|
||||
|
||||
export { MAXIMUM_CHUNK_TOKEN_LENGTH, useSegmentationState } from './use-segmentation-state'
|
||||
export type { ParentChildConfig } from './use-segmentation-state'
|
||||
@@ -0,0 +1,52 @@
|
||||
// https://github.com/iamakulov/unescape-js/blob/master/src/index.js
|
||||
|
||||
/**
|
||||
* \\ - matches the backslash which indicates the beginning of an escape sequence
|
||||
* (
|
||||
* u\{([0-9A-Fa-f]+)\} - first alternative; matches the variable-length hexadecimal escape sequence (\u{ABCD0})
|
||||
* |
|
||||
* u([0-9A-Fa-f]{4}) - second alternative; matches the 4-digit hexadecimal escape sequence (\uABCD)
|
||||
* |
|
||||
* x([0-9A-Fa-f]{2}) - third alternative; matches the 2-digit hexadecimal escape sequence (\xA5)
|
||||
* |
|
||||
* ([1-7][0-7]{0,2}|[0-7]{2,3}) - fourth alternative; matches the up-to-3-digit octal escape sequence (\5 or \512)
|
||||
* |
|
||||
* (['"tbrnfv0\\]) - fifth alternative; matches the special escape characters (\t, \n and so on)
|
||||
* |
|
||||
* \U([0-9A-Fa-f]+) - sixth alternative; matches the 8-digit hexadecimal escape sequence used by python (\U0001F3B5)
|
||||
* )
|
||||
*/
|
||||
const jsEscapeRegex =
|
||||
/\\(u\{([0-9A-Fa-f]+)\}|u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([1-7][0-7]{0,2}|[0-7]{2,3})|(['"tbrnfv0\\]))|\\U([0-9A-Fa-f]{8})/g
|
||||
|
||||
const usualEscapeSequences: Record<string, string> = {
|
||||
'0': '\0',
|
||||
b: '\b',
|
||||
f: '\f',
|
||||
n: '\n',
|
||||
r: '\r',
|
||||
t: '\t',
|
||||
v: '\v',
|
||||
"'": "'",
|
||||
'"': '"',
|
||||
'\\': '\\',
|
||||
}
|
||||
|
||||
const fromHex = (str: string) => String.fromCodePoint(Number.parseInt(str, 16))
|
||||
const fromOct = (str: string) => String.fromCodePoint(Number.parseInt(str, 8))
|
||||
|
||||
const unescape = (str: string) => {
|
||||
return str.replace(
|
||||
jsEscapeRegex,
|
||||
(_, __, varHex, longHex, shortHex, octal, specialCharacter, python) => {
|
||||
if (varHex !== undefined) return fromHex(varHex)
|
||||
else if (longHex !== undefined) return fromHex(longHex)
|
||||
else if (shortHex !== undefined) return fromHex(shortHex)
|
||||
else if (octal !== undefined) return fromOct(octal)
|
||||
else if (python !== undefined) return fromHex(python)
|
||||
else return usualEscapeSequences[specialCharacter]!
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
export default unescape
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
import type {
|
||||
DatasetAndDocumentResponse,
|
||||
DocumentDetailResponse,
|
||||
} from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { StepTwoFile, StepTwoNotionPage } from '../types'
|
||||
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type {
|
||||
ChunkingMode,
|
||||
CrawlOptions,
|
||||
CrawlResultItem,
|
||||
CreateDocumentReq,
|
||||
ProcessRule,
|
||||
SummaryIndexSetting as SummaryIndexSettingType,
|
||||
} from '@/models/datasets'
|
||||
import type { RetrievalConfig, RETRIEVE_METHOD } from '@/types/app'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { trackEvent } from '@/app/components/base/amplitude'
|
||||
import { isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { DataSourceProvider } from '@/models/common'
|
||||
import { DataSourceType, ProcessMode } from '@/models/datasets'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { getNotionInfo, getWebsiteInfo } from '../creation-params'
|
||||
import { IndexingType } from './use-indexing-config'
|
||||
import { MAXIMUM_CHUNK_TOKEN_LENGTH } from './use-segmentation-state'
|
||||
|
||||
type UseDocumentCreationOptions = {
|
||||
datasetId?: string
|
||||
isSetting?: boolean
|
||||
documentDetail?: DocumentDetailResponse
|
||||
dataSourceType: DataSourceType
|
||||
files: StepTwoFile[]
|
||||
notionPages: StepTwoNotionPage[]
|
||||
notionCredentialId: string
|
||||
websitePages: CrawlResultItem[]
|
||||
crawlOptions?: CrawlOptions
|
||||
websiteCrawlProvider?: DataSourceProvider
|
||||
websiteCrawlJobId?: string
|
||||
canCreateDocument?: boolean
|
||||
// Callbacks
|
||||
onStepChange?: (delta: number) => void
|
||||
updateIndexingTypeCache?: (type: string) => void
|
||||
updateResultCache?: (res: DatasetAndDocumentResponse) => void
|
||||
updateRetrievalMethodCache?: (method: RETRIEVE_METHOD | '') => void
|
||||
onSave?: () => void
|
||||
mutateDatasetRes?: () => void
|
||||
}
|
||||
type ValidationParams = {
|
||||
segmentationType: ProcessMode
|
||||
maxChunkLength: number
|
||||
limitMaxChunkLength: number
|
||||
overlap: number
|
||||
indexType: IndexingType
|
||||
embeddingModel: DefaultModel
|
||||
rerankModelList: ProviderWithModelsResponse[]
|
||||
retrievalConfig: RetrievalConfig
|
||||
}
|
||||
export const useDocumentCreation = (options: UseDocumentCreationOptions) => {
|
||||
const { t } = useTranslation(['appDebug', 'datasetCreation'])
|
||||
const {
|
||||
datasetId,
|
||||
isSetting,
|
||||
documentDetail,
|
||||
dataSourceType,
|
||||
files,
|
||||
notionPages,
|
||||
notionCredentialId,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
websiteCrawlProvider = DataSourceProvider.jinaReader,
|
||||
websiteCrawlJobId = '',
|
||||
canCreateDocument = true,
|
||||
onStepChange,
|
||||
updateIndexingTypeCache,
|
||||
updateResultCache,
|
||||
updateRetrievalMethodCache,
|
||||
onSave,
|
||||
mutateDatasetRes,
|
||||
} = options
|
||||
const { mutateAsync: createFirstDocument, isPending: isCreatingFirstDocument } = useMutation(
|
||||
consoleQuery.datasets.init.post.mutationOptions(),
|
||||
)
|
||||
const { mutateAsync: createDocument, isPending: isCreatingDocument } = useMutation(
|
||||
consoleQuery.datasets.byDatasetId.documents.post.mutationOptions(),
|
||||
)
|
||||
const queryClient = useQueryClient()
|
||||
const invalidDatasetList = useCallback(() => {
|
||||
queryClient.invalidateQueries({ queryKey: consoleQuery.datasets.get.key() })
|
||||
}, [queryClient])
|
||||
const isCreating = isCreatingFirstDocument || isCreatingDocument
|
||||
// Validate creation params
|
||||
const validateParams = useCallback(
|
||||
(params: ValidationParams): boolean => {
|
||||
const {
|
||||
segmentationType,
|
||||
maxChunkLength,
|
||||
limitMaxChunkLength,
|
||||
overlap,
|
||||
indexType,
|
||||
embeddingModel,
|
||||
rerankModelList,
|
||||
retrievalConfig,
|
||||
} = params
|
||||
if (segmentationType === ProcessMode.general && overlap > maxChunkLength) {
|
||||
toast.error(t(($) => $['stepTwo.overlapCheck'], { ns: 'datasetCreation' }))
|
||||
return false
|
||||
}
|
||||
if (segmentationType === ProcessMode.general && maxChunkLength > limitMaxChunkLength) {
|
||||
toast.error(
|
||||
t(($) => $['stepTwo.maxLengthCheck'], {
|
||||
ns: 'datasetCreation',
|
||||
limit: limitMaxChunkLength,
|
||||
}),
|
||||
)
|
||||
return false
|
||||
}
|
||||
if (!isSetting) {
|
||||
if (
|
||||
indexType === IndexingType.QUALIFIED &&
|
||||
(!embeddingModel.model || !embeddingModel.provider)
|
||||
) {
|
||||
toast.error(t(($) => $['datasetConfig.embeddingModelRequired'], { ns: 'appDebug' }))
|
||||
return false
|
||||
}
|
||||
if (
|
||||
!isReRankModelSelected({
|
||||
rerankModelList,
|
||||
retrievalConfig,
|
||||
indexMethod: indexType,
|
||||
})
|
||||
) {
|
||||
toast.error(t(($) => $['datasetConfig.rerankModelRequired'], { ns: 'appDebug' }))
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
},
|
||||
[t, isSetting],
|
||||
)
|
||||
// Build creation params
|
||||
const buildCreationParams = useCallback(
|
||||
(
|
||||
currentDocForm: ChunkingMode,
|
||||
docLanguage: string,
|
||||
processRule: ProcessRule,
|
||||
retrievalConfig: RetrievalConfig,
|
||||
embeddingModel: DefaultModel,
|
||||
indexingTechnique: string,
|
||||
summaryIndexSetting?: SummaryIndexSettingType,
|
||||
): CreateDocumentReq | null => {
|
||||
if (isSetting) {
|
||||
return {
|
||||
original_document_id: documentDetail?.id,
|
||||
doc_form: currentDocForm,
|
||||
doc_language: docLanguage,
|
||||
process_rule: processRule,
|
||||
summary_index_setting: summaryIndexSetting,
|
||||
retrieval_model: retrievalConfig,
|
||||
embedding_model: embeddingModel.model,
|
||||
embedding_model_provider: embeddingModel.provider,
|
||||
indexing_technique: indexingTechnique,
|
||||
} as CreateDocumentReq
|
||||
}
|
||||
const params: CreateDocumentReq = {
|
||||
data_source: {
|
||||
type: dataSourceType,
|
||||
info_list: {
|
||||
data_source_type: dataSourceType,
|
||||
},
|
||||
},
|
||||
indexing_technique: indexingTechnique,
|
||||
process_rule: processRule,
|
||||
summary_index_setting: summaryIndexSetting,
|
||||
doc_form: currentDocForm,
|
||||
doc_language: docLanguage,
|
||||
retrieval_model: retrievalConfig,
|
||||
embedding_model: embeddingModel.model,
|
||||
embedding_model_provider: embeddingModel.provider,
|
||||
} as CreateDocumentReq
|
||||
// Add data source specific info
|
||||
if (dataSourceType === DataSourceType.FILE) {
|
||||
params.data_source!.info_list.file_info_list = {
|
||||
file_ids: files.map((file) => file.id || '').filter(Boolean),
|
||||
}
|
||||
}
|
||||
if (dataSourceType === DataSourceType.NOTION)
|
||||
params.data_source!.info_list.notion_info_list = getNotionInfo(
|
||||
notionPages,
|
||||
notionCredentialId,
|
||||
)
|
||||
if (dataSourceType === DataSourceType.WEB) {
|
||||
params.data_source!.info_list.website_info_list = getWebsiteInfo({
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
})
|
||||
}
|
||||
return params
|
||||
},
|
||||
[
|
||||
isSetting,
|
||||
documentDetail,
|
||||
dataSourceType,
|
||||
files,
|
||||
notionPages,
|
||||
notionCredentialId,
|
||||
websitePages,
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
crawlOptions,
|
||||
],
|
||||
)
|
||||
// Execute creation
|
||||
const executeCreation = useCallback(
|
||||
async (
|
||||
params: CreateDocumentReq,
|
||||
indexType: IndexingType,
|
||||
retrievalConfig: RetrievalConfig,
|
||||
) => {
|
||||
if (datasetId && !isSetting && !canCreateDocument) return
|
||||
|
||||
if (!datasetId) {
|
||||
await createFirstDocument(
|
||||
{ body: params },
|
||||
{
|
||||
onSuccess(data) {
|
||||
updateIndexingTypeCache?.(indexType)
|
||||
updateResultCache?.(data)
|
||||
updateRetrievalMethodCache?.(retrievalConfig.search_method as RETRIEVE_METHOD)
|
||||
},
|
||||
},
|
||||
)
|
||||
} else {
|
||||
await createDocument(
|
||||
{ params: { dataset_id: datasetId }, body: params },
|
||||
{
|
||||
onSuccess(data) {
|
||||
updateIndexingTypeCache?.(indexType)
|
||||
updateResultCache?.(data)
|
||||
updateRetrievalMethodCache?.(retrievalConfig.search_method as RETRIEVE_METHOD)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
mutateDatasetRes?.()
|
||||
invalidDatasetList()
|
||||
trackEvent('create_datasets', {
|
||||
data_source_type: dataSourceType,
|
||||
indexing_technique: indexType,
|
||||
})
|
||||
onStepChange?.(+1)
|
||||
if (isSetting) onSave?.()
|
||||
},
|
||||
[
|
||||
datasetId,
|
||||
createFirstDocument,
|
||||
createDocument,
|
||||
updateIndexingTypeCache,
|
||||
updateResultCache,
|
||||
updateRetrievalMethodCache,
|
||||
mutateDatasetRes,
|
||||
invalidDatasetList,
|
||||
dataSourceType,
|
||||
onStepChange,
|
||||
isSetting,
|
||||
canCreateDocument,
|
||||
onSave,
|
||||
],
|
||||
)
|
||||
// Validate preview params
|
||||
const validatePreviewParams = useCallback(
|
||||
(maxChunkLength: number): boolean => {
|
||||
if (maxChunkLength > MAXIMUM_CHUNK_TOKEN_LENGTH) {
|
||||
toast.error(
|
||||
t(($) => $['stepTwo.maxLengthCheck'], {
|
||||
ns: 'datasetCreation',
|
||||
limit: MAXIMUM_CHUNK_TOKEN_LENGTH,
|
||||
}),
|
||||
)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
[t],
|
||||
)
|
||||
return {
|
||||
isCreating,
|
||||
validateParams,
|
||||
buildCreationParams,
|
||||
executeCreation,
|
||||
validatePreviewParams,
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { RetrievalConfig } from '@/types/app'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { checkShowMultiModalTip } from '@/app/components/datasets/settings/utils'
|
||||
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import {
|
||||
useDefaultModel,
|
||||
useModelListAndDefaultModelAndCurrentProviderAndModel,
|
||||
} from '@/app/components/header/account-setting/model-provider-page/hooks'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { RETRIEVE_METHOD } from '@/types/app'
|
||||
|
||||
export const IndexingType = {
|
||||
QUALIFIED: 'high_quality',
|
||||
ECONOMICAL: 'economy',
|
||||
} as const
|
||||
|
||||
export type IndexingType = (typeof IndexingType)[keyof typeof IndexingType]
|
||||
|
||||
const DEFAULT_RETRIEVAL_CONFIG: RetrievalConfig = {
|
||||
search_method: RETRIEVE_METHOD.semantic,
|
||||
reranking_enable: false,
|
||||
reranking_model: {
|
||||
reranking_provider_name: '',
|
||||
reranking_model_name: '',
|
||||
},
|
||||
top_k: 3,
|
||||
score_threshold_enabled: false,
|
||||
score_threshold: 0.5,
|
||||
}
|
||||
|
||||
type UseIndexingConfigOptions = {
|
||||
initialIndexType?: IndexingType
|
||||
initialEmbeddingModel?: DefaultModel
|
||||
initialRetrievalConfig?: RetrievalConfig
|
||||
isAPIKeySet: boolean
|
||||
hasSetIndexType: boolean
|
||||
}
|
||||
|
||||
export const useIndexingConfig = (options: UseIndexingConfigOptions) => {
|
||||
const {
|
||||
initialIndexType,
|
||||
initialEmbeddingModel,
|
||||
initialRetrievalConfig,
|
||||
isAPIKeySet,
|
||||
hasSetIndexType,
|
||||
} = options
|
||||
|
||||
// Rerank model
|
||||
const {
|
||||
modelList: rerankModelList,
|
||||
defaultModel: rerankDefaultModel,
|
||||
currentModel: isRerankDefaultModelValid,
|
||||
} = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.rerank)
|
||||
|
||||
// Embedding model list
|
||||
const { data: embeddingModelList = [] } = useQuery(
|
||||
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
|
||||
input: { params: { model_type: ModelTypeEnum.textEmbedding } },
|
||||
select: (response) => response.data,
|
||||
}),
|
||||
)
|
||||
const { data: defaultEmbeddingModel } = useDefaultModel(ModelTypeEnum.textEmbedding)
|
||||
|
||||
// Index type state
|
||||
const [indexType, setIndexType] = useState<IndexingType>(() => {
|
||||
if (initialIndexType) return initialIndexType
|
||||
return isAPIKeySet ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL
|
||||
})
|
||||
|
||||
// Embedding model state
|
||||
const [embeddingModel, setEmbeddingModel] = useState<DefaultModel>(
|
||||
initialEmbeddingModel ?? {
|
||||
provider: defaultEmbeddingModel?.provider.provider || '',
|
||||
model: defaultEmbeddingModel?.model || '',
|
||||
},
|
||||
)
|
||||
|
||||
// Retrieval config state
|
||||
const [retrievalConfig, setRetrievalConfig] = useState<RetrievalConfig>(
|
||||
initialRetrievalConfig ?? DEFAULT_RETRIEVAL_CONFIG,
|
||||
)
|
||||
|
||||
// Sync retrieval config with rerank model when available
|
||||
useEffect(() => {
|
||||
if (initialRetrievalConfig) return
|
||||
|
||||
setRetrievalConfig({
|
||||
search_method: RETRIEVE_METHOD.semantic,
|
||||
reranking_enable: !!isRerankDefaultModelValid,
|
||||
reranking_model: {
|
||||
reranking_provider_name: isRerankDefaultModelValid
|
||||
? (rerankDefaultModel?.provider.provider ?? '')
|
||||
: '',
|
||||
reranking_model_name: isRerankDefaultModelValid ? (rerankDefaultModel?.model ?? '') : '',
|
||||
},
|
||||
top_k: 3,
|
||||
score_threshold_enabled: false,
|
||||
score_threshold: 0.5,
|
||||
})
|
||||
}, [rerankDefaultModel, isRerankDefaultModelValid, initialRetrievalConfig])
|
||||
|
||||
// Sync index type with props
|
||||
useEffect(() => {
|
||||
if (initialIndexType) setIndexType(initialIndexType)
|
||||
else setIndexType(isAPIKeySet ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
|
||||
}, [isAPIKeySet, initialIndexType])
|
||||
|
||||
// Show multimodal tip
|
||||
const showMultiModalTip = useMemo(() => {
|
||||
return checkShowMultiModalTip({
|
||||
embeddingModel,
|
||||
rerankingEnable: retrievalConfig.reranking_enable,
|
||||
rerankModel: {
|
||||
rerankingProviderName: retrievalConfig.reranking_model.reranking_provider_name,
|
||||
rerankingModelName: retrievalConfig.reranking_model.reranking_model_name,
|
||||
},
|
||||
indexMethod: indexType,
|
||||
embeddingModelList,
|
||||
rerankModelList,
|
||||
})
|
||||
}, [embeddingModel, retrievalConfig, indexType, embeddingModelList, rerankModelList])
|
||||
|
||||
// Get effective indexing technique
|
||||
const getIndexingTechnique = () => initialIndexType || indexType
|
||||
|
||||
return {
|
||||
// Index type
|
||||
indexType,
|
||||
setIndexType,
|
||||
hasSetIndexType,
|
||||
getIndexingTechnique,
|
||||
|
||||
// Embedding model
|
||||
embeddingModel,
|
||||
setEmbeddingModel,
|
||||
embeddingModelList,
|
||||
defaultEmbeddingModel,
|
||||
|
||||
// Retrieval config
|
||||
retrievalConfig,
|
||||
setRetrievalConfig,
|
||||
rerankModelList,
|
||||
rerankDefaultModel,
|
||||
isRerankDefaultModelValid,
|
||||
|
||||
// Computed
|
||||
showMultiModalTip,
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import type { StepTwoFile, StepTwoNotionPage } from '../types'
|
||||
import type { IndexingType } from './use-indexing-config'
|
||||
import type { ChunkingMode, CrawlOptions, CrawlResultItem, ProcessRule } from '@/models/datasets'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useCallback } from 'react'
|
||||
import { DataSourceProvider } from '@/models/common'
|
||||
import { DataSourceType } from '@/models/datasets'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import {
|
||||
getFileIndexingEstimateParamsForFile,
|
||||
getFileIndexingEstimateParamsForNotion,
|
||||
getFileIndexingEstimateParamsForWeb,
|
||||
} from '../creation-params'
|
||||
|
||||
type UseIndexingEstimateOptions = {
|
||||
dataSourceType: DataSourceType
|
||||
datasetId?: string
|
||||
// Document settings
|
||||
currentDocForm: ChunkingMode
|
||||
docLanguage: string
|
||||
// File data source
|
||||
files: StepTwoFile[]
|
||||
previewItemId?: string
|
||||
// Notion data source
|
||||
notionPages: StepTwoNotionPage[]
|
||||
notionCredentialId: string
|
||||
// Website data source
|
||||
websitePages: CrawlResultItem[]
|
||||
crawlOptions?: CrawlOptions
|
||||
websiteCrawlProvider?: DataSourceProvider
|
||||
websiteCrawlJobId?: string
|
||||
// Processing
|
||||
indexingTechnique: IndexingType
|
||||
processRule: ProcessRule
|
||||
}
|
||||
|
||||
export const useIndexingEstimate = (options: UseIndexingEstimateOptions) => {
|
||||
const {
|
||||
dataSourceType,
|
||||
datasetId,
|
||||
currentDocForm,
|
||||
docLanguage,
|
||||
files,
|
||||
previewItemId,
|
||||
notionPages,
|
||||
notionCredentialId,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
} = options
|
||||
|
||||
// Step two keeps one data source, so one estimate request serves it.
|
||||
const estimateMutation = useMutation(
|
||||
consoleQuery.datasets.indexingEstimate.post.mutationOptions(),
|
||||
)
|
||||
|
||||
const getEstimateParams = useCallback(
|
||||
(selectedId?: string) => {
|
||||
if (dataSourceType === DataSourceType.FILE) {
|
||||
return getFileIndexingEstimateParamsForFile({
|
||||
docForm: currentDocForm,
|
||||
docLanguage,
|
||||
dataSourceType: DataSourceType.FILE,
|
||||
files: selectedId ? files.filter((file) => file.id === selectedId) : files,
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
dataset_id: datasetId!,
|
||||
})
|
||||
}
|
||||
if (dataSourceType === DataSourceType.NOTION) {
|
||||
return getFileIndexingEstimateParamsForNotion({
|
||||
docForm: currentDocForm,
|
||||
docLanguage,
|
||||
dataSourceType: DataSourceType.NOTION,
|
||||
notionPages: notionPages.filter((page) => page.page_id === selectedId),
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
dataset_id: datasetId || '',
|
||||
credential_id: notionCredentialId,
|
||||
})
|
||||
}
|
||||
return getFileIndexingEstimateParamsForWeb({
|
||||
docForm: currentDocForm,
|
||||
docLanguage,
|
||||
dataSourceType: DataSourceType.WEB,
|
||||
websitePages: websitePages.filter((page) => page.source_url === selectedId),
|
||||
crawlOptions,
|
||||
websiteCrawlProvider: websiteCrawlProvider ?? DataSourceProvider.jinaReader,
|
||||
websiteCrawlJobId: websiteCrawlJobId ?? '',
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
dataset_id: datasetId || '',
|
||||
})
|
||||
},
|
||||
[
|
||||
dataSourceType,
|
||||
currentDocForm,
|
||||
docLanguage,
|
||||
files,
|
||||
notionPages,
|
||||
notionCredentialId,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
indexingTechnique,
|
||||
processRule,
|
||||
datasetId,
|
||||
],
|
||||
)
|
||||
|
||||
const { mutate } = estimateMutation
|
||||
const fetchEstimate = useCallback(
|
||||
(selectedId = previewItemId) => {
|
||||
mutate({ body: getEstimateParams(selectedId) })
|
||||
},
|
||||
[mutate, getEstimateParams, previewItemId],
|
||||
)
|
||||
|
||||
return {
|
||||
currentMutation: estimateMutation,
|
||||
estimate: estimateMutation.data,
|
||||
isIdle: estimateMutation.isIdle,
|
||||
isPending: estimateMutation.isPending,
|
||||
fetchEstimate,
|
||||
reset: estimateMutation.reset,
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import type { DocumentDetailResponse } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { StepTwoFile, StepTwoNotionPage } from '../types'
|
||||
import type { CrawlResultItem, DocumentItem } from '@/models/datasets'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { DataSourceType } from '@/models/datasets'
|
||||
|
||||
type UsePreviewStateOptions = {
|
||||
dataSourceType: DataSourceType
|
||||
files: StepTwoFile[]
|
||||
notionPages: StepTwoNotionPage[]
|
||||
websitePages: CrawlResultItem[]
|
||||
documentDetail?: DocumentDetailResponse
|
||||
datasetId?: string
|
||||
}
|
||||
|
||||
export const usePreviewState = (options: UsePreviewStateOptions) => {
|
||||
const { dataSourceType, files, notionPages, websitePages, documentDetail, datasetId } = options
|
||||
|
||||
// File preview state
|
||||
// Editing an existing document has no preview item until one is picked.
|
||||
const isEditing = !!datasetId && !!documentDetail
|
||||
const [previewFile, setPreviewFile] = useState<StepTwoFile | DocumentItem | undefined>(
|
||||
isEditing ? undefined : files[0],
|
||||
)
|
||||
|
||||
// Notion page preview state
|
||||
const [previewNotionPage, setPreviewNotionPage] = useState<StepTwoNotionPage | undefined>(
|
||||
isEditing ? undefined : notionPages[0],
|
||||
)
|
||||
|
||||
// Website page preview state
|
||||
const [previewWebsitePage, setPreviewWebsitePage] = useState<CrawlResultItem | undefined>(
|
||||
isEditing ? undefined : websitePages[0],
|
||||
)
|
||||
|
||||
// Get preview items for document picker based on data source type
|
||||
const getPreviewPickerItems = useCallback(() => {
|
||||
if (dataSourceType === DataSourceType.FILE) {
|
||||
return files.map((file) => ({
|
||||
id: file.id ?? '',
|
||||
name: file.name,
|
||||
extension: file.extension ?? '',
|
||||
}))
|
||||
}
|
||||
if (dataSourceType === DataSourceType.NOTION) {
|
||||
return notionPages.map((page) => ({
|
||||
id: page.page_id,
|
||||
name: page.page_name,
|
||||
extension: 'md',
|
||||
}))
|
||||
}
|
||||
if (dataSourceType === DataSourceType.WEB) {
|
||||
return websitePages.map((page) => ({
|
||||
id: page.source_url,
|
||||
name: page.title,
|
||||
extension: 'md',
|
||||
}))
|
||||
}
|
||||
return []
|
||||
}, [dataSourceType, files, notionPages, websitePages])
|
||||
|
||||
// Get current preview value for picker
|
||||
const getPreviewPickerValue = useCallback(() => {
|
||||
if (dataSourceType === DataSourceType.FILE) {
|
||||
return (
|
||||
previewFile && {
|
||||
id: previewFile.id ?? '',
|
||||
name: previewFile.name,
|
||||
extension: previewFile.extension ?? '',
|
||||
}
|
||||
)
|
||||
}
|
||||
if (dataSourceType === DataSourceType.NOTION) {
|
||||
return {
|
||||
id: previewNotionPage?.page_id || '',
|
||||
name: previewNotionPage?.page_name || '',
|
||||
extension: 'md',
|
||||
}
|
||||
}
|
||||
if (dataSourceType === DataSourceType.WEB) {
|
||||
return {
|
||||
id: previewWebsitePage?.source_url || '',
|
||||
name: previewWebsitePage?.title || '',
|
||||
extension: 'md',
|
||||
}
|
||||
}
|
||||
return { id: '', name: '', extension: '' }
|
||||
}, [dataSourceType, previewFile, previewNotionPage, previewWebsitePage])
|
||||
|
||||
// Handle preview change
|
||||
const handlePreviewChange = useCallback(
|
||||
(selected: { id: string; name: string }) => {
|
||||
if (dataSourceType === DataSourceType.FILE) {
|
||||
setPreviewFile(files.find((file) => file.id === selected.id))
|
||||
} else if (dataSourceType === DataSourceType.NOTION) {
|
||||
const selectedPage = notionPages.find((page) => page.page_id === selected.id)
|
||||
if (selectedPage) setPreviewNotionPage(selectedPage)
|
||||
} else if (dataSourceType === DataSourceType.WEB) {
|
||||
const selectedPage = websitePages.find((page) => page.source_url === selected.id)
|
||||
if (selectedPage) setPreviewWebsitePage(selectedPage)
|
||||
}
|
||||
},
|
||||
[dataSourceType, files, notionPages, websitePages],
|
||||
)
|
||||
|
||||
return {
|
||||
// File preview
|
||||
previewFile,
|
||||
setPreviewFile,
|
||||
|
||||
// Notion preview
|
||||
previewNotionPage,
|
||||
setPreviewNotionPage,
|
||||
|
||||
// Website preview
|
||||
previewWebsitePage,
|
||||
setPreviewWebsitePage,
|
||||
|
||||
// Picker helpers
|
||||
getPreviewPickerItems,
|
||||
getPreviewPickerValue,
|
||||
handlePreviewChange,
|
||||
}
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
import type { PreProcessingRule } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type {
|
||||
ParentMode,
|
||||
ProcessRule,
|
||||
Rules,
|
||||
SummaryIndexSetting as SummaryIndexSettingType,
|
||||
} from '@/models/datasets'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { env } from '@/env'
|
||||
import { ChunkingMode, ProcessMode } from '@/models/datasets'
|
||||
import escape from './escape'
|
||||
import unescape from './unescape'
|
||||
|
||||
// Constants
|
||||
const DEFAULT_SEGMENT_IDENTIFIER = '\\n\\n'
|
||||
const DEFAULT_MAXIMUM_CHUNK_LENGTH = 1024
|
||||
const DEFAULT_OVERLAP = 50
|
||||
export const MAXIMUM_CHUNK_TOKEN_LENGTH = env.NEXT_PUBLIC_INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH
|
||||
|
||||
export type ParentChildConfig = {
|
||||
chunkForContext: ParentMode
|
||||
parent: {
|
||||
delimiter: string
|
||||
maxLength: number
|
||||
}
|
||||
child: {
|
||||
delimiter: string
|
||||
maxLength: number
|
||||
}
|
||||
}
|
||||
|
||||
const defaultParentChildConfig: ParentChildConfig = {
|
||||
chunkForContext: 'paragraph',
|
||||
parent: {
|
||||
delimiter: '\\n\\n',
|
||||
maxLength: 1024,
|
||||
},
|
||||
child: {
|
||||
delimiter: '\\n',
|
||||
maxLength: 512,
|
||||
},
|
||||
}
|
||||
|
||||
type UseSegmentationStateOptions = {
|
||||
initialSegmentationType?: ProcessMode
|
||||
initialSummaryIndexSetting?: SummaryIndexSettingType
|
||||
}
|
||||
|
||||
export const useSegmentationState = (options: UseSegmentationStateOptions = {}) => {
|
||||
const { initialSegmentationType, initialSummaryIndexSetting } = options
|
||||
|
||||
// Segmentation type (general or parent-child)
|
||||
const [segmentationType, setSegmentationType] = useState<ProcessMode>(
|
||||
initialSegmentationType ?? ProcessMode.general,
|
||||
)
|
||||
|
||||
// General chunking settings
|
||||
const [segmentIdentifier, doSetSegmentIdentifier] = useState(DEFAULT_SEGMENT_IDENTIFIER)
|
||||
const [maxChunkLength, setMaxChunkLength] = useState(DEFAULT_MAXIMUM_CHUNK_LENGTH)
|
||||
const [limitMaxChunkLength, setLimitMaxChunkLength] = useState(MAXIMUM_CHUNK_TOKEN_LENGTH)
|
||||
const [overlap, setOverlap] = useState(DEFAULT_OVERLAP)
|
||||
|
||||
// Pre-processing rules
|
||||
const [rules, setRules] = useState<PreProcessingRule[]>([])
|
||||
const [defaultConfig, setDefaultConfig] = useState<Rules>()
|
||||
const [summaryIndexSetting, setSummaryIndexSetting] = useState<
|
||||
SummaryIndexSettingType | undefined
|
||||
>(initialSummaryIndexSetting)
|
||||
const summaryIndexSettingRef = useRef<SummaryIndexSettingType | undefined>(
|
||||
initialSummaryIndexSetting,
|
||||
)
|
||||
const handleSummaryIndexSettingChange = useCallback((payload: SummaryIndexSettingType) => {
|
||||
setSummaryIndexSetting((prev) => {
|
||||
const newSetting = { ...prev, ...payload }
|
||||
summaryIndexSettingRef.current = newSetting
|
||||
return newSetting
|
||||
})
|
||||
}, [])
|
||||
|
||||
// Parent-child config
|
||||
const [parentChildConfig, setParentChildConfig] =
|
||||
useState<ParentChildConfig>(defaultParentChildConfig)
|
||||
|
||||
// Escaped segment identifier setter
|
||||
const setSegmentIdentifier = useCallback((value: string, canEmpty?: boolean) => {
|
||||
if (value) {
|
||||
doSetSegmentIdentifier(escape(value))
|
||||
} else {
|
||||
doSetSegmentIdentifier(canEmpty ? '' : DEFAULT_SEGMENT_IDENTIFIER)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Rule toggle handler
|
||||
const toggleRule = useCallback((id: string) => {
|
||||
setRules((prev) =>
|
||||
prev.map((rule) => (rule.id === id ? { ...rule, enabled: !rule.enabled } : rule)),
|
||||
)
|
||||
}, [])
|
||||
|
||||
// Reset to defaults
|
||||
const resetToDefaults = useCallback(() => {
|
||||
if (defaultConfig) {
|
||||
setSegmentIdentifier(defaultConfig.segmentation.separator)
|
||||
setMaxChunkLength(defaultConfig.segmentation.max_tokens)
|
||||
setOverlap(defaultConfig.segmentation.chunk_overlap!)
|
||||
setRules(defaultConfig.pre_processing_rules)
|
||||
}
|
||||
setParentChildConfig(defaultParentChildConfig)
|
||||
}, [defaultConfig, setSegmentIdentifier])
|
||||
|
||||
// Apply config from document detail
|
||||
const applyConfigFromRules = useCallback(
|
||||
(rulesConfig: Rules, isHierarchical: boolean) => {
|
||||
const separator = rulesConfig.segmentation.separator
|
||||
const max = rulesConfig.segmentation.max_tokens
|
||||
const chunkOverlap = rulesConfig.segmentation.chunk_overlap
|
||||
|
||||
setSegmentIdentifier(separator)
|
||||
setMaxChunkLength(max)
|
||||
setOverlap(chunkOverlap!)
|
||||
setRules(rulesConfig.pre_processing_rules)
|
||||
setDefaultConfig(rulesConfig)
|
||||
|
||||
if (isHierarchical) {
|
||||
setParentChildConfig({
|
||||
chunkForContext: rulesConfig.parent_mode || 'paragraph',
|
||||
parent: {
|
||||
delimiter: escape(rulesConfig.segmentation.separator),
|
||||
maxLength: rulesConfig.segmentation.max_tokens,
|
||||
},
|
||||
child: {
|
||||
delimiter: escape(rulesConfig.subchunk_segmentation!.separator),
|
||||
maxLength: rulesConfig.subchunk_segmentation!.max_tokens,
|
||||
},
|
||||
})
|
||||
}
|
||||
},
|
||||
[setSegmentIdentifier],
|
||||
)
|
||||
|
||||
// Get process rule for API
|
||||
const getProcessRule = useCallback(
|
||||
(docForm: ChunkingMode): ProcessRule => {
|
||||
if (docForm === ChunkingMode.parentChild) {
|
||||
return {
|
||||
rules: {
|
||||
pre_processing_rules: rules,
|
||||
segmentation: {
|
||||
separator: unescape(parentChildConfig.parent.delimiter),
|
||||
max_tokens: parentChildConfig.parent.maxLength,
|
||||
},
|
||||
parent_mode: parentChildConfig.chunkForContext,
|
||||
subchunk_segmentation: {
|
||||
separator: unescape(parentChildConfig.child.delimiter),
|
||||
max_tokens: parentChildConfig.child.maxLength,
|
||||
},
|
||||
},
|
||||
mode: 'hierarchical',
|
||||
summary_index_setting: summaryIndexSettingRef.current,
|
||||
} as ProcessRule
|
||||
}
|
||||
|
||||
return {
|
||||
rules: {
|
||||
pre_processing_rules: rules,
|
||||
segmentation: {
|
||||
separator: unescape(segmentIdentifier),
|
||||
max_tokens: maxChunkLength,
|
||||
chunk_overlap: overlap,
|
||||
},
|
||||
},
|
||||
mode: segmentationType,
|
||||
summary_index_setting: summaryIndexSettingRef.current,
|
||||
} as ProcessRule
|
||||
},
|
||||
[rules, parentChildConfig, segmentIdentifier, maxChunkLength, overlap, segmentationType],
|
||||
)
|
||||
|
||||
// Update parent config field
|
||||
const updateParentConfig = useCallback(
|
||||
(field: 'delimiter' | 'maxLength', value: string | number) => {
|
||||
setParentChildConfig((prev) => {
|
||||
let newValue: string | number
|
||||
if (field === 'delimiter') newValue = value ? escape(value as string) : ''
|
||||
else newValue = value
|
||||
return {
|
||||
...prev,
|
||||
parent: { ...prev.parent, [field]: newValue },
|
||||
}
|
||||
})
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// Update child config field
|
||||
const updateChildConfig = useCallback(
|
||||
(field: 'delimiter' | 'maxLength', value: string | number) => {
|
||||
setParentChildConfig((prev) => {
|
||||
let newValue: string | number
|
||||
if (field === 'delimiter') newValue = value ? escape(value as string) : ''
|
||||
else newValue = value
|
||||
return {
|
||||
...prev,
|
||||
child: { ...prev.child, [field]: newValue },
|
||||
}
|
||||
})
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// Set chunk for context mode
|
||||
const setChunkForContext = useCallback((mode: ParentMode) => {
|
||||
setParentChildConfig((prev) => ({ ...prev, chunkForContext: mode }))
|
||||
}, [])
|
||||
|
||||
return {
|
||||
// General chunking state
|
||||
segmentationType,
|
||||
setSegmentationType,
|
||||
segmentIdentifier,
|
||||
setSegmentIdentifier,
|
||||
maxChunkLength,
|
||||
setMaxChunkLength,
|
||||
limitMaxChunkLength,
|
||||
setLimitMaxChunkLength,
|
||||
overlap,
|
||||
setOverlap,
|
||||
|
||||
// Rules
|
||||
rules,
|
||||
setRules,
|
||||
defaultConfig,
|
||||
setDefaultConfig,
|
||||
toggleRule,
|
||||
summaryIndexSetting,
|
||||
handleSummaryIndexSettingChange,
|
||||
|
||||
// Parent-child config
|
||||
parentChildConfig,
|
||||
setParentChildConfig,
|
||||
updateParentConfig,
|
||||
updateChildConfig,
|
||||
setChunkForContext,
|
||||
|
||||
// Actions
|
||||
resetToDefaults,
|
||||
applyConfigFromRules,
|
||||
getProcessRule,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
@reference "../../../../styles/globals.css";
|
||||
|
||||
.pageHeader {
|
||||
@apply flex items-center justify-between px-16;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
left: 0;
|
||||
padding-top: 42px;
|
||||
padding-bottom: 12px;
|
||||
background-color: #fff;
|
||||
font-weight: 600;
|
||||
font-size: 18px;
|
||||
line-height: 28px;
|
||||
color: #101828;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.segmentationItem {
|
||||
min-height: 68px;
|
||||
}
|
||||
|
||||
.indexItem {
|
||||
min-height: 126px;
|
||||
}
|
||||
|
||||
.indexItem .disableMask {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(255, 255, 255, 0.5);
|
||||
border-radius: 12px;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.indexItem .warningTip {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
padding: 8px 20px 8px 40px;
|
||||
background: #fffaeb;
|
||||
border-top: 0.5px solid #fef0c7;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: #344054;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.indexItem .warningTip::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 11px;
|
||||
left: 20px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background: center no-repeat url(../assets/alert-triangle.svg);
|
||||
background-size: 12px;
|
||||
}
|
||||
|
||||
.indexItem .warningTip .click {
|
||||
color: #155eef;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.disabled {
|
||||
cursor: not-allowed !important;
|
||||
}
|
||||
|
||||
.indexItem.disabled:hover {
|
||||
background-color: #fcfcfd;
|
||||
border-color: #f2f4f7;
|
||||
box-shadow: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.indexItem.disabled:hover .radio {
|
||||
@apply h-4 w-4 rounded-full border-[2px] border-gray-200;
|
||||
}
|
||||
|
||||
.radioItem {
|
||||
@apply relative mb-2 cursor-pointer rounded-xl border border-components-option-card-option-border bg-components-option-card-option-bg;
|
||||
}
|
||||
|
||||
.radioItem.segmentationItem.custom {
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.radioItem.segmentationItem.custom .typeHeader {
|
||||
/* height: 65px; */
|
||||
}
|
||||
|
||||
.radioItem.indexItem .typeHeader {
|
||||
@apply py-4 pr-5;
|
||||
}
|
||||
|
||||
.radioItem.indexItem.active .typeHeader {
|
||||
padding: 15.5px 19.5px 15.5px 63.5px;
|
||||
}
|
||||
|
||||
.radioItem.indexItem .radio {
|
||||
top: 16px;
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
.radioItem.indexItem.active .radio {
|
||||
top: 16px;
|
||||
right: 19.5px;
|
||||
}
|
||||
|
||||
.radioItem.indexItem .typeHeader .title {
|
||||
@apply pb-1;
|
||||
}
|
||||
|
||||
.radioItem .typeIcon {
|
||||
position: absolute;
|
||||
top: 18px;
|
||||
left: 20px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
background: #eef4ff center no-repeat;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.typeIcon.auto {
|
||||
background-color: #f5f3ff;
|
||||
background-image: url(../assets/zap-fast.svg);
|
||||
}
|
||||
|
||||
.typeIcon.customize {
|
||||
background-image: url(../assets/sliders-02.svg);
|
||||
}
|
||||
|
||||
.typeIcon.qualified {
|
||||
background-color: #fff6ed;
|
||||
background-image: url(../assets/star-07.svg);
|
||||
}
|
||||
|
||||
.typeIcon.economical {
|
||||
background-image: url(../assets/piggy-bank-mod.svg);
|
||||
}
|
||||
|
||||
.radioItem .radio {
|
||||
@apply h-4 w-4 rounded-full border-[2px] border-gray-200;
|
||||
position: absolute;
|
||||
top: 26px;
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
.radioItem:hover {
|
||||
background-color: #ffffff;
|
||||
border-color: #b2ccff;
|
||||
box-shadow:
|
||||
0px 12px 16px -4px rgba(16, 24, 40, 0.08),
|
||||
0px 4px 6px -2px rgba(16, 24, 40, 0.03);
|
||||
}
|
||||
|
||||
.radioItem:hover .radio {
|
||||
border-color: #155eef;
|
||||
}
|
||||
|
||||
.radioItem.active {
|
||||
border-width: 1.5px;
|
||||
border-color: #528bff;
|
||||
box-shadow:
|
||||
0px 1px 3px rgba(16, 24, 40, 0.1),
|
||||
0px 1px 2px rgba(16, 24, 40, 0.06);
|
||||
}
|
||||
|
||||
.radioItem.active .radio {
|
||||
top: 25.5px;
|
||||
right: 19.5px;
|
||||
border-width: 5px;
|
||||
border-color: #155eef;
|
||||
}
|
||||
|
||||
.radioItem.active:hover {
|
||||
border-width: 1.5px;
|
||||
border-color: #528bff;
|
||||
box-shadow:
|
||||
0px 1px 3px rgba(16, 24, 40, 0.1),
|
||||
0px 1px 2px rgba(16, 24, 40, 0.06);
|
||||
}
|
||||
|
||||
.radioItem.active .typeIcon {
|
||||
top: 17.5px;
|
||||
left: 19.5px;
|
||||
}
|
||||
|
||||
.radioItem.active .typeHeader {
|
||||
padding: 11.5px 63.5px;
|
||||
}
|
||||
|
||||
.typeHeader {
|
||||
@apply flex flex-col justify-center px-16 py-3;
|
||||
}
|
||||
|
||||
.typeHeader .title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-bottom: 2px;
|
||||
font-weight: 500;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
color: #101828;
|
||||
}
|
||||
|
||||
.typeHeader .tip {
|
||||
font-weight: 400;
|
||||
font-size: 13px;
|
||||
line-height: 18px;
|
||||
color: #667085;
|
||||
}
|
||||
|
||||
.recommendTag {
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 0 6px;
|
||||
margin-left: 4px;
|
||||
border: 1px solid #e0eaff;
|
||||
border-radius: 6px;
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
color: #444ce7;
|
||||
}
|
||||
|
||||
.typeFormBody {
|
||||
@apply px-16;
|
||||
border-top: 1px solid #f2f4f7;
|
||||
}
|
||||
|
||||
.formRow {
|
||||
@apply mt-6 flex justify-between;
|
||||
}
|
||||
|
||||
.formRow .label {
|
||||
@apply mb-2 p-0;
|
||||
font-weight: 500;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
color: #101828;
|
||||
}
|
||||
|
||||
.ruleItem {
|
||||
@apply flex items-center py-1.5;
|
||||
}
|
||||
|
||||
.formFooter {
|
||||
padding: 16px 0 28px;
|
||||
}
|
||||
|
||||
.formFooter .button {
|
||||
font-size: 13px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.input {
|
||||
@apply inline-flex h-9 w-full rounded-lg px-2 py-1 pr-14 text-xs leading-normal;
|
||||
@apply bg-gray-100 caret-primary-600 placeholder:text-gray-400 hover:bg-gray-100 focus:bg-white focus:inset-ring-1 focus:inset-ring-gray-200 focus-visible:outline-hidden;
|
||||
}
|
||||
|
||||
.source {
|
||||
@apply mt-8 flex items-center justify-between rounded-xl border border-gray-100 bg-gray-50 px-6 py-4;
|
||||
}
|
||||
|
||||
.source .divider {
|
||||
@apply mx-4 w-px shrink-0 bg-gray-200;
|
||||
height: 42px;
|
||||
}
|
||||
|
||||
.fileIcon {
|
||||
@apply mr-1 inline-flex h-6 w-6 bg-center bg-no-repeat;
|
||||
background-image: url(../assets/pdf.svg);
|
||||
background-size: 24px;
|
||||
}
|
||||
|
||||
.fileIcon.pdf {
|
||||
background-image: url(../assets/pdf.svg);
|
||||
}
|
||||
|
||||
.fileIcon.csv {
|
||||
background-image: url(../assets/csv.svg);
|
||||
}
|
||||
|
||||
.fileIcon.doc {
|
||||
background-image: url(../assets/doc.svg);
|
||||
}
|
||||
|
||||
.fileIcon.docx {
|
||||
background-image: url(../assets/docx.svg);
|
||||
}
|
||||
|
||||
.fileIcon.xlsx,
|
||||
.fileIcon.xls {
|
||||
background-image: url(../assets/xlsx.svg);
|
||||
}
|
||||
|
||||
.fileIcon.html,
|
||||
.fileIcon.htm {
|
||||
background-image: url(../assets/html.svg);
|
||||
}
|
||||
|
||||
.fileIcon.md,
|
||||
.fileIcon.markdown {
|
||||
background-image: url(../assets/md.svg);
|
||||
}
|
||||
|
||||
.fileIcon.txt {
|
||||
background-image: url(../assets/txt.svg);
|
||||
}
|
||||
|
||||
.fileIcon.json {
|
||||
background-image: url(../assets/json.svg);
|
||||
}
|
||||
|
||||
.sourceContent {
|
||||
width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.sourceCount {
|
||||
@apply ml-1 shrink-0;
|
||||
font-weight: 500;
|
||||
font-size: 13px;
|
||||
line-height: 18px;
|
||||
color: #667085;
|
||||
}
|
||||
|
||||
.segmentCount {
|
||||
flex: 1 1 30%;
|
||||
max-width: 120px;
|
||||
}
|
||||
|
||||
.divider {
|
||||
@apply mx-3 h-4 w-px bg-gray-200;
|
||||
}
|
||||
|
||||
.calculating {
|
||||
color: #98a2b3;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.sideTip {
|
||||
@apply flex shrink-0 flex-col items-center;
|
||||
padding-top: 108px;
|
||||
width: 524px;
|
||||
border-left: 0.5px solid #f2f4f7;
|
||||
}
|
||||
|
||||
.tipCard {
|
||||
@apply flex flex-col items-start p-6;
|
||||
width: 320px;
|
||||
background-color: #f9fafb;
|
||||
box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.tipCard .icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 1px solid #eaecf0;
|
||||
border-radius: 6px;
|
||||
background: center no-repeat url(../assets/book-open-01.svg);
|
||||
background-size: 16px;
|
||||
}
|
||||
|
||||
.tipCard .title {
|
||||
margin: 12px 0;
|
||||
font-weight: 500;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
color: #344054;
|
||||
}
|
||||
|
||||
.tipCard .content {
|
||||
font-weight: 400;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
color: #344054;
|
||||
}
|
||||
|
||||
.previewWrap {
|
||||
flex-shrink: 0;
|
||||
width: 524px;
|
||||
}
|
||||
|
||||
.previewWrap.isMobile {
|
||||
max-width: 524px;
|
||||
}
|
||||
|
||||
/*
|
||||
* `fixed` must under `previewHeader` because of style override would not work
|
||||
*/
|
||||
.fixed {
|
||||
padding-top: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
border-bottom: 0.5px solid #eaecf0;
|
||||
backdrop-filter: blur(4px);
|
||||
animation: fix 0.5s;
|
||||
}
|
||||
|
||||
@keyframes fix {
|
||||
from {
|
||||
padding-top: 42px;
|
||||
font-size: 18px;
|
||||
line-height: 28px;
|
||||
}
|
||||
|
||||
to {
|
||||
padding-top: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
'use client'
|
||||
|
||||
import type { FC, MouseEvent } from 'react'
|
||||
import type { StepTwoProps } from './types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RadioGroup } from '@langgenius/dify-ui/radio-group'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useLocale } from '#i18n'
|
||||
import {
|
||||
toChunkingMode,
|
||||
toCreationDataSourceType,
|
||||
toRetrievalConfig,
|
||||
toSummaryIndexSetting,
|
||||
} from '@/app/components/datasets/dataset-fields'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
|
||||
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
|
||||
import { LanguagesSupported } from '@/i18n/language'
|
||||
import { DataSourceProvider } from '@/models/common'
|
||||
import { ChunkingMode, ProcessMode } from '@/models/datasets'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import {
|
||||
GeneralChunkingOptions,
|
||||
IndexingModeSection,
|
||||
ParentChildOptions,
|
||||
PreviewPanel,
|
||||
StepTwoFooter,
|
||||
} from './components'
|
||||
import {
|
||||
IndexingType,
|
||||
MAXIMUM_CHUNK_TOKEN_LENGTH,
|
||||
useDocumentCreation,
|
||||
useIndexingConfig,
|
||||
useIndexingEstimate,
|
||||
usePreviewState,
|
||||
useSegmentationState,
|
||||
} from './hooks'
|
||||
import { isProcessMode, toSegmentationRules } from './process-rule'
|
||||
|
||||
// oxlint-disable-next-line no-barrel-files/no-barrel-files
|
||||
export { IndexingType }
|
||||
|
||||
const StepTwo: FC<StepTwoProps> = ({
|
||||
isSetting,
|
||||
documentDetail,
|
||||
isAPIKeySet,
|
||||
datasetId,
|
||||
indexingType: propsIndexingType,
|
||||
dataSourceType: inCreatePageDataSourceType,
|
||||
files,
|
||||
notionPages = [],
|
||||
notionCredentialId,
|
||||
websitePages = [],
|
||||
crawlOptions,
|
||||
websiteCrawlProvider = DataSourceProvider.jinaReader,
|
||||
websiteCrawlJobId = '',
|
||||
canCreateDocument = true,
|
||||
onStepChange,
|
||||
updateIndexingTypeCache,
|
||||
updateResultCache,
|
||||
onSave,
|
||||
onCancel,
|
||||
updateRetrievalMethodCache,
|
||||
}) => {
|
||||
const generalChunkingModes: readonly ChunkingMode[] = [ChunkingMode.text, ChunkingMode.qa]
|
||||
|
||||
const { t } = useTranslation(['datasetCreation'])
|
||||
const locale = useLocale()
|
||||
const isMobile = useBreakpoints() === MediaType.mobile
|
||||
const [isPreviewOpen, setIsPreviewOpen] = useState(false)
|
||||
const previewTriggerRef = useRef<HTMLButtonElement | null>(null)
|
||||
const currentDataset = useDatasetDetailContextWithSelector((s) => s.dataset)
|
||||
const mutateDatasetRes = useDatasetDetailContextWithSelector((s) => s.mutateDatasetRes)
|
||||
|
||||
// Computed flags
|
||||
const isInUpload = Boolean(currentDataset)
|
||||
const isUploadInEmptyDataset = isInUpload && !currentDataset?.doc_form
|
||||
const isNotUploadInEmptyDataset = !isUploadInEmptyDataset
|
||||
const isInInit = !isInUpload && !isSetting
|
||||
const isInCreatePage = !datasetId || (datasetId && !currentDataset?.data_source_type)
|
||||
const dataSourceType = isInCreatePage
|
||||
? inCreatePageDataSourceType
|
||||
: (toCreationDataSourceType(currentDataset?.data_source_type) ?? inCreatePageDataSourceType)
|
||||
const hasSetIndexType = !!propsIndexingType
|
||||
const isModelAndRetrievalConfigDisabled = !!datasetId && !!currentDataset?.data_source_type
|
||||
|
||||
// Document form state
|
||||
const [docForm, setDocForm] = useState<ChunkingMode>(
|
||||
(datasetId && toChunkingMode(documentDetail?.doc_form)) || ChunkingMode.text,
|
||||
)
|
||||
const [docLanguage, setDocLanguage] = useState<string>(() =>
|
||||
datasetId && documentDetail?.doc_language
|
||||
? documentDetail.doc_language
|
||||
: locale !== LanguagesSupported[1]
|
||||
? 'English'
|
||||
: 'Chinese Simplified',
|
||||
)
|
||||
const [isQAConfirmDialogOpen, setIsQAConfirmDialogOpen] = useState(false)
|
||||
const datasetChunkingMode = toChunkingMode(currentDataset?.doc_form)
|
||||
const currentDocForm = datasetChunkingMode || docForm
|
||||
|
||||
// Custom hooks
|
||||
const segmentation = useSegmentationState({
|
||||
initialSegmentationType:
|
||||
datasetChunkingMode === ChunkingMode.parentChild
|
||||
? ProcessMode.parentChild
|
||||
: ProcessMode.general,
|
||||
initialSummaryIndexSetting:
|
||||
currentDataset?.summary_index_setting &&
|
||||
toSummaryIndexSetting(currentDataset.summary_index_setting),
|
||||
})
|
||||
const showSummaryIndexSetting = !currentDataset
|
||||
const indexing = useIndexingConfig({
|
||||
initialIndexType: propsIndexingType,
|
||||
initialEmbeddingModel: currentDataset?.embedding_model
|
||||
? {
|
||||
provider: currentDataset.embedding_model_provider ?? '',
|
||||
model: currentDataset.embedding_model,
|
||||
}
|
||||
: undefined,
|
||||
initialRetrievalConfig:
|
||||
currentDataset && toRetrievalConfig(currentDataset.retrieval_model_dict),
|
||||
isAPIKeySet,
|
||||
hasSetIndexType,
|
||||
})
|
||||
const preview = usePreviewState({
|
||||
dataSourceType,
|
||||
files,
|
||||
notionPages,
|
||||
websitePages,
|
||||
documentDetail,
|
||||
datasetId,
|
||||
})
|
||||
const creation = useDocumentCreation({
|
||||
datasetId,
|
||||
isSetting,
|
||||
documentDetail,
|
||||
dataSourceType,
|
||||
files,
|
||||
notionPages,
|
||||
notionCredentialId,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
canCreateDocument,
|
||||
onStepChange,
|
||||
updateIndexingTypeCache,
|
||||
updateResultCache,
|
||||
updateRetrievalMethodCache,
|
||||
onSave,
|
||||
mutateDatasetRes,
|
||||
})
|
||||
const estimateHook = useIndexingEstimate({
|
||||
dataSourceType,
|
||||
datasetId,
|
||||
currentDocForm,
|
||||
docLanguage,
|
||||
files,
|
||||
previewItemId: preview.getPreviewPickerValue()?.id,
|
||||
notionPages,
|
||||
notionCredentialId,
|
||||
websitePages,
|
||||
crawlOptions,
|
||||
websiteCrawlProvider,
|
||||
websiteCrawlJobId,
|
||||
indexingTechnique: indexing.getIndexingTechnique() as IndexingType,
|
||||
processRule: segmentation.getProcessRule(currentDocForm),
|
||||
})
|
||||
|
||||
// Fetch default process rule
|
||||
const fetchDefaultProcessRuleMutation = useMutation({
|
||||
...consoleQuery.datasets.processRule.get.mutationOptions(),
|
||||
onSuccess(data) {
|
||||
const defaultRules = data.rules ? toSegmentationRules(data.rules) : undefined
|
||||
if (defaultRules) {
|
||||
segmentation.setSegmentIdentifier(defaultRules.segmentation.separator)
|
||||
segmentation.setMaxChunkLength(defaultRules.segmentation.max_tokens)
|
||||
segmentation.setOverlap(defaultRules.segmentation.chunk_overlap!)
|
||||
segmentation.setRules(defaultRules.pre_processing_rules)
|
||||
segmentation.setDefaultConfig(defaultRules)
|
||||
}
|
||||
segmentation.setLimitMaxChunkLength(data.limits.indexing_max_segmentation_tokens_length)
|
||||
},
|
||||
})
|
||||
|
||||
// Event handlers
|
||||
const handleDocFormChange = useCallback(
|
||||
(value: ChunkingMode) => {
|
||||
if (value === ChunkingMode.qa && indexing.indexType === IndexingType.ECONOMICAL) {
|
||||
setIsQAConfirmDialogOpen(true)
|
||||
return
|
||||
}
|
||||
if (value === ChunkingMode.parentChild && indexing.indexType === IndexingType.ECONOMICAL)
|
||||
indexing.setIndexType(IndexingType.QUALIFIED)
|
||||
setDocForm(value)
|
||||
segmentation.setSegmentationType(
|
||||
value === ChunkingMode.parentChild ? ProcessMode.parentChild : ProcessMode.general,
|
||||
)
|
||||
estimateHook.reset()
|
||||
},
|
||||
[indexing, segmentation, estimateHook],
|
||||
)
|
||||
|
||||
const updatePreview = useCallback(
|
||||
(event: MouseEvent<HTMLButtonElement>) => {
|
||||
if (
|
||||
segmentation.segmentationType === ProcessMode.general &&
|
||||
segmentation.maxChunkLength > MAXIMUM_CHUNK_TOKEN_LENGTH
|
||||
) {
|
||||
toast.error(
|
||||
t(($) => $['stepTwo.maxLengthCheck'], {
|
||||
ns: 'datasetCreation',
|
||||
limit: MAXIMUM_CHUNK_TOKEN_LENGTH,
|
||||
}),
|
||||
)
|
||||
return
|
||||
}
|
||||
previewTriggerRef.current = event.currentTarget
|
||||
setIsPreviewOpen(true)
|
||||
estimateHook.fetchEstimate()
|
||||
},
|
||||
[segmentation, t, estimateHook],
|
||||
)
|
||||
|
||||
const handleCreate = useCallback(async () => {
|
||||
if (!canCreateDocument) return
|
||||
|
||||
const isValid = creation.validateParams({
|
||||
segmentationType: segmentation.segmentationType,
|
||||
maxChunkLength: segmentation.maxChunkLength,
|
||||
limitMaxChunkLength: segmentation.limitMaxChunkLength,
|
||||
overlap: segmentation.overlap,
|
||||
indexType: indexing.indexType,
|
||||
embeddingModel: indexing.embeddingModel,
|
||||
rerankModelList: indexing.rerankModelList,
|
||||
retrievalConfig: indexing.retrievalConfig,
|
||||
})
|
||||
if (!isValid) return
|
||||
const params = creation.buildCreationParams(
|
||||
currentDocForm,
|
||||
docLanguage,
|
||||
segmentation.getProcessRule(currentDocForm),
|
||||
indexing.retrievalConfig,
|
||||
indexing.embeddingModel,
|
||||
indexing.getIndexingTechnique(),
|
||||
segmentation.summaryIndexSetting,
|
||||
)
|
||||
if (!params) return
|
||||
try {
|
||||
await creation.executeCreation(params, indexing.indexType, indexing.retrievalConfig)
|
||||
} catch {
|
||||
// The service reports request failures; keep this step and its draft available for retry.
|
||||
}
|
||||
}, [canCreateDocument, creation, segmentation, indexing, currentDocForm, docLanguage])
|
||||
|
||||
const handlePickerChange = useCallback(
|
||||
(selected: { id: string; name: string }) => {
|
||||
estimateHook.reset()
|
||||
preview.handlePreviewChange(selected)
|
||||
estimateHook.fetchEstimate(selected.id)
|
||||
},
|
||||
[estimateHook, preview],
|
||||
)
|
||||
|
||||
const handleQAConfirm = useCallback(() => {
|
||||
setIsQAConfirmDialogOpen(false)
|
||||
indexing.setIndexType(IndexingType.QUALIFIED)
|
||||
setDocForm(ChunkingMode.qa)
|
||||
}, [indexing])
|
||||
|
||||
// Initialize rules
|
||||
useEffect(() => {
|
||||
if (!isSetting) {
|
||||
fetchDefaultProcessRuleMutation.mutate({})
|
||||
} else if (documentDetail?.dataset_process_rule) {
|
||||
const { mode, rules } = documentDetail.dataset_process_rule
|
||||
const segmentationRules = rules ? toSegmentationRules(rules) : undefined
|
||||
if (segmentationRules) {
|
||||
const isHierarchical =
|
||||
documentDetail.doc_form === ChunkingMode.parentChild ||
|
||||
Boolean(segmentationRules.parent_mode && segmentationRules.subchunk_segmentation)
|
||||
segmentation.applyConfigFromRules(segmentationRules, isHierarchical)
|
||||
}
|
||||
if (isProcessMode(mode)) segmentation.setSegmentationType(mode)
|
||||
}
|
||||
// oxlint-disable-next-line react/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// Show options conditions
|
||||
const showGeneralOption =
|
||||
(isInUpload && !!datasetChunkingMode && generalChunkingModes.includes(datasetChunkingMode)) ||
|
||||
isUploadInEmptyDataset ||
|
||||
isInInit
|
||||
const showParentChildOption =
|
||||
(isInUpload && datasetChunkingMode === ChunkingMode.parentChild) ||
|
||||
isUploadInEmptyDataset ||
|
||||
isInInit
|
||||
|
||||
return (
|
||||
<div className={cn('flex size-full min-w-0', isMobile && 'flex-col overflow-y-auto')}>
|
||||
<div
|
||||
className={cn(
|
||||
'@container/chunkfields relative min-w-0 py-6',
|
||||
isMobile ? 'w-full shrink-0 px-4' : 'h-full w-1/2 overflow-y-auto px-12',
|
||||
)}
|
||||
>
|
||||
<h1 className="mb-1 system-md-semibold text-text-secondary">
|
||||
{t(($) => $['stepTwo.segmentation'], { ns: 'datasetCreation' })}
|
||||
</h1>
|
||||
<RadioGroup<ChunkingMode>
|
||||
className="block"
|
||||
aria-label={t(($) => $['stepTwo.segmentation'], { ns: 'datasetCreation' })}
|
||||
value={currentDocForm === ChunkingMode.qa ? ChunkingMode.text : currentDocForm}
|
||||
onValueChange={handleDocFormChange}
|
||||
>
|
||||
{showGeneralOption && (
|
||||
<GeneralChunkingOptions
|
||||
segmentIdentifier={segmentation.segmentIdentifier}
|
||||
maxChunkLength={segmentation.maxChunkLength}
|
||||
overlap={segmentation.overlap}
|
||||
rules={segmentation.rules}
|
||||
currentDocForm={currentDocForm}
|
||||
docLanguage={docLanguage}
|
||||
isActive={generalChunkingModes.includes(currentDocForm)}
|
||||
isInUpload={isInUpload}
|
||||
isNotUploadInEmptyDataset={isNotUploadInEmptyDataset}
|
||||
hasCurrentDatasetDocForm={!!currentDataset?.doc_form}
|
||||
onSegmentIdentifierChange={(value) => segmentation.setSegmentIdentifier(value, true)}
|
||||
onMaxChunkLengthChange={segmentation.setMaxChunkLength}
|
||||
onOverlapChange={segmentation.setOverlap}
|
||||
onRuleToggle={segmentation.toggleRule}
|
||||
onDocFormChange={handleDocFormChange}
|
||||
onDocLanguageChange={setDocLanguage}
|
||||
onPreview={updatePreview}
|
||||
onReset={segmentation.resetToDefaults}
|
||||
locale={locale}
|
||||
showSummaryIndexSetting={showSummaryIndexSetting}
|
||||
summaryIndexSetting={segmentation.summaryIndexSetting}
|
||||
onSummaryIndexSettingChange={segmentation.handleSummaryIndexSettingChange}
|
||||
/>
|
||||
)}
|
||||
{showParentChildOption && (
|
||||
<ParentChildOptions
|
||||
parentChildConfig={segmentation.parentChildConfig}
|
||||
rules={segmentation.rules}
|
||||
currentDocForm={currentDocForm}
|
||||
isActive={currentDocForm === ChunkingMode.parentChild}
|
||||
isInUpload={isInUpload}
|
||||
isNotUploadInEmptyDataset={isNotUploadInEmptyDataset}
|
||||
onChunkForContextChange={segmentation.setChunkForContext}
|
||||
onParentDelimiterChange={(v) => segmentation.updateParentConfig('delimiter', v)}
|
||||
onParentMaxLengthChange={(v) => segmentation.updateParentConfig('maxLength', v)}
|
||||
onChildDelimiterChange={(v) => segmentation.updateChildConfig('delimiter', v)}
|
||||
onChildMaxLengthChange={(v) => segmentation.updateChildConfig('maxLength', v)}
|
||||
onRuleToggle={segmentation.toggleRule}
|
||||
onPreview={updatePreview}
|
||||
onReset={segmentation.resetToDefaults}
|
||||
showSummaryIndexSetting={showSummaryIndexSetting}
|
||||
summaryIndexSetting={segmentation.summaryIndexSetting}
|
||||
onSummaryIndexSettingChange={segmentation.handleSummaryIndexSettingChange}
|
||||
/>
|
||||
)}
|
||||
</RadioGroup>
|
||||
<Separator className="my-5 h-[0.5px]" />
|
||||
<IndexingModeSection
|
||||
indexType={indexing.indexType}
|
||||
hasSetIndexType={hasSetIndexType}
|
||||
docForm={docForm}
|
||||
embeddingModel={indexing.embeddingModel}
|
||||
embeddingModelList={indexing.embeddingModelList}
|
||||
retrievalConfig={indexing.retrievalConfig}
|
||||
showMultiModalTip={indexing.showMultiModalTip}
|
||||
isModelAndRetrievalConfigDisabled={isModelAndRetrievalConfigDisabled}
|
||||
datasetId={datasetId}
|
||||
isQAConfirmDialogOpen={isQAConfirmDialogOpen}
|
||||
onIndexTypeChange={indexing.setIndexType}
|
||||
onEmbeddingModelChange={indexing.setEmbeddingModel}
|
||||
onRetrievalConfigChange={indexing.setRetrievalConfig}
|
||||
onQAConfirmDialogClose={() => setIsQAConfirmDialogOpen(false)}
|
||||
onQAConfirmDialogConfirm={handleQAConfirm}
|
||||
/>
|
||||
<StepTwoFooter
|
||||
isSetting={isSetting}
|
||||
isCreating={creation.isCreating}
|
||||
onPrevious={() => onStepChange?.(-1)}
|
||||
onCreate={handleCreate}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
</div>
|
||||
<PreviewPanel
|
||||
isMobile={isMobile}
|
||||
isOpen={isPreviewOpen}
|
||||
onClose={() => setIsPreviewOpen(false)}
|
||||
finalFocus={previewTriggerRef}
|
||||
dataSourceType={dataSourceType}
|
||||
currentDocForm={currentDocForm}
|
||||
estimate={estimateHook.estimate}
|
||||
parentChildConfig={segmentation.parentChildConfig}
|
||||
isSetting={isSetting}
|
||||
pickerFiles={preview.getPreviewPickerItems()}
|
||||
pickerValue={preview.getPreviewPickerValue()}
|
||||
isIdle={estimateHook.isIdle}
|
||||
isPending={estimateHook.isPending}
|
||||
onPickerChange={handlePickerChange}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default StepTwo
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { languages } from '@/i18n/language'
|
||||
import LanguageSelect from '../index'
|
||||
|
||||
it('offers only supported prompt languages and applies the selected name', async () => {
|
||||
const user = userEvent.setup()
|
||||
const Harness = () => {
|
||||
const [language, setLanguage] = useState('English')
|
||||
return <LanguageSelect currentLanguage={language} onSelect={setLanguage} />
|
||||
}
|
||||
render(<Harness />)
|
||||
const trigger = screen.getByRole('combobox', { name: 'language' })
|
||||
expect(trigger).toHaveTextContent('English')
|
||||
await user.click(trigger)
|
||||
const list = await screen.findByRole('listbox')
|
||||
expect(
|
||||
within(list)
|
||||
.getAllByRole('option')
|
||||
.map((option) => option.textContent),
|
||||
).toEqual(
|
||||
languages.filter((language) => language.supported).map((language) => language.prompt_name),
|
||||
)
|
||||
await user.click(within(list).getByRole('option', { name: 'French' }))
|
||||
expect(trigger).toHaveTextContent('French')
|
||||
})
|
||||
|
||||
it('prevents changing the language when disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSelect = vi.fn()
|
||||
render(<LanguageSelect currentLanguage="English" onSelect={onSelect} disabled />)
|
||||
const trigger = screen.getByRole('combobox', { name: 'language' })
|
||||
expect(trigger).toBeDisabled()
|
||||
await user.click(trigger)
|
||||
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
|
||||
expect(onSelect).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectItemIndicator,
|
||||
SelectItemText,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@langgenius/dify-ui/select'
|
||||
import * as React from 'react'
|
||||
import { languages } from '@/i18n/language'
|
||||
|
||||
type ILanguageSelectProps = {
|
||||
currentLanguage: string
|
||||
onSelect: (language: string) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const LanguageSelect: FC<ILanguageSelectProps> = ({ currentLanguage, onSelect, disabled }) => {
|
||||
const supportedLanguages = languages.filter((language) => language.supported)
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={currentLanguage}
|
||||
onValueChange={(value) => {
|
||||
if (value == null) return
|
||||
onSelect(value)
|
||||
}}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger
|
||||
size="small"
|
||||
aria-label="language"
|
||||
className={cn(
|
||||
'mx-1 w-auto shrink-0 bg-components-button-tertiary-bg text-components-button-tertiary-text hover:bg-components-button-tertiary-bg',
|
||||
'data-disabled:cursor-not-allowed data-disabled:bg-components-button-tertiary-bg-disabled data-disabled:text-components-button-tertiary-text-disabled data-disabled:hover:bg-components-button-tertiary-bg-disabled',
|
||||
)}
|
||||
>
|
||||
<SelectValue placeholder={<span> </span>} />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="w-max">
|
||||
{supportedLanguages.map(({ prompt_name }) => (
|
||||
<SelectItem key={prompt_name} value={prompt_name}>
|
||||
<SelectItemText>{prompt_name}</SelectItemText>
|
||||
<SelectItemIndicator />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
export default React.memo(LanguageSelect)
|
||||
@@ -0,0 +1,44 @@
|
||||
import type {
|
||||
DocumentProcessRulesResponse,
|
||||
PreProcessingRule,
|
||||
Rule,
|
||||
} from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { Rules } from '@/models/datasets'
|
||||
import { ProcessMode } from '@/models/datasets'
|
||||
|
||||
const PRE_PROCESSING_RULE_IDS = new Set<string>([
|
||||
'remove_extra_spaces',
|
||||
'remove_stopwords',
|
||||
'remove_urls_emails',
|
||||
] satisfies PreProcessingRule['id'][])
|
||||
|
||||
const isPreProcessingRule = (rule: { id: string; enabled: boolean }): rule is PreProcessingRule =>
|
||||
PRE_PROCESSING_RULE_IDS.has(rule.id)
|
||||
|
||||
export const isProcessMode = (mode: string): mode is ProcessMode =>
|
||||
Object.values<string>(ProcessMode).includes(mode)
|
||||
|
||||
type StoredRules = DocumentProcessRulesResponse | Rule
|
||||
|
||||
const toSegmentation = (segmentation: NonNullable<StoredRules['segmentation']>) => ({
|
||||
// The backend defaults an unspecified separator to a newline and overlap to zero.
|
||||
separator: segmentation.separator ?? '\n',
|
||||
max_tokens: segmentation.max_tokens,
|
||||
chunk_overlap: segmentation.chunk_overlap ?? 0,
|
||||
})
|
||||
|
||||
/**
|
||||
* Segmentation settings from a stored process rule. Automatic-mode rules store no segmentation,
|
||||
* so there is nothing to restore for them.
|
||||
*/
|
||||
export const toSegmentationRules = (rules: StoredRules): Rules | undefined => {
|
||||
if (!rules.segmentation) return undefined
|
||||
return {
|
||||
pre_processing_rules: (rules.pre_processing_rules ?? []).filter(isPreProcessingRule),
|
||||
segmentation: toSegmentation(rules.segmentation),
|
||||
parent_mode: rules.parent_mode ?? undefined,
|
||||
subchunk_segmentation: rules.subchunk_segmentation
|
||||
? toSegmentation(rules.subchunk_segmentation)
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type {
|
||||
DatasetAndDocumentResponse,
|
||||
DocumentDetailResponse,
|
||||
} from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { IndexingType } from './hooks'
|
||||
import type { DataSourceProvider, NotionPage } from '@/models/common'
|
||||
import type { CrawlOptions, CrawlResultItem, CustomFile, DataSourceType } from '@/models/datasets'
|
||||
import type { RETRIEVE_METHOD } from '@/types/app'
|
||||
|
||||
/** The fields step two reads from a file to index; uploads and stored documents both provide them. */
|
||||
export type StepTwoFile = Pick<CustomFile, 'id' | 'name' | 'extension'>
|
||||
|
||||
/** The fields step two reads from a Notion page to index. */
|
||||
export type StepTwoNotionPage = Pick<
|
||||
NotionPage,
|
||||
'workspace_id' | 'page_id' | 'page_name' | 'page_icon' | 'type'
|
||||
>
|
||||
|
||||
export type StepTwoProps = {
|
||||
isSetting?: boolean
|
||||
documentDetail?: DocumentDetailResponse
|
||||
isAPIKeySet: boolean
|
||||
onSetting: () => void
|
||||
datasetId?: string
|
||||
indexingType?: IndexingType
|
||||
retrievalMethod?: string
|
||||
dataSourceType: DataSourceType
|
||||
files: StepTwoFile[]
|
||||
notionPages?: StepTwoNotionPage[]
|
||||
notionCredentialId: string
|
||||
websitePages?: CrawlResultItem[]
|
||||
crawlOptions?: CrawlOptions
|
||||
websiteCrawlProvider?: DataSourceProvider
|
||||
websiteCrawlJobId?: string
|
||||
canCreateDocument?: boolean
|
||||
onStepChange?: (delta: number) => void
|
||||
updateIndexingTypeCache?: (type: string) => void
|
||||
updateRetrievalMethodCache?: (method: RETRIEVE_METHOD | '') => void
|
||||
updateResultCache?: (res: DatasetAndDocumentResponse) => void
|
||||
onSave?: () => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
Reference in new issue
Block a user