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
+43
@@ -0,0 +1,43 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { PluginCategoryEnum } from '../../types'
|
||||
import CategoryEmptyState from '../category-empty-state'
|
||||
import { getCategoryMarketplaceId } from '../category-marketplace'
|
||||
|
||||
vi.mock('react-i18next', async () => {
|
||||
const { createReactI18nextMock } = await import('@/test/i18n-mock')
|
||||
return {
|
||||
...createReactI18nextMock(),
|
||||
Trans: ({ components }: { components: { marketplace: ReactNode } }) => (
|
||||
<>You can install integrations from the {components.marketplace}.</>
|
||||
),
|
||||
}
|
||||
})
|
||||
|
||||
describe('CategoryEmptyState', () => {
|
||||
it.each([
|
||||
[PluginCategoryEnum.trigger, 'plugin.list.noTriggerFound'],
|
||||
[PluginCategoryEnum.agent, 'plugin.list.noAgentStrategyFound'],
|
||||
[PluginCategoryEnum.extension, 'plugin.list.noExtensionFound'],
|
||||
] as const)(
|
||||
'renders the compact %s empty state with an embedded marketplace link',
|
||||
(category, label) => {
|
||||
render(<CategoryEmptyState category={category} showMarketplaceLink />)
|
||||
|
||||
expect(screen.getByText(label)).toBeInTheDocument()
|
||||
expect(screen.getByText(/You can install integrations from the/)).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'plugin.marketplace.difyMarketplace' }),
|
||||
).toHaveAttribute('href', `#${getCategoryMarketplaceId(category)}`)
|
||||
},
|
||||
)
|
||||
|
||||
it('removes the middle install entry when marketplace is disabled', () => {
|
||||
render(<CategoryEmptyState category={PluginCategoryEnum.trigger} showMarketplaceLink={false} />)
|
||||
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.source.github')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.source.local')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { consoleClient } from '@/service/console'
|
||||
import type { marketplaceClient } from '@/service/marketplace'
|
||||
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
|
||||
import { zGetWorkspacesCurrentPluginMarketplacePkgResponse } from '@dify/contracts/api/console/workspaces/zod.gen'
|
||||
import { screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ThemeProvider } from 'next-themes'
|
||||
import { marketplaceLinks } from '@/features/marketplace/links'
|
||||
import { seedModelProviderQueries } from '@/test/console/model-provider'
|
||||
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createMarketplacePluginFixture, createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import { PluginCategoryEnum as Category, PermissionType } from '../../types'
|
||||
import CategoryMarketplacePanel from '../category-marketplace-panel'
|
||||
|
||||
const { getInstalledIds, search, declaration } = vi.hoisted(() => ({
|
||||
getInstalledIds: vi.fn<typeof consoleClient.workspaces.current.plugin.installedIds.get>(),
|
||||
search: vi.fn<typeof marketplaceClient.searchAdvanced>(),
|
||||
declaration: vi.fn<typeof consoleClient.workspaces.current.plugin.marketplace.pkg.get>(),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses, withConsoleClientResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.installedIds.get': getInstalledIds,
|
||||
'workspaces.current.plugin.list.installations.ids.post': async () => ({ plugins: [] }),
|
||||
}),
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.permission.fetch.get': async () => ({
|
||||
install_permission: PermissionType.everyone,
|
||||
debug_permission: PermissionType.everyone,
|
||||
}),
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
'workspaces.current.plugin.marketplace.pkg.get': declaration,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/service/marketplace', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/marketplace')>()),
|
||||
marketplaceClient: { searchAdvanced: search },
|
||||
}))
|
||||
|
||||
const calendar = createMarketplacePluginFixture({
|
||||
org: 'langgenius',
|
||||
name: 'calendar',
|
||||
plugin_id: 'langgenius/calendar',
|
||||
label: { 'en-US': 'Calendar' },
|
||||
brief: { 'en-US': 'Calendar events' },
|
||||
latest_package_identifier: 'langgenius/calendar:1.0.0@checksum',
|
||||
category: Category.trigger,
|
||||
})
|
||||
const installed = createMarketplacePluginFixture({
|
||||
plugin_id: 'installed/plugin',
|
||||
label: { 'en-US': 'Installed plugin' },
|
||||
category: Category.trigger,
|
||||
})
|
||||
|
||||
const setup = (
|
||||
props: Partial<ComponentProps<typeof CategoryMarketplacePanel>> = {},
|
||||
options: ConsoleQueryTestOptions = {},
|
||||
) => {
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedModelProviderQueries(queryClient)
|
||||
const rendered = renderWithConsoleQuery(
|
||||
<ThemeProvider defaultTheme="light" forcedTheme="light" enableSystem={false}>
|
||||
<CategoryMarketplacePanel
|
||||
marketplace={marketplaceLinks}
|
||||
category={Category.trigger}
|
||||
searchText="calendar"
|
||||
{...props}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
{
|
||||
queryClient,
|
||||
accountProfileMeta: { currentVersion: '1.0.0' },
|
||||
workspacePermissionKeys: ['plugin.install'],
|
||||
systemFeatures: {
|
||||
deployment_edition: 'CLOUD',
|
||||
rbac_enabled: true,
|
||||
enable_marketplace: true,
|
||||
},
|
||||
...options,
|
||||
},
|
||||
)
|
||||
return { ...rendered, user: userEvent.setup() }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
getInstalledIds.mockReset().mockResolvedValue({ plugin_ids: [installed.plugin_id] })
|
||||
search.mockReset().mockResolvedValue({ data: { plugins: [installed, calendar], total: 2 } })
|
||||
declaration.mockReset().mockResolvedValue(
|
||||
zGetWorkspacesCurrentPluginMarketplacePkgResponse.parse({
|
||||
manifest: {
|
||||
...createPluginEntity().declaration,
|
||||
name: calendar.name,
|
||||
category: Category.trigger,
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it.each([Category.trigger, Category.agent, Category.extension])(
|
||||
'searches the %s category with selected tags and excludes installed plugins',
|
||||
async (category) => {
|
||||
search.mockResolvedValue({
|
||||
data: {
|
||||
plugins: [
|
||||
{ ...installed, category },
|
||||
{ ...calendar, category },
|
||||
],
|
||||
total: 2,
|
||||
},
|
||||
})
|
||||
setup({ category, tags: ['search'] })
|
||||
|
||||
expect(await screen.findByRole('article', { name: 'Calendar' })).toBeVisible()
|
||||
expect(screen.queryByRole('article', { name: 'Installed plugin' })).not.toBeInTheDocument()
|
||||
expect(getInstalledIds).toHaveBeenCalledWith({ query: { category } })
|
||||
expect(search).toHaveBeenCalledWith(
|
||||
{
|
||||
params: { kind: 'plugins' },
|
||||
body: {
|
||||
category,
|
||||
query: 'calendar',
|
||||
tags: ['search'],
|
||||
page: 1,
|
||||
page_size: 30,
|
||||
sort_by: 'install_count',
|
||||
sort_order: 'DESC',
|
||||
},
|
||||
},
|
||||
expect.anything(),
|
||||
)
|
||||
const link = screen.getByRole('link', { name: 'plugin.marketplace.difyMarketplace' })
|
||||
const url = new URL(link.getAttribute('href')!, window.location.origin)
|
||||
expect(url.pathname).toBe(`/plugins/${category}`)
|
||||
expect(url.searchParams.get('theme')).toBe('light')
|
||||
},
|
||||
)
|
||||
|
||||
it('shows provider information and opens the selected package in the real installer', async () => {
|
||||
const { user } = setup()
|
||||
const card = within(await screen.findByRole('article', { name: 'Calendar' }))
|
||||
expect(card.getByRole('heading', { name: 'Calendar' })).toBeVisible()
|
||||
expect(card.getByText('langgenius')).toBeVisible()
|
||||
expect(card.getByText('Calendar events')).toBeVisible()
|
||||
expect(card.getByText('42')).toBeVisible()
|
||||
expect(card.getByText('search')).toBeVisible()
|
||||
expect(card.getByText('agent')).toBeVisible()
|
||||
await user.click(
|
||||
card.getByRole('button', { name: 'plugin.detailPanel.operation.install Calendar' }),
|
||||
)
|
||||
const dialog = await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
|
||||
expect(within(dialog).getByText('Calendar')).toBeVisible()
|
||||
await waitFor(() =>
|
||||
expect(declaration).toHaveBeenCalledWith({
|
||||
query: { plugin_unique_identifier: calendar.latest_package_identifier },
|
||||
}),
|
||||
)
|
||||
await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(
|
||||
card.getByRole('button', { name: 'plugin.detailPanel.operation.install Calendar' }),
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it.each(['CLOUD', 'COMMUNITY', 'ENTERPRISE'] as const)(
|
||||
'links provider details to the appropriate destination for %s',
|
||||
async (edition) => {
|
||||
setup({}, { systemFeatures: { deployment_edition: edition, rbac_enabled: true } })
|
||||
const card = within(await screen.findByRole('article', { name: 'Calendar' }))
|
||||
const link = card.getByRole('link', { name: 'plugin.detailPanel.operation.detail Calendar' })
|
||||
const url = new URL(link.getAttribute('href')!, window.location.origin)
|
||||
expect(url.pathname).toBe(`${edition === 'CLOUD' ? '/plugins' : '/plugin'}/langgenius/calendar`)
|
||||
expect(url.searchParams.get('language')).toBe('en-US')
|
||||
expect(url.searchParams.get('theme')).toBe('light')
|
||||
if (edition !== 'CLOUD') {
|
||||
expect(url.origin).toBe('https://marketplace.dify.ai')
|
||||
expect(url.searchParams.get('source')).toBe(window.location.origin)
|
||||
}
|
||||
expect(link).toHaveAttribute('target', '_blank')
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps provider details available but hides installation without workspace permission', async () => {
|
||||
setup({}, { workspacePermissionKeys: [] })
|
||||
const card = within(await screen.findByRole('article', { name: 'Calendar' }))
|
||||
expect(
|
||||
card.getByRole('link', { name: 'plugin.detailPanel.operation.detail Calendar' }),
|
||||
).toBeVisible()
|
||||
expect(
|
||||
card.queryByRole('button', { name: /plugin.detailPanel.operation.install/ }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('waits for installed IDs and resumes search after retrying a failed request', async () => {
|
||||
getInstalledIds.mockRejectedValueOnce(new Error('Unavailable'))
|
||||
const { user } = setup()
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('common.errorBoundary.title')
|
||||
expect(search).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))
|
||||
expect(await screen.findByRole('article', { name: 'Calendar' })).toBeVisible()
|
||||
expect(screen.queryByRole('article', { name: 'Installed plugin' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('restores collapsed results and appends the next marketplace page', async () => {
|
||||
const firstPage = Array.from({ length: 30 }, (_, index) =>
|
||||
createMarketplacePluginFixture({
|
||||
...calendar,
|
||||
plugin_id: `langgenius/calendar-${index}`,
|
||||
name: `calendar-${index}`,
|
||||
label: { 'en-US': `Calendar ${index + 1}` },
|
||||
}),
|
||||
)
|
||||
search
|
||||
.mockResolvedValueOnce({ data: { plugins: firstPage, total: 31 } })
|
||||
.mockResolvedValue({ data: { plugins: [calendar], total: 31 } })
|
||||
const { user } = setup()
|
||||
await screen.findByRole('article', { name: 'Calendar 1' })
|
||||
const toggle = screen.getByRole('button', { name: 'plugin.list.source.marketplace' })
|
||||
await user.click(toggle)
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(screen.queryByRole('article')).not.toBeInTheDocument()
|
||||
await user.click(toggle)
|
||||
expect(await screen.findByRole('article', { name: 'Calendar 1' })).toBeVisible()
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.loadMore' }))
|
||||
expect(await screen.findByRole('article', { name: 'Calendar' })).toBeVisible()
|
||||
expect(screen.getAllByRole('article')).toHaveLength(31)
|
||||
expect(search).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ body: expect.objectContaining({ page: 2 }) }),
|
||||
expect.anything(),
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: 'workflow.common.loadMore' })).not.toBeInTheDocument()
|
||||
})
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import type { ReactElement, ReactNode } from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { createConsoleQueryWrapper } from '@/test/console/query-data'
|
||||
import { usePluginPageContext } from '../context'
|
||||
import { PluginPageContextProvider } from '../context-provider'
|
||||
|
||||
vi.mock('../../hooks', () => ({
|
||||
PLUGIN_PAGE_TABS_MAP: {
|
||||
plugins: 'plugins',
|
||||
marketplace: 'discover',
|
||||
},
|
||||
usePluginPageTabs: () => [
|
||||
{ value: 'plugins', text: 'Plugins' },
|
||||
{ value: 'discover', text: 'Discover' },
|
||||
],
|
||||
}))
|
||||
|
||||
const renderWithProviders = (
|
||||
ui: ReactElement,
|
||||
options: { enableMarketplace: boolean; searchParams?: string } = { enableMarketplace: true },
|
||||
) => {
|
||||
const { wrapper: ConsoleQueryWrapper } = createConsoleQueryWrapper({
|
||||
systemFeatures: { enable_marketplace: options.enableMarketplace },
|
||||
})
|
||||
const Wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<ConsoleQueryWrapper>
|
||||
<NuqsTestingAdapter searchParams={options.searchParams ?? ''}>{children}</NuqsTestingAdapter>
|
||||
</ConsoleQueryWrapper>
|
||||
)
|
||||
return render(ui, { wrapper: Wrapper })
|
||||
}
|
||||
|
||||
const Consumer = () => {
|
||||
const selectedItem = usePluginPageContext((v) => v.selectedItem)
|
||||
const setSelectedItem = usePluginPageContext((v) => v.setSelectedItem)
|
||||
const options = usePluginPageContext((v) => v.options)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<output aria-label="Selected item">
|
||||
{selectedItem ? `${selectedItem.type}:${selectedItem.id}` : 'none'}
|
||||
</output>
|
||||
<output aria-label="Available tabs">{options.length}</output>
|
||||
<button onClick={() => setSelectedItem({ type: 'builtinTool', id: 'builtin-1' })}>
|
||||
select builtin tool
|
||||
</button>
|
||||
<button onClick={() => setSelectedItem({ type: 'plugin', id: 'plugin-1' })}>
|
||||
select plugin
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
describe('PluginPageContextProvider', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('filters out the marketplace tab when the feature is disabled', () => {
|
||||
renderWithProviders(
|
||||
<PluginPageContextProvider>
|
||||
<Consumer />
|
||||
</PluginPageContextProvider>,
|
||||
{ enableMarketplace: false },
|
||||
)
|
||||
|
||||
expect(screen.getByRole('status', { name: 'Available tabs' })).toHaveTextContent('1')
|
||||
})
|
||||
|
||||
it('keeps the query-state tab and replaces the selected item', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderWithProviders(
|
||||
<PluginPageContextProvider>
|
||||
<Consumer />
|
||||
</PluginPageContextProvider>,
|
||||
{ enableMarketplace: true, searchParams: '?tab=discover' },
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'select builtin tool' }))
|
||||
|
||||
expect(screen.getByRole('status', { name: 'Selected item' })).toHaveTextContent(
|
||||
'builtinTool:builtin-1',
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'select plugin' }))
|
||||
|
||||
expect(screen.getByRole('status', { name: 'Selected item' })).toHaveTextContent(
|
||||
'plugin:plugin-1',
|
||||
)
|
||||
expect(screen.getByRole('status', { name: 'Available tabs' })).toHaveTextContent('2')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
|
||||
import DebugInfo from '../debug-info'
|
||||
|
||||
vi.mock('@/context/i18n', () => ({
|
||||
useDocLink: () => (path: string) => `https://docs.example.com${path}`,
|
||||
}))
|
||||
|
||||
const debugKey = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.debuggingKey.get': debugKey,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
describe('DebugInfo', () => {
|
||||
beforeEach(() => {
|
||||
debugKey.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
it('renders nothing while the debug key is loading', () => {
|
||||
debugKey.mockReturnValue(new Promise(() => {}))
|
||||
const { container } = render(<DebugInfo />)
|
||||
|
||||
expect(container.innerHTML).toBe('')
|
||||
})
|
||||
|
||||
it('renders a disabled trigger when debug info is unavailable', async () => {
|
||||
render(<DebugInfo />)
|
||||
|
||||
const trigger = await screen.findByRole('button', { name: 'plugin.debugInfo.title' })
|
||||
expect(trigger).toBeDisabled()
|
||||
})
|
||||
|
||||
it('opens a popover with debug metadata and masks the key when info is available', async () => {
|
||||
debugKey.mockResolvedValue({
|
||||
host: '127.0.0.1',
|
||||
port: 5001,
|
||||
key: '12345678abcdefghijklmnopqrst87654321',
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
render(<DebugInfo />)
|
||||
|
||||
const trigger = await screen.findByRole('button', { name: 'plugin.debugInfo.title' })
|
||||
expect(trigger).toBeEnabled()
|
||||
|
||||
// Popover is closed initially — content not rendered yet
|
||||
expect(screen.queryByText('plugin.debugInfo.title')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(trigger)
|
||||
|
||||
expect(screen.getByText('plugin.debugInfo.title')).toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: 'plugin.debugInfo.viewDocs' })).toHaveAttribute(
|
||||
'href',
|
||||
'https://docs.example.com/develop-plugin/features-and-specs/plugin-types/remote-debug-a-plugin',
|
||||
)
|
||||
expect(screen.getByRole('group', { name: 'Port' })).toHaveTextContent('127.0.0.1:5001')
|
||||
expect(screen.getByRole('group', { name: 'Key' })).toHaveTextContent('12345678********87654321')
|
||||
expect(screen.queryByText('12345678abcdefghijklmnopqrst87654321')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import InstallPluginMenu from '../install-plugin-menu'
|
||||
|
||||
const { upload } = vi.hoisted(() => ({ upload: vi.fn() }))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
uploadFile: upload,
|
||||
}))
|
||||
// Catalog invalidation is independent of choosing and closing an installer.
|
||||
vi.mock('../../install-plugin/hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: vi.fn() }),
|
||||
}))
|
||||
const renderMenu = (
|
||||
props: Partial<ComponentProps<typeof InstallPluginMenu>> = {},
|
||||
systemFeatures: ConsoleQueryTestOptions['systemFeatures'] = { enable_marketplace: true },
|
||||
) => {
|
||||
const onSwitchToMarketplaceTab = vi.fn()
|
||||
return {
|
||||
...renderWithConsoleQuery(
|
||||
<InstallPluginMenu onSwitchToMarketplaceTab={onSwitchToMarketplaceTab} {...props} />,
|
||||
{ systemFeatures },
|
||||
),
|
||||
onSwitchToMarketplaceTab,
|
||||
}
|
||||
}
|
||||
const openMenu = async (
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
name = 'plugin.installPlugin',
|
||||
) => {
|
||||
await user.click(screen.getByRole('button', { name }))
|
||||
}
|
||||
|
||||
it('offers all enabled installation sources and switches to the marketplace', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSwitchToMarketplaceTab } = renderMenu({ triggerLabel: 'Install' })
|
||||
await openMenu(user, 'Install')
|
||||
expect(screen.getByRole('menuitem', { name: 'plugin.source.github' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('menuitem', { name: 'plugin.source.local' })).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('menuitem', { name: 'plugin.source.marketplace' }))
|
||||
expect(onSwitchToMarketplaceTab).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('prevents opening the menu or selecting a file while installation is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { container, onSwitchToMarketplaceTab } = renderMenu({ disabled: true })
|
||||
const trigger = screen.getByRole('button', { name: 'plugin.installPlugin' })
|
||||
expect(trigger).toBeDisabled()
|
||||
await user.click(trigger)
|
||||
// A native file input has no implicit ARIA role and is activated by the menu action.
|
||||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!
|
||||
expect(input).toBeDisabled()
|
||||
await user.upload(input, new File(['content'], 'plugin.difypkg'))
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(onSwitchToMarketplaceTab).not.toHaveBeenCalled()
|
||||
expect(upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('offers only the marketplace when custom installation is restricted', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderMenu(
|
||||
{},
|
||||
{
|
||||
enable_marketplace: true,
|
||||
plugin_installation_permission: { restrict_to_marketplace_only: true },
|
||||
},
|
||||
)
|
||||
await openMenu(user)
|
||||
expect(screen.getByRole('menuitem', { name: 'plugin.source.marketplace' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('menuitem', { name: 'plugin.source.github' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('menuitem', { name: 'plugin.source.local' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the GitHub installer and returns to the dropdown when it is cancelled', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
await openMenu(user)
|
||||
await user.click(screen.getByRole('menuitem', { name: 'plugin.source.github' }))
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installPlugin' })
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
await openMenu(user)
|
||||
expect(screen.getByRole('menuitem', { name: 'plugin.source.github' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('passes the selected file to the real installer and permits selecting the same file after closing', async () => {
|
||||
const user = userEvent.setup()
|
||||
upload.mockRejectedValue(new Error('Upload unavailable'))
|
||||
const { container } = renderMenu()
|
||||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!
|
||||
const file = new File(['content'], 'plugin.difypkg')
|
||||
const filePicker = vi.spyOn(input, 'click')
|
||||
await openMenu(user)
|
||||
await user.click(screen.getByRole('menuitem', { name: 'plugin.source.local' }))
|
||||
expect(filePicker).toHaveBeenCalledOnce()
|
||||
filePicker.mockRestore()
|
||||
await user.upload(input, file)
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.uploadFailed' })
|
||||
expect(upload).toHaveBeenCalledExactlyOnceWith(file, false)
|
||||
await user.click(screen.getByText('common.operation.close'))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
|
||||
await openMenu(user)
|
||||
await user.click(screen.getByRole('menuitem', { name: 'plugin.source.local' }))
|
||||
await user.upload(input, file)
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.uploadFailed' })
|
||||
expect(upload).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
+490
@@ -0,0 +1,490 @@
|
||||
import type { ComponentProps, ReactNode } from 'react'
|
||||
import type { PluginDetail } from '../../types'
|
||||
import type { PluginPageSelection } from '../context'
|
||||
import type { FilterState } from '../filter-management'
|
||||
import type { Collection } from '@/app/components/tools/types'
|
||||
import { act, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import {
|
||||
getStepByStepTourTargetSelector,
|
||||
STEP_BY_STEP_TOUR_TARGETS,
|
||||
} from '@/app/components/step-by-step-tour/target-registry'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import { PluginCategoryEnum } from '../../types'
|
||||
import { PluginPageContext } from '../context'
|
||||
import PluginsPanel from '../plugins-panel'
|
||||
|
||||
const requests = vi.hoisted(() => ({ list: vi.fn() }))
|
||||
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, {
|
||||
'workspaces.current.plugin.list.get': requests.list,
|
||||
'workspaces.current.plugin.byCategory.list.get': requests.list,
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Marketplace version enrichment is independent of installed-list pagination and filtering.
|
||||
vi.mock('../../hooks', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../hooks')>()),
|
||||
usePluginsWithLatestVersion: (plugins: PluginDetail[] = []) => plugins,
|
||||
}))
|
||||
vi.mock('@/context/modal-context', () => ({
|
||||
useModalContext: () => ({ setShowUpdatePluginModal: vi.fn() }),
|
||||
}))
|
||||
vi.mock('@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: vi.fn() }),
|
||||
}))
|
||||
|
||||
// Detail editors and marketplace catalogs are independently tested feature boundaries.
|
||||
vi.mock('@/app/components/tools/provider/detail', () => ({
|
||||
default: ({ collection, onHide }: { collection: Collection; onHide: () => void }) => (
|
||||
<section aria-label="Builtin tool details">
|
||||
<span>{collection.id}</span>
|
||||
<button onClick={onHide}>Close builtin details</button>
|
||||
</section>
|
||||
),
|
||||
}))
|
||||
vi.mock('@/app/components/plugins/plugin-detail-panel', () => ({
|
||||
default: ({
|
||||
detail,
|
||||
onHide,
|
||||
onUpdate,
|
||||
}: {
|
||||
detail?: PluginDetail
|
||||
onHide: () => void
|
||||
onUpdate: () => void
|
||||
}) =>
|
||||
detail ? (
|
||||
<section aria-label="Plugin details">
|
||||
<span>{detail.plugin_id}</span>
|
||||
<button onClick={onHide}>Close plugin details</button>
|
||||
<button onClick={onUpdate}>Refresh plugin details</button>
|
||||
</section>
|
||||
) : null,
|
||||
}))
|
||||
vi.mock('@/app/components/tools/marketplace/builtin-marketplace-panel', () => ({
|
||||
BuiltinMarketplacePanel: ({
|
||||
keywords,
|
||||
tagFilterValue,
|
||||
}: {
|
||||
keywords: string
|
||||
tagFilterValue: string[]
|
||||
}) => (
|
||||
<section aria-label="Tool marketplace">
|
||||
{keywords} {tagFilterValue.join(',')}
|
||||
</section>
|
||||
),
|
||||
}))
|
||||
vi.mock('../category-marketplace-panel', () => ({
|
||||
default: ({
|
||||
category,
|
||||
searchText,
|
||||
tags,
|
||||
}: {
|
||||
category: string
|
||||
searchText: string
|
||||
tags: string[]
|
||||
}) => (
|
||||
<section aria-label={`${category} marketplace`}>
|
||||
{searchText} {tags.join(',')}
|
||||
</section>
|
||||
),
|
||||
}))
|
||||
|
||||
const createPlugin = (
|
||||
pluginId: string,
|
||||
label: string,
|
||||
tags: string[] = [],
|
||||
category: PluginCategoryEnum = PluginCategoryEnum.tool,
|
||||
): ReturnType<typeof createPluginEntity> => {
|
||||
const base = createPluginEntity()
|
||||
return {
|
||||
...base,
|
||||
id: pluginId,
|
||||
plugin_id: pluginId,
|
||||
plugin_unique_identifier: `${pluginId}-uid`,
|
||||
declaration: {
|
||||
...base.declaration,
|
||||
name: pluginId,
|
||||
category,
|
||||
label: { en_US: label },
|
||||
description: { en_US: `${label} description` },
|
||||
tags,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const createBuiltinTool = (id: string, label: string, labels: string[] = []): Collection => ({
|
||||
id,
|
||||
name: id,
|
||||
author: 'Dify',
|
||||
description: { en_US: `${label} description`, zh_Hans: `${label} description` },
|
||||
icon: '',
|
||||
label: { en_US: label, zh_Hans: label },
|
||||
type: 'builtin',
|
||||
team_credentials: {},
|
||||
is_team_authorization: false,
|
||||
allow_delete: false,
|
||||
labels,
|
||||
})
|
||||
|
||||
let plugins: ReturnType<typeof createPluginEntity>[]
|
||||
let builtinTools: Collection[]
|
||||
const observers: IntersectionObserverCallback[] = []
|
||||
const initialFilters: FilterState = { categories: [], tags: [], searchQuery: '' }
|
||||
function Harness({
|
||||
children,
|
||||
filters: initial = initialFilters,
|
||||
selection,
|
||||
}: {
|
||||
children: ReactNode
|
||||
filters?: FilterState
|
||||
selection?: PluginPageSelection
|
||||
}) {
|
||||
const [filters, setFilters] = useState(initial)
|
||||
const [selectedItem, setSelectedItem] = useState(selection)
|
||||
return (
|
||||
<PluginPageContext.Provider
|
||||
value={{
|
||||
containerRef: { current: null },
|
||||
filters,
|
||||
setFilters,
|
||||
selectedItem,
|
||||
setSelectedItem,
|
||||
activeTab: 'plugins',
|
||||
setActiveTab: () => {},
|
||||
options: [],
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PluginPageContext.Provider>
|
||||
)
|
||||
}
|
||||
const renderPanel = async (
|
||||
props: ComponentProps<typeof PluginsPanel> = {},
|
||||
filters = initialFilters,
|
||||
marketplace = true,
|
||||
selection?: PluginPageSelection,
|
||||
) => {
|
||||
const result = renderWithConsoleQuery(
|
||||
<Harness filters={filters} selection={selection}>
|
||||
<PluginsPanel {...props} />
|
||||
</Harness>,
|
||||
{ systemFeatures: { enable_marketplace: marketplace } },
|
||||
)
|
||||
await waitFor(() => expect(result.queryClient.isFetching()).toBe(0))
|
||||
return result
|
||||
}
|
||||
|
||||
const pluginButton = (name: string) => screen.getByRole('button', { name })
|
||||
|
||||
beforeEach(() => {
|
||||
plugins = []
|
||||
builtinTools = []
|
||||
observers.length = 0
|
||||
requests.list.mockReset().mockImplementation(async () => ({
|
||||
plugins,
|
||||
builtin_tools: builtinTools,
|
||||
total: plugins.length,
|
||||
has_more: false,
|
||||
}))
|
||||
vi.stubGlobal(
|
||||
'IntersectionObserver',
|
||||
class {
|
||||
constructor(callback: IntersectionObserverCallback) {
|
||||
observers.push(callback)
|
||||
}
|
||||
observe = vi.fn()
|
||||
disconnect = vi.fn()
|
||||
},
|
||||
)
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('Plugin list panel', () => {
|
||||
it('shows loading before exposing installed results', async () => {
|
||||
const request = createDeferred<{
|
||||
plugins: ReturnType<typeof createPluginEntity>[]
|
||||
total: number
|
||||
}>()
|
||||
requests.list.mockReturnValue(request.promise)
|
||||
const rendered = renderPanel()
|
||||
expect(screen.getByRole('status', { name: 'common.loading' })).toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.list.noInstalled')).not.toBeInTheDocument()
|
||||
await act(async () => request.resolve({ plugins: [], total: 0 }))
|
||||
await rendered
|
||||
})
|
||||
|
||||
it('locks the fixed category while retaining tag filters and toolbar actions', async () => {
|
||||
plugins = [
|
||||
createPlugin('trigger', 'Trigger Plugin', [], PluginCategoryEnum.trigger),
|
||||
createPlugin('tool', 'Tool Plugin'),
|
||||
]
|
||||
await renderPanel({
|
||||
fixedCategory: PluginCategoryEnum.trigger,
|
||||
toolbarAction: <button>Update settings</button>,
|
||||
})
|
||||
expect(pluginButton('Trigger Plugin')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Tool Plugin' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'plugin.allCategories' })).not.toBeInTheDocument()
|
||||
expect(pluginButton('common.tag.tags')).toBeInTheDocument()
|
||||
expect(pluginButton('Update settings')).toBeInTheDocument()
|
||||
expect(requests.list).toHaveBeenCalledWith({
|
||||
params: { category: PluginCategoryEnum.trigger },
|
||||
query: { page: 1, page_size: 30, language: 'en_US' },
|
||||
})
|
||||
})
|
||||
|
||||
it('applies tag filters to both installed tools and the marketplace handoff', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
|
||||
plugins = [
|
||||
createPlugin('search-plugin', 'Search Plugin', ['search']),
|
||||
createPlugin('rag-plugin', 'Rag Plugin', ['rag']),
|
||||
]
|
||||
builtinTools = [
|
||||
createBuiltinTool('search-builtin', 'Search Builtin', ['search']),
|
||||
createBuiltinTool('rag-builtin', 'Rag Builtin', ['rag']),
|
||||
]
|
||||
await renderPanel({ fixedCategory: PluginCategoryEnum.tool })
|
||||
await user.click(pluginButton('common.tag.tags'))
|
||||
await user.click(await screen.findByRole('checkbox', { name: 'pluginTags.tags.search' }))
|
||||
await user.keyboard('{Escape}')
|
||||
await act(async () => vi.advanceTimersByTimeAsync(600))
|
||||
expect(await screen.findByRole('button', { name: 'Search Plugin' })).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Rag Plugin' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /Search Builtin/ })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /Rag Builtin/ })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('region', { name: 'Tool marketplace' })).toHaveTextContent('search')
|
||||
expect(requests.list).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ query: expect.objectContaining({ tags: ['search'] }) }),
|
||||
)
|
||||
})
|
||||
|
||||
it('switches between builtin and installed plugin details and clears the selection when closed', async () => {
|
||||
const user = userEvent.setup()
|
||||
plugins = [createPlugin('tool-plugin', 'Tool Plugin')]
|
||||
builtinTools = [createBuiltinTool('builtin-tool', 'Builtin Tool')]
|
||||
await renderPanel({ fixedCategory: PluginCategoryEnum.tool })
|
||||
const builtin = screen.getByRole('button', { name: /Builtin Tool/ })
|
||||
await user.click(builtin)
|
||||
expect(builtin).toHaveAttribute('aria-current', 'true')
|
||||
expect(screen.getByRole('region', { name: 'Builtin tool details' })).toHaveTextContent(
|
||||
'builtin-tool',
|
||||
)
|
||||
await user.click(pluginButton('Tool Plugin'))
|
||||
expect(screen.getByRole('region', { name: 'Plugin details' })).toHaveTextContent('tool-plugin')
|
||||
expect(screen.queryByRole('region', { name: 'Builtin tool details' })).not.toBeInTheDocument()
|
||||
expect(builtin).not.toHaveAttribute('aria-current')
|
||||
plugins = [createPlugin('tool-plugin', 'Updated Plugin')]
|
||||
await user.click(pluginButton('Refresh plugin details'))
|
||||
expect(await screen.findByRole('button', { name: 'Updated Plugin' })).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Tool Plugin' })).not.toBeInTheDocument()
|
||||
await user.click(pluginButton('Close plugin details'))
|
||||
expect(screen.queryByRole('region', { name: 'Plugin details' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
category: PluginCategoryEnum.trigger,
|
||||
empty: 'noTriggerFound',
|
||||
target: STEP_BY_STEP_TOUR_TARGETS.integrationTriggerGrid,
|
||||
supportsTags: true,
|
||||
},
|
||||
{
|
||||
category: PluginCategoryEnum.agent,
|
||||
empty: 'noAgentStrategyFound',
|
||||
target: STEP_BY_STEP_TOUR_TARGETS.integrationAgentStrategyEmpty,
|
||||
supportsTags: false,
|
||||
},
|
||||
{
|
||||
category: PluginCategoryEnum.extension,
|
||||
empty: 'noExtensionFound',
|
||||
target: STEP_BY_STEP_TOUR_TARGETS.integrationExtensionGrid,
|
||||
supportsTags: false,
|
||||
},
|
||||
])(
|
||||
'keeps the $category catalog browsable without install permission and hides unsupported filters',
|
||||
async ({ category, empty, target, supportsTags }) => {
|
||||
await renderPanel({ fixedCategory: category, canInstall: false })
|
||||
expect(screen.getByText(`plugin.list.${empty}`)).toBeInTheDocument()
|
||||
expect(screen.getByRole('region', { name: `${category} marketplace` })).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'plugin.marketplace.difyMarketplace' }),
|
||||
).toHaveAttribute('href', `#plugin-category-marketplace-${category}`)
|
||||
expect(screen.queryByRole('button', { name: 'plugin.allCategories' })).not.toBeInTheDocument()
|
||||
expect(!!screen.queryByRole('button', { name: 'common.tag.tags' })).toBe(supportsTags)
|
||||
expect(document.querySelector(getStepByStepTourTargetSelector(target))).toContainElement(
|
||||
screen.getByText(`plugin.list.${empty}`),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([PluginCategoryEnum.trigger, PluginCategoryEnum.agent, PluginCategoryEnum.extension])(
|
||||
'omits %s marketplace navigation when disabled',
|
||||
async (category) => {
|
||||
await renderPanel({ fixedCategory: category }, initialFilters, false)
|
||||
expect(
|
||||
screen.queryByRole('region', { name: `${category} marketplace` }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'plugin.marketplace.difyMarketplace' }),
|
||||
).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([PluginCategoryEnum.agent, PluginCategoryEnum.extension])(
|
||||
'ignores hidden tag filters for %s in both local results and service requests',
|
||||
async (category) => {
|
||||
plugins = [
|
||||
createPlugin('rag', 'Rag Plugin', ['rag'], category),
|
||||
createPlugin('search', 'Search Plugin', ['search'], category),
|
||||
]
|
||||
await renderPanel({ fixedCategory: category }, { ...initialFilters, tags: ['search'] })
|
||||
expect(pluginButton('Rag Plugin')).toBeInTheDocument()
|
||||
expect(pluginButton('Search Plugin')).toBeInTheDocument()
|
||||
expect(requests.list).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ query: { page: 1, page_size: 30, language: 'en_US' } }),
|
||||
)
|
||||
expect(screen.getByRole('region', { name: `${category} marketplace` })).not.toHaveTextContent(
|
||||
'search',
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
it('debounces search changes and filters installed and builtin tools while forwarding marketplace search', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
|
||||
plugins = [
|
||||
createPlugin('alpha-plugin', 'Alpha Plugin'),
|
||||
createPlugin('beta-plugin', 'Beta Plugin'),
|
||||
]
|
||||
builtinTools = [
|
||||
createBuiltinTool('alpha-builtin', 'Alpha Builtin'),
|
||||
createBuiltinTool('beta-builtin', 'Beta Builtin'),
|
||||
]
|
||||
await renderPanel({ fixedCategory: PluginCategoryEnum.tool })
|
||||
await user.type(screen.getByRole('searchbox', { name: 'plugin.search' }), 'beta')
|
||||
expect(pluginButton('Alpha Plugin')).toBeInTheDocument()
|
||||
await act(async () => vi.advanceTimersByTimeAsync(600))
|
||||
expect(await screen.findByRole('button', { name: 'Beta Plugin' })).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Alpha Plugin' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /Beta Builtin/ })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /Alpha Builtin/ })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('region', { name: 'Tool marketplace' })).toHaveTextContent('beta')
|
||||
})
|
||||
|
||||
it('offers manual pagination on the standalone plugin page and appends the returned cards', async () => {
|
||||
const user = userEvent.setup()
|
||||
const firstPage = Array.from({ length: 100 }, (_, index) =>
|
||||
createPlugin(`tool-${index}`, `Tool ${index}`),
|
||||
)
|
||||
requests.list
|
||||
.mockResolvedValueOnce({ plugins: firstPage, total: 101 })
|
||||
.mockResolvedValueOnce({ plugins: [createPlugin('last-tool', 'Last Tool')], total: 101 })
|
||||
await renderPanel()
|
||||
await user.click(pluginButton('workflow.common.loadMore'))
|
||||
expect(await screen.findByRole('button', { name: 'Last Tool' })).toBeVisible()
|
||||
expect(pluginButton('Tool 0')).toBeVisible()
|
||||
expect(pluginButton('Tool 99')).toBeVisible()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflow.common.loadMore' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(requests.list).toHaveBeenLastCalledWith({ query: { page: 2, page_size: 100 } })
|
||||
})
|
||||
|
||||
it('loads another integration page once per intersection and announces pagination without replacing the status', async () => {
|
||||
const nextPage = createDeferred<{
|
||||
plugins: ReturnType<typeof createPluginEntity>[]
|
||||
has_more: boolean
|
||||
}>()
|
||||
const firstPage = Array.from({ length: 30 }, (_, index) =>
|
||||
createPlugin(`tool-${index}`, `Tool ${index}`),
|
||||
)
|
||||
requests.list
|
||||
.mockResolvedValueOnce({ plugins: firstPage, has_more: true })
|
||||
.mockReturnValueOnce(nextPage.promise)
|
||||
await renderPanel({ fixedCategory: PluginCategoryEnum.tool })
|
||||
const status = screen.getByRole('status')
|
||||
expect(status).toHaveTextContent('plugin.marketplace.pluginsResult')
|
||||
const intersect = () =>
|
||||
observers[0]!(
|
||||
[{ isIntersecting: true } as IntersectionObserverEntry],
|
||||
{} as IntersectionObserver,
|
||||
)
|
||||
act(() => {
|
||||
intersect()
|
||||
intersect()
|
||||
})
|
||||
await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('common.loading'))
|
||||
expect(screen.getByRole('status')).toBe(status)
|
||||
expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-live')
|
||||
expect(requests.list).toHaveBeenCalledTimes(2)
|
||||
expect(requests.list).toHaveBeenLastCalledWith({
|
||||
params: { category: PluginCategoryEnum.tool },
|
||||
query: { page: 2, page_size: 30, language: 'en_US' },
|
||||
})
|
||||
await act(async () =>
|
||||
nextPage.resolve({ plugins: [createPlugin('last-tool', 'Last Tool')], has_more: false }),
|
||||
)
|
||||
expect(await screen.findByRole('button', { name: 'Last Tool' })).toBeVisible()
|
||||
expect(pluginButton('Tool 0')).toBeVisible()
|
||||
expect(pluginButton('Tool 29')).toBeVisible()
|
||||
expect(screen.getByRole('status')).toBe(status)
|
||||
expect(status).toHaveTextContent('plugin.marketplace.pluginsResult')
|
||||
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('preserves the selected plugin details when filtering hides its card', async () => {
|
||||
const user = userEvent.setup()
|
||||
plugins = [createPlugin('tool-plugin', 'Tool Plugin')]
|
||||
await renderPanel({}, { ...initialFilters, searchQuery: 'missing' }, true, {
|
||||
type: 'plugin',
|
||||
id: 'tool-plugin',
|
||||
})
|
||||
expect(screen.getByText('plugin.list.notFound')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Tool Plugin' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('region', { name: 'Plugin details' })).toHaveTextContent('tool-plugin')
|
||||
await user.click(pluginButton('Close plugin details'))
|
||||
expect(screen.queryByRole('region', { name: 'Plugin details' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps category marketplace search available without presenting a no-installation prompt for unmatched searches', async () => {
|
||||
plugins = [createPlugin('trigger', 'Trigger Plugin', [], PluginCategoryEnum.trigger)]
|
||||
await renderPanel(
|
||||
{ fixedCategory: PluginCategoryEnum.trigger },
|
||||
{ ...initialFilters, searchQuery: 'missing' },
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: 'Trigger Plugin' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.list.noTriggerFound')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.list.noInstalled')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('region', { name: 'trigger marketplace' })).toHaveTextContent('missing')
|
||||
})
|
||||
})
|
||||
|
||||
vi.mock('react-i18next', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react-i18next')>()
|
||||
const { createReactI18nextMock, withSelectorKeyProps } = await import('@/test/i18n-mock')
|
||||
return {
|
||||
...actual,
|
||||
...createReactI18nextMock(),
|
||||
Trans: withSelectorKeyProps(
|
||||
({ i18nKey, components }: { i18nKey: string; components?: Record<string, ReactNode> }) => (
|
||||
<span>
|
||||
{i18nKey}
|
||||
{components?.marketplace}
|
||||
</span>
|
||||
),
|
||||
),
|
||||
}
|
||||
})
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
import type { ConsoleStateFixture } from '@/test/console/state-fixture'
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { renderHookWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { PermissionType, PluginCategoryEnum } from '../../types'
|
||||
import useReferenceSetting, { useCanInstallPluginFromMarketplace } from '../use-reference-setting'
|
||||
|
||||
let consoleState: ConsoleStateFixture = {}
|
||||
|
||||
vi.mock('@/context/workspace-state', async () => {
|
||||
const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
|
||||
return createWorkspaceStateModuleMock(() => consoleState)
|
||||
})
|
||||
vi.mock('@/context/permission-state', async () => {
|
||||
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
|
||||
return createPermissionStateModuleMock(() => consoleState)
|
||||
})
|
||||
|
||||
const requests = vi.hoisted(() => ({
|
||||
getAutoUpgrade: vi.fn(),
|
||||
getPermission: vi.fn(),
|
||||
autoUpgrade: vi.fn(),
|
||||
permission: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.autoUpgrade.fetch.get': requests.getAutoUpgrade,
|
||||
'workspaces.current.plugin.permission.fetch.get': requests.getPermission,
|
||||
'workspaces.current.plugin.autoUpgrade.change.post': requests.autoUpgrade,
|
||||
'workspaces.current.plugin.permission.change.post': requests.permission,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const autoUpgrade = {
|
||||
strategy_setting: 'fix_only' as const,
|
||||
upgrade_time_of_day: 0,
|
||||
upgrade_mode: 'all' as const,
|
||||
exclude_plugins: [],
|
||||
include_plugins: [],
|
||||
}
|
||||
const permissions: { install_permission: PermissionType; debug_permission: PermissionType } = {
|
||||
install_permission: PermissionType.everyone,
|
||||
debug_permission: PermissionType.everyone,
|
||||
}
|
||||
const allKeys = ['plugin.install', 'plugin.delete', 'plugin.debug', 'plugin.plugin_preferences']
|
||||
const toastSuccess = vi.spyOn(toast, 'success').mockReturnValue('toast-success')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
consoleState = { workspacePermissionKeys: [] }
|
||||
requests.getPermission.mockResolvedValue(permissions)
|
||||
requests.getAutoUpgrade.mockResolvedValue({
|
||||
category: PluginCategoryEnum.tool,
|
||||
auto_upgrade: autoUpgrade,
|
||||
})
|
||||
requests.autoUpgrade.mockResolvedValue({})
|
||||
requests.permission.mockResolvedValue({})
|
||||
})
|
||||
|
||||
describe('plugin settings access', () => {
|
||||
it.each([
|
||||
{
|
||||
name: 'legacy access with all keys',
|
||||
rbac: false,
|
||||
keys: allKeys,
|
||||
legacy: PermissionType.everyone,
|
||||
manager: false,
|
||||
owner: false,
|
||||
install: true,
|
||||
debug: true,
|
||||
},
|
||||
{
|
||||
name: 'legacy install still requires a key',
|
||||
rbac: false,
|
||||
keys: [],
|
||||
legacy: PermissionType.everyone,
|
||||
manager: false,
|
||||
owner: false,
|
||||
install: false,
|
||||
debug: true,
|
||||
},
|
||||
{
|
||||
name: 'legacy noOne blocks even managers',
|
||||
rbac: false,
|
||||
keys: allKeys,
|
||||
legacy: PermissionType.noOne,
|
||||
manager: true,
|
||||
owner: false,
|
||||
install: false,
|
||||
debug: false,
|
||||
},
|
||||
{
|
||||
name: 'legacy admin grants managers debug access',
|
||||
rbac: false,
|
||||
keys: [],
|
||||
legacy: PermissionType.admin,
|
||||
manager: true,
|
||||
owner: false,
|
||||
install: false,
|
||||
debug: true,
|
||||
},
|
||||
{
|
||||
name: 'legacy admin grants owners debug access',
|
||||
rbac: false,
|
||||
keys: [],
|
||||
legacy: PermissionType.admin,
|
||||
manager: false,
|
||||
owner: true,
|
||||
install: false,
|
||||
debug: true,
|
||||
},
|
||||
{
|
||||
name: 'legacy admin excludes members',
|
||||
rbac: false,
|
||||
keys: allKeys,
|
||||
legacy: PermissionType.admin,
|
||||
manager: false,
|
||||
owner: false,
|
||||
install: false,
|
||||
debug: false,
|
||||
},
|
||||
{
|
||||
name: 'RBAC keys override legacy noOne',
|
||||
rbac: true,
|
||||
keys: allKeys,
|
||||
legacy: PermissionType.noOne,
|
||||
manager: false,
|
||||
owner: false,
|
||||
install: true,
|
||||
debug: true,
|
||||
},
|
||||
{
|
||||
name: 'RBAC excludes managers without keys',
|
||||
rbac: true,
|
||||
keys: [],
|
||||
legacy: PermissionType.everyone,
|
||||
manager: true,
|
||||
owner: false,
|
||||
install: false,
|
||||
debug: false,
|
||||
},
|
||||
])('$name', async ({ rbac, keys, legacy, manager, owner, install, debug }) => {
|
||||
consoleState = {
|
||||
workspacePermissionKeys: keys,
|
||||
isCurrentWorkspaceManager: manager,
|
||||
isCurrentWorkspaceOwner: owner,
|
||||
}
|
||||
requests.getPermission.mockResolvedValue({
|
||||
install_permission: legacy,
|
||||
debug_permission: legacy,
|
||||
})
|
||||
const { result } = renderHookWithConsoleQuery(
|
||||
() => useReferenceSetting(PluginCategoryEnum.tool),
|
||||
{
|
||||
systemFeatures: { rbac_enabled: rbac },
|
||||
},
|
||||
)
|
||||
await waitFor(() => expect(result.current.isPermissionLoading).toBe(false))
|
||||
expect(result.current).toMatchObject({
|
||||
canInstallPlugin: install,
|
||||
canManagement: install,
|
||||
canUpdatePlugin: install,
|
||||
canDeletePlugin: install && keys.includes('plugin.delete'),
|
||||
canDebugPlugin: debug,
|
||||
canDebugger: debug,
|
||||
canSetPluginPreferences: keys.includes('plugin.plugin_preferences'),
|
||||
canSetPermissions: !rbac && keys.includes('plugin.plugin_preferences'),
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps install and delete permissions independent', async () => {
|
||||
consoleState = { workspacePermissionKeys: ['plugin.install'] }
|
||||
const { result } = renderHookWithConsoleQuery(() =>
|
||||
useReferenceSetting(PluginCategoryEnum.tool),
|
||||
)
|
||||
await waitFor(() => expect(result.current.isPermissionLoading).toBe(false))
|
||||
expect(result.current.canInstallPlugin).toBe(true)
|
||||
expect(result.current.canDeletePlugin).toBe(false)
|
||||
})
|
||||
|
||||
it('allows permission-based actions while auto-upgrade settings are loading', async () => {
|
||||
consoleState = { workspacePermissionKeys: ['plugin.install', 'plugin.debug'] }
|
||||
requests.getAutoUpgrade.mockReturnValue(new Promise(() => {}))
|
||||
const { result } = renderHookWithConsoleQuery(() =>
|
||||
useReferenceSetting(PluginCategoryEnum.tool),
|
||||
)
|
||||
await waitFor(() => expect(result.current.isPermissionLoading).toBe(false))
|
||||
expect(result.current.referenceSetting).toBeUndefined()
|
||||
expect(result.current.isReferenceSettingLoading).toBe(true)
|
||||
expect(result.current.canManagement).toBe(true)
|
||||
expect(result.current.canDebugger).toBe(true)
|
||||
})
|
||||
|
||||
it.each(['isLoadingWorkspacePermissionKeys', 'isLoadingCurrentWorkspace'] as const)(
|
||||
'stays loading while %s is true',
|
||||
async (loadingKey) => {
|
||||
consoleState = { [loadingKey]: true, workspacePermissionKeys: [] }
|
||||
const { result } = renderHookWithConsoleQuery(() =>
|
||||
useReferenceSetting(PluginCategoryEnum.tool),
|
||||
)
|
||||
await waitFor(() => expect(result.current.referenceSetting).toBeDefined())
|
||||
expect(result.current.isPermissionLoading).toBe(true)
|
||||
expect(result.current.canInstallPlugin).toBe(false)
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('saving reference settings', () => {
|
||||
it('submits only changed settings and refreshes server data after the pending save completes', async () => {
|
||||
const request = createDeferred<object>()
|
||||
requests.autoUpgrade.mockReturnValueOnce(request.promise)
|
||||
const { result } = renderHookWithConsoleQuery(() =>
|
||||
useReferenceSetting(PluginCategoryEnum.tool),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(result.current.referenceSetting).toEqual({
|
||||
permission: permissions,
|
||||
auto_upgrade: autoUpgrade,
|
||||
}),
|
||||
)
|
||||
const updated = { ...autoUpgrade, strategy_setting: 'latest' as const }
|
||||
act(() =>
|
||||
result.current.setReferenceSettings({ permission: permissions, auto_upgrade: updated }),
|
||||
)
|
||||
await waitFor(() => expect(result.current.isUpdatePending).toBe(true))
|
||||
expect(requests.autoUpgrade).toHaveBeenCalledWith({
|
||||
body: { category: 'tool', auto_upgrade: updated },
|
||||
})
|
||||
expect(requests.permission).not.toHaveBeenCalled()
|
||||
expect(toastSuccess).not.toHaveBeenCalled()
|
||||
requests.getAutoUpgrade.mockResolvedValue({
|
||||
category: PluginCategoryEnum.tool,
|
||||
auto_upgrade: updated,
|
||||
})
|
||||
request.resolve({})
|
||||
await waitFor(() => expect(result.current.isUpdatePending).toBe(false))
|
||||
await waitFor(() => expect(requests.getAutoUpgrade).toHaveBeenCalledTimes(2))
|
||||
expect(result.current.referenceSetting).toEqual({
|
||||
permission: permissions,
|
||||
auto_upgrade: updated,
|
||||
})
|
||||
expect(toastSuccess).toHaveBeenCalledWith('common.api.actionSuccess')
|
||||
})
|
||||
})
|
||||
|
||||
describe('marketplace install access', () => {
|
||||
it.each([
|
||||
{
|
||||
marketplace: true,
|
||||
keys: ['plugin.install'],
|
||||
legacy: PermissionType.everyone,
|
||||
rbac: false,
|
||||
allowed: true,
|
||||
},
|
||||
{
|
||||
marketplace: false,
|
||||
keys: ['plugin.install'],
|
||||
legacy: PermissionType.everyone,
|
||||
rbac: false,
|
||||
allowed: false,
|
||||
},
|
||||
{ marketplace: true, keys: [], legacy: PermissionType.everyone, rbac: false, allowed: false },
|
||||
{
|
||||
marketplace: true,
|
||||
keys: ['plugin.install'],
|
||||
legacy: PermissionType.noOne,
|
||||
rbac: false,
|
||||
allowed: false,
|
||||
},
|
||||
{
|
||||
marketplace: true,
|
||||
keys: ['plugin.install'],
|
||||
legacy: PermissionType.noOne,
|
||||
rbac: true,
|
||||
allowed: true,
|
||||
},
|
||||
])(
|
||||
'marketplace=$marketplace, keys=$keys, legacy=$legacy, RBAC=$rbac → $allowed',
|
||||
async ({ marketplace, keys, legacy, rbac, allowed }) => {
|
||||
consoleState = { workspacePermissionKeys: keys }
|
||||
const response = createDeferred<typeof permissions>()
|
||||
requests.getPermission.mockReturnValueOnce(response.promise)
|
||||
const { result } = renderHookWithConsoleQuery(() => useCanInstallPluginFromMarketplace(), {
|
||||
systemFeatures: { enable_marketplace: marketplace, rbac_enabled: rbac },
|
||||
})
|
||||
await act(async () =>
|
||||
response.resolve({ install_permission: legacy, debug_permission: legacy }),
|
||||
)
|
||||
await waitFor(() => expect(result.current.canInstallPluginFromMarketplace).toBe(allowed))
|
||||
expect(requests.getPermission).toHaveBeenCalledOnce()
|
||||
expect(requests.getAutoUpgrade).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
import { act, fireEvent, render, renderHook, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createElement, useRef } from 'react'
|
||||
import { useUploader } from '../use-uploader'
|
||||
|
||||
const file = new File(['content'], 'test.difypkg', { type: 'application/octet-stream' })
|
||||
|
||||
function Uploader({
|
||||
onFileChange,
|
||||
enabled = true,
|
||||
}: {
|
||||
onFileChange: (file: File | null) => void
|
||||
enabled?: boolean
|
||||
}) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const { dragging, fileUploader, fileChangeHandle, removeFile } = useUploader({
|
||||
onFileChange,
|
||||
containerRef,
|
||||
enabled,
|
||||
})
|
||||
return createElement(
|
||||
'div',
|
||||
{ ref: containerRef, 'aria-label': 'Plugin upload', role: 'region' },
|
||||
createElement('span', { role: 'status' }, dragging ? 'Drop package here' : 'Choose package'),
|
||||
createElement('input', {
|
||||
ref: fileUploader,
|
||||
type: 'file',
|
||||
'aria-label': 'Package',
|
||||
disabled: !fileChangeHandle,
|
||||
onChange: fileChangeHandle ?? undefined,
|
||||
}),
|
||||
createElement('button', { disabled: !removeFile, onClick: removeFile ?? undefined }, 'Remove'),
|
||||
)
|
||||
}
|
||||
|
||||
it('shows file dragging, ignores text drags and keeps the drop target active over children', () => {
|
||||
render(createElement(Uploader, { onFileChange: vi.fn() }))
|
||||
const target = screen.getByRole('region')
|
||||
fireEvent.dragEnter(target, { dataTransfer: { types: ['text/plain'] } })
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Choose package')
|
||||
fireEvent.dragEnter(target, { dataTransfer: { types: ['Files'] } })
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Drop package here')
|
||||
const leaveToChild = new MouseEvent('dragleave', {
|
||||
bubbles: true,
|
||||
relatedTarget: screen.getByLabelText('Package'),
|
||||
})
|
||||
fireEvent(target, leaveToChild)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Drop package here')
|
||||
fireEvent.dragLeave(target, { relatedTarget: document.body })
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Choose package')
|
||||
fireEvent.dragEnter(target, { dataTransfer: { types: ['Files'] } })
|
||||
fireEvent.dragLeave(target, { relatedTarget: null })
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Choose package')
|
||||
})
|
||||
|
||||
it('prevents browser drag navigation and consumes only the first dropped package', () => {
|
||||
const onFileChange = vi.fn()
|
||||
render(createElement(Uploader, { onFileChange }))
|
||||
const target = screen.getByRole('region')
|
||||
const bubble = vi.fn()
|
||||
document.body.addEventListener('dragover', bubble)
|
||||
try {
|
||||
const event = new Event('dragover', { bubbles: true, cancelable: true })
|
||||
fireEvent(target, event)
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
expect(bubble).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
document.body.removeEventListener('dragover', bubble)
|
||||
}
|
||||
fireEvent.dragEnter(target, { dataTransfer: { types: ['Files'] } })
|
||||
fireEvent.drop(target, { dataTransfer: { files: [file, new File(['other'], 'other.difypkg')] } })
|
||||
expect(onFileChange).toHaveBeenCalledExactlyOnceWith(file)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Choose package')
|
||||
})
|
||||
|
||||
it.each([undefined, { files: [] }])(
|
||||
'clears dragging without selecting a file for an empty drop (%s)',
|
||||
(dataTransfer) => {
|
||||
const onFileChange = vi.fn()
|
||||
render(createElement(Uploader, { onFileChange }))
|
||||
const target = screen.getByRole('region')
|
||||
fireEvent.dragEnter(target, { dataTransfer: { types: ['Files'] } })
|
||||
fireEvent.drop(target, { dataTransfer })
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Choose package')
|
||||
expect(onFileChange).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('selects, removes and reselects the same file through the real input', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onFileChange = vi.fn()
|
||||
render(createElement(Uploader, { onFileChange }))
|
||||
const input = screen.getByLabelText('Package') as HTMLInputElement
|
||||
await user.upload(input, file)
|
||||
expect(onFileChange).toHaveBeenLastCalledWith(file)
|
||||
await user.click(screen.getByRole('button', { name: 'Remove' }))
|
||||
expect(onFileChange).toHaveBeenLastCalledWith(null)
|
||||
expect(input.value).toBe('')
|
||||
await user.upload(input, file)
|
||||
expect(onFileChange).toHaveBeenCalledTimes(3)
|
||||
expect(onFileChange).toHaveBeenLastCalledWith(file)
|
||||
fireEvent.change(input, { target: { files: [] } })
|
||||
expect(onFileChange).toHaveBeenLastCalledWith(null)
|
||||
})
|
||||
|
||||
it('ignores dragging and drops while disabled, then enables the upload controls', () => {
|
||||
const onFileChange = vi.fn()
|
||||
const { rerender } = render(createElement(Uploader, { onFileChange, enabled: false }))
|
||||
const target = screen.getByRole('region')
|
||||
fireEvent.dragEnter(target, { dataTransfer: { types: ['Files'] } })
|
||||
fireEvent.drop(target, { dataTransfer: { files: [file] } })
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Choose package')
|
||||
expect(screen.getByLabelText('Package')).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Remove' })).toBeDisabled()
|
||||
expect(onFileChange).not.toHaveBeenCalled()
|
||||
rerender(createElement(Uploader, { onFileChange }))
|
||||
fireEvent.drop(target, { dataTransfer: { files: [file] } })
|
||||
expect(onFileChange).toHaveBeenCalledExactlyOnceWith(file)
|
||||
})
|
||||
|
||||
it('stops responding to drops after the hook unmounts', () => {
|
||||
const containerRef = { current: document.createElement('div') }
|
||||
const onFileChange = vi.fn()
|
||||
const { unmount } = renderHook(() => useUploader({ containerRef, onFileChange }))
|
||||
unmount()
|
||||
act(() => fireEvent.drop(containerRef.current, { dataTransfer: { files: [file] } }))
|
||||
expect(onFileChange).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { EmbeddedMarketplaceCategory } from './category-marketplace'
|
||||
import { Trans, useTranslation } from 'react-i18next'
|
||||
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
|
||||
import { getCategoryMarketplaceId } from './category-marketplace'
|
||||
|
||||
const categoryConfig = {
|
||||
trigger: {
|
||||
categoryKey: 'category.triggers',
|
||||
iconClassName: 'i-custom-vender-integrations-trigger-active',
|
||||
textKey: 'list.noTriggerFound',
|
||||
tourTarget: STEP_BY_STEP_TOUR_TARGETS.integrationTriggerGrid,
|
||||
},
|
||||
'agent-strategy': {
|
||||
categoryKey: 'category.agents',
|
||||
iconClassName: 'i-custom-vender-integrations-agent-strategy-active',
|
||||
textKey: 'list.noAgentStrategyFound',
|
||||
tourTarget: STEP_BY_STEP_TOUR_TARGETS.integrationAgentStrategyEmpty,
|
||||
},
|
||||
extension: {
|
||||
categoryKey: 'category.extensions',
|
||||
iconClassName: 'i-custom-vender-integrations-extension-active',
|
||||
textKey: 'list.noExtensionFound',
|
||||
tourTarget: STEP_BY_STEP_TOUR_TARGETS.integrationExtensionGrid,
|
||||
},
|
||||
} as const
|
||||
|
||||
type Category = keyof typeof categoryConfig
|
||||
|
||||
const CategoryEmptyState = ({
|
||||
category,
|
||||
showMarketplaceLink,
|
||||
}: {
|
||||
category: EmbeddedMarketplaceCategory
|
||||
showMarketplaceLink: boolean
|
||||
}) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const config = categoryConfig[category as Category]
|
||||
|
||||
if (!config) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="mb-2 rounded-[10px] bg-workflow-process-bg p-4"
|
||||
data-step-by-step-tour-target={config.tourTarget}
|
||||
>
|
||||
<div className="flex size-10 items-center justify-center rounded-[10px] border-[0.5px] border-components-card-border bg-components-card-bg shadow-lg backdrop-blur-sm">
|
||||
<span aria-hidden className={`${config.iconClassName} size-5 text-text-primary`} />
|
||||
</div>
|
||||
<div className="mt-2 system-sm-medium text-text-secondary">
|
||||
{t(($) => $[config.textKey], { ns: 'plugin' })}
|
||||
</div>
|
||||
{showMarketplaceLink && (
|
||||
<p className="mt-1 system-xs-regular text-text-tertiary">
|
||||
<Trans
|
||||
components={{
|
||||
marketplace: (
|
||||
<a
|
||||
className="system-xs-medium text-text-accent hover:underline"
|
||||
href={`#${getCategoryMarketplaceId(category)}`}
|
||||
>
|
||||
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
|
||||
</a>
|
||||
),
|
||||
}}
|
||||
i18nKey={($) => $['list.emptyInstallFromMarketplace']}
|
||||
ns="plugin"
|
||||
values={{ category: t(($) => $[config.categoryKey], { ns: 'plugin' }) }}
|
||||
/>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CategoryEmptyState
|
||||
@@ -0,0 +1,173 @@
|
||||
'use client'
|
||||
|
||||
import type { PluginsSearchParams } from '@dify/contracts/marketplace'
|
||||
import type { Plugin } from '../types'
|
||||
import type { EmbeddedMarketplaceCategory } from './category-marketplace'
|
||||
import type { MarketplaceLinks } from '@/features/marketplace/links'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
|
||||
import List from '@/app/components/plugins/marketplace/list'
|
||||
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/query'
|
||||
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
|
||||
import ProviderCard from '@/app/components/plugins/provider-card'
|
||||
import Link from '@/next/link'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { getCategoryMarketplaceId } from './category-marketplace'
|
||||
|
||||
const MARKETPLACE_PAGE_SIZE = 30
|
||||
|
||||
const CategoryMarketplacePanel = ({
|
||||
marketplace,
|
||||
category,
|
||||
searchText,
|
||||
tags = [],
|
||||
}: {
|
||||
marketplace: MarketplaceLinks
|
||||
category: EmbeddedMarketplaceCategory
|
||||
searchText: string
|
||||
tags?: string[]
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin', 'workflow', 'modelProvider'])
|
||||
const { theme } = useTheme()
|
||||
const { canInstallPlugin } = usePluginSettingsAccess()
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
const {
|
||||
data: installedPluginIds,
|
||||
isError: hasInstalledPluginIdsError,
|
||||
isFetching: isFetchingInstalledPluginIds,
|
||||
isPending: isLoadingInstalledPluginIds,
|
||||
refetch: refetchInstalledPluginIds,
|
||||
} = useQuery({
|
||||
...consoleQuery.workspaces.current.plugin.installedIds.get.queryOptions({
|
||||
input: { query: { category } },
|
||||
}),
|
||||
select: (data) => data.plugin_ids,
|
||||
})
|
||||
const hasLoadedInstalledPluginIds = installedPluginIds !== undefined
|
||||
const marketplaceSearchParams = useMemo<PluginsSearchParams | undefined>(() => {
|
||||
if (!hasLoadedInstalledPluginIds || collapsed) return undefined
|
||||
|
||||
return {
|
||||
category,
|
||||
exclude: installedPluginIds ?? [],
|
||||
page_size: MARKETPLACE_PAGE_SIZE,
|
||||
query: searchText,
|
||||
sort_by: 'install_count',
|
||||
sort_order: 'DESC',
|
||||
...(tags.length ? { tags } : {}),
|
||||
type: 'plugin',
|
||||
}
|
||||
}, [category, collapsed, hasLoadedInstalledPluginIds, installedPluginIds, searchText, tags])
|
||||
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
|
||||
useMarketplacePlugins(marketplaceSearchParams)
|
||||
const plugins = useMemo(
|
||||
() =>
|
||||
data?.pages
|
||||
.flatMap((page) => page.plugins)
|
||||
.filter((plugin) => !installedPluginIds?.includes(plugin.plugin_id)),
|
||||
[data, installedPluginIds],
|
||||
)
|
||||
|
||||
const marketplaceLink = marketplace.category(category, { theme })
|
||||
const showInstalledPluginIdsError = hasInstalledPluginIdsError && !hasLoadedInstalledPluginIds
|
||||
const showLoading = isLoadingInstalledPluginIds || !!(marketplaceSearchParams && isPending)
|
||||
const cardRender = useCallback(
|
||||
(plugin: Plugin) => {
|
||||
if (plugin.type === 'bundle') return null
|
||||
|
||||
return (
|
||||
<ProviderCard
|
||||
key={plugin.plugin_id}
|
||||
className="h-36.5"
|
||||
marketplace={marketplace}
|
||||
payload={plugin}
|
||||
/>
|
||||
)
|
||||
},
|
||||
[marketplace],
|
||||
)
|
||||
|
||||
return (
|
||||
<section
|
||||
className="flex scroll-mt-4 flex-col gap-2 pb-2"
|
||||
id={getCategoryMarketplaceId(category)}
|
||||
>
|
||||
<Separator className="my-2" />
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={!collapsed}
|
||||
className="flex cursor-pointer items-center gap-1 border-0 bg-transparent p-0 text-left system-md-semibold text-text-primary"
|
||||
onClick={() => setCollapsed((value) => !value)}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn('i-ri-arrow-down-s-line size-4', collapsed && '-rotate-90 rtl:rotate-90')}
|
||||
/>
|
||||
{t(($) => $['list.source.marketplace'], { ns: 'plugin' })}
|
||||
</button>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="system-sm-regular text-text-tertiary">
|
||||
{t(($) => $['modelProvider.discoverMore'], { ns: 'modelProvider' })}
|
||||
</span>
|
||||
<Link
|
||||
className="inline-flex items-center system-sm-medium text-text-accent"
|
||||
href={marketplaceLink}
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-arrow-right-up-line size-4 [&:dir(rtl)]:-scale-x-100"
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<div>
|
||||
{showLoading && <LoadingPlaceholder />}
|
||||
{showInstalledPluginIdsError && (
|
||||
<div className="flex flex-col items-center gap-2 py-4">
|
||||
<span className="system-sm-regular text-text-tertiary" role="alert">
|
||||
{t(($) => $['errorBoundary.title'], { ns: 'common' })}
|
||||
</span>
|
||||
<Button
|
||||
loading={isFetchingInstalledPluginIds}
|
||||
onClick={() => refetchInstalledPluginIds()}
|
||||
>
|
||||
{t(($) => $['operation.retry'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{!showLoading && !showInstalledPluginIdsError && (
|
||||
<List
|
||||
cardContainerClassName="grid-cols-1 sm:grid-cols-2 lg:grid-cols-3"
|
||||
emptyClassName="h-auto"
|
||||
marketplaceCollections={[]}
|
||||
marketplaceCollectionPluginsMap={{}}
|
||||
plugins={plugins ?? []}
|
||||
showInstallButton={canInstallPlugin}
|
||||
cardRender={cardRender}
|
||||
/>
|
||||
)}
|
||||
{!showLoading && hasNextPage && (
|
||||
<div className="flex justify-center py-4">
|
||||
<Button loading={isFetchingNextPage} onClick={() => fetchNextPage()}>
|
||||
{t(($) => $['common.loadMore'], { ns: 'workflow' })}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export default CategoryMarketplacePanel
|
||||
@@ -0,0 +1,13 @@
|
||||
import { PluginCategoryEnum } from '../types'
|
||||
|
||||
export type EmbeddedMarketplaceCategory = 'agent-strategy' | 'extension' | 'trigger'
|
||||
|
||||
export const isEmbeddedMarketplaceCategory = (
|
||||
category?: EmbeddedMarketplaceCategory | PluginCategoryEnum,
|
||||
): category is EmbeddedMarketplaceCategory =>
|
||||
category === PluginCategoryEnum.trigger ||
|
||||
category === PluginCategoryEnum.agent ||
|
||||
category === PluginCategoryEnum.extension
|
||||
|
||||
export const getCategoryMarketplaceId = (category: EmbeddedMarketplaceCategory) =>
|
||||
`plugin-category-marketplace-${category}`
|
||||
@@ -0,0 +1,11 @@
|
||||
export type PluginPageContentInset = 'default' | 'compact'
|
||||
|
||||
export const pluginPageContentFrameClassNames: Record<PluginPageContentInset, string> = {
|
||||
default: 'w-full',
|
||||
compact: 'mx-auto box-border w-full max-w-[1600px]',
|
||||
}
|
||||
|
||||
export const pluginPageContentInsetClassNames: Record<PluginPageContentInset, string> = {
|
||||
default: 'px-12',
|
||||
compact: 'px-6',
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PluginPageSelection, PluginPageTab } from './context'
|
||||
import type { FilterState } from './filter-management'
|
||||
import { parseAsStringEnum, useQueryState } from 'nuqs'
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { useMarketplace } from '@/features/marketplace/client'
|
||||
import { PLUGIN_PAGE_TABS_MAP, usePluginPageTabs } from '../hooks'
|
||||
import { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/constants'
|
||||
import { PluginPageContext } from './context'
|
||||
|
||||
const PLUGIN_PAGE_TAB_VALUES: PluginPageTab[] = [
|
||||
PLUGIN_PAGE_TABS_MAP.plugins,
|
||||
PLUGIN_PAGE_TABS_MAP.marketplace,
|
||||
...Object.values(PLUGIN_TYPE_SEARCH_MAP),
|
||||
]
|
||||
|
||||
const parseAsPluginPageTab = parseAsStringEnum<PluginPageTab>(PLUGIN_PAGE_TAB_VALUES).withDefault(
|
||||
PLUGIN_PAGE_TABS_MAP.plugins,
|
||||
)
|
||||
|
||||
type PluginPageContextProviderProps = {
|
||||
children: ReactNode
|
||||
initialFilters?: FilterState
|
||||
}
|
||||
|
||||
export const PluginPageContextProvider = ({
|
||||
children,
|
||||
initialFilters,
|
||||
}: PluginPageContextProviderProps) => {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
const [filters, setFilters] = useState<FilterState>(
|
||||
initialFilters ?? {
|
||||
categories: [],
|
||||
tags: [],
|
||||
searchQuery: '',
|
||||
},
|
||||
)
|
||||
const [selectedItem, setSelectedItem] = useState<PluginPageSelection | undefined>()
|
||||
|
||||
const enable_marketplace = useMarketplace() !== null
|
||||
const tabs = usePluginPageTabs()
|
||||
const options = useMemo(() => {
|
||||
return enable_marketplace
|
||||
? tabs
|
||||
: tabs.filter((tab) => tab.value !== PLUGIN_PAGE_TABS_MAP.marketplace)
|
||||
}, [tabs, enable_marketplace])
|
||||
const [activeTab, setActiveTab] = useQueryState('tab', parseAsPluginPageTab)
|
||||
|
||||
return (
|
||||
<PluginPageContext.Provider
|
||||
value={{
|
||||
containerRef,
|
||||
selectedItem,
|
||||
setSelectedItem,
|
||||
filters,
|
||||
setFilters,
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
options,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PluginPageContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
'use client'
|
||||
|
||||
import type { RefObject } from 'react'
|
||||
import type { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/constants'
|
||||
import type { FilterState } from './filter-management'
|
||||
import { noop } from 'es-toolkit/function'
|
||||
import { createContext, useContextSelector } from 'use-context-selector'
|
||||
import { PLUGIN_PAGE_TABS_MAP } from '../hooks'
|
||||
|
||||
export type PluginPageTab =
|
||||
| (typeof PLUGIN_PAGE_TABS_MAP)[keyof typeof PLUGIN_PAGE_TABS_MAP]
|
||||
| (typeof PLUGIN_TYPE_SEARCH_MAP)[keyof typeof PLUGIN_TYPE_SEARCH_MAP]
|
||||
|
||||
export type PluginPageSelection =
|
||||
| { type: 'builtinTool'; id: string }
|
||||
| { type: 'plugin'; id: string }
|
||||
|
||||
type PluginPageContextValue = {
|
||||
containerRef: RefObject<HTMLDivElement | null>
|
||||
selectedItem: PluginPageSelection | undefined
|
||||
setSelectedItem: (item?: PluginPageSelection) => void
|
||||
filters: FilterState
|
||||
setFilters: (filter: FilterState) => void
|
||||
activeTab: PluginPageTab
|
||||
setActiveTab: (tab: PluginPageTab) => void
|
||||
options: Array<{ value: string; text: string }>
|
||||
}
|
||||
|
||||
const emptyContainerRef: RefObject<HTMLDivElement | null> = { current: null }
|
||||
|
||||
export const PluginPageContext = createContext<PluginPageContextValue>({
|
||||
containerRef: emptyContainerRef,
|
||||
selectedItem: undefined,
|
||||
setSelectedItem: noop,
|
||||
filters: {
|
||||
categories: [],
|
||||
tags: [],
|
||||
searchQuery: '',
|
||||
},
|
||||
setFilters: noop,
|
||||
activeTab: PLUGIN_PAGE_TABS_MAP.plugins,
|
||||
setActiveTab: noop,
|
||||
options: [],
|
||||
})
|
||||
|
||||
export function usePluginPageContext<T>(selector: (value: PluginPageContextValue) => T) {
|
||||
return useContextSelector(PluginPageContext, selector)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
'use client'
|
||||
import type { ButtonProps } from '@langgenius/dify-ui/button'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useDocLink } from '@/context/i18n'
|
||||
import { useDebugKey } from '@/service/use-plugins'
|
||||
import KeyValueItem from '../base/key-value-item'
|
||||
import { PluginSidecarPanel } from './plugin-sidecar-panel'
|
||||
|
||||
const i18nPrefix = 'debugInfo'
|
||||
|
||||
type DebugInfoProps = {
|
||||
triggerClassName?: string
|
||||
triggerContent?: ReactNode
|
||||
triggerVariant?: ButtonProps['variant']
|
||||
}
|
||||
|
||||
function DebugInfo({
|
||||
triggerClassName,
|
||||
triggerContent,
|
||||
triggerVariant = 'secondary',
|
||||
}: DebugInfoProps) {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const docLink = useDocLink()
|
||||
const { data: info, isLoading } = useDebugKey()
|
||||
const title = t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })
|
||||
const trigger = triggerContent ?? <span aria-hidden className="i-ri-bug-line size-4" />
|
||||
const triggerClassNames = cn(
|
||||
!triggerClassName && 'size-full p-2 text-components-button-secondary-text',
|
||||
triggerClassName,
|
||||
)
|
||||
|
||||
// info.key likes 4580bdb7-b878-471c-a8a4-bfd760263a53 mask the middle part using *.
|
||||
const maskedKey = info?.key?.replace(/(.{8})(.*)(.{8})/, '$1********$3')
|
||||
|
||||
if (isLoading) return null
|
||||
|
||||
if (!info) {
|
||||
return (
|
||||
<Button variant={triggerVariant} className={triggerClassNames} aria-label={title} disabled>
|
||||
{trigger}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button variant={triggerVariant} className={triggerClassNames} aria-label={title}>
|
||||
{trigger}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverContent side="top" align="start" className="border-0 bg-transparent p-0 shadow-none">
|
||||
<PluginSidecarPanel
|
||||
title={title}
|
||||
footer={
|
||||
<div className="flex w-full shrink-0 flex-col items-start">
|
||||
<div className="flex w-full shrink-0 items-center justify-end gap-2 px-4 pt-2 pb-4">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1">
|
||||
<a
|
||||
href={docLink(
|
||||
'/develop-plugin/features-and-specs/plugin-types/remote-debug-a-plugin',
|
||||
)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex cursor-pointer items-center gap-1 rounded-xs system-xs-regular text-text-accent focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
|
||||
>
|
||||
<span>{t(($) => $[`${i18nPrefix}.viewDocs`], { ns: 'plugin' })}</span>
|
||||
<span aria-hidden className="i-ri-arrow-right-up-line size-3" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex w-full shrink-0 flex-col items-start justify-center gap-1 px-4 py-2">
|
||||
<KeyValueItem label="Port" value={`${info.host}:${info.port}`} />
|
||||
<KeyValueItem
|
||||
label="Key"
|
||||
value={info.key || ''}
|
||||
maskedValue={maskedKey}
|
||||
valueMaxWidthClassName="max-w-[224px]"
|
||||
/>
|
||||
</div>
|
||||
</PluginSidecarPanel>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default DebugInfo
|
||||
@@ -0,0 +1,219 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { PluginPageTab } from '../../context'
|
||||
import type { FilterState } from '../../filter-management'
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { seedModelProviderQueries } from '@/test/console/model-provider'
|
||||
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createInstalledPluginFixture } from '@/test/fixtures/plugin'
|
||||
import { PluginPageContext } from '../../context'
|
||||
import Empty from '../index'
|
||||
|
||||
const requests = vi.hoisted(() => ({ list: vi.fn(), upload: vi.fn() }))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
uploadFile: requests.upload,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses, withConsoleClientResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.get': requests.list,
|
||||
'workspaces.current.plugin.list.installations.ids.post': () => ({ plugins: [] }),
|
||||
}),
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.permission.fetch.get': () => ({
|
||||
install_permission: 'everyone',
|
||||
debug_permission: 'everyone',
|
||||
}),
|
||||
'workspaces.current.plugin.tasks.get': () => ({ tasks: [] }),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
function renderEmpty({
|
||||
filters = {},
|
||||
marketplace = true,
|
||||
restricted = false,
|
||||
customNavigation = false,
|
||||
...props
|
||||
}: Partial<ComponentProps<typeof Empty>> & {
|
||||
filters?: Partial<FilterState>
|
||||
marketplace?: boolean
|
||||
restricted?: boolean
|
||||
customNavigation?: boolean
|
||||
} = {}) {
|
||||
const initialFilters: FilterState = { categories: [], tags: [], searchQuery: '', ...filters }
|
||||
function Caller() {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [activeTab, setActiveTab] = useState<PluginPageTab>('plugins')
|
||||
const [customOpen, setCustomOpen] = useState(false)
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
containerRef,
|
||||
selectedItem: undefined,
|
||||
setSelectedItem: () => {},
|
||||
filters: initialFilters,
|
||||
setFilters: () => {},
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
options: [],
|
||||
}),
|
||||
[activeTab],
|
||||
)
|
||||
return (
|
||||
<PluginPageContext.Provider value={value}>
|
||||
{activeTab === 'discover' && <section aria-label="Discover marketplace" />}
|
||||
{customOpen && <section aria-label="Caller marketplace" />}
|
||||
<Empty
|
||||
{...props}
|
||||
onSwitchToMarketplace={
|
||||
customNavigation ? () => setCustomOpen(true) : props.onSwitchToMarketplace
|
||||
}
|
||||
/>
|
||||
</PluginPageContext.Provider>
|
||||
)
|
||||
}
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedModelProviderQueries(queryClient)
|
||||
return renderWithConsoleQuery(<Caller />, {
|
||||
queryClient,
|
||||
workspacePermissionKeys: ['plugin.install'],
|
||||
systemFeatures: {
|
||||
rbac_enabled: true,
|
||||
enable_marketplace: marketplace,
|
||||
plugin_installation_permission: {
|
||||
plugin_installation_scope: 'all',
|
||||
restrict_to_marketplace_only: restricted,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const getFileInput = () => document.querySelector<HTMLInputElement>('input[type="file"]')!
|
||||
const createFile = (name: string) =>
|
||||
new File(['package'], name, { type: 'application/octet-stream' })
|
||||
|
||||
beforeEach(() => {
|
||||
requests.list.mockReset().mockResolvedValue({ plugins: [], total: 0 })
|
||||
// These existing scenarios cancel before uploading finishes. Keep the transport
|
||||
// pending so the real upload view and its close action own the interaction.
|
||||
requests.upload.mockReset().mockReturnValue(new Promise(() => {}))
|
||||
})
|
||||
|
||||
it('shows the no-installed message even when filters are active', async () => {
|
||||
renderEmpty({ filters: { categories: ['model'], searchQuery: 'test' } })
|
||||
expect(await screen.findByText('plugin.list.noInstalled')).toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.list.notFound')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([{ categories: ['model'] }, { tags: ['tag1'] }, { searchQuery: 'test query' }])(
|
||||
'shows no results for an installed list filtered by %o',
|
||||
async (filters) => {
|
||||
requests.list.mockResolvedValue({ plugins: [createInstalledPluginFixture()], total: 1 })
|
||||
renderEmpty({ filters })
|
||||
expect(await screen.findByText('plugin.list.notFound')).toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.list.noInstalled')).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
{ marketplace: true, restricted: false, methods: ['marketplace', 'github', 'local'] },
|
||||
{ marketplace: true, restricted: true, methods: ['marketplace'] },
|
||||
{ marketplace: false, restricted: false, methods: ['github', 'local'] },
|
||||
{ marketplace: false, restricted: true, methods: [] },
|
||||
])(
|
||||
'offers $methods with marketplace=$marketplace and restricted=$restricted',
|
||||
({ marketplace, restricted, methods }) => {
|
||||
renderEmpty({ marketplace, restricted })
|
||||
for (const method of ['marketplace', 'github', 'local']) {
|
||||
const button = screen.queryByRole('button', { name: `plugin.source.${method}` })
|
||||
if (methods.includes(method)) expect(button).toBeInTheDocument()
|
||||
else expect(button).not.toBeInTheDocument()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('hides installation actions and ignores file changes without install permission', () => {
|
||||
renderEmpty({ canInstall: false })
|
||||
expect(screen.queryAllByRole('button')).toHaveLength(0)
|
||||
fireEvent.change(getFileInput(), { target: { files: [createFile('blocked.difypkg')] } })
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(requests.upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the discovery tab from the marketplace action', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEmpty()
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
|
||||
expect(screen.getByRole('region', { name: 'Discover marketplace' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the supplied marketplace navigation instead of switching tabs', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEmpty({ customNavigation: true })
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
|
||||
expect(screen.getByRole('region', { name: 'Caller marketplace' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('region', { name: 'Discover marketplace' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens, closes, and reopens the real GitHub installer', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEmpty()
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
|
||||
const dialog = await screen.findByRole('dialog', {
|
||||
name: 'plugin.installFromGitHub.installPlugin',
|
||||
})
|
||||
expect(within(dialog).getByRole('textbox')).toHaveValue('')
|
||||
await user.click(within(dialog).getByRole('button', { name: 'plugin.installModal.cancel' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
|
||||
expect(
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installPlugin' }),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the file picker for supported plugin and bundle files', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEmpty()
|
||||
const input = getFileInput()
|
||||
const clickSpy = vi.spyOn(input, 'click')
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.source.local' }))
|
||||
expect(clickSpy).toHaveBeenCalledOnce()
|
||||
expect(input).toHaveAttribute('accept', '.difypkg,.difybndl')
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('uploads the selected package and accepts a new bundle after closing', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEmpty()
|
||||
const file = createFile('my-plugin.difypkg')
|
||||
await user.upload(getFileInput(), file)
|
||||
const dialog = await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
|
||||
expect(within(dialog).getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
|
||||
file.name,
|
||||
)
|
||||
expect(requests.upload).toHaveBeenCalledWith(file, false)
|
||||
await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
|
||||
const bundle = createFile('my-bundle.difybndl')
|
||||
await user.upload(getFileInput(), bundle)
|
||||
const reopened = await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
|
||||
expect(within(reopened).getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
|
||||
bundle.name,
|
||||
)
|
||||
expect(requests.upload).toHaveBeenLastCalledWith(bundle, true)
|
||||
})
|
||||
|
||||
it('does not open an installer when file selection is cancelled', () => {
|
||||
renderEmpty()
|
||||
fireEvent.change(getFileInput(), { target: { files: [] } })
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(requests.upload).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -0,0 +1,201 @@
|
||||
'use client'
|
||||
import type { PluginPageContentInset } from '../content-inset'
|
||||
import type { PluginCategoryEnum } from '@/app/components/plugins/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { noop } from 'es-toolkit/function'
|
||||
import * as React from 'react'
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
|
||||
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
|
||||
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
|
||||
import { useMarketplace } from '@/features/marketplace/client'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
import { useInstalledPluginList } from '@/service/use-plugins'
|
||||
import Line from '../../marketplace/empty/line'
|
||||
import {
|
||||
pluginPageContentFrameClassNames,
|
||||
pluginPageContentInsetClassNames,
|
||||
} from '../content-inset'
|
||||
import { usePluginPageContext } from '../context'
|
||||
|
||||
type InstallMethod = {
|
||||
iconClassName: string
|
||||
text: string
|
||||
action: string
|
||||
}
|
||||
|
||||
type EmptyProps = {
|
||||
canInstall?: boolean
|
||||
contentInset?: PluginPageContentInset
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
onSwitchToMarketplace?: () => void
|
||||
}
|
||||
|
||||
const Empty = ({
|
||||
canInstall = true,
|
||||
contentInset = 'default',
|
||||
installContextCategory,
|
||||
onSwitchToMarketplace,
|
||||
}: EmptyProps) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [selectedAction, setSelectedAction] = useState<string | null>(null)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const enable_marketplace = useMarketplace() !== null
|
||||
const { data: plugin_installation_permission } = useSuspenseQuery({
|
||||
...systemFeaturesQueryOptions(),
|
||||
select: (s) => s.plugin_installation_permission,
|
||||
})
|
||||
const setActiveTab = usePluginPageContext((v) => v.setActiveTab)
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!canInstall) {
|
||||
setSelectedFile(null)
|
||||
setSelectedAction(null)
|
||||
return
|
||||
}
|
||||
|
||||
const file = event.target.files?.[0]
|
||||
if (file) {
|
||||
setSelectedFile(file)
|
||||
setSelectedAction('local')
|
||||
}
|
||||
}
|
||||
const filters = usePluginPageContext((v) => v.filters)
|
||||
const { data: pluginList } = useInstalledPluginList()
|
||||
|
||||
const text = useMemo(() => {
|
||||
if (pluginList?.plugins.length === 0) return t(($) => $['list.noInstalled'], { ns: 'plugin' })
|
||||
if (filters.categories.length > 0 || filters.tags.length > 0 || filters.searchQuery)
|
||||
return t(($) => $['list.notFound'], { ns: 'plugin' })
|
||||
}, [
|
||||
pluginList?.plugins.length,
|
||||
t,
|
||||
filters.categories.length,
|
||||
filters.tags.length,
|
||||
filters.searchQuery,
|
||||
])
|
||||
|
||||
const installMethods = useMemo<InstallMethod[]>(() => {
|
||||
if (!canInstall) return []
|
||||
|
||||
const methods: InstallMethod[] = []
|
||||
if (enable_marketplace)
|
||||
methods.push({
|
||||
iconClassName: 'i-custom-vender-solid-mediaAndDevices-magic-box',
|
||||
text: t(($) => $['source.marketplace'], { ns: 'plugin' }),
|
||||
action: 'marketplace',
|
||||
})
|
||||
|
||||
if (plugin_installation_permission.restrict_to_marketplace_only) return methods
|
||||
|
||||
methods.push({
|
||||
iconClassName: 'i-custom-vender-solid-general-github',
|
||||
text: t(($) => $['source.github'], { ns: 'plugin' }),
|
||||
action: 'github',
|
||||
})
|
||||
methods.push({
|
||||
iconClassName: 'i-custom-vender-solid-files-file-zip',
|
||||
text: t(($) => $['source.local'], { ns: 'plugin' }),
|
||||
action: 'local',
|
||||
})
|
||||
return methods
|
||||
}, [canInstall, plugin_installation_permission, enable_marketplace, t])
|
||||
const contentPaddingClassName = pluginPageContentInsetClassNames[contentInset]
|
||||
const contentFrameClassName = cn(
|
||||
pluginPageContentFrameClassNames[contentInset],
|
||||
contentPaddingClassName,
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="relative z-0 w-full grow bg-components-panel-bg">
|
||||
<div
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'pointer-events-none absolute top-0 left-1/2 z-10 grid h-full -translate-x-1/2 grid-cols-2 content-start gap-2 overflow-hidden',
|
||||
contentFrameClassName,
|
||||
)}
|
||||
>
|
||||
{Array.from({ length: 20 }, (_, i) => (
|
||||
<div key={i} className="h-24 rounded-xl bg-components-card-bg" />
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 z-20 bg-linear-to-b from-components-panel-bg-transparent to-components-panel-bg"
|
||||
/>
|
||||
<div className="relative z-30 flex h-full items-center justify-center">
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-y-3">
|
||||
<div className="flex flex-col items-center gap-y-3">
|
||||
<div className="relative -z-10 flex size-14 items-center justify-center rounded-xl border border-dashed border-divider-deep bg-components-card-bg shadow-xl shadow-shadow-shadow-5 backdrop-blur-md">
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-other-group size-5 text-text-tertiary"
|
||||
/>
|
||||
<Line className="absolute top-1/2 -right-px -translate-y-1/2" />
|
||||
<Line className="absolute top-1/2 -left-px -translate-y-1/2" />
|
||||
<Line className="absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 rotate-90" />
|
||||
<Line className="absolute top-full left-1/2 -translate-x-1/2 -translate-y-1/2 rotate-90" />
|
||||
</div>
|
||||
<div className="system-md-regular text-text-tertiary">{text}</div>
|
||||
</div>
|
||||
<div className="flex w-59 flex-col">
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileChange}
|
||||
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
|
||||
/>
|
||||
<div className="flex w-full flex-col gap-y-1">
|
||||
{installMethods.map(({ iconClassName, text, action }) => (
|
||||
<Button
|
||||
key={action}
|
||||
variant="secondary"
|
||||
title={text}
|
||||
className="h-8 w-full justify-start py-2 system-sm-medium"
|
||||
onClick={() => {
|
||||
if (action === 'local') fileInputRef.current?.click()
|
||||
else if (action === 'marketplace')
|
||||
onSwitchToMarketplace ? onSwitchToMarketplace() : setActiveTab('discover')
|
||||
else setSelectedAction(action)
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(iconClassName, 'size-4 text-components-button-secondary-text')}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-left">{text}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{selectedAction === 'github' && (
|
||||
<InstallFromGitHub
|
||||
installContextCategory={installContextCategory}
|
||||
onSuccess={noop}
|
||||
onClose={() => setSelectedAction(null)}
|
||||
/>
|
||||
)}
|
||||
{selectedAction === 'local' && selectedFile && (
|
||||
<InstallFromLocalPackage
|
||||
file={selectedFile}
|
||||
installContextCategory={installContextCategory}
|
||||
onClose={() => setSelectedAction(null)}
|
||||
onSuccess={noop}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Empty.displayName = 'Empty'
|
||||
|
||||
export default React.memo(Empty)
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import * as React from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
|
||||
const mockCategories = [
|
||||
{ name: 'tool', label: 'Tool' },
|
||||
{ name: 'model', label: 'Model' },
|
||||
{ name: 'extension', label: 'Extension' },
|
||||
]
|
||||
|
||||
vi.mock('../../../hooks', () => ({
|
||||
useCategories: () => ({
|
||||
categories: mockCategories,
|
||||
categoriesMap: {
|
||||
tool: { label: 'Tool' },
|
||||
model: { label: 'Model' },
|
||||
extension: { label: 'Extension' },
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('CategoriesFilter', () => {
|
||||
let CategoriesFilter: (typeof import('../category-filter'))['default']
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
const mod = await import('../category-filter')
|
||||
CategoriesFilter = mod.default
|
||||
})
|
||||
|
||||
it('should show +N when more than 2 selected', () => {
|
||||
render(<CategoriesFilter value={['tool', 'model', 'extension']} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('+1'))!.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears categories through a separate keyboard control and restores focus', async () => {
|
||||
const user = userEvent.setup()
|
||||
function Harness() {
|
||||
const [categories, setCategories] = React.useState(['tool'])
|
||||
return <CategoriesFilter value={categories} onChange={setCategories} />
|
||||
}
|
||||
|
||||
render(<Harness />)
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Tool' })
|
||||
const clearButton = screen.getByRole('button', {
|
||||
name: 'plugin.clearSearch:{"label":"plugin.allCategories"}',
|
||||
})
|
||||
expect(trigger).not.toContainElement(clearButton)
|
||||
|
||||
await user.tab()
|
||||
expect(trigger).toHaveFocus()
|
||||
await user.tab()
|
||||
expect(clearButton).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
expect(clearButton).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'plugin.allCategories' })).toHaveFocus()
|
||||
})
|
||||
|
||||
it('should toggle category on option click', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mockOnChange = vi.fn()
|
||||
render(<CategoriesFilter value={[]} onChange={mockOnChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.allCategories' }))
|
||||
await user.click(screen.getByText('Tool'))
|
||||
expect(mockOnChange).toHaveBeenCalledWith(['tool'])
|
||||
})
|
||||
|
||||
it('should remove category when clicking already selected', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mockOnChange = vi.fn()
|
||||
render(<CategoriesFilter value={['tool']} onChange={mockOnChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Tool/ }))
|
||||
await user.click(within(await screen.findByRole('dialog')).getByText('Tool'))
|
||||
expect(mockOnChange).toHaveBeenCalledWith([])
|
||||
})
|
||||
|
||||
it('should filter categories by search text', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.allCategories' }))
|
||||
expect(within(await screen.findByRole('dialog')).getByText('Tool')).toBeInTheDocument()
|
||||
expect(within(screen.getByRole('dialog')).getByText('Extension')).toBeInTheDocument()
|
||||
await user.type(screen.getByRole('searchbox', { name: 'plugin.searchCategories' }), 'mod')
|
||||
|
||||
expect(screen.queryByText('Tool')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Model')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Extension')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import type { FilterState } from '../index'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import FilterManagement from '../index'
|
||||
|
||||
let initialFilters: FilterState = {
|
||||
categories: [],
|
||||
tags: [],
|
||||
searchQuery: '',
|
||||
}
|
||||
|
||||
vi.mock('../../context', () => ({
|
||||
usePluginPageContext: (selector: (state: { filters: FilterState }) => unknown) =>
|
||||
selector({ filters: initialFilters }),
|
||||
}))
|
||||
|
||||
vi.mock('../../../hooks', () => ({
|
||||
useCategories: () => ({
|
||||
categories: [{ name: 'model', label: 'Models' }],
|
||||
categoriesMap: { model: { name: 'model', label: 'Models' } },
|
||||
}),
|
||||
useTags: () => ({
|
||||
tags: [{ name: 'agent', label: 'Agent' }],
|
||||
getTagLabel: (name: string) => ({ agent: 'Agent' })[name] ?? name,
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('FilterManagement', () => {
|
||||
beforeEach(() => {
|
||||
initialFilters = { categories: [], tags: [], searchQuery: '' }
|
||||
})
|
||||
|
||||
it('renders filters from the plugin page state', () => {
|
||||
initialFilters = { categories: ['model'], tags: ['agent'], searchQuery: 'search' }
|
||||
|
||||
render(<FilterManagement onFilterChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Models/ })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Agent' })).toBeInTheDocument()
|
||||
expect(screen.getByDisplayValue('search')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('emits the complete filter state when search changes', () => {
|
||||
const onFilterChange = vi.fn()
|
||||
initialFilters = { categories: ['model'], tags: ['agent'], searchQuery: '' }
|
||||
render(<FilterManagement onFilterChange={onFilterChange} />)
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
|
||||
target: { value: 'new query' },
|
||||
})
|
||||
|
||||
expect(onFilterChange).toHaveBeenCalledWith({
|
||||
categories: ['model'],
|
||||
tags: ['agent'],
|
||||
searchQuery: 'new query',
|
||||
})
|
||||
})
|
||||
|
||||
it('hides optional filters', () => {
|
||||
render(<FilterManagement hideCategoryFilter hideTagFilter onFilterChange={vi.fn()} />)
|
||||
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(screen.getByPlaceholderText('plugin.search')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a right-side slot', () => {
|
||||
render(<FilterManagement onFilterChange={vi.fn()} rightSlot={<span>Sort controls</span>} />)
|
||||
|
||||
expect(screen.getByText('Sort controls')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
|
||||
describe('SearchBox', () => {
|
||||
let SearchBox: (typeof import('../search-box'))['default']
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
const mod = await import('../search-box')
|
||||
SearchBox = mod.default
|
||||
})
|
||||
|
||||
it('should expose a labeled search box and forward the edited query', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mockOnChange = vi.fn()
|
||||
const TestSearchBox = () => {
|
||||
const [query, setQuery] = useState('test query')
|
||||
|
||||
return (
|
||||
<SearchBox
|
||||
searchQuery={query}
|
||||
onChange={(nextQuery) => {
|
||||
setQuery(nextQuery)
|
||||
mockOnChange(nextQuery)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
render(<TestSearchBox />)
|
||||
|
||||
const searchBox = screen.getByRole('searchbox', { name: 'plugin.search' })
|
||||
expect(searchBox).toHaveAttribute('placeholder', 'plugin.search')
|
||||
expect(searchBox).toHaveValue('test query')
|
||||
|
||||
await user.clear(searchBox)
|
||||
await user.type(searchBox, 'new query')
|
||||
|
||||
expect(mockOnChange).toHaveBeenCalledWith('new query')
|
||||
})
|
||||
})
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import TagFilter from '../tag-filter'
|
||||
|
||||
vi.mock('../../../hooks', () => ({
|
||||
useTags: () => ({
|
||||
tags: [
|
||||
{ name: 'agent', label: 'Agent' },
|
||||
{ name: 'rag', label: 'RAG' },
|
||||
{ name: 'search', label: 'Search' },
|
||||
],
|
||||
getTagLabel: (name: string) =>
|
||||
({
|
||||
agent: 'Agent',
|
||||
rag: 'RAG',
|
||||
search: 'Search',
|
||||
})[name] ?? name,
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('TagFilter', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders selected tag labels and the overflow counter', () => {
|
||||
render(<TagFilter value={['agent', 'rag', 'search']} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('Agent,RAG')).toBeInTheDocument()
|
||||
expect(screen.getByText('+1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('filters options by search text and toggles tag selection', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<TagFilter value={['agent']} onChange={onChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Agent' }))
|
||||
const portal = await screen.findByRole('dialog')
|
||||
|
||||
await user.type(screen.getByPlaceholderText('pluginTags.searchTags'), 'ra')
|
||||
|
||||
expect(within(portal).queryByText('Agent')).not.toBeInTheDocument()
|
||||
expect(within(portal).getByText('RAG')).toBeInTheDocument()
|
||||
|
||||
await user.click(within(portal).getByText('RAG'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['agent', 'rag'])
|
||||
})
|
||||
|
||||
it('clears selected tags through a separate keyboard control and restores focus', async () => {
|
||||
const user = userEvent.setup()
|
||||
function Harness() {
|
||||
const [tags, setTags] = useState(['agent'])
|
||||
return <TagFilter value={tags} onChange={setTags} />
|
||||
}
|
||||
|
||||
render(<Harness />)
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Agent' })
|
||||
const clearButton = screen.getByRole('button', {
|
||||
name: /^pluginTags\.clearSelectedTags/,
|
||||
})
|
||||
expect(trigger).not.toContainElement(clearButton)
|
||||
|
||||
await user.tab()
|
||||
expect(trigger).toHaveFocus()
|
||||
await user.tab()
|
||||
expect(clearButton).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /^pluginTags\.clearSelectedTags/ }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'common.tag.tags' })).toHaveFocus()
|
||||
})
|
||||
|
||||
it('removes a selected tag when clicking the same option again', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<TagFilter value={['agent']} onChange={onChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Agent' }))
|
||||
await user.click(within(await screen.findByRole('dialog')).getByText('Agent'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith([])
|
||||
})
|
||||
})
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Checkbox } from '@langgenius/dify-ui/checkbox'
|
||||
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { RiArrowDownSLine, RiCloseCircleFill } from '@remixicon/react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useCategories } from '../../hooks'
|
||||
|
||||
type CategoriesFilterProps = {
|
||||
value: string[]
|
||||
onChange: (categories: string[]) => void
|
||||
}
|
||||
const CategoriesFilter = ({ value, onChange }: CategoriesFilterProps) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const searchLabel = t(($) => $.searchCategories, { ns: 'plugin' })
|
||||
const { categories: options, categoriesMap } = useCategories()
|
||||
const filteredOptions = options.filter((option) =>
|
||||
option.name.toLowerCase().includes(searchText.toLowerCase()),
|
||||
)
|
||||
const selectedTagsLength = value.length
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const shouldRestoreFocusRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedTagsLength || !shouldRestoreFocusRef.current) return
|
||||
|
||||
shouldRestoreFocusRef.current = false
|
||||
triggerRef.current?.focus()
|
||||
}, [selectedTagsLength])
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<div className="relative inline-flex h-8 items-center">
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
variant="ghost"
|
||||
size="medium"
|
||||
className={cn(
|
||||
'h-8 rounded-lg bg-components-input-bg-normal px-2 py-1 text-text-tertiary hover:bg-state-base-hover-alt focus-visible:ring-inset',
|
||||
selectedTagsLength && 'pr-8 text-text-secondary',
|
||||
'data-popup-open:bg-state-base-hover',
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center p-1 system-sm-medium">
|
||||
{!selectedTagsLength && t(($) => $.allCategories, { ns: 'plugin' })}
|
||||
{!!selectedTagsLength &&
|
||||
value
|
||||
.map((val) => categoriesMap[val]!.label)
|
||||
.slice(0, 2)
|
||||
.join(',')}
|
||||
{selectedTagsLength > 2 && (
|
||||
<span className="ml-1 system-xs-medium text-text-tertiary">
|
||||
+{selectedTagsLength - 2}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{!selectedTagsLength && <RiArrowDownSLine aria-hidden="true" className="size-4" />}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{!!selectedTagsLength && (
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="md"
|
||||
aria-label={t(($) => $.clearSearch, {
|
||||
ns: 'plugin',
|
||||
label: t(($) => $.allCategories, { ns: 'plugin' }),
|
||||
})}
|
||||
className="absolute right-1 focus-visible:ring-inset"
|
||||
onClick={() => {
|
||||
shouldRestoreFocusRef.current = true
|
||||
onChange([])
|
||||
}}
|
||||
>
|
||||
<RiCloseCircleFill aria-hidden="true" className="size-4 text-text-quaternary" />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
className="border-none bg-transparent shadow-none"
|
||||
>
|
||||
<div className="w-60 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-xs">
|
||||
<div className="p-2 pb-1">
|
||||
<InputGroup>
|
||||
<InputGroupInput
|
||||
type="search"
|
||||
aria-label={searchLabel}
|
||||
autoComplete="off"
|
||||
className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"
|
||||
placeholder={searchLabel}
|
||||
value={searchText}
|
||||
onValueChange={setSearchText}
|
||||
/>
|
||||
<InputGroupAddon className="ps-2 pe-0.5">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="i-ri-search-line size-4 text-components-input-text-placeholder"
|
||||
/>
|
||||
</InputGroupAddon>
|
||||
</InputGroup>
|
||||
</div>
|
||||
<CheckboxGroup
|
||||
aria-label={t(($) => $.allCategories, { ns: 'plugin' })}
|
||||
value={value}
|
||||
onValueChange={(nextValue) => onChange(nextValue)}
|
||||
className="max-h-112 overflow-y-auto p-1"
|
||||
>
|
||||
{filteredOptions.map((option) => (
|
||||
<label
|
||||
key={option.name}
|
||||
className="flex h-7 cursor-pointer items-center rounded-lg px-2 py-1.5 hover:bg-state-base-hover"
|
||||
>
|
||||
<Checkbox className="mr-1" value={option.name} />
|
||||
<div className="px-1 system-sm-medium text-text-secondary">{option.label}</div>
|
||||
</label>
|
||||
))}
|
||||
</CheckboxGroup>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default CategoriesFilter
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { useState } from 'react'
|
||||
import { usePluginPageContext } from '../context'
|
||||
import CategoriesFilter from './category-filter'
|
||||
import SearchBox from './search-box'
|
||||
import TagFilter from './tag-filter'
|
||||
|
||||
export type FilterState = {
|
||||
categories: string[]
|
||||
tags: string[]
|
||||
searchQuery: string
|
||||
}
|
||||
|
||||
type FilterManagementProps = {
|
||||
hideCategoryFilter?: boolean
|
||||
hideTagFilter?: boolean
|
||||
onFilterChange: (filters: FilterState) => void
|
||||
rightSlot?: ReactNode
|
||||
}
|
||||
|
||||
const FilterManagement = ({
|
||||
hideCategoryFilter,
|
||||
hideTagFilter,
|
||||
onFilterChange,
|
||||
rightSlot,
|
||||
}: FilterManagementProps) => {
|
||||
const initFilters = usePluginPageContext((v) => v.filters) as FilterState
|
||||
const [filters, setFilters] = useState<FilterState>(initFilters)
|
||||
const showRightSlot = rightSlot !== undefined && rightSlot !== null
|
||||
|
||||
const updateFilters = (newFilters: Partial<FilterState>) => {
|
||||
const updatedFilters = { ...filters, ...newFilters }
|
||||
setFilters(updatedFilters)
|
||||
onFilterChange(updatedFilters)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full items-center gap-2 self-stretch">
|
||||
{!hideCategoryFilter && (
|
||||
<CategoriesFilter
|
||||
value={filters.categories}
|
||||
onChange={(categories) => updateFilters({ categories })}
|
||||
/>
|
||||
)}
|
||||
{!hideTagFilter && (
|
||||
<TagFilter value={filters.tags} onChange={(tags) => updateFilters({ tags })} />
|
||||
)}
|
||||
<SearchBox
|
||||
searchQuery={filters.searchQuery}
|
||||
onChange={(searchQuery) => updateFilters({ searchQuery })}
|
||||
/>
|
||||
{showRightSlot && <div className="ml-auto shrink-0">{rightSlot}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FilterManagement
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
'use client'
|
||||
|
||||
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type SearchBoxProps = {
|
||||
searchQuery: string
|
||||
onChange: (query: string) => void
|
||||
}
|
||||
|
||||
const SearchBox: React.FC<SearchBoxProps> = ({ searchQuery, onChange }) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const searchLabel = t(($) => $.search, { ns: 'plugin' })
|
||||
|
||||
return (
|
||||
<InputGroup className="w-50">
|
||||
<InputGroupInput
|
||||
type="search"
|
||||
aria-label={searchLabel}
|
||||
autoComplete="off"
|
||||
className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"
|
||||
placeholder={searchLabel}
|
||||
value={searchQuery}
|
||||
onValueChange={onChange}
|
||||
/>
|
||||
<InputGroupAddon className="ps-2 pe-0.5">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="i-ri-search-line size-4 text-components-input-text-placeholder"
|
||||
/>
|
||||
</InputGroupAddon>
|
||||
</InputGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export default SearchBox
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Checkbox } from '@langgenius/dify-ui/checkbox'
|
||||
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { SearchInput } from '@/app/components/base/search-input'
|
||||
import { useTags } from '../../hooks'
|
||||
|
||||
type TagsFilterProps = {
|
||||
value: string[]
|
||||
onChange: (tags: string[]) => void
|
||||
}
|
||||
const TagsFilter = ({ value, onChange }: TagsFilterProps) => {
|
||||
const { t } = useTranslation(['common', 'pluginTags'])
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const { tags: options, getTagLabel } = useTags()
|
||||
const filteredOptions = options.filter((option) =>
|
||||
option.name.toLowerCase().includes(searchText.toLowerCase()),
|
||||
)
|
||||
const selectedTagsLength = value.length
|
||||
const selectedTagLabels = value.map((tag) => getTagLabel(tag))
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const shouldRestoreFocusRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedTagsLength || !shouldRestoreFocusRef.current) return
|
||||
|
||||
shouldRestoreFocusRef.current = false
|
||||
triggerRef.current?.focus()
|
||||
}, [selectedTagsLength])
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<div className="relative inline-flex h-8 items-center">
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
variant="ghost"
|
||||
size="medium"
|
||||
className={cn(
|
||||
'h-8 rounded-lg bg-components-input-bg-normal px-2 py-1 text-text-tertiary select-none hover:bg-state-base-hover-alt focus-visible:ring-inset',
|
||||
selectedTagsLength && 'pr-8 text-text-secondary',
|
||||
'data-popup-open:bg-state-base-hover',
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center p-1 system-sm-medium">
|
||||
{!selectedTagsLength && t(($) => $['tag.tags'], { ns: 'common' })}
|
||||
{!!selectedTagsLength && selectedTagLabels.slice(0, 2).join(',')}
|
||||
{selectedTagsLength > 2 && (
|
||||
<span className="ml-1 system-xs-medium text-text-tertiary">
|
||||
+{selectedTagsLength - 2}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{!selectedTagsLength && (
|
||||
<span aria-hidden className="i-ri-arrow-down-s-line size-4" />
|
||||
)}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{!!selectedTagsLength && (
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="md"
|
||||
aria-label={t(($) => $.clearSelectedTags, {
|
||||
ns: 'pluginTags',
|
||||
tags: selectedTagLabels.join(', '),
|
||||
})}
|
||||
className="absolute right-1 focus-visible:ring-inset"
|
||||
onClick={() => {
|
||||
shouldRestoreFocusRef.current = true
|
||||
onChange([])
|
||||
}}
|
||||
>
|
||||
<span aria-hidden className="i-ri-close-circle-fill size-4 text-text-quaternary" />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
className="border-none bg-transparent shadow-none"
|
||||
>
|
||||
<div className="w-60 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-xs">
|
||||
<div className="p-2 pb-1">
|
||||
<SearchInput
|
||||
value={searchText}
|
||||
onValueChange={setSearchText}
|
||||
placeholder={t(($) => $.searchTags, { ns: 'pluginTags' })}
|
||||
/>
|
||||
</div>
|
||||
<CheckboxGroup
|
||||
aria-label={t(($) => $.allTags, { ns: 'pluginTags' })}
|
||||
value={value}
|
||||
onValueChange={(nextValue) => onChange(nextValue)}
|
||||
className="max-h-112 overflow-y-auto p-1"
|
||||
>
|
||||
{filteredOptions.map((option) => (
|
||||
<label
|
||||
key={option.name}
|
||||
className="flex h-7 cursor-pointer items-center rounded-lg px-2 py-1.5 select-none hover:bg-state-base-hover"
|
||||
>
|
||||
<Checkbox className="mr-1" value={option.name} />
|
||||
<div className="px-1 system-sm-medium text-text-secondary">{option.label}</div>
|
||||
</label>
|
||||
))}
|
||||
</CheckboxGroup>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default TagsFilter
|
||||
@@ -0,0 +1,212 @@
|
||||
'use client'
|
||||
|
||||
import type { ButtonProps } from '@langgenius/dify-ui/button'
|
||||
import type { PluginCategoryEnum } from '@/app/components/plugins/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Menu,
|
||||
MenuContent,
|
||||
MenuGroup,
|
||||
MenuGroupLabel,
|
||||
MenuItem,
|
||||
MenuTrigger,
|
||||
} from '@langgenius/dify-ui/menu'
|
||||
import { RiAddCircleFill, RiArrowDownSLine } from '@remixicon/react'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { noop } from 'es-toolkit/function'
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
|
||||
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
|
||||
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
|
||||
import { useMarketplace } from '@/features/marketplace/client'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
import {
|
||||
GithubInstallSourceIcon,
|
||||
LocalPackageInstallSourceIcon,
|
||||
MarketplaceInstallSourceIcon,
|
||||
} from './install-source-icons'
|
||||
|
||||
type Props = Readonly<{
|
||||
disabled?: boolean
|
||||
onSwitchToMarketplaceTab: () => void
|
||||
popupClassName?: string
|
||||
rootClassName?: string
|
||||
triggerClassName?: string
|
||||
triggerLabel?: string
|
||||
triggerVariant?: ButtonProps['variant']
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
showTriggerArrow?: boolean
|
||||
}>
|
||||
|
||||
type InstallMethod = {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
text: string
|
||||
action: string
|
||||
}
|
||||
|
||||
const InstallPluginMenu = ({
|
||||
disabled = false,
|
||||
onSwitchToMarketplaceTab,
|
||||
popupClassName,
|
||||
rootClassName,
|
||||
triggerClassName,
|
||||
triggerLabel,
|
||||
triggerVariant,
|
||||
installContextCategory,
|
||||
showTriggerArrow = true,
|
||||
}: Props) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false)
|
||||
const [selectedAction, setSelectedAction] = useState<string | null>(null)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const buttonLabel = triggerLabel ?? t(($) => $.installPlugin, { ns: 'plugin' })
|
||||
const enable_marketplace = useMarketplace() !== null
|
||||
const { data: plugin_installation_permission } = useSuspenseQuery({
|
||||
...systemFeaturesQueryOptions(),
|
||||
select: (s) => s.plugin_installation_permission,
|
||||
})
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0] ?? null
|
||||
event.target.value = ''
|
||||
if (disabled) return
|
||||
|
||||
if (file) {
|
||||
setSelectedFile(file)
|
||||
setSelectedAction('local')
|
||||
setIsMenuOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseLocalInstaller = () => {
|
||||
setSelectedAction(null)
|
||||
setSelectedFile(null)
|
||||
if (fileInputRef.current) fileInputRef.current.value = ''
|
||||
}
|
||||
|
||||
// TODO TEST INSTALL : uninstall
|
||||
// const [pluginLists, setPluginLists] = useState<any>([])
|
||||
// useEffect(() => {
|
||||
// (async () => {
|
||||
// const list: any = await get('workspaces/current/plugin/list')
|
||||
// })()
|
||||
// })
|
||||
|
||||
// const handleUninstall = async (id: string) => {
|
||||
// const res = await post('workspaces/current/plugin/uninstall', { body: { plugin_installation_id: id } })
|
||||
// console.log(res)
|
||||
// }
|
||||
|
||||
const installMethods = useMemo<InstallMethod[]>(() => {
|
||||
const methods: InstallMethod[] = []
|
||||
if (enable_marketplace)
|
||||
methods.push({
|
||||
icon: MarketplaceInstallSourceIcon,
|
||||
text: t(($) => $['source.marketplace'], { ns: 'plugin' }),
|
||||
action: 'marketplace',
|
||||
})
|
||||
|
||||
if (plugin_installation_permission.restrict_to_marketplace_only) return methods
|
||||
|
||||
methods.push({
|
||||
icon: GithubInstallSourceIcon,
|
||||
text: t(($) => $['source.github'], { ns: 'plugin' }),
|
||||
action: 'github',
|
||||
})
|
||||
methods.push({
|
||||
icon: LocalPackageInstallSourceIcon,
|
||||
text: t(($) => $['source.local'], { ns: 'plugin' }),
|
||||
action: 'local',
|
||||
})
|
||||
return methods
|
||||
}, [plugin_installation_permission, enable_marketplace, t])
|
||||
|
||||
const handleInstallMethodSelect = (action: string) => {
|
||||
if (disabled) return
|
||||
|
||||
if (action === 'local') {
|
||||
fileInputRef.current?.click()
|
||||
return
|
||||
}
|
||||
|
||||
if (action === 'marketplace') {
|
||||
onSwitchToMarketplaceTab()
|
||||
return
|
||||
}
|
||||
|
||||
queueMicrotask(() => {
|
||||
setSelectedAction(action)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={!disabled && isMenuOpen}
|
||||
onOpenChange={(open) => setIsMenuOpen(disabled ? false : open)}
|
||||
modal={false}
|
||||
>
|
||||
<div className={cn('relative', rootClassName)}>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
disabled={disabled}
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileChange}
|
||||
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
|
||||
/>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
variant={triggerVariant}
|
||||
disabled={disabled}
|
||||
title={buttonLabel}
|
||||
className={cn('size-full p-2 data-popup-open:bg-state-base-hover', triggerClassName)}
|
||||
>
|
||||
<RiAddCircleFill className="size-4 shrink-0" />
|
||||
<span className={cn(!showTriggerArrow && 'min-w-0 flex-1 text-left')}>
|
||||
{buttonLabel}
|
||||
</span>
|
||||
{showTriggerArrow && <RiArrowDownSLine className="size-4" />}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<MenuContent align="start" className={cn('w-50 pb-2', popupClassName)}>
|
||||
<MenuGroup>
|
||||
<MenuGroupLabel>{t(($) => $.installFrom, { ns: 'plugin' })}</MenuGroupLabel>
|
||||
{installMethods.map(({ icon: Icon, text, action }) => (
|
||||
<MenuItem key={action} onClick={() => handleInstallMethodSelect(action)}>
|
||||
<div className="flex items-center gap-1">
|
||||
<Icon className="size-4 text-text-tertiary" />
|
||||
<span className="px-1 system-md-regular text-text-secondary">{text}</span>
|
||||
</div>
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuGroup>
|
||||
</MenuContent>
|
||||
</div>
|
||||
{selectedAction === 'github' && (
|
||||
<InstallFromGitHub
|
||||
installContextCategory={installContextCategory}
|
||||
onSuccess={noop}
|
||||
onClose={() => setSelectedAction(null)}
|
||||
/>
|
||||
)}
|
||||
{selectedAction === 'local' && selectedFile && (
|
||||
<InstallFromLocalPackage
|
||||
file={selectedFile}
|
||||
installContextCategory={installContextCategory}
|
||||
onClose={handleCloseLocalInstaller}
|
||||
onSuccess={noop}
|
||||
/>
|
||||
)}
|
||||
{/* {pluginLists.map((item: any) => (
|
||||
<div key={item.id} onClick={() => handleUninstall(item.id)}>{item.name} 卸载</div>
|
||||
))} */}
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
export default InstallPluginMenu
|
||||
@@ -0,0 +1,11 @@
|
||||
export const MarketplaceInstallSourceIcon = () => (
|
||||
<span aria-hidden className="i-custom-vender-plugin-box-sparkle-fill size-4 shrink-0" />
|
||||
)
|
||||
|
||||
export const GithubInstallSourceIcon = () => (
|
||||
<span aria-hidden className="i-custom-vender-solid-general-github size-4 shrink-0" />
|
||||
)
|
||||
|
||||
export const LocalPackageInstallSourceIcon = () => (
|
||||
<span aria-hidden className="i-custom-vender-solid-files-file-zip size-4 shrink-0" />
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { FC, ReactNode } from 'react'
|
||||
import type { PluginDetail } from '../../types'
|
||||
import PluginItem from '../../plugin-item'
|
||||
|
||||
type IPluginListProps = {
|
||||
canDeletePlugin?: boolean
|
||||
canUpdatePlugin?: boolean
|
||||
children?: ReactNode
|
||||
firstPluginTarget?: string
|
||||
pluginList: PluginDetail[]
|
||||
}
|
||||
|
||||
const PluginList: FC<IPluginListProps> = ({
|
||||
canDeletePlugin = true,
|
||||
canUpdatePlugin = true,
|
||||
children,
|
||||
firstPluginTarget,
|
||||
pluginList,
|
||||
}) => {
|
||||
return (
|
||||
<div className="pb-3">
|
||||
<div className="grid w-full grid-cols-1 gap-3 lg:grid-cols-2">
|
||||
{pluginList.map((plugin, index) => (
|
||||
<div
|
||||
key={plugin.plugin_id}
|
||||
data-step-by-step-tour-target={index === 0 ? firstPluginTarget : undefined}
|
||||
>
|
||||
<PluginItem
|
||||
plugin={plugin}
|
||||
canDeletePlugin={canDeletePlugin}
|
||||
canUpdatePlugin={canUpdatePlugin}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default PluginList
|
||||
@@ -0,0 +1,132 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import type { DocPathWithoutLang } from '@/types/doc-paths'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import {
|
||||
Menu,
|
||||
MenuContent,
|
||||
MenuLinkItem,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from '@langgenius/dify-ui/menu'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { Fragment, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useDocLink } from '@/context/i18n'
|
||||
import { marketplaceLinks } from '@/features/marketplace/links'
|
||||
|
||||
type GuideMenuItemProps = {
|
||||
href: string
|
||||
icon: ReactNode
|
||||
text: string
|
||||
}
|
||||
|
||||
function GuideMenuItem({ href, icon, text }: GuideMenuItemProps) {
|
||||
return (
|
||||
<MenuLinkItem
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="gap-2 rounded-lg px-3 py-2"
|
||||
>
|
||||
{icon}
|
||||
<span className="system-sm-medium text-text-secondary">{text}</span>
|
||||
<span className="ml-auto i-ri-arrow-right-up-line size-4 shrink-0 text-text-tertiary" />
|
||||
</MenuLinkItem>
|
||||
)
|
||||
}
|
||||
|
||||
type OptionLabelKey =
|
||||
| 'requestAPlugin'
|
||||
| 'pluginDevelopmentGuide'
|
||||
| 'pluginPublishGuide'
|
||||
| 'templatePublishingGuide'
|
||||
|
||||
function getOptions(docLink: (path: DocPathWithoutLang) => string): {
|
||||
href: string
|
||||
icon: ReactNode
|
||||
labelKey: OptionLabelKey
|
||||
}[] {
|
||||
return [
|
||||
{
|
||||
href: 'https://github.com/langgenius/dify-plugins/issues/new?template=plugin_request.yaml',
|
||||
icon: <span className="i-ri-plug-line size-4 shrink-0 text-text-tertiary" />,
|
||||
labelKey: 'requestAPlugin',
|
||||
},
|
||||
{
|
||||
href: docLink('/develop-plugin/getting-started/getting-started-dify-plugin'),
|
||||
icon: <span className="i-ri-book-open-line size-4 shrink-0 text-text-tertiary" />,
|
||||
labelKey: 'pluginDevelopmentGuide',
|
||||
},
|
||||
{
|
||||
href: docLink('/develop-plugin/publishing/marketplace-listing/release-overview'),
|
||||
icon: <span className="i-ri-book-open-line size-4 shrink-0 text-text-tertiary" />,
|
||||
labelKey: 'pluginPublishGuide',
|
||||
},
|
||||
{
|
||||
href: marketplaceLinks.creatorCenter,
|
||||
icon: <span className="i-ri-book-open-line size-4 shrink-0 text-text-tertiary" />,
|
||||
labelKey: 'templatePublishingGuide',
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
type SubmitRequestMenuProps = {
|
||||
dividerAfterFirst?: boolean
|
||||
}
|
||||
|
||||
type SubmitRequestMenuViewProps = SubmitRequestMenuProps & {
|
||||
docLink: (path: DocPathWithoutLang) => string
|
||||
}
|
||||
|
||||
// Presentational menu. Callers that cannot use useDocLink() -- standalone
|
||||
// Marketplace SSR -- pass a locale-composed docLink instead.
|
||||
export function SubmitRequestMenuView({ dividerAfterFirst, docLink }: SubmitRequestMenuViewProps) {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const [open, setOpen] = useState(false)
|
||||
const options = getOptions(docLink)
|
||||
const guideLabel = t(($) => $['marketplace.home.guide'], { ns: 'plugin' })
|
||||
|
||||
return (
|
||||
<Menu open={open} onOpenChange={setOpen}>
|
||||
<Tooltip disabled={open}>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<IconButton
|
||||
aria-label={guideLabel}
|
||||
size="lg"
|
||||
className="data-popup-open:bg-state-base-hover data-popup-open:text-text-secondary"
|
||||
>
|
||||
<span aria-hidden className="i-ri-book-open-line size-4 shrink-0" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<TooltipContent side="bottom" role="tooltip">
|
||||
{guideLabel}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<MenuContent className="min-w-50">
|
||||
{options.map((option, index) => (
|
||||
<Fragment key={option.href}>
|
||||
{dividerAfterFirst && index === 1 && <MenuSeparator className="my-1" />}
|
||||
<GuideMenuItem
|
||||
href={option.href}
|
||||
icon={option.icon}
|
||||
text={t(($) => $[option.labelKey], { ns: 'plugin' })}
|
||||
/>
|
||||
</Fragment>
|
||||
))}
|
||||
</MenuContent>
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
export function SubmitRequestMenu({ dividerAfterFirst }: SubmitRequestMenuProps) {
|
||||
const docLink = useDocLink()
|
||||
return <SubmitRequestMenuView dividerAfterFirst={dividerAfterFirst} docLink={docLink} />
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import {
|
||||
DialogBody,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import KeyValueItem from '../base/key-value-item'
|
||||
import { convertRepoToUrl } from '../install-plugin/utils'
|
||||
|
||||
const i18nPrefix = 'pluginInfoModal'
|
||||
type Props = Readonly<{
|
||||
repository?: string
|
||||
release?: string
|
||||
packageName?: string
|
||||
}>
|
||||
|
||||
const PluginInfoContent: FC<Props> = ({ repository, release, packageName }) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const labelWidthClassName = 'w-[96px]'
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })}</DialogTitle>
|
||||
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
|
||||
</DialogHeader>
|
||||
<DialogBody className="space-y-3">
|
||||
{repository && (
|
||||
<KeyValueItem
|
||||
label={t(($) => $[`${i18nPrefix}.repository`], { ns: 'plugin' })}
|
||||
labelWidthClassName={labelWidthClassName}
|
||||
value={`${convertRepoToUrl(repository)}`}
|
||||
valueMaxWidthClassName="max-w-[190px]"
|
||||
/>
|
||||
)}
|
||||
{release && (
|
||||
<KeyValueItem
|
||||
label={t(($) => $[`${i18nPrefix}.release`], { ns: 'plugin' })}
|
||||
labelWidthClassName={labelWidthClassName}
|
||||
value={release}
|
||||
/>
|
||||
)}
|
||||
{packageName && (
|
||||
<KeyValueItem
|
||||
label={t(($) => $[`${i18nPrefix}.packageName`], { ns: 'plugin' })}
|
||||
labelWidthClassName={labelWidthClassName}
|
||||
value={packageName}
|
||||
/>
|
||||
)}
|
||||
</DialogBody>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default React.memo(PluginInfoContent)
|
||||
@@ -0,0 +1,54 @@
|
||||
'use client'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { SkeletonContainer, SkeletonPoint, SkeletonRectangle } from '@/app/components/base/skeleton'
|
||||
|
||||
const PluginCardSkeleton = () => (
|
||||
<div
|
||||
data-testid="plugin-card-skeleton"
|
||||
className="relative overflow-hidden rounded-xl border-[1.5px] border-background-section-burn bg-background-section-burn p-1"
|
||||
>
|
||||
<div className="relative rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-4 pb-3 shadow-xs">
|
||||
<div className="flex">
|
||||
<SkeletonRectangle className="size-10 shrink-0 animate-pulse rounded-xl" />
|
||||
<div className="ml-3 w-0 grow">
|
||||
<div className="flex h-5 items-center">
|
||||
<SkeletonRectangle className="h-4 w-2/5 animate-pulse" />
|
||||
</div>
|
||||
<SkeletonContainer className="mt-0.5 h-4 gap-0">
|
||||
<SkeletonRectangle className="h-3 w-4/5 animate-pulse" />
|
||||
</SkeletonContainer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-1.5 mb-1 flex h-4 items-center gap-x-2 px-4">
|
||||
<SkeletonRectangle className="h-3 w-20 animate-pulse" />
|
||||
<SkeletonPoint />
|
||||
<SkeletonRectangle className="h-3 w-24 animate-pulse" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
type PluginListSkeletonProps = {
|
||||
contentFrameClassName: string
|
||||
}
|
||||
|
||||
const PluginListSkeleton = ({ contentFrameClassName }: PluginListSkeletonProps) => {
|
||||
const { t } = useTranslation(['common'])
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-label={t(($) => $.loading, { ns: 'common' })}
|
||||
className={cn('min-h-0 grow self-stretch bg-components-panel-bg', contentFrameClassName)}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-3 pb-3 lg:grid-cols-2">
|
||||
{Array.from({ length: 6 }, (_, index) => (
|
||||
<PluginCardSkeleton key={index} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginListSkeleton
|
||||
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { PopoverClose, PopoverTitle } from '@langgenius/dify-ui/popover'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type PluginSidecarPanelProps = {
|
||||
children: ReactNode
|
||||
footer?: ReactNode
|
||||
title: ReactNode
|
||||
}
|
||||
|
||||
export function PluginSidecarPanel({ children, footer, title }: PluginSidecarPanelProps) {
|
||||
const { t } = useTranslation(['common'])
|
||||
|
||||
return (
|
||||
<div className="flex w-90 flex-col items-start overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl shadow-shadow-shadow-9">
|
||||
<div className="relative flex w-full shrink-0 flex-col gap-0.5 px-3 pt-3.5 pb-1">
|
||||
<div className="flex w-full shrink-0 items-start">
|
||||
<div className="flex min-w-0 flex-1 flex-col items-start pr-8 pl-1">
|
||||
<PopoverTitle className="w-full system-xl-semibold text-text-primary">
|
||||
{title}
|
||||
</PopoverTitle>
|
||||
</div>
|
||||
</div>
|
||||
<PopoverClose
|
||||
render={
|
||||
<IconButton
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
size="lg"
|
||||
className="absolute top-2.5 right-2.5"
|
||||
>
|
||||
<span aria-hidden className="i-ri-close-line size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{children}
|
||||
{footer}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
import type { PluginStatus, PluginTask } from '@/app/components/plugins/types'
|
||||
import { act, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { PermissionType, PluginSource, TaskStatus } from '@/app/components/plugins/types'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import PluginTasks from '../index'
|
||||
|
||||
const requests = vi.hoisted(() => ({ list: vi.fn(), clear: vi.fn(), refresh: vi.fn() }))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.tasks.get': requests.list,
|
||||
'workspaces.current.plugin.tasks.byTaskId.delete.byIdentifier.post': requests.clear,
|
||||
'workspaces.current.plugin.permission.fetch.get': async () => ({
|
||||
install_permission: PermissionType.everyone,
|
||||
debug_permission: PermissionType.everyone,
|
||||
}),
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Refreshing unrelated catalogs has its own service tests.
|
||||
vi.mock('@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: requests.refresh }),
|
||||
}))
|
||||
|
||||
const plugin = (name: string, status: TaskStatus, message = ''): PluginStatus => ({
|
||||
plugin_unique_identifier: `test/${name}:1.0.0`,
|
||||
plugin_id: `test/${name}`,
|
||||
source: PluginSource.marketplace,
|
||||
status,
|
||||
message,
|
||||
icon: 'test-icon.png',
|
||||
labels: { en_US: name },
|
||||
taskId: 'task-1',
|
||||
})
|
||||
let tasks: PluginTask[]
|
||||
const task = (plugins: PluginStatus[], id = 'task-1'): PluginTask => ({
|
||||
id,
|
||||
plugins,
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
status: plugins.some((p) => p.status === TaskStatus.running || p.status === TaskStatus.pending)
|
||||
? TaskStatus.running
|
||||
: plugins.some((p) => p.status === TaskStatus.failed)
|
||||
? TaskStatus.failed
|
||||
: TaskStatus.success,
|
||||
total_plugins: plugins.length,
|
||||
completed_plugins: plugins.filter((p) => p.status === TaskStatus.success).length,
|
||||
})
|
||||
const render = () =>
|
||||
renderWithConsoleQuery(<PluginTasks />, { workspacePermissionKeys: ['plugin.install'] })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
tasks = []
|
||||
requests.list.mockImplementation(async () => ({ tasks }))
|
||||
requests.clear.mockImplementation(
|
||||
async ({ params }: { params: { task_id: string; identifier: string } }) => {
|
||||
tasks = tasks
|
||||
.map((t) =>
|
||||
t.id === params.task_id
|
||||
? task(
|
||||
t.plugins.filter((p) => p.plugin_unique_identifier !== params.identifier),
|
||||
t.id,
|
||||
)
|
||||
: t,
|
||||
)
|
||||
.filter((t) => t.plugins.length > 0)
|
||||
return {}
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('plugin installation tasks', () => {
|
||||
it('hides the task trigger after an empty server response', async () => {
|
||||
const { queryClient } = render()
|
||||
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
|
||||
expect(requests.list).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ statuses: [TaskStatus.pending, TaskStatus.running], tip: 'installing', badge: null },
|
||||
{
|
||||
statuses: [TaskStatus.running, TaskStatus.success],
|
||||
tip: 'installingWithSuccess',
|
||||
badge: null,
|
||||
},
|
||||
{
|
||||
statuses: [TaskStatus.running, TaskStatus.failed],
|
||||
tip: 'installingWithError',
|
||||
badge: 'error',
|
||||
},
|
||||
{ statuses: [TaskStatus.success], tip: 'installSuccess', badge: 'success' },
|
||||
{ statuses: [TaskStatus.success, TaskStatus.failed], tip: 'installedError', badge: 'error' },
|
||||
])('announces $tip and opens the actual task list', async ({ statuses, tip, badge }) => {
|
||||
const user = userEvent.setup()
|
||||
tasks = [task(statuses.map((status, index) => plugin(`Plugin ${index}`, status)))]
|
||||
render()
|
||||
const trigger = await screen.findByRole('button', {
|
||||
name: new RegExp(`^plugin\\.task\\.${tip}(?::|$)`),
|
||||
})
|
||||
if (badge) expect(screen.getByTestId(`task-status-${badge}-badge`)).toBeInTheDocument()
|
||||
else {
|
||||
expect(screen.queryByTestId('task-status-success-badge')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('task-status-error-badge')).not.toBeInTheDocument()
|
||||
}
|
||||
await user.click(trigger)
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'true')
|
||||
for (const [index] of statuses.entries())
|
||||
expect(await screen.findByText(`Plugin ${index}`)).toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'false'))
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ status: TaskStatus.success, tip: 'installSuccess', message: 'plugin.task.installed' },
|
||||
{ status: TaskStatus.failed, tip: 'installedError', message: 'Network error' },
|
||||
])(
|
||||
'updates an open task list when installation ends with $status',
|
||||
async ({ status, tip, message }) => {
|
||||
const user = userEvent.setup()
|
||||
tasks = [task([plugin('Search plugin', TaskStatus.running, 'Downloading package')])]
|
||||
const { queryClient } = render()
|
||||
await user.click(await screen.findByRole('button', { name: 'plugin.task.installing' }))
|
||||
expect(await screen.findByText('Downloading package')).toBeInTheDocument()
|
||||
tasks = [task([plugin('Search plugin', status, status === TaskStatus.failed ? message : '')])]
|
||||
await act(async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['plugins', 'pluginTaskList'] })
|
||||
})
|
||||
expect(
|
||||
await screen.findByRole('button', { name: new RegExp(`^plugin\\.task\\.${tip}(?::|$)`) }),
|
||||
).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(screen.getByText(message)).toBeInTheDocument()
|
||||
expect(screen.queryByText('Downloading package')).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it('clears only failed plugins across tasks and keeps running and successful entries visible', async () => {
|
||||
const user = userEvent.setup()
|
||||
tasks = [
|
||||
task([
|
||||
plugin('Running', TaskStatus.running),
|
||||
plugin('Installed', TaskStatus.success),
|
||||
plugin('Failed A', TaskStatus.failed, 'Error A'),
|
||||
]),
|
||||
task(
|
||||
[plugin('Pending', TaskStatus.pending), plugin('Failed B', TaskStatus.failed, 'Error B')],
|
||||
'task-2',
|
||||
),
|
||||
]
|
||||
render()
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: /^plugin\.task\.installingWithError(?::|$)/ }),
|
||||
)
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'plugin.task.runningPlugins (2)' }),
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'plugin.task.successPlugins (1)' }),
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'plugin.task.errorPlugins (2)' }),
|
||||
).toBeInTheDocument()
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'plugin.task.errorPlugins plugin.task.clearAll' }),
|
||||
)
|
||||
await waitFor(() => expect(requests.clear).toHaveBeenCalledTimes(2))
|
||||
expect(requests.clear).toHaveBeenCalledWith({
|
||||
params: { task_id: 'task-1', identifier: 'test/Failed A:1.0.0' },
|
||||
})
|
||||
expect(requests.clear).toHaveBeenCalledWith({
|
||||
params: { task_id: 'task-2', identifier: 'test/Failed B:1.0.0' },
|
||||
})
|
||||
await waitFor(() => expect(screen.queryByText('Failed B')).not.toBeInTheDocument())
|
||||
expect(screen.queryByText('Failed A')).not.toBeInTheDocument()
|
||||
for (const name of ['Running', 'Pending', 'Installed'])
|
||||
expect(screen.getByText(name)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears completed successes and failures together and hides the empty menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
tasks = [task([plugin('Installed', TaskStatus.success), plugin('Failed', TaskStatus.failed)])]
|
||||
render()
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: /^plugin\.task\.installedError(?::|$)/ }),
|
||||
)
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'plugin.task.successPlugins plugin.task.clearAll' }),
|
||||
)
|
||||
await waitFor(() => expect(screen.queryByText('Installed')).not.toBeInTheDocument())
|
||||
expect(requests.clear.mock.calls).toEqual([
|
||||
[{ params: { task_id: 'task-1', identifier: 'test/Installed:1.0.0' } }],
|
||||
[{ params: { task_id: 'task-1', identifier: 'test/Failed:1.0.0' } }],
|
||||
])
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /^plugin\.task\.installedError(?::|$)/ }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('waits for an individual clear request before refreshing and closing the last failure', async () => {
|
||||
const user = userEvent.setup()
|
||||
const pending = createDeferred<object>()
|
||||
requests.clear.mockReturnValueOnce(pending.promise)
|
||||
tasks = [task([plugin('Failed', TaskStatus.failed)])]
|
||||
render()
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: /^plugin\.task\.installedError(?::|$)/ }),
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Clear Failed' }))
|
||||
expect(requests.clear).toHaveBeenCalledExactlyOnceWith({
|
||||
params: { task_id: 'task-1', identifier: 'test/Failed:1.0.0' },
|
||||
})
|
||||
expect(requests.list).toHaveBeenCalledOnce()
|
||||
expect(screen.getByText('Failed')).toBeInTheDocument()
|
||||
tasks = []
|
||||
pending.resolve({})
|
||||
await waitFor(() => expect(requests.list).toHaveBeenCalledTimes(2))
|
||||
await waitFor(() => expect(screen.queryByText('Failed')).not.toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
import type { PluginInfoFromMarketPlace } from '@dify/contracts/marketplace'
|
||||
import type { PluginStatus } from '@/app/components/plugins/types'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import {
|
||||
PermissionType,
|
||||
PluginCategoryEnum,
|
||||
PluginSource,
|
||||
TaskStatus,
|
||||
} from '@/app/components/plugins/types'
|
||||
import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
|
||||
import ErrorPluginItem from '../error-plugin-item'
|
||||
|
||||
const { install, refresh } = vi.hoisted(() => ({ install: vi.fn(), refresh: vi.fn() }))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
fetchPluginInfoFromMarketPlace: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: refresh }),
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses, withConsoleClientResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.permission.fetch.get': async () => ({
|
||||
install_permission: PermissionType.everyone,
|
||||
debug_permission: PermissionType.everyone,
|
||||
}),
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
'workspaces.current.plugin.marketplace.pkg.get': async () => ({
|
||||
manifest: createPluginDeclarationFixture(),
|
||||
}),
|
||||
'workspaces.current.plugin.install.marketplace.post': install,
|
||||
}),
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': async () => ({ plugins: [] }),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock(
|
||||
'@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission',
|
||||
() => ({
|
||||
default: () => ({
|
||||
canInstallPlugin: true,
|
||||
currentDifyVersion: '1.0.0',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
const mockFetch = vi.mocked(fetchPluginInfoFromMarketPlace)
|
||||
const mockGetIconUrl = vi.fn((icon: string) => `https://icons/${icon}`)
|
||||
|
||||
function createMarketplaceResponse(identifier: string, version: string) {
|
||||
return {
|
||||
data: {
|
||||
plugin: {
|
||||
category: PluginCategoryEnum.tool,
|
||||
latest_package_identifier: identifier,
|
||||
latest_version: version,
|
||||
} satisfies PluginInfoFromMarketPlace,
|
||||
version: { version },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const createPlugin = (overrides: Partial<PluginStatus> = {}): PluginStatus => ({
|
||||
plugin_unique_identifier: 'org/plugin:1.0.0',
|
||||
plugin_id: 'org/plugin',
|
||||
source: PluginSource.marketplace,
|
||||
status: TaskStatus.failed,
|
||||
message: '',
|
||||
icon: 'icon.png',
|
||||
labels: { en_US: 'Test Plugin' } as PluginStatus['labels'],
|
||||
taskId: 'task-1',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('ErrorPluginItem', () => {
|
||||
const renderError = (overrides: Partial<PluginStatus> = {}) => {
|
||||
const onClear = vi.fn()
|
||||
renderWithConsoleQuery(
|
||||
<ErrorPluginItem
|
||||
plugin={createPlugin(overrides)}
|
||||
getIconUrl={mockGetIconUrl}
|
||||
language="en_US"
|
||||
onClear={onClear}
|
||||
/>,
|
||||
{ systemFeatures: { enable_marketplace: true } },
|
||||
)
|
||||
return { onClear }
|
||||
}
|
||||
const retry = () => screen.getByRole('button', { name: 'plugin.task.installFromMarketplace' })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockFetch.mockResolvedValue(createMarketplaceResponse('org/plugin:2.0.0', '2.0.0'))
|
||||
install.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
[PluginSource.marketplace, 'org/plugin', 'marketplace', 'plugin.task.installFromMarketplace'],
|
||||
[PluginSource.github, 'org/plugin', 'github', 'plugin.task.installFromGithub'],
|
||||
[
|
||||
PluginSource.github,
|
||||
'https://github.com/user/repo',
|
||||
'github',
|
||||
'plugin.task.installFromGithub',
|
||||
],
|
||||
[PluginSource.local, 'my-github-plugin', 'unknown', null],
|
||||
[PluginSource.debugging, 'remote-plugin', 'unknown', null],
|
||||
] as const)(
|
||||
'derives the error and retry action from %s, not the id %s',
|
||||
(source, plugin_id, message, action) => {
|
||||
renderError({ source, plugin_id })
|
||||
expect(screen.getByText('Test Plugin')).toBeInTheDocument()
|
||||
expect(screen.getByText(`plugin.task.errorMsg.${message}`)).toBeInTheDocument()
|
||||
if (action) expect(screen.getByRole('button', { name: action })).toBeInTheDocument()
|
||||
else
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /plugin.task.installFrom/ }),
|
||||
).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it('shows the server error and lets the user clear the failed task', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onClear } = renderError({ message: 'Custom error occurred' })
|
||||
expect(screen.getByText('Custom error occurred')).toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.task.errorMsg.marketplace')).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Clear Test Plugin' }))
|
||||
expect(onClear).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('opens the latest marketplace version and cancels without clearing the error', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onClear } = renderError()
|
||||
await user.click(retry())
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
|
||||
expect(mockFetch).toHaveBeenCalledExactlyOnceWith({ org: 'org', name: 'plugin' })
|
||||
expect(screen.getByText('2.0.0')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(onClear).not.toHaveBeenCalled()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('installs the latest version before clearing the completed error item', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onClear } = renderError()
|
||||
await user.click(retry())
|
||||
await user.click(await screen.findByRole('button', { name: 'plugin.installModal.install' }))
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['org/plugin:2.0.0'] },
|
||||
})
|
||||
expect(onClear).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByText('common.operation.close'))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(onClear).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps the failed task retryable after a marketplace lookup failure', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockFetch.mockRejectedValueOnce(new Error('Network error'))
|
||||
const { onClear } = renderError()
|
||||
await user.click(retry())
|
||||
await waitFor(() => expect(retry()).toBeEnabled())
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(onClear).not.toHaveBeenCalled()
|
||||
await user.click(retry())
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not request an invalid marketplace identifier', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderError({ plugin_id: 'single-part' })
|
||||
await user.click(retry())
|
||||
expect(mockFetch).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
import type { FC } from 'react'
|
||||
import type { Plugin, PluginStatus } from '@/app/components/plugins/types'
|
||||
import type { PluginLanguage } from '@/i18n/metadata'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PluginInstallPermissionProvider } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'
|
||||
import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'
|
||||
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
|
||||
import { toPluginText } from '@/app/components/plugins/install-plugin/utils'
|
||||
import { PluginSource } from '@/app/components/plugins/types'
|
||||
import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'
|
||||
import PluginItem from './plugin-item'
|
||||
|
||||
type ErrorPluginItemProps = {
|
||||
plugin: PluginStatus
|
||||
getIconUrl: (icon: string) => string
|
||||
language: PluginLanguage
|
||||
onClear: () => void
|
||||
}
|
||||
|
||||
const ErrorPluginItem: FC<ErrorPluginItemProps> = ({ plugin, getIconUrl, language, onClear }) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const source = plugin.source
|
||||
const [showInstallModal, setShowInstallModal] = useState(false)
|
||||
const [installPayload, setInstallPayload] = useState<{
|
||||
uniqueIdentifier: string
|
||||
manifest: Plugin
|
||||
} | null>(null)
|
||||
const [isFetching, setIsFetching] = useState(false)
|
||||
const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()
|
||||
|
||||
const handleInstallFromMarketplace = useCallback(async () => {
|
||||
const parts = plugin.plugin_id.split('/')
|
||||
if (parts.length < 2) return
|
||||
const [org, name] = parts
|
||||
setIsFetching(true)
|
||||
try {
|
||||
const response = await fetchPluginInfoFromMarketPlace({ org: org!, name: name! })
|
||||
const info = response.data.plugin
|
||||
const manifest: Plugin = {
|
||||
plugin_id: plugin.plugin_id,
|
||||
type: info.category as Plugin['type'],
|
||||
category: info.category as Plugin['category'],
|
||||
name: name!,
|
||||
org: org!,
|
||||
version: info.latest_version,
|
||||
latest_version: info.latest_version,
|
||||
latest_package_identifier: info.latest_package_identifier,
|
||||
label: toPluginText(plugin.labels),
|
||||
brief: {},
|
||||
description: {},
|
||||
icon: plugin.icon,
|
||||
verified: true,
|
||||
introduction: '',
|
||||
repository: '',
|
||||
install_count: 0,
|
||||
endpoint: { settings: [] },
|
||||
tags: [],
|
||||
badges: [],
|
||||
verification: { authorized_category: 'langgenius' },
|
||||
from: 'marketplace',
|
||||
}
|
||||
setInstallPayload({ uniqueIdentifier: info.latest_package_identifier, manifest })
|
||||
setShowInstallModal(true)
|
||||
} catch {
|
||||
// silently fail
|
||||
} finally {
|
||||
setIsFetching(false)
|
||||
}
|
||||
}, [plugin.plugin_id, plugin.labels, plugin.icon])
|
||||
|
||||
const errorMsgKey:
|
||||
| 'task.errorMsg.marketplace'
|
||||
| 'task.errorMsg.github'
|
||||
| 'task.errorMsg.unknown' =
|
||||
source === PluginSource.marketplace
|
||||
? 'task.errorMsg.marketplace'
|
||||
: source === PluginSource.github
|
||||
? 'task.errorMsg.github'
|
||||
: 'task.errorMsg.unknown'
|
||||
|
||||
const errorMsg = t(($) => $[errorMsgKey], { ns: 'plugin' })
|
||||
|
||||
const renderAction = () => {
|
||||
if (source === PluginSource.marketplace && canInstallPlugin) {
|
||||
return (
|
||||
<div className="pt-1">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
loading={isFetching}
|
||||
onClick={handleInstallFromMarketplace}
|
||||
>
|
||||
{t(($) => $['task.installFromMarketplace'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (source === PluginSource.github && canInstallPlugin) {
|
||||
return (
|
||||
<div className="pt-1">
|
||||
<Button variant="secondary" size="small">
|
||||
{t(($) => $['task.installFromGithub'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PluginItem
|
||||
plugin={plugin}
|
||||
getIconUrl={getIconUrl}
|
||||
language={language}
|
||||
statusIcon={
|
||||
<span className="flex size-4 items-center justify-center rounded-full border border-components-panel-bg bg-components-panel-bg">
|
||||
<span className="i-ri-error-warning-fill size-4 text-text-destructive" />
|
||||
</span>
|
||||
}
|
||||
statusText={
|
||||
<span className="block max-w-full min-w-0 wrap-anywhere wrap-break-word whitespace-pre-wrap">
|
||||
{plugin.message || errorMsg}
|
||||
</span>
|
||||
}
|
||||
statusClassName="text-text-destructive"
|
||||
action={renderAction()}
|
||||
onClear={onClear}
|
||||
/>
|
||||
{showInstallModal && installPayload && canInstallPlugin && (
|
||||
<PluginInstallPermissionProvider
|
||||
canInstallPlugin={canInstallPlugin}
|
||||
currentDifyVersion={currentDifyVersion}
|
||||
>
|
||||
<InstallFromMarketplace
|
||||
uniqueIdentifier={installPayload.uniqueIdentifier}
|
||||
manifest={installPayload.manifest}
|
||||
onClose={() => setShowInstallModal(false)}
|
||||
onSuccess={() => {
|
||||
setShowInstallModal(false)
|
||||
onClear()
|
||||
}}
|
||||
/>
|
||||
</PluginInstallPermissionProvider>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default ErrorPluginItem
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PluginStatus } from '@/app/components/plugins/types'
|
||||
import type { PluginLanguage } from '@/i18n/metadata'
|
||||
import CardIcon from '@/app/components/plugins/card/base/card-icon'
|
||||
|
||||
type PluginItemProps = {
|
||||
plugin: PluginStatus
|
||||
getIconUrl: (icon: string) => string
|
||||
language: PluginLanguage
|
||||
statusIcon: ReactNode
|
||||
statusText: ReactNode
|
||||
statusClassName?: string
|
||||
action?: ReactNode
|
||||
onClear?: () => void
|
||||
}
|
||||
|
||||
function PluginItem({
|
||||
plugin,
|
||||
getIconUrl,
|
||||
language,
|
||||
statusIcon,
|
||||
statusText,
|
||||
statusClassName,
|
||||
action,
|
||||
onClear,
|
||||
}: PluginItemProps) {
|
||||
const hasPluginIcon = !!plugin.icon
|
||||
const pluginName = plugin.labels[language] || plugin.plugin_unique_identifier
|
||||
|
||||
return (
|
||||
<div className="group/item flex w-full max-w-full min-w-0 gap-1 overflow-hidden rounded-lg p-2 hover:bg-state-base-hover">
|
||||
<div className="relative shrink-0 self-start">
|
||||
{hasPluginIcon ? (
|
||||
<CardIcon size="small" src={getIconUrl(plugin.icon)} />
|
||||
) : (
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-solid-mediaAndDevices-magic-box size-8 text-text-tertiary"
|
||||
/>
|
||||
)}
|
||||
<div className="absolute -right-0.5 -bottom-0.5 z-10">{statusIcon}</div>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5 px-1 wrap-anywhere">
|
||||
<div className="truncate system-sm-medium text-text-secondary">
|
||||
{plugin.labels[language]}
|
||||
</div>
|
||||
<div
|
||||
className={`max-w-full min-w-0 system-xs-regular wrap-anywhere wrap-break-word ${statusClassName || 'text-text-tertiary'}`}
|
||||
>
|
||||
{statusText}
|
||||
</div>
|
||||
{action}
|
||||
</div>
|
||||
{onClear && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Clear ${pluginName}`}
|
||||
className="flex size-6 shrink-0 items-center justify-center self-start rounded-md opacity-0 outline-hidden group-hover/item:opacity-100 hover:bg-state-base-hover-alt focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-state-accent-solid [@media(hover:none)]:opacity-100"
|
||||
onClick={onClear}
|
||||
>
|
||||
<span className="i-ri-close-line size-4 text-text-tertiary" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginItem
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PluginStatus } from '@/app/components/plugins/types'
|
||||
import type { PluginLanguage } from '@/i18n/metadata'
|
||||
import {
|
||||
ScrollArea,
|
||||
ScrollAreaContent,
|
||||
ScrollAreaScrollbar,
|
||||
ScrollAreaThumb,
|
||||
ScrollAreaViewport,
|
||||
} from '@langgenius/dify-ui/scroll-area'
|
||||
import PluginItem from './plugin-item'
|
||||
|
||||
type PluginSectionProps = {
|
||||
title: string
|
||||
count: number
|
||||
plugins: PluginStatus[]
|
||||
getIconUrl: (icon: string) => string
|
||||
language: PluginLanguage
|
||||
statusIcon: ReactNode
|
||||
defaultStatusText: ReactNode
|
||||
statusClassName?: string
|
||||
headerAction?: ReactNode
|
||||
renderItemAction?: (plugin: PluginStatus) => ReactNode
|
||||
onClearSingle?: (taskId: string, pluginId: string) => void
|
||||
}
|
||||
|
||||
function PluginSection({
|
||||
title,
|
||||
count,
|
||||
plugins,
|
||||
getIconUrl,
|
||||
language,
|
||||
statusIcon,
|
||||
defaultStatusText,
|
||||
statusClassName,
|
||||
headerAction,
|
||||
renderItemAction,
|
||||
onClearSingle,
|
||||
}: PluginSectionProps) {
|
||||
if (plugins.length === 0) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="sticky top-0 flex items-start justify-between pt-1 pr-1 pl-2 system-sm-semibold-uppercase text-text-secondary">
|
||||
<h3 className="flex h-6 items-center">
|
||||
{title} ({count})
|
||||
</h3>
|
||||
{headerAction}
|
||||
</div>
|
||||
<ScrollArea className="overflow-hidden">
|
||||
<ScrollAreaViewport className="overscroll-contain">
|
||||
<ScrollAreaContent style={{ minWidth: 0 }}>
|
||||
{plugins.map((plugin) => (
|
||||
<PluginItem
|
||||
key={plugin.plugin_unique_identifier}
|
||||
plugin={plugin}
|
||||
getIconUrl={getIconUrl}
|
||||
language={language}
|
||||
statusIcon={statusIcon}
|
||||
statusText={plugin.message || defaultStatusText}
|
||||
statusClassName={statusClassName}
|
||||
action={renderItemAction?.(plugin)}
|
||||
onClear={
|
||||
onClearSingle
|
||||
? () => onClearSingle(plugin.taskId, plugin.plugin_unique_identifier)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ScrollAreaContent>
|
||||
</ScrollAreaViewport>
|
||||
<ScrollAreaScrollbar>
|
||||
<ScrollAreaThumb />
|
||||
</ScrollAreaScrollbar>
|
||||
</ScrollArea>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginSection
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
import type { PluginStatus } from '@/app/components/plugins/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import {
|
||||
ScrollArea,
|
||||
ScrollAreaContent,
|
||||
ScrollAreaScrollbar,
|
||||
ScrollAreaThumb,
|
||||
ScrollAreaViewport,
|
||||
} from '@langgenius/dify-ui/scroll-area'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useGetLanguage } from '@/context/i18n'
|
||||
import ErrorPluginItem from './error-plugin-item'
|
||||
import PluginSection from './plugin-section'
|
||||
|
||||
type PluginTaskListProps = {
|
||||
runningPlugins: PluginStatus[]
|
||||
successPlugins: PluginStatus[]
|
||||
errorPlugins: PluginStatus[]
|
||||
getIconUrl: (icon: string) => string
|
||||
onClearAll: () => void
|
||||
onClearErrors: () => void
|
||||
onClearSingle: (taskId: string, pluginId: string) => void
|
||||
}
|
||||
|
||||
function PluginTaskList({
|
||||
runningPlugins,
|
||||
successPlugins,
|
||||
errorPlugins,
|
||||
getIconUrl,
|
||||
onClearAll,
|
||||
onClearErrors,
|
||||
onClearSingle,
|
||||
}: PluginTaskListProps) {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const language = useGetLanguage()
|
||||
const runningSectionTitle = t(($) => $['task.runningPlugins'], { ns: 'plugin' })
|
||||
const successSectionTitle = t(($) => $['task.successPlugins'], { ns: 'plugin' })
|
||||
const errorSectionTitle = t(($) => $['task.errorPlugins'], { ns: 'plugin' })
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-90 max-w-[calc(100vw-32px)] overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg"
|
||||
data-testid="plugin-task-list"
|
||||
>
|
||||
<ScrollArea className="max-h-105 overflow-hidden">
|
||||
<ScrollAreaViewport
|
||||
aria-label={t(($) => $['task.installing'], { ns: 'plugin' })}
|
||||
style={{ overflowX: 'hidden' }}
|
||||
className="max-h-105 overscroll-contain"
|
||||
role="region"
|
||||
>
|
||||
<ScrollAreaContent style={{ minWidth: 0 }} className="w-full max-w-full pr-3">
|
||||
{runningPlugins.length > 0 && (
|
||||
<PluginSection
|
||||
title={runningSectionTitle}
|
||||
count={runningPlugins.length}
|
||||
plugins={runningPlugins}
|
||||
getIconUrl={getIconUrl}
|
||||
language={language}
|
||||
statusIcon={
|
||||
<span className="i-ri-loader-2-line size-3.5 animate-spin text-text-accent" />
|
||||
}
|
||||
defaultStatusText={t(($) => $['task.installingHint'], { ns: 'plugin' })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{successPlugins.length > 0 && (
|
||||
<PluginSection
|
||||
title={successSectionTitle}
|
||||
count={successPlugins.length}
|
||||
plugins={successPlugins}
|
||||
getIconUrl={getIconUrl}
|
||||
language={language}
|
||||
statusIcon={
|
||||
<span className="i-ri-checkbox-circle-fill size-3.5 text-text-success" />
|
||||
}
|
||||
defaultStatusText={t(($) => $['task.installed'], { ns: 'plugin' })}
|
||||
statusClassName="text-text-success"
|
||||
headerAction={
|
||||
<Button
|
||||
aria-label={`${successSectionTitle} ${t(($) => $['task.clearAll'], { ns: 'plugin' })}`}
|
||||
className="shrink-0"
|
||||
size="small"
|
||||
variant="ghost"
|
||||
onClick={onClearAll}
|
||||
>
|
||||
{t(($) => $['task.clearAll'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
}
|
||||
onClearSingle={onClearSingle}
|
||||
/>
|
||||
)}
|
||||
|
||||
{errorPlugins.length > 0 && (
|
||||
<>
|
||||
<div className="sticky top-0 flex h-7 items-center justify-between px-2 pt-1 system-sm-semibold-uppercase text-text-secondary">
|
||||
<h3>
|
||||
{errorSectionTitle} ({errorPlugins.length})
|
||||
</h3>
|
||||
<Button
|
||||
aria-label={`${errorSectionTitle} ${t(($) => $['task.clearAll'], { ns: 'plugin' })}`}
|
||||
className="shrink-0"
|
||||
size="small"
|
||||
variant="ghost"
|
||||
onClick={onClearErrors}
|
||||
>
|
||||
{t(($) => $['task.clearAll'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="w-full max-w-full min-w-0 overflow-hidden">
|
||||
{errorPlugins.map((plugin) => (
|
||||
<ErrorPluginItem
|
||||
key={plugin.plugin_unique_identifier}
|
||||
plugin={plugin}
|
||||
getIconUrl={getIconUrl}
|
||||
language={language}
|
||||
onClear={() => onClearSingle(plugin.taskId, plugin.plugin_unique_identifier)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</ScrollAreaContent>
|
||||
</ScrollAreaViewport>
|
||||
<ScrollAreaScrollbar>
|
||||
<ScrollAreaThumb />
|
||||
</ScrollAreaScrollbar>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginTaskList
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
@reference "../../../../../styles/globals.css";
|
||||
|
||||
.indicator {
|
||||
@apply relative overflow-visible bg-components-panel-bg p-2 shadow-none inset-ring-components-panel-border-subtle;
|
||||
|
||||
&[data-disabled] {
|
||||
@apply cursor-default bg-components-panel-bg text-components-button-secondary-text shadow-none inset-ring-components-panel-border-subtle backdrop-blur-[5px];
|
||||
}
|
||||
|
||||
&[data-popup-open] {
|
||||
@apply bg-components-button-secondary-bg-hover shadow-xs shadow-shadow-shadow-3 inset-ring-components-button-secondary-border-hover backdrop-blur-[5px];
|
||||
}
|
||||
|
||||
&[data-error] {
|
||||
@apply cursor-pointer bg-state-destructive-hover text-components-button-destructive-secondary-text shadow-xs shadow-shadow-shadow-3 inset-ring-components-button-destructive-secondary-border-hover backdrop-blur-[5px];
|
||||
|
||||
&:hover,
|
||||
&[data-popup-open] {
|
||||
@apply bg-state-destructive-hover-alt;
|
||||
}
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import type { IconButtonProps } from '@langgenius/dify-ui/icon-button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import DownloadingIcon from '@/app/components/header/plugins-nav/downloading-icon'
|
||||
import styles from './task-status-indicator.module.css'
|
||||
|
||||
type TaskStatusIndicatorProps = Omit<
|
||||
IconButtonProps,
|
||||
'aria-label' | 'aria-labelledby' | 'children' | 'size' | 'tone' | 'variant'
|
||||
> & {
|
||||
tip: string
|
||||
isInstalling: boolean
|
||||
isInstallingWithSuccess: boolean
|
||||
isInstallingWithError: boolean
|
||||
isSuccess: boolean
|
||||
isFailed: boolean
|
||||
successPluginsLength: number
|
||||
runningPluginsLength: number
|
||||
}
|
||||
|
||||
function ErrorBadgeIcon() {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden
|
||||
data-status-badge="error"
|
||||
data-testid="task-status-error-badge"
|
||||
className="size-3.5 text-text-destructive"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10s-4.477 10-10 10m-1-7v2h2v-2zm0-8v6h2V7z"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function SuccessBadgeIcon() {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden
|
||||
data-status-badge="success"
|
||||
data-testid="task-status-success-badge"
|
||||
className="size-3.5 text-text-success"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2S2 6.477 2 12s4.477 10 10 10m5.457-12.543L11 15.914l-4.207-4.207l1.414-1.414L11 13.086l5.043-5.043z"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function TaskStatusIndicator({
|
||||
tip,
|
||||
isInstalling,
|
||||
isInstallingWithSuccess,
|
||||
isInstallingWithError,
|
||||
isSuccess,
|
||||
isFailed,
|
||||
successPluginsLength,
|
||||
runningPluginsLength,
|
||||
className,
|
||||
...buttonProps
|
||||
}: TaskStatusIndicatorProps) {
|
||||
const showErrorStyle = isInstallingWithError || isFailed
|
||||
const hasActiveInstall = isInstalling || isInstallingWithSuccess || isInstallingWithError
|
||||
const showSuccessIcon =
|
||||
isSuccess ||
|
||||
(!hasActiveInstall && !isFailed && successPluginsLength > 0 && runningPluginsLength === 0)
|
||||
const showSuccessBadge = showSuccessIcon && !isInstallingWithError && !isFailed
|
||||
const showBadge = isInstallingWithError || showSuccessBadge || isFailed
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<IconButton
|
||||
{...buttonProps}
|
||||
aria-label={tip}
|
||||
variant="secondary"
|
||||
size="lg"
|
||||
focusableWhenDisabled
|
||||
data-error={showErrorStyle ? '' : undefined}
|
||||
className={cn(styles.indicator, className)}
|
||||
>
|
||||
<span aria-hidden className="contents">
|
||||
<DownloadingIcon active={hasActiveInstall} />
|
||||
{showBadge && (
|
||||
<span className="absolute -top-1.5 -right-1.5 box-content flex size-3.5 items-center justify-center rounded-full border border-components-panel-bg bg-components-panel-bg">
|
||||
{isInstallingWithError && <ErrorBadgeIcon />}
|
||||
{showSuccessBadge && <SuccessBadgeIcon />}
|
||||
{isFailed && <ErrorBadgeIcon />}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{tip}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default TaskStatusIndicator
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { PluginStatus } from '@/app/components/plugins/types'
|
||||
import { useCallback } from 'react'
|
||||
import { TaskStatus } from '@/app/components/plugins/types'
|
||||
import { useMutationClearTaskPlugin, usePluginTaskList } from '@/service/use-plugins'
|
||||
|
||||
const isUnfinishedStatus = (status: PluginStatus['status']) =>
|
||||
status === TaskStatus.pending || status === TaskStatus.running
|
||||
|
||||
export const usePluginTaskStatus = () => {
|
||||
const { pluginTasks, handleRefetch } = usePluginTaskList()
|
||||
const { mutateAsync } = useMutationClearTaskPlugin()
|
||||
const allPlugins = pluginTasks
|
||||
.map((task) =>
|
||||
task.plugins.map((plugin) => {
|
||||
return {
|
||||
...plugin,
|
||||
taskId: task.id,
|
||||
}
|
||||
}),
|
||||
)
|
||||
.flat()
|
||||
const errorPlugins: PluginStatus[] = []
|
||||
const successPlugins: PluginStatus[] = []
|
||||
const runningPlugins: PluginStatus[] = []
|
||||
|
||||
allPlugins.forEach((plugin) => {
|
||||
if (isUnfinishedStatus(plugin.status)) runningPlugins.push(plugin)
|
||||
if (plugin.status === TaskStatus.failed) errorPlugins.push(plugin)
|
||||
if (plugin.status === TaskStatus.success) successPlugins.push(plugin)
|
||||
})
|
||||
|
||||
const handleClearErrorPlugin = useCallback(
|
||||
async (taskId: string, pluginId: string) => {
|
||||
await mutateAsync({
|
||||
taskId,
|
||||
pluginId,
|
||||
})
|
||||
handleRefetch()
|
||||
},
|
||||
[mutateAsync, handleRefetch],
|
||||
)
|
||||
const totalPluginsLength = allPlugins.length
|
||||
const runningPluginsLength = runningPlugins.length
|
||||
const errorPluginsLength = errorPlugins.length
|
||||
const successPluginsLength = successPlugins.length
|
||||
|
||||
const isInstalling =
|
||||
runningPluginsLength > 0 && errorPluginsLength === 0 && successPluginsLength === 0
|
||||
const isInstallingWithSuccess =
|
||||
runningPluginsLength > 0 && successPluginsLength > 0 && errorPluginsLength === 0
|
||||
const isInstallingWithError = runningPluginsLength > 0 && errorPluginsLength > 0
|
||||
const isSuccess = successPluginsLength === totalPluginsLength && totalPluginsLength > 0
|
||||
const isFailed =
|
||||
runningPluginsLength === 0 &&
|
||||
errorPluginsLength + successPluginsLength === totalPluginsLength &&
|
||||
totalPluginsLength > 0 &&
|
||||
errorPluginsLength > 0
|
||||
|
||||
return {
|
||||
errorPlugins,
|
||||
successPlugins,
|
||||
runningPlugins,
|
||||
runningPluginsLength,
|
||||
errorPluginsLength,
|
||||
successPluginsLength,
|
||||
totalPluginsLength,
|
||||
isInstalling,
|
||||
isInstallingWithSuccess,
|
||||
isInstallingWithError,
|
||||
isSuccess,
|
||||
isFailed,
|
||||
handleClearErrorPlugin,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import type { PopoverPositionerProps } from '@langgenius/dify-ui/popover'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Popover,
|
||||
PopoverPopup,
|
||||
PopoverPortal,
|
||||
PopoverPositioner,
|
||||
PopoverTrigger,
|
||||
} from '@langgenius/dify-ui/popover'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
|
||||
import PluginTaskList from './components/plugin-task-list'
|
||||
import TaskStatusIndicator from './components/task-status-indicator'
|
||||
import { usePluginTaskStatus } from './hooks'
|
||||
|
||||
type PluginTasksProps = Pick<PopoverPositionerProps, 'anchor'> & {
|
||||
animatedSlot?: boolean
|
||||
}
|
||||
|
||||
const PluginTasks = ({ animatedSlot = false, anchor }: PluginTasksProps) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const [open, setOpen] = useState(false)
|
||||
const {
|
||||
errorPlugins,
|
||||
successPlugins,
|
||||
runningPlugins,
|
||||
runningPluginsLength,
|
||||
successPluginsLength,
|
||||
errorPluginsLength,
|
||||
totalPluginsLength,
|
||||
isInstalling,
|
||||
isInstallingWithSuccess,
|
||||
isInstallingWithError,
|
||||
isSuccess,
|
||||
isFailed,
|
||||
handleClearErrorPlugin,
|
||||
} = usePluginTaskStatus()
|
||||
const { getIconUrl } = useGetIcon()
|
||||
const hasPluginTasks = totalPluginsLength > 0
|
||||
const canOpenPopover =
|
||||
isFailed || isInstalling || isInstallingWithSuccess || isInstallingWithError || isSuccess
|
||||
|
||||
// Generate tooltip text based on status
|
||||
const tip = useMemo(() => {
|
||||
if (isInstallingWithError)
|
||||
return t(($) => $['task.installingWithError'], {
|
||||
ns: 'plugin',
|
||||
installingLength: runningPluginsLength,
|
||||
successLength: successPluginsLength,
|
||||
errorLength: errorPluginsLength,
|
||||
})
|
||||
if (isInstallingWithSuccess)
|
||||
return t(($) => $['task.installingWithSuccess'], {
|
||||
ns: 'plugin',
|
||||
installingLength: runningPluginsLength,
|
||||
successLength: successPluginsLength,
|
||||
})
|
||||
if (isInstalling) return t(($) => $['task.installing'], { ns: 'plugin' })
|
||||
if (isFailed)
|
||||
return t(($) => $['task.installedError'], { ns: 'plugin', errorLength: errorPluginsLength })
|
||||
if (isSuccess)
|
||||
return t(($) => $['task.installSuccess'], {
|
||||
ns: 'plugin',
|
||||
successLength: successPluginsLength,
|
||||
})
|
||||
return t(($) => $['task.installed'], { ns: 'plugin' })
|
||||
}, [
|
||||
errorPluginsLength,
|
||||
isFailed,
|
||||
isInstalling,
|
||||
isInstallingWithError,
|
||||
isInstallingWithSuccess,
|
||||
isSuccess,
|
||||
runningPluginsLength,
|
||||
successPluginsLength,
|
||||
t,
|
||||
])
|
||||
|
||||
// Generic clear function that handles clearing and modal closing
|
||||
const clearPluginsAndClose = useCallback(
|
||||
async (plugins: Array<{ taskId: string; plugin_unique_identifier: string }>) => {
|
||||
for (const plugin of plugins)
|
||||
await handleClearErrorPlugin(plugin.taskId, plugin.plugin_unique_identifier)
|
||||
if (runningPluginsLength === 0) setOpen(false)
|
||||
},
|
||||
[handleClearErrorPlugin, runningPluginsLength],
|
||||
)
|
||||
|
||||
// Clear handlers using the generic function
|
||||
const handleClearAll = useCallback(
|
||||
() => clearPluginsAndClose([...successPlugins, ...errorPlugins]),
|
||||
[clearPluginsAndClose, successPlugins, errorPlugins],
|
||||
)
|
||||
|
||||
const handleClearErrors = useCallback(
|
||||
() => clearPluginsAndClose(errorPlugins),
|
||||
[clearPluginsAndClose, errorPlugins],
|
||||
)
|
||||
|
||||
const handleClearSingle = useCallback(
|
||||
(taskId: string, pluginId: string) =>
|
||||
clearPluginsAndClose([{ taskId, plugin_unique_identifier: pluginId }]),
|
||||
[clearPluginsAndClose],
|
||||
)
|
||||
|
||||
const rootClassName = animatedSlot
|
||||
? cn(
|
||||
'flex shrink-0 items-center overflow-visible transition-[width,margin-left,opacity] duration-200 ease-out',
|
||||
hasPluginTasks ? 'ml-1 w-8 opacity-100' : 'ml-0 w-0 opacity-0',
|
||||
)
|
||||
: 'flex items-center'
|
||||
|
||||
if (!hasPluginTasks) {
|
||||
if (animatedSlot) return <div aria-hidden className={rootClassName} />
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={rootClassName}>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<TaskStatusIndicator
|
||||
id="plugin-task-trigger"
|
||||
tip={tip}
|
||||
isInstalling={isInstalling}
|
||||
isInstallingWithSuccess={isInstallingWithSuccess}
|
||||
isInstallingWithError={isInstallingWithError}
|
||||
isSuccess={isSuccess}
|
||||
isFailed={isFailed}
|
||||
successPluginsLength={successPluginsLength}
|
||||
runningPluginsLength={runningPluginsLength}
|
||||
/>
|
||||
}
|
||||
disabled={!canOpenPopover}
|
||||
/>
|
||||
<PopoverPortal>
|
||||
<PopoverPositioner align="start" sideOffset={4} anchor={anchor}>
|
||||
<PopoverPopup aria-label={tip}>
|
||||
<PluginTaskList
|
||||
runningPlugins={runningPlugins}
|
||||
successPlugins={successPlugins}
|
||||
errorPlugins={errorPlugins}
|
||||
getIconUrl={getIconUrl}
|
||||
onClearAll={handleClearAll}
|
||||
onClearErrors={handleClearErrors}
|
||||
onClearSingle={handleClearSingle}
|
||||
/>
|
||||
</PopoverPopup>
|
||||
</PopoverPositioner>
|
||||
</PopoverPortal>
|
||||
</Popover>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginTasks
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import type { PluginStatus } from '@/app/components/plugins/types'
|
||||
import { userEvent } from 'vite-plus/test/browser'
|
||||
import { render } from 'vitest-browser-react'
|
||||
import { PluginSource, TaskStatus } from '@/app/components/plugins/types'
|
||||
import PluginTasks from './index'
|
||||
|
||||
const service = vi.hoisted(() => ({ clear: vi.fn().mockResolvedValue({}), refetch: vi.fn() }))
|
||||
vi.mock('@/service/use-plugins', () => ({
|
||||
usePluginTaskList: () => ({
|
||||
pluginTasks: [
|
||||
{
|
||||
id: 'task-1',
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: 'plugin-1',
|
||||
plugin_id: 'plugin-1',
|
||||
source: PluginSource.marketplace,
|
||||
status: TaskStatus.success,
|
||||
message: '',
|
||||
icon: '',
|
||||
labels: { en_US: 'Installed Plugin' },
|
||||
} satisfies Omit<PluginStatus, 'taskId'>,
|
||||
],
|
||||
},
|
||||
],
|
||||
handleRefetch: service.refetch,
|
||||
}),
|
||||
useMutationClearTaskPlugin: () => ({ mutateAsync: service.clear }),
|
||||
}))
|
||||
vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () => ({
|
||||
default: () => null,
|
||||
}))
|
||||
vi.mock('@/app/components/plugins/install-plugin/base/use-get-icon', () => ({
|
||||
default: () => ({ getIconUrl: () => '' }),
|
||||
}))
|
||||
vi.mock('@/context/i18n', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/context/i18n')>()),
|
||||
useGetLanguage: () => 'en_US',
|
||||
}))
|
||||
|
||||
it('clears a completed plugin installation task using the keyboard and returns focus to installation status', async () => {
|
||||
// Native Tab must include the button that CSS used to hide from keyboard users.
|
||||
const screen = await render(<PluginTasks />)
|
||||
const trigger = screen.getByRole('button', { name: /plugin.task.installSuccess/ })
|
||||
await trigger.click()
|
||||
const taskDetails = screen.getByRole('dialog')
|
||||
await expect.element(taskDetails).toBeVisible()
|
||||
await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
|
||||
const clearAll = screen.getByRole('button', {
|
||||
name: 'plugin.task.successPlugins plugin.task.clearAll',
|
||||
})
|
||||
clearAll.element().focus()
|
||||
await userEvent.tab()
|
||||
const clear = screen.getByRole('button', { name: 'Clear Installed Plugin' })
|
||||
await expect.element(clear).toHaveFocus()
|
||||
await expect.poll(() => clear.element().checkVisibility({ checkOpacity: true })).toBe(true)
|
||||
await userEvent.keyboard('{Enter}')
|
||||
expect(service.clear).toHaveBeenCalledExactlyOnceWith({ taskId: 'task-1', pluginId: 'plugin-1' })
|
||||
await expect.element(taskDetails).not.toBeInTheDocument()
|
||||
await expect.element(trigger).toHaveFocus()
|
||||
})
|
||||
@@ -0,0 +1,219 @@
|
||||
import type { RefObject } from 'react'
|
||||
import type { PluginDetail } from '../types'
|
||||
import type { EmbeddedMarketplaceCategory } from './category-marketplace'
|
||||
import type { PluginPageContentInset } from './content-inset'
|
||||
import type { Collection } from '@/app/components/tools/types'
|
||||
import type { MarketplaceLinks } from '@/features/marketplace/links'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
ScrollArea,
|
||||
ScrollAreaContent,
|
||||
ScrollAreaScrollbar,
|
||||
ScrollAreaThumb,
|
||||
ScrollAreaViewport,
|
||||
} from '@langgenius/dify-ui/scroll-area'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
|
||||
import IntegrationsToolProviderCard from '@/app/components/integrations/tool-provider-card'
|
||||
import { BuiltinMarketplacePanel } from '@/app/components/tools/marketplace/builtin-marketplace-panel'
|
||||
import CategoryEmptyState from './category-empty-state'
|
||||
import CategoryMarketplacePanel from './category-marketplace-panel'
|
||||
import List from './list'
|
||||
|
||||
type PluginsPanelResultsProps = {
|
||||
autoLoadNextPage: boolean
|
||||
canDeletePlugin: boolean
|
||||
canUpdatePlugin: boolean
|
||||
categoryEmptyState?: EmbeddedMarketplaceCategory
|
||||
categoryMarketplace?: EmbeddedMarketplaceCategory
|
||||
containerRef: RefObject<HTMLDivElement | null>
|
||||
contentFrameClassName: string
|
||||
contentInset: PluginPageContentInset
|
||||
currentBuiltinToolID?: string
|
||||
firstBuiltinToolTarget?: string
|
||||
firstPluginTarget?: string
|
||||
filteredBuiltinTools: Collection[]
|
||||
filteredList: Array<PluginDetail & { latest_version: string }>
|
||||
hasToolMarketplacePanel: boolean
|
||||
marketplace: MarketplaceLinks | null
|
||||
hasVisibleBuiltinTools: boolean
|
||||
hasVisiblePlugins: boolean
|
||||
hasEmbeddedMarketplace: boolean
|
||||
isFetching: boolean
|
||||
isLastPage: boolean
|
||||
keywords: string
|
||||
loadNextPage: () => void
|
||||
onSelectBuiltinTool: (id: string) => void
|
||||
scrollAreaLabel?: string
|
||||
showCategoryEmptyState: boolean
|
||||
tagFilterValue: string[]
|
||||
}
|
||||
|
||||
const PluginsPanelResults = ({
|
||||
autoLoadNextPage,
|
||||
canDeletePlugin,
|
||||
canUpdatePlugin,
|
||||
categoryEmptyState,
|
||||
categoryMarketplace,
|
||||
containerRef,
|
||||
contentFrameClassName,
|
||||
contentInset,
|
||||
currentBuiltinToolID,
|
||||
firstBuiltinToolTarget,
|
||||
firstPluginTarget,
|
||||
filteredBuiltinTools,
|
||||
filteredList,
|
||||
hasToolMarketplacePanel,
|
||||
marketplace,
|
||||
hasVisibleBuiltinTools,
|
||||
hasVisiblePlugins,
|
||||
hasEmbeddedMarketplace,
|
||||
isFetching,
|
||||
isLastPage,
|
||||
keywords,
|
||||
loadNextPage,
|
||||
onSelectBuiltinTool,
|
||||
scrollAreaLabel,
|
||||
showCategoryEmptyState,
|
||||
tagFilterValue,
|
||||
}: PluginsPanelResultsProps) => {
|
||||
const { t } = useTranslation(['common', 'plugin', 'workflow'])
|
||||
const loadMoreAnchorRef = useRef<HTMLDivElement>(null)
|
||||
const loadNextPageRequestedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
const anchor = loadMoreAnchorRef.current
|
||||
const root = containerRef.current
|
||||
|
||||
if (!isFetching) loadNextPageRequestedRef.current = false
|
||||
|
||||
if (
|
||||
!autoLoadNextPage ||
|
||||
!anchor ||
|
||||
!root ||
|
||||
isFetching ||
|
||||
isLastPage ||
|
||||
!globalThis.IntersectionObserver
|
||||
)
|
||||
return
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (!entries[0]?.isIntersecting || loadNextPageRequestedRef.current) return
|
||||
|
||||
loadNextPageRequestedRef.current = true
|
||||
loadNextPage()
|
||||
},
|
||||
{
|
||||
root,
|
||||
rootMargin: '200px',
|
||||
threshold: 0.1,
|
||||
},
|
||||
)
|
||||
|
||||
observer.observe(anchor)
|
||||
return () => observer.disconnect()
|
||||
}, [autoLoadNextPage, containerRef, isFetching, isLastPage, loadNextPage])
|
||||
|
||||
return (
|
||||
<ScrollArea
|
||||
className={cn(
|
||||
'min-h-0 grow self-stretch overflow-hidden bg-components-panel-bg',
|
||||
contentFrameClassName,
|
||||
)}
|
||||
>
|
||||
<div role="status" aria-atomic="true" className="sr-only">
|
||||
{isFetching
|
||||
? t(($) => $.loading, { ns: 'common' })
|
||||
: t(($) => $['marketplace.pluginsResult'], {
|
||||
ns: 'plugin',
|
||||
num:
|
||||
(hasVisiblePlugins ? filteredList.length : 0) +
|
||||
(hasVisibleBuiltinTools ? filteredBuiltinTools.length : 0),
|
||||
})}
|
||||
</div>
|
||||
<ScrollAreaViewport
|
||||
ref={containerRef}
|
||||
aria-label={scrollAreaLabel}
|
||||
className="overscroll-contain"
|
||||
role={scrollAreaLabel ? 'region' : undefined}
|
||||
>
|
||||
<ScrollAreaContent
|
||||
className={cn('flex min-h-full flex-col', hasEmbeddedMarketplace && 'pt-1')}
|
||||
>
|
||||
{showCategoryEmptyState && categoryEmptyState && (
|
||||
<CategoryEmptyState
|
||||
category={categoryEmptyState}
|
||||
showMarketplaceLink={!!categoryMarketplace}
|
||||
/>
|
||||
)}
|
||||
{(hasVisiblePlugins || hasVisibleBuiltinTools) && (
|
||||
<List
|
||||
pluginList={filteredList}
|
||||
canDeletePlugin={canDeletePlugin}
|
||||
canUpdatePlugin={canUpdatePlugin}
|
||||
firstPluginTarget={firstPluginTarget}
|
||||
>
|
||||
{filteredBuiltinTools.map((collection, index) => (
|
||||
<button
|
||||
key={collection.id}
|
||||
type="button"
|
||||
aria-current={currentBuiltinToolID === collection.id ? 'true' : undefined}
|
||||
className="min-w-0 cursor-pointer appearance-none border-0 bg-transparent p-0 text-left"
|
||||
data-step-by-step-tour-target={
|
||||
filteredList.length === 0 && index === 0 ? firstBuiltinToolTarget : undefined
|
||||
}
|
||||
onClick={() => onSelectBuiltinTool(collection.id)}
|
||||
>
|
||||
<IntegrationsToolProviderCard
|
||||
collection={collection}
|
||||
current={currentBuiltinToolID === collection.id}
|
||||
showBuiltInBadge
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
{!isLastPage && (
|
||||
<div className="flex w-full justify-center py-4">
|
||||
{isFetching ? (
|
||||
<LoadingPlaceholder className="size-8" />
|
||||
) : autoLoadNextPage ? null : (
|
||||
<Button onClick={loadNextPage}>
|
||||
{t(($) => $['common.loadMore'], { ns: 'workflow' })}
|
||||
</Button>
|
||||
)}
|
||||
{autoLoadNextPage && (
|
||||
<div ref={loadMoreAnchorRef} className="h-px w-full" aria-hidden />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{marketplace && hasToolMarketplacePanel && (
|
||||
<BuiltinMarketplacePanel
|
||||
marketplace={marketplace}
|
||||
containerRef={containerRef}
|
||||
contentInset={contentInset}
|
||||
keywords={keywords}
|
||||
tagFilterValue={tagFilterValue}
|
||||
/>
|
||||
)}
|
||||
{marketplace && categoryMarketplace && (
|
||||
<CategoryMarketplacePanel
|
||||
marketplace={marketplace}
|
||||
category={categoryMarketplace}
|
||||
searchText={keywords}
|
||||
tags={categoryMarketplace === 'trigger' ? tagFilterValue : []}
|
||||
/>
|
||||
)}
|
||||
</ScrollAreaContent>
|
||||
</ScrollAreaViewport>
|
||||
<ScrollAreaScrollbar>
|
||||
<ScrollAreaThumb />
|
||||
</ScrollAreaScrollbar>
|
||||
</ScrollArea>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginsPanelResults
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Collection } from '@/app/components/tools/types'
|
||||
import { renderI18nObject } from '@/i18n/metadata'
|
||||
|
||||
export const EMPTY_BUILTIN_TOOLS: Collection[] = []
|
||||
|
||||
export const filterBuiltinTools = (
|
||||
collections: Collection[],
|
||||
query: string,
|
||||
locale: string,
|
||||
tags: string[] = [],
|
||||
) => {
|
||||
if (!query && !tags.length) return collections
|
||||
|
||||
const lowerQuery = query.toLowerCase()
|
||||
return collections.filter((collection) => {
|
||||
if (tags.length && collection.labels.every((label) => !tags.includes(label))) return false
|
||||
|
||||
if (!query) return true
|
||||
|
||||
if (collection.name.toLowerCase().includes(lowerQuery)) return true
|
||||
|
||||
const label = renderI18nObject(collection.label, locale)
|
||||
if (label?.toLowerCase().includes(lowerQuery)) return true
|
||||
|
||||
const description = renderI18nObject(collection.description, locale)
|
||||
return !!description?.toLowerCase().includes(lowerQuery)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
'use client'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PluginDetail } from '../types'
|
||||
import type { PluginPageContentInset } from './content-inset'
|
||||
import type { FilterState } from './filter-management'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useDebounceFn } from 'ahooks'
|
||||
import { useMemo, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { isSearchResultEmpty } from '@/app/components/base/search-input/search-state'
|
||||
import PluginDetailPanel from '@/app/components/plugins/plugin-detail-panel'
|
||||
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
|
||||
import ProviderDetail from '@/app/components/tools/provider/detail'
|
||||
import { useGetLanguage } from '@/context/i18n'
|
||||
import { useMarketplace } from '@/features/marketplace/client'
|
||||
import { renderI18nObject } from '@/i18n/metadata'
|
||||
import {
|
||||
normalizePluginCategoryListLanguage,
|
||||
useInstalledPluginList,
|
||||
useInvalidateInstalledPluginList,
|
||||
useRemoveFilteredInstalledPluginPageOnUnmount,
|
||||
} from '@/service/use-plugins'
|
||||
import { usePluginsWithLatestVersion } from '../hooks'
|
||||
import { PluginCategoryEnum } from '../types'
|
||||
import { isEmbeddedMarketplaceCategory } from './category-marketplace'
|
||||
import { pluginPageContentFrameClassNames, pluginPageContentInsetClassNames } from './content-inset'
|
||||
import { usePluginPageContext } from './context'
|
||||
import Empty from './empty'
|
||||
import FilterManagement from './filter-management'
|
||||
import PluginListSkeleton from './plugin-list-skeleton'
|
||||
import PluginsPanelResults from './plugins-panel-results'
|
||||
import { EMPTY_BUILTIN_TOOLS, filterBuiltinTools } from './plugins-panel-utils'
|
||||
|
||||
const INTEGRATION_PLUGIN_PAGE_SIZE = 30
|
||||
const INTEGRATION_PLUGIN_STALE_TIME = 5 * 60 * 1000
|
||||
const INTEGRATION_PLUGIN_GC_TIME = 10 * 60 * 1000
|
||||
|
||||
const matchesSearchQuery = (
|
||||
plugin: PluginDetail & { latest_version: string },
|
||||
query: string,
|
||||
locale: string,
|
||||
): boolean => {
|
||||
if (!query) return true
|
||||
const lowerQuery = query.toLowerCase()
|
||||
const { declaration } = plugin
|
||||
// Match plugin_id
|
||||
if (plugin.plugin_id.toLowerCase().includes(lowerQuery)) return true
|
||||
// Match plugin name
|
||||
if (plugin.name?.toLowerCase().includes(lowerQuery)) return true
|
||||
// Match declaration name
|
||||
if (declaration.name?.toLowerCase().includes(lowerQuery)) return true
|
||||
// Match localized label
|
||||
const label = renderI18nObject(declaration.label, locale)
|
||||
if (label?.toLowerCase().includes(lowerQuery)) return true
|
||||
// Match localized description
|
||||
const description = renderI18nObject(declaration.description, locale)
|
||||
if (description?.toLowerCase().includes(lowerQuery)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
type PluginsPanelProps = {
|
||||
canInstall?: boolean
|
||||
canDeletePlugin?: boolean
|
||||
canUpdatePlugin?: boolean
|
||||
contentInset?: PluginPageContentInset
|
||||
fixedCategory?: PluginCategoryEnum
|
||||
layout?: (parts: { body: ReactNode; toolbar: ReactNode }) => ReactNode
|
||||
onSwitchToMarketplace?: () => void
|
||||
toolbarAction?: ReactNode
|
||||
}
|
||||
|
||||
const PluginsPanel = ({
|
||||
canInstall = true,
|
||||
canDeletePlugin = true,
|
||||
canUpdatePlugin = true,
|
||||
contentInset = 'default',
|
||||
fixedCategory,
|
||||
layout,
|
||||
onSwitchToMarketplace,
|
||||
toolbarAction,
|
||||
}: PluginsPanelProps) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const locale = useGetLanguage()
|
||||
const filters = usePluginPageContext((v) => v.filters) as FilterState
|
||||
const setFilters = usePluginPageContext((v) => v.setFilters)
|
||||
const isToolIntegrationPage = fixedCategory === PluginCategoryEnum.tool
|
||||
const isTriggerIntegrationPage = fixedCategory === PluginCategoryEnum.trigger
|
||||
const isAgentStrategyIntegrationPage = fixedCategory === PluginCategoryEnum.agent
|
||||
const isExtensionIntegrationPage = fixedCategory === PluginCategoryEnum.extension
|
||||
const hasEmbeddedMarketplace = isEmbeddedMarketplaceCategory(fixedCategory)
|
||||
const isIntegrationCategoryPage =
|
||||
isToolIntegrationPage ||
|
||||
isTriggerIntegrationPage ||
|
||||
isAgentStrategyIntegrationPage ||
|
||||
isExtensionIntegrationPage
|
||||
const supportsTagFilter = !fixedCategory || isToolIntegrationPage || isTriggerIntegrationPage
|
||||
const installedPluginFilters = useMemo(
|
||||
() =>
|
||||
isIntegrationCategoryPage
|
||||
? {
|
||||
language: normalizePluginCategoryListLanguage(locale),
|
||||
query: filters.searchQuery,
|
||||
tags: supportsTagFilter ? filters.tags : [],
|
||||
}
|
||||
: undefined,
|
||||
[filters.searchQuery, filters.tags, isIntegrationCategoryPage, locale, supportsTagFilter],
|
||||
)
|
||||
const marketplace = useMarketplace()
|
||||
const {
|
||||
data: pluginList,
|
||||
isLoading: isPluginListLoading,
|
||||
isFetching,
|
||||
isLastPage,
|
||||
loadNextPage,
|
||||
} = useInstalledPluginList({
|
||||
category: fixedCategory,
|
||||
filters: installedPluginFilters,
|
||||
gcTime: isIntegrationCategoryPage ? INTEGRATION_PLUGIN_GC_TIME : undefined,
|
||||
pageSize: isIntegrationCategoryPage ? INTEGRATION_PLUGIN_PAGE_SIZE : 100,
|
||||
staleTime: isIntegrationCategoryPage ? INTEGRATION_PLUGIN_STALE_TIME : undefined,
|
||||
})
|
||||
const pluginListWithLatestVersion = usePluginsWithLatestVersion(pluginList?.plugins)
|
||||
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
|
||||
useRemoveFilteredInstalledPluginPageOnUnmount(
|
||||
isIntegrationCategoryPage ? fixedCategory : undefined,
|
||||
INTEGRATION_PLUGIN_PAGE_SIZE,
|
||||
installedPluginFilters,
|
||||
)
|
||||
const selectedItem = usePluginPageContext((v) => v.selectedItem)
|
||||
const setSelectedItem = usePluginPageContext((v) => v.setSelectedItem)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const { run: handleFilterChange } = useDebounceFn(
|
||||
(filters: FilterState) => {
|
||||
setFilters(filters)
|
||||
},
|
||||
{ wait: 500 },
|
||||
)
|
||||
|
||||
const categoryList = useMemo(() => {
|
||||
if (!fixedCategory) return pluginListWithLatestVersion
|
||||
|
||||
return pluginListWithLatestVersion.filter(
|
||||
(plugin) => plugin.declaration.category === fixedCategory,
|
||||
)
|
||||
}, [fixedCategory, pluginListWithLatestVersion])
|
||||
|
||||
const filteredList = useMemo(() => {
|
||||
const { categories, searchQuery, tags } = filters
|
||||
const filteredList = categoryList.filter((plugin) => {
|
||||
return (
|
||||
(fixedCategory ||
|
||||
categories.length === 0 ||
|
||||
categories.includes(plugin.declaration.category)) &&
|
||||
(!supportsTagFilter ||
|
||||
tags.length === 0 ||
|
||||
tags.some((tag) => plugin.declaration.tags.includes(tag))) &&
|
||||
matchesSearchQuery(plugin, searchQuery, locale)
|
||||
)
|
||||
})
|
||||
return filteredList
|
||||
}, [categoryList, fixedCategory, supportsTagFilter, filters, locale])
|
||||
const builtinTools = isToolIntegrationPage
|
||||
? (pluginList?.builtin_tools ?? EMPTY_BUILTIN_TOOLS)
|
||||
: EMPTY_BUILTIN_TOOLS
|
||||
const filteredBuiltinTools = useMemo(() => {
|
||||
if (!isToolIntegrationPage) return []
|
||||
|
||||
return filterBuiltinTools(builtinTools, filters.searchQuery, locale, filters.tags)
|
||||
}, [builtinTools, filters.searchQuery, filters.tags, isToolIntegrationPage, locale])
|
||||
const hasVisiblePlugins = (filteredList?.length ?? 0) > 0
|
||||
const hasVisibleBuiltinTools = filteredBuiltinTools.length > 0
|
||||
const isFilteringCategory =
|
||||
!!filters.searchQuery.trim() || (supportsTagFilter && filters.tags.length > 0)
|
||||
const isIntegrationCategorySearchEmpty =
|
||||
isIntegrationCategoryPage &&
|
||||
isSearchResultEmpty({
|
||||
hasActiveFilter: isFilteringCategory,
|
||||
isLoading: isPluginListLoading,
|
||||
resultCount: filteredList.length + filteredBuiltinTools.length,
|
||||
sourceCount: categoryList.length + builtinTools.length,
|
||||
})
|
||||
|
||||
const currentPluginID = selectedItem?.type === 'plugin' ? selectedItem.id : undefined
|
||||
const currentBuiltinToolID = selectedItem?.type === 'builtinTool' ? selectedItem.id : undefined
|
||||
const currentPluginDetail = useMemo(
|
||||
() => pluginListWithLatestVersion.find((plugin) => plugin.plugin_id === currentPluginID),
|
||||
[currentPluginID, pluginListWithLatestVersion],
|
||||
)
|
||||
const currentBuiltinTool = useMemo(() => {
|
||||
return filteredBuiltinTools.find((collection) => collection.id === currentBuiltinToolID)
|
||||
}, [currentBuiltinToolID, filteredBuiltinTools])
|
||||
|
||||
const handleDetailHide = () => setSelectedItem(undefined)
|
||||
const hasToolMarketplacePanel = marketplace !== null && isToolIntegrationPage
|
||||
const categoryMarketplace = marketplace && hasEmbeddedMarketplace ? fixedCategory : undefined
|
||||
const contentPaddingClassName = pluginPageContentInsetClassNames[contentInset]
|
||||
const contentFrameClassName = cn(
|
||||
pluginPageContentFrameClassNames[contentInset],
|
||||
contentPaddingClassName,
|
||||
)
|
||||
const scrollAreaLabel = isTriggerIntegrationPage
|
||||
? t(($) => $['categorySingle.trigger'], { ns: 'plugin' })
|
||||
: isAgentStrategyIntegrationPage
|
||||
? t(($) => $['categorySingle.agent'], { ns: 'plugin' })
|
||||
: isExtensionIntegrationPage
|
||||
? t(($) => $['categorySingle.extension'], { ns: 'plugin' })
|
||||
: isToolIntegrationPage
|
||||
? t(($) => $['categorySingle.tool'], { ns: 'plugin' })
|
||||
: undefined
|
||||
const resultTarget = isTriggerIntegrationPage
|
||||
? STEP_BY_STEP_TOUR_TARGETS.integrationTriggerGrid
|
||||
: isAgentStrategyIntegrationPage
|
||||
? STEP_BY_STEP_TOUR_TARGETS.integrationAgentStrategyEmpty
|
||||
: isExtensionIntegrationPage
|
||||
? STEP_BY_STEP_TOUR_TARGETS.integrationExtensionGrid
|
||||
: undefined
|
||||
|
||||
const toolbar = (
|
||||
<div
|
||||
className={cn(
|
||||
layout
|
||||
? 'flex w-full items-center bg-components-panel-bg'
|
||||
: [
|
||||
isIntegrationCategoryPage
|
||||
? 'flex h-12 shrink-0 items-center bg-components-panel-bg py-2'
|
||||
: 'sticky top-0 z-10 flex flex-col items-start justify-center gap-3 self-stretch bg-components-panel-bg pt-1 pb-3',
|
||||
contentFrameClassName,
|
||||
],
|
||||
)}
|
||||
>
|
||||
{!layout && !isIntegrationCategoryPage && (
|
||||
<div className="h-px self-stretch bg-divider-subtle"></div>
|
||||
)}
|
||||
<FilterManagement
|
||||
hideCategoryFilter={!!fixedCategory}
|
||||
hideTagFilter={!supportsTagFilter}
|
||||
onFilterChange={handleFilterChange}
|
||||
rightSlot={toolbarAction}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
const body = (
|
||||
<>
|
||||
{isPluginListLoading && <PluginListSkeleton contentFrameClassName={contentFrameClassName} />}
|
||||
{!isPluginListLoading && (
|
||||
<>
|
||||
{hasVisiblePlugins ||
|
||||
hasVisibleBuiltinTools ||
|
||||
hasToolMarketplacePanel ||
|
||||
hasEmbeddedMarketplace ? (
|
||||
<PluginsPanelResults
|
||||
autoLoadNextPage={isIntegrationCategoryPage}
|
||||
containerRef={containerRef}
|
||||
contentFrameClassName={contentFrameClassName}
|
||||
contentInset={contentInset}
|
||||
currentBuiltinToolID={currentBuiltinToolID}
|
||||
firstBuiltinToolTarget={
|
||||
isToolIntegrationPage
|
||||
? STEP_BY_STEP_TOUR_TARGETS.integrationToolPluginFirstCard
|
||||
: undefined
|
||||
}
|
||||
firstPluginTarget={
|
||||
isToolIntegrationPage
|
||||
? STEP_BY_STEP_TOUR_TARGETS.integrationToolPluginFirstCard
|
||||
: resultTarget
|
||||
}
|
||||
filteredBuiltinTools={filteredBuiltinTools}
|
||||
filteredList={filteredList}
|
||||
hasToolMarketplacePanel={hasToolMarketplacePanel}
|
||||
marketplace={marketplace}
|
||||
hasVisibleBuiltinTools={hasVisibleBuiltinTools}
|
||||
hasVisiblePlugins={hasVisiblePlugins}
|
||||
hasEmbeddedMarketplace={hasEmbeddedMarketplace}
|
||||
isFetching={isFetching}
|
||||
isLastPage={isLastPage}
|
||||
keywords={filters.searchQuery}
|
||||
loadNextPage={loadNextPage}
|
||||
scrollAreaLabel={scrollAreaLabel}
|
||||
onSelectBuiltinTool={(id) => setSelectedItem({ type: 'builtinTool', id })}
|
||||
tagFilterValue={filters.tags}
|
||||
canDeletePlugin={canDeletePlugin}
|
||||
canUpdatePlugin={canUpdatePlugin}
|
||||
categoryEmptyState={hasEmbeddedMarketplace ? fixedCategory : undefined}
|
||||
categoryMarketplace={categoryMarketplace}
|
||||
showCategoryEmptyState={
|
||||
hasEmbeddedMarketplace &&
|
||||
!isFilteringCategory &&
|
||||
!hasVisiblePlugins &&
|
||||
!hasVisibleBuiltinTools
|
||||
}
|
||||
/>
|
||||
) : isIntegrationCategorySearchEmpty ? (
|
||||
<div className={cn('min-h-0 grow bg-components-panel-bg', contentFrameClassName)} />
|
||||
) : (
|
||||
<Empty
|
||||
canInstall={canInstall}
|
||||
contentInset={contentInset}
|
||||
onSwitchToMarketplace={onSwitchToMarketplace}
|
||||
installContextCategory={fixedCategory}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{layout ? (
|
||||
layout({ body, toolbar })
|
||||
) : (
|
||||
<>
|
||||
{toolbar}
|
||||
{body}
|
||||
</>
|
||||
)}
|
||||
<PluginDetailPanel
|
||||
detail={currentPluginDetail}
|
||||
onUpdate={() => {
|
||||
invalidateInstalledPluginList(fixedCategory)
|
||||
}}
|
||||
onHide={handleDetailHide}
|
||||
canDeletePlugin={canDeletePlugin}
|
||||
canUpdatePlugin={canUpdatePlugin}
|
||||
/>
|
||||
{currentBuiltinTool && !currentBuiltinTool.plugin_id && (
|
||||
<ProviderDetail
|
||||
collection={currentBuiltinTool}
|
||||
onHide={handleDetailHide}
|
||||
onRefreshData={invalidateInstalledPluginList}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginsPanel
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { PluginCategoryEnum } from '../types'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from '@/app/notifications'
|
||||
import {
|
||||
workspacePermissionKeysAtom,
|
||||
workspacePermissionKeysLoadingAtom,
|
||||
} from '@/context/permission-state'
|
||||
import {
|
||||
currentWorkspaceLoadingAtom,
|
||||
isCurrentWorkspaceManagerAtom,
|
||||
isCurrentWorkspaceOwnerAtom,
|
||||
} from '@/context/workspace-state'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { useMarketplace } from '@/features/marketplace/client'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
import {
|
||||
useInvalidateReferenceSettings,
|
||||
useMutationPluginPermissionSettings,
|
||||
useMutationReferenceSettings,
|
||||
usePluginAutoUpgradeSettings,
|
||||
usePluginPermissionSettings,
|
||||
} from '@/service/use-plugins'
|
||||
import { hasPermission } from '@/utils/permission'
|
||||
import { hasLegacyPluginPermissionAccess } from '../plugin-permissions'
|
||||
|
||||
const useCanSetPluginSettings = () => {
|
||||
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
|
||||
const { data: rbacEnabled } = useSuspenseQuery({
|
||||
...systemFeaturesQueryOptions(),
|
||||
select: (s) => s.rbac_enabled,
|
||||
})
|
||||
const canSetPluginPreferences = hasPermission(
|
||||
workspacePermissionKeys,
|
||||
'plugin.plugin_preferences',
|
||||
)
|
||||
|
||||
return {
|
||||
canSetPermissions: !rbacEnabled && canSetPluginPreferences,
|
||||
canSetPluginPreferences,
|
||||
}
|
||||
}
|
||||
|
||||
export const usePluginSettingsAccess = () => {
|
||||
const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)
|
||||
const isCurrentWorkspaceOwner = useAtomValue(isCurrentWorkspaceOwnerAtom)
|
||||
const isLoadingCurrentWorkspace = useAtomValue(currentWorkspaceLoadingAtom)
|
||||
const isLoadingWorkspacePermissionKeys = useAtomValue(workspacePermissionKeysLoadingAtom)
|
||||
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
|
||||
const { data: rbacEnabled } = useSuspenseQuery({
|
||||
...systemFeaturesQueryOptions(),
|
||||
select: (data) => data.rbac_enabled,
|
||||
})
|
||||
const { data: currentVersion } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.meta.currentVersion ?? '',
|
||||
})
|
||||
const { canSetPermissions, canSetPluginPreferences } = useCanSetPluginSettings()
|
||||
const permissionQuery = usePluginPermissionSettings()
|
||||
const { data: permissions } = permissionQuery
|
||||
const { mutate: setPluginPermissionSettings, isPending: isPermissionUpdatePending } =
|
||||
useMutationPluginPermissionSettings()
|
||||
const isAdminOrOwner = isCurrentWorkspaceManager || isCurrentWorkspaceOwner
|
||||
const legacyCanInstallPlugin = hasLegacyPluginPermissionAccess({
|
||||
isAdminOrOwner,
|
||||
permission: permissions?.install_permission,
|
||||
rbacEnabled,
|
||||
})
|
||||
const legacyCanDebugPlugin = hasLegacyPluginPermissionAccess({
|
||||
isAdminOrOwner,
|
||||
permission: permissions?.debug_permission,
|
||||
rbacEnabled,
|
||||
})
|
||||
const canInstallPlugin =
|
||||
hasPermission(workspacePermissionKeys, 'plugin.install') && legacyCanInstallPlugin
|
||||
const canUpdatePlugin =
|
||||
hasPermission(workspacePermissionKeys, 'plugin.install') && legacyCanInstallPlugin
|
||||
const canDeletePlugin =
|
||||
hasPermission(workspacePermissionKeys, 'plugin.delete') && legacyCanInstallPlugin
|
||||
const canDebugPlugin = rbacEnabled
|
||||
? hasPermission(workspacePermissionKeys, 'plugin.debug')
|
||||
: legacyCanDebugPlugin
|
||||
|
||||
return {
|
||||
permission: permissions,
|
||||
setPluginPermissionSettings,
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin,
|
||||
canDeletePlugin,
|
||||
canDebugPlugin,
|
||||
canSetPluginPreferences,
|
||||
canManagement: canInstallPlugin,
|
||||
canDebugger: canDebugPlugin,
|
||||
canSetPermissions,
|
||||
currentDifyVersion: currentVersion,
|
||||
isPermissionLoading:
|
||||
permissionQuery.isLoading ||
|
||||
permissionQuery.isFetching ||
|
||||
!!isLoadingCurrentWorkspace ||
|
||||
!!isLoadingWorkspacePermissionKeys,
|
||||
permissionError: permissionQuery.error,
|
||||
isPermissionUpdatePending,
|
||||
}
|
||||
}
|
||||
|
||||
const useReferenceSetting = (category: PluginCategoryEnum) => {
|
||||
const { t } = useTranslation(['common'])
|
||||
const permissionAccess = usePluginSettingsAccess()
|
||||
const autoUpgradeQuery = usePluginAutoUpgradeSettings(category)
|
||||
const data =
|
||||
permissionAccess.permission && autoUpgradeQuery.data?.auto_upgrade
|
||||
? {
|
||||
permission: permissionAccess.permission,
|
||||
auto_upgrade: autoUpgradeQuery.data.auto_upgrade,
|
||||
}
|
||||
: undefined
|
||||
const invalidateReferenceSettings = useInvalidateReferenceSettings()
|
||||
const { mutate: updateReferenceSetting, isPending: isUpdatePending } =
|
||||
useMutationReferenceSettings({
|
||||
category,
|
||||
currentReferenceSetting: data,
|
||||
onSuccess: () => {
|
||||
invalidateReferenceSettings()
|
||||
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
referenceSetting: data,
|
||||
setReferenceSettings: updateReferenceSetting,
|
||||
canManagement: permissionAccess.canManagement,
|
||||
canDebugger: permissionAccess.canDebugger,
|
||||
canInstallPlugin: permissionAccess.canInstallPlugin,
|
||||
canUpdatePlugin: permissionAccess.canUpdatePlugin,
|
||||
canDeletePlugin: permissionAccess.canDeletePlugin,
|
||||
canDebugPlugin: permissionAccess.canDebugPlugin,
|
||||
canSetPermissions: permissionAccess.canSetPermissions,
|
||||
canSetPluginPreferences: permissionAccess.canSetPluginPreferences,
|
||||
currentDifyVersion: permissionAccess.currentDifyVersion,
|
||||
isPermissionLoading: permissionAccess.isPermissionLoading,
|
||||
permissionError: permissionAccess.permissionError,
|
||||
isReferenceSettingLoading: autoUpgradeQuery.isLoading || autoUpgradeQuery.isFetching,
|
||||
referenceSettingError: autoUpgradeQuery.error,
|
||||
isUpdatePending,
|
||||
}
|
||||
}
|
||||
|
||||
export const useCanInstallPluginFromMarketplace = () => {
|
||||
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
|
||||
const marketplaceAccess = useMarketplace() !== null
|
||||
const rbacEnabled = systemFeatures.rbac_enabled
|
||||
const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)
|
||||
const isCurrentWorkspaceOwner = useAtomValue(isCurrentWorkspaceOwnerAtom)
|
||||
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
|
||||
const permissionQuery = usePluginPermissionSettings()
|
||||
const { data: permissions } = permissionQuery
|
||||
const legacyCanInstallPlugin = hasLegacyPluginPermissionAccess({
|
||||
isAdminOrOwner: isCurrentWorkspaceManager || isCurrentWorkspaceOwner,
|
||||
permission: permissions?.install_permission,
|
||||
rbacEnabled,
|
||||
})
|
||||
const canInstallPlugin =
|
||||
hasPermission(workspacePermissionKeys, 'plugin.install') && legacyCanInstallPlugin
|
||||
|
||||
const canInstallPluginFromMarketplace = useMemo(() => {
|
||||
return Boolean(marketplaceAccess && canInstallPlugin)
|
||||
}, [marketplaceAccess, canInstallPlugin])
|
||||
|
||||
return {
|
||||
canInstallPluginFromMarketplace,
|
||||
}
|
||||
}
|
||||
|
||||
export default useReferenceSetting
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { RefObject } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
type UploaderHookProps = {
|
||||
onFileChange: (file: File | null) => void
|
||||
containerRef: RefObject<HTMLDivElement | null>
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export const useUploader = ({ onFileChange, containerRef, enabled = true }: UploaderHookProps) => {
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const fileUploader = useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleDragEnter = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.dataTransfer?.types.includes('Files')) setDragging(true)
|
||||
}
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.relatedTarget === null || !containerRef.current?.contains(e.relatedTarget as Node))
|
||||
setDragging(false)
|
||||
}
|
||||
|
||||
const handleDrop = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setDragging(false)
|
||||
if (!e.dataTransfer) return
|
||||
const files = Array.from(e.dataTransfer.files)
|
||||
if (files.length > 0) onFileChange(files[0]!)
|
||||
}
|
||||
|
||||
const fileChangeHandle = enabled
|
||||
? (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0] || null
|
||||
onFileChange(file)
|
||||
}
|
||||
: null
|
||||
|
||||
const removeFile = enabled
|
||||
? () => {
|
||||
if (fileUploader.current) fileUploader.current.value = ''
|
||||
|
||||
onFileChange(null)
|
||||
}
|
||||
: null
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
|
||||
const current = containerRef.current
|
||||
if (current) {
|
||||
current.addEventListener('dragenter', handleDragEnter)
|
||||
current.addEventListener('dragover', handleDragOver)
|
||||
current.addEventListener('dragleave', handleDragLeave)
|
||||
current.addEventListener('drop', handleDrop)
|
||||
}
|
||||
return () => {
|
||||
if (current) {
|
||||
current.removeEventListener('dragenter', handleDragEnter)
|
||||
current.removeEventListener('dragover', handleDragOver)
|
||||
current.removeEventListener('dragleave', handleDragLeave)
|
||||
current.removeEventListener('drop', handleDrop)
|
||||
}
|
||||
}
|
||||
}, [containerRef, enabled])
|
||||
|
||||
return {
|
||||
dragging: enabled ? dragging : false,
|
||||
fileUploader,
|
||||
fileChangeHandle,
|
||||
removeFile,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user