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
+400
@@ -0,0 +1,400 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import { act, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createHttpError } from '@/service/http-error'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import InstallFromGitHub from '../index'
|
||||
|
||||
const { fetchReleases, upload, install, pollTask, refresh, notify, installed, upgrade } =
|
||||
vi.hoisted(() => ({
|
||||
installed: vi.fn(),
|
||||
upgrade: vi.fn(),
|
||||
fetchReleases: vi.fn(),
|
||||
upload: vi.fn(),
|
||||
install: vi.fn(),
|
||||
pollTask: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
uploadGitHub: upload,
|
||||
updateFromGitHub: upgrade,
|
||||
checkTaskStatus: pollTask,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleClientResponses, withConsoleResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': installed,
|
||||
}),
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
'workspaces.current.plugin.install.github.post': install,
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Refreshing the separate model/tool catalogs is covered by use-refresh-plugin-list.
|
||||
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: refresh }),
|
||||
}))
|
||||
vi.mock('@/app/notifications', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/app/notifications')>()
|
||||
return { ...actual, toast: Object.assign(vi.fn(), actual.toast, { error: notify }) }
|
||||
})
|
||||
|
||||
const manifest = createPluginDeclarationFixture({ name: 'github' })
|
||||
const uploadedPackage = { unique_identifier: 'test/github:1.0.0', manifest }
|
||||
const releases = [
|
||||
{
|
||||
tag: 'v1.0.0',
|
||||
assets: [
|
||||
{ downloadUrl: 'https://github.com/owner/repo/releases/download/v1.0.0/plugin.difypkg' },
|
||||
],
|
||||
},
|
||||
{
|
||||
tag: 'v0.9.0',
|
||||
assets: [{ downloadUrl: 'https://github.com/owner/repo/releases/download/v0.9.0/old.difypkg' }],
|
||||
},
|
||||
]
|
||||
const renderInstaller = (props: Partial<ComponentProps<typeof InstallFromGitHub>> = {}) => {
|
||||
const onSuccess = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
renderWithConsoleQuery(<InstallFromGitHub onSuccess={onSuccess} onClose={onClose} {...props} />)
|
||||
return { onSuccess, onClose }
|
||||
}
|
||||
const nextButton = () => screen.getByRole('button', { name: 'plugin.installModal.next' })
|
||||
const versionSelect = () =>
|
||||
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
|
||||
const packageSelect = () =>
|
||||
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' })
|
||||
const submitRepo = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
|
||||
'https://github.com/owner/repo',
|
||||
)
|
||||
await user.keyboard('{Enter}')
|
||||
await screen.findByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
|
||||
}
|
||||
const selectPackage = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await user.click(versionSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'v1.0.0' }))
|
||||
await user.click(packageSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'plugin.difypkg' }))
|
||||
}
|
||||
const loadPackage = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
await user.click(nextButton())
|
||||
return await screen.findByRole('button', { name: 'plugin.installModal.install' })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
installed.mockResolvedValue({ plugins: [] })
|
||||
upgrade.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
vi.stubGlobal('fetch', fetchReleases)
|
||||
fetchReleases.mockImplementation(async () => Response.json({ releases }))
|
||||
upload.mockResolvedValue(uploadedPackage)
|
||||
install.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
})
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('submits the URL with Enter, installs the selected release, and waits for asynchronous completion handling', async () => {
|
||||
const user = userEvent.setup()
|
||||
const success = createDeferred<void>()
|
||||
const onSuccess = vi.fn(() => success.promise)
|
||||
const { onClose } = renderInstaller({ onSuccess })
|
||||
const input = screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' })
|
||||
await waitFor(() => expect(input).toHaveFocus())
|
||||
expect(nextButton()).toBeDisabled()
|
||||
const button = await loadPackage(user)
|
||||
expect(fetchReleases).toHaveBeenCalledExactlyOnceWith('https://ungh.cc/repos/owner/repo/releases')
|
||||
expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
|
||||
silent: true,
|
||||
})
|
||||
await user.click(button)
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce())
|
||||
const pendingButton = screen.getByRole('button', { name: 'plugin.installModal.installing' })
|
||||
await user.click(pendingButton)
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: {
|
||||
repo: 'owner/repo',
|
||||
version: 'v1.0.0',
|
||||
package: 'plugin.difypkg',
|
||||
plugin_unique_identifier: 'test/github:1.0.0',
|
||||
},
|
||||
})
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' }),
|
||||
).not.toBeInTheDocument()
|
||||
success.resolve()
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
expect(screen.getByText('Test Plugin')).toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.installFromGitHub.installNote')).not.toBeInTheDocument()
|
||||
expect(refresh).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({
|
||||
name: 'github',
|
||||
icon: expect.stringContaining('filename=test-icon.png'),
|
||||
}),
|
||||
)
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps URL and selections when navigating back through the real steps', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInstaller()
|
||||
await loadPackage(user)
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.installModal.back' }))
|
||||
expect(versionSelect()).toHaveTextContent('v1.0.0')
|
||||
expect(packageSelect()).toHaveTextContent('plugin.difypkg')
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.installModal.back' }))
|
||||
expect(screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' })).toHaveValue(
|
||||
'https://github.com/owner/repo',
|
||||
)
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('derives the package options from the selected release and blocks upload before selection', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInstaller()
|
||||
await submitRepo(user)
|
||||
expect(packageSelect()).toBeDisabled()
|
||||
expect(nextButton()).toBeDisabled()
|
||||
await user.click(versionSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'v0.9.0' }))
|
||||
await user.click(packageSelect())
|
||||
expect(await screen.findByRole('option', { name: 'old.difypkg' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('option', { name: 'plugin.difypkg' })).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(nextButton()).toBeDisabled()
|
||||
expect(upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks a release without assets from proceeding to upload', async () => {
|
||||
const user = userEvent.setup()
|
||||
fetchReleases.mockImplementation(async () =>
|
||||
Response.json({ releases: [{ tag: 'v1.0.0', assets: [] }] }),
|
||||
)
|
||||
renderInstaller()
|
||||
await submitRepo(user)
|
||||
await user.click(versionSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'v1.0.0' }))
|
||||
await user.click(packageSelect())
|
||||
expect(screen.queryByRole('option')).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(nextButton()).toBeDisabled()
|
||||
expect(upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an invalid URL before fetching releases', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInstaller()
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
|
||||
'invalid-url',
|
||||
)
|
||||
await user.click(nextButton())
|
||||
expect(notify).toHaveBeenCalledWith('plugin.error.inValidGitHubUrl')
|
||||
expect(fetchReleases).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each(['empty', 'error'])(
|
||||
'allows retrying release lookup after an %s response',
|
||||
async (response) => {
|
||||
const user = userEvent.setup()
|
||||
if (response === 'empty') fetchReleases.mockResolvedValueOnce(Response.json({ releases: [] }))
|
||||
else fetchReleases.mockRejectedValueOnce(new Error('Release service unavailable'))
|
||||
renderInstaller()
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
|
||||
'https://github.com/owner/repo',
|
||||
)
|
||||
await user.click(nextButton())
|
||||
await waitFor(() =>
|
||||
expect(notify).toHaveBeenCalledExactlyOnceWith(
|
||||
response === 'empty' ? 'plugin.error.noReleasesFound' : 'plugin.error.fetchReleasesError',
|
||||
),
|
||||
)
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
|
||||
await user.click(nextButton())
|
||||
await screen.findByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
|
||||
expect(fetchReleases).toHaveBeenCalledTimes(2)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
[new Error('Package download failed'), 'Package download failed'],
|
||||
[
|
||||
createHttpError(new Response(null, { status: 500 }), { message: 'Package rejected' }),
|
||||
'Package rejected',
|
||||
],
|
||||
['Unexpected server response', 'plugin.installFromGitHub.uploadFailed'],
|
||||
])('shows upload failure %s without starting installation', async (error, message) => {
|
||||
const user = userEvent.setup()
|
||||
upload.mockRejectedValue(error)
|
||||
const { onSuccess, onClose } = renderInstaller()
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
await user.click(nextButton())
|
||||
await screen.findByText(message)
|
||||
expect(notify).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each([TaskStatus.success, TaskStatus.failed])(
|
||||
'shows the asynchronous install result: %s',
|
||||
async (status) => {
|
||||
const user = userEvent.setup()
|
||||
install.mockResolvedValue({ all_installed: false, task_id: 'github-task' })
|
||||
pollTask.mockResolvedValue({
|
||||
task: {
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: 'test/github:1.0.0',
|
||||
status,
|
||||
message: 'Plugin initialization failed',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
const { onSuccess } = renderInstaller()
|
||||
await user.click(await loadPackage(user))
|
||||
await screen.findByRole('dialog', {
|
||||
name:
|
||||
status === TaskStatus.success
|
||||
? 'plugin.installFromGitHub.installedSuccessfully'
|
||||
: 'plugin.installFromGitHub.installFailed',
|
||||
})
|
||||
expect(pollTask).toHaveBeenCalledExactlyOnceWith('github-task')
|
||||
if (status === TaskStatus.failed) {
|
||||
expect(screen.getByText('Plugin initialization failed')).toBeInTheDocument()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
} else expect(onSuccess).toHaveBeenCalledOnce()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
[new Error('Connection failed'), 'plugin.installModal.installFailedDesc'],
|
||||
['Server install error', 'Server install error'],
|
||||
])('shows the install failure for %s', async (error, message) => {
|
||||
const user = userEvent.setup()
|
||||
install.mockRejectedValue(error)
|
||||
const { onSuccess } = renderInstaller()
|
||||
await user.click(await loadPackage(user))
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installFailed' })
|
||||
expect(screen.getByText(message)).toBeInTheDocument()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['plugin.installModal.cancel', 'common.operation.close'])(
|
||||
'allows %s before selecting a repository',
|
||||
async (name) => {
|
||||
const user = userEvent.setup()
|
||||
const { onClose } = renderInstaller()
|
||||
await user.click(screen.getByRole('button', { name }))
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(fetchReleases).not.toHaveBeenCalled()
|
||||
expect(upload).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('blocks repeated upload and backward navigation until the selected package finishes loading', async () => {
|
||||
const user = userEvent.setup()
|
||||
const pending = createDeferred<typeof uploadedPackage>()
|
||||
upload.mockReturnValueOnce(pending.promise)
|
||||
renderInstaller()
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
const next = nextButton()
|
||||
await user.click(next)
|
||||
expect(next).toBeDisabled()
|
||||
const back = screen.getByRole('button', { name: 'plugin.installModal.back' })
|
||||
expect(back).toBeDisabled()
|
||||
await user.click(next)
|
||||
await user.click(back)
|
||||
expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
|
||||
silent: true,
|
||||
})
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).not.toBeInTheDocument()
|
||||
pending.resolve(uploadedPackage)
|
||||
expect(
|
||||
await screen.findByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).toBeInTheDocument()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('waits for the installed version before upgrading the package selected from GitHub', async () => {
|
||||
const user = userEvent.setup()
|
||||
const existing = createPluginEntity({
|
||||
plugin_id: 'test/github',
|
||||
plugin_unique_identifier: 'test/github:0.9.0',
|
||||
})
|
||||
existing.declaration.version = '0.9.0'
|
||||
const lookup = createDeferred<{ plugins: ReturnType<typeof createPluginEntity>[] }>()
|
||||
installed.mockReturnValueOnce(lookup.promise)
|
||||
upload.mockResolvedValueOnce({
|
||||
...uploadedPackage,
|
||||
manifest: { ...manifest, plugin_id: 'test/github' },
|
||||
})
|
||||
const { onSuccess } = renderInstaller()
|
||||
const button = await loadPackage(user)
|
||||
expect(button).toBeDisabled()
|
||||
await user.click(button)
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
expect(upgrade).not.toHaveBeenCalled()
|
||||
await act(async () => lookup.resolve({ plugins: [existing] }))
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
expect(screen.getByText('0.9.0 -> 1.0.0')).toBeInTheDocument()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
await user.click(button)
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
expect(upgrade).toHaveBeenCalledExactlyOnceWith(
|
||||
'owner/repo',
|
||||
'v1.0.0',
|
||||
'plugin.difypkg',
|
||||
'test/github:0.9.0',
|
||||
'test/github:1.0.0',
|
||||
)
|
||||
expect(onSuccess).toHaveBeenCalledOnce()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('finishes without an install or upgrade when the selected GitHub package is already installed', async () => {
|
||||
const user = userEvent.setup()
|
||||
installed.mockResolvedValueOnce({
|
||||
plugins: [
|
||||
createPluginEntity({
|
||||
plugin_id: 'test/github',
|
||||
plugin_unique_identifier: uploadedPackage.unique_identifier,
|
||||
}),
|
||||
],
|
||||
})
|
||||
upload.mockResolvedValueOnce({
|
||||
...uploadedPackage,
|
||||
manifest: { ...manifest, plugin_id: 'test/github' },
|
||||
})
|
||||
const { onSuccess } = renderInstaller()
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
await user.click(nextButton())
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
expect(onSuccess).toHaveBeenCalledOnce()
|
||||
expect(upgrade).not.toHaveBeenCalled()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { UpdateFromGitHubPayload } from '../../../types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
|
||||
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
|
||||
import InstallFromGitHub from '../index'
|
||||
|
||||
const { uploadGitHub, updateFromGitHub } = vi.hoisted(() => ({
|
||||
uploadGitHub: vi.fn(),
|
||||
updateFromGitHub: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
uploadGitHub,
|
||||
updateFromGitHub,
|
||||
}))
|
||||
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': async () => ({ tasks: [] }),
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Model/tool catalog refresh is covered by its own hook tests.
|
||||
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: vi.fn() }),
|
||||
}))
|
||||
|
||||
const github: UpdateFromGitHubPayload = {
|
||||
originalPackageInfo: {
|
||||
id: 'github-original-id',
|
||||
repo: 'owner/repo',
|
||||
version: 'v1.0.0',
|
||||
package: 'plugin.difypkg',
|
||||
releases: [
|
||||
{
|
||||
tag_name: 'v1.0.0',
|
||||
assets: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'plugin.difypkg',
|
||||
browser_download_url:
|
||||
'https://github.com/owner/repo/releases/download/v1.0.0/plugin.difypkg',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tag_name: 'v2.0.0',
|
||||
assets: [
|
||||
{
|
||||
id: 2,
|
||||
name: 'plugin.difypkg',
|
||||
browser_download_url:
|
||||
'https://github.com/owner/repo/releases/download/v2.0.0/plugin.difypkg',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
beforeEach(() => vi.resetAllMocks())
|
||||
|
||||
it('updates a GitHub plugin using the selected release and the existing installation identifier', async () => {
|
||||
const user = userEvent.setup()
|
||||
uploadGitHub.mockResolvedValueOnce({
|
||||
unique_identifier: 'github-target-id',
|
||||
manifest: createPluginDeclarationFixture({ version: '2.0.0' }),
|
||||
})
|
||||
updateFromGitHub.mockResolvedValueOnce({ all_installed: true, task_id: '' })
|
||||
const onSave = vi.fn()
|
||||
const onCancel = vi.fn()
|
||||
render(<InstallFromGitHub updatePayload={github} onSuccess={onSave} onClose={onCancel} />)
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }))
|
||||
expect(await screen.findByRole('option', { name: /v1\.0\.0.*INSTALLED/ })).toBeInTheDocument()
|
||||
await user.click(await screen.findByRole('option', { name: 'v2.0.0' }))
|
||||
expect(
|
||||
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }),
|
||||
).toHaveTextContent('v1.0.0 -> v2.0.0')
|
||||
expect(screen.queryByRole('button', { name: 'plugin.installModal.back' })).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'plugin.difypkg' }))
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
|
||||
const install = await screen.findByRole('button', { name: 'plugin.installModal.install' })
|
||||
expect(uploadGitHub).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v2.0.0', 'plugin.difypkg', {
|
||||
silent: true,
|
||||
})
|
||||
await user.click(install)
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
|
||||
expect(updateFromGitHub).toHaveBeenCalledExactlyOnceWith(
|
||||
'owner/repo',
|
||||
'v2.0.0',
|
||||
'plugin.difypkg',
|
||||
'github-original-id',
|
||||
'github-target-id',
|
||||
)
|
||||
expect(onSave).toHaveBeenCalledOnce()
|
||||
expect(onCancel).not.toHaveBeenCalled()
|
||||
})
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
'use client'
|
||||
import type { PluginCategoryEnum, PluginDeclaration, UpdateFromGitHubPayload } from '../../types'
|
||||
import type { InstallState } from '@/app/components/plugins/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Dialog,
|
||||
DialogBody,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
|
||||
import { Form } from '@langgenius/dify-ui/form'
|
||||
import { Input } from '@langgenius/dify-ui/input'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { InstallStepFromGitHub } from '../../types'
|
||||
import Installed from '../base/installed'
|
||||
import { fetchReleases } from '../hooks'
|
||||
import useHideLogic from '../hooks/use-hide-logic'
|
||||
import useRefreshPluginList from '../hooks/use-refresh-plugin-list'
|
||||
import { convertRepoToUrl, parseGitHubUrl } from '../utils'
|
||||
import Loaded from './steps/loaded'
|
||||
import SelectPackage from './steps/selectPackage'
|
||||
|
||||
const i18nPrefix = 'installFromGitHub'
|
||||
|
||||
type SelectOption = {
|
||||
value: string
|
||||
name: string
|
||||
}
|
||||
|
||||
type InstallFromGitHubProps = {
|
||||
updatePayload?: UpdateFromGitHubPayload
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
onClose: () => void
|
||||
onSuccess: () => void | Promise<void>
|
||||
}
|
||||
|
||||
const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({
|
||||
updatePayload,
|
||||
installContextCategory,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}) => {
|
||||
const repoUrlInputRef = useRef<HTMLInputElement>(null)
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const { getIconUrl } = useGetIcon()
|
||||
const { refreshPluginList } = useRefreshPluginList()
|
||||
|
||||
const { modalClassName, foldAnimInto, setIsInstalling, handleStartToInstall } =
|
||||
useHideLogic(onClose)
|
||||
|
||||
const [state, setState] = useState<InstallState>({
|
||||
step: updatePayload ? InstallStepFromGitHub.selectPackage : InstallStepFromGitHub.setUrl,
|
||||
repoUrl: updatePayload?.originalPackageInfo?.repo
|
||||
? convertRepoToUrl(updatePayload.originalPackageInfo.repo)
|
||||
: '',
|
||||
selectedVersion: '',
|
||||
selectedPackage: '',
|
||||
releases: updatePayload ? updatePayload.originalPackageInfo.releases : [],
|
||||
})
|
||||
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
|
||||
const [manifest, setManifest] = useState<PluginDeclaration | null>(null)
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
||||
|
||||
const versions: SelectOption[] = state.releases.map((release) => ({
|
||||
value: release.tag_name,
|
||||
name: release.tag_name,
|
||||
}))
|
||||
|
||||
const packages: SelectOption[] = state.selectedVersion
|
||||
? state.releases
|
||||
.find((release) => release.tag_name === state.selectedVersion)
|
||||
?.assets.map((asset) => ({
|
||||
value: asset.name,
|
||||
name: asset.name,
|
||||
})) || []
|
||||
: []
|
||||
|
||||
const getTitle = useCallback(() => {
|
||||
if (state.step === InstallStepFromGitHub.installed)
|
||||
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
|
||||
if (state.step === InstallStepFromGitHub.installFailed)
|
||||
return t(($) => $[`${i18nPrefix}.installFailed`], { ns: 'plugin' })
|
||||
|
||||
return updatePayload
|
||||
? t(($) => $[`${i18nPrefix}.updatePlugin`], { ns: 'plugin' })
|
||||
: t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
|
||||
}, [state.step, t, updatePayload])
|
||||
|
||||
const handleUrlSubmit = async () => {
|
||||
const { isValid, owner, repo } = parseGitHubUrl(state.repoUrl)
|
||||
if (!isValid || !owner || !repo) {
|
||||
toast.error(t(($) => $['error.inValidGitHubUrl'], { ns: 'plugin' }))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const fetchedReleases = await fetchReleases(owner, repo)
|
||||
if (fetchedReleases.length > 0) {
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
releases: fetchedReleases,
|
||||
step: InstallStepFromGitHub.selectPackage,
|
||||
}))
|
||||
} else {
|
||||
toast.error(t(($) => $['error.noReleasesFound'], { ns: 'plugin' }))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t(($) => $['error.fetchReleasesError'], { ns: 'plugin' }))
|
||||
}
|
||||
}
|
||||
|
||||
const handleError = (e: any, isInstall: boolean) => {
|
||||
const message =
|
||||
(e instanceof Error ? e.message : undefined) ||
|
||||
t(($) => $['installModal.installFailedDesc'], { ns: 'plugin' })
|
||||
setErrorMsg(message)
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
step: isInstall ? InstallStepFromGitHub.installFailed : InstallStepFromGitHub.uploadFailed,
|
||||
}))
|
||||
}
|
||||
|
||||
const handleUploaded = async (GitHubPackage: any) => {
|
||||
try {
|
||||
const icon = await getIconUrl(GitHubPackage.manifest.icon)
|
||||
setManifest({
|
||||
...GitHubPackage.manifest,
|
||||
icon,
|
||||
})
|
||||
setUniqueIdentifier(GitHubPackage.uniqueIdentifier)
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.readyToInstall }))
|
||||
} catch (e) {
|
||||
handleError(e, false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadFail = useCallback((errorMsg: string) => {
|
||||
setErrorMsg(errorMsg)
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.uploadFailed }))
|
||||
}, [])
|
||||
|
||||
const handleInstalled = useCallback(
|
||||
async (notRefresh?: boolean) => {
|
||||
if (!notRefresh) refreshPluginList(manifest)
|
||||
await onSuccess()
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installed }))
|
||||
setIsInstalling(false)
|
||||
},
|
||||
[manifest, onSuccess, refreshPluginList, setIsInstalling],
|
||||
)
|
||||
|
||||
const handleFailed = useCallback(
|
||||
(errorMsg?: string) => {
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installFailed }))
|
||||
setIsInstalling(false)
|
||||
if (errorMsg) setErrorMsg(errorMsg)
|
||||
},
|
||||
[setIsInstalling],
|
||||
)
|
||||
|
||||
const handleBack = () => {
|
||||
setState((prevState) => {
|
||||
switch (prevState.step) {
|
||||
case InstallStepFromGitHub.selectPackage:
|
||||
return { ...prevState, step: InstallStepFromGitHub.setUrl }
|
||||
case InstallStepFromGitHub.readyToInstall:
|
||||
return { ...prevState, step: InstallStepFromGitHub.selectPackage }
|
||||
default:
|
||||
return prevState
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const completedSteps: InstallStepFromGitHub[] = [
|
||||
InstallStepFromGitHub.uploadFailed,
|
||||
InstallStepFromGitHub.installed,
|
||||
InstallStepFromGitHub.installFailed,
|
||||
]
|
||||
const failedSteps: InstallStepFromGitHub[] = [
|
||||
InstallStepFromGitHub.uploadFailed,
|
||||
InstallStepFromGitHub.installFailed,
|
||||
]
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) foldAnimInto()
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
initialFocus={repoUrlInputRef}
|
||||
backdropProps={{ forceRender: true }}
|
||||
className={cn('w-140', modalClassName, 'max-h-[calc(100dvh-48px)]')}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{getTitle()}</DialogTitle>
|
||||
{!completedSteps.includes(state.step) && (
|
||||
<DialogDescription>
|
||||
{t(($) => $['installFromGitHub.installNote'], { ns: 'plugin' })}
|
||||
</DialogDescription>
|
||||
)}
|
||||
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
|
||||
</DialogHeader>
|
||||
{completedSteps.includes(state.step) ? (
|
||||
<Installed
|
||||
payload={manifest}
|
||||
isFailed={failedSteps.includes(state.step)}
|
||||
errMsg={errorMsg}
|
||||
installContextCategory={installContextCategory}
|
||||
onCancel={onClose}
|
||||
/>
|
||||
) : state.step === InstallStepFromGitHub.setUrl ? (
|
||||
<Form className="contents" onFormSubmit={handleUrlSubmit}>
|
||||
<DialogBody>
|
||||
<Field name="repoUrl" className="gap-4">
|
||||
<FieldLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
|
||||
<span className="system-sm-semibold">
|
||||
{t(($) => $['installFromGitHub.gitHubRepo'], { ns: 'plugin' })}
|
||||
</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
ref={repoUrlInputRef}
|
||||
type="text"
|
||||
inputMode="url"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={state.repoUrl}
|
||||
onValueChange={(value) =>
|
||||
setState((prevState) => ({ ...prevState, repoUrl: value }))
|
||||
}
|
||||
className="flex grow items-center gap-0.5 self-stretch overflow-hidden rounded-lg border-components-input-border-active bg-components-input-bg-active p-2 text-ellipsis"
|
||||
placeholder="Please enter GitHub repo URL"
|
||||
/>
|
||||
</Field>
|
||||
</DialogBody>
|
||||
<DialogFooter>
|
||||
<Button variant="secondary" className="min-w-18" onClick={onClose}>
|
||||
{t(($) => $['installModal.cancel'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
type="submit"
|
||||
className="min-w-18"
|
||||
disabled={!state.repoUrl.trim()}
|
||||
>
|
||||
{t(($) => $['installModal.next'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
) : (
|
||||
<DialogBody className="flex flex-col items-start gap-4">
|
||||
{state.step === InstallStepFromGitHub.selectPackage && (
|
||||
<SelectPackage
|
||||
updatePayload={updatePayload!}
|
||||
repoUrl={state.repoUrl}
|
||||
selectedVersion={state.selectedVersion}
|
||||
versions={versions}
|
||||
onSelectVersion={(item) =>
|
||||
setState((prevState) => ({ ...prevState, selectedVersion: String(item.value) }))
|
||||
}
|
||||
selectedPackage={state.selectedPackage}
|
||||
packages={packages}
|
||||
onSelectPackage={(item) =>
|
||||
setState((prevState) => ({ ...prevState, selectedPackage: String(item.value) }))
|
||||
}
|
||||
onUploaded={handleUploaded}
|
||||
onFailed={handleUploadFail}
|
||||
onBack={handleBack}
|
||||
/>
|
||||
)}
|
||||
{state.step === InstallStepFromGitHub.readyToInstall &&
|
||||
manifest &&
|
||||
uniqueIdentifier && (
|
||||
<Loaded
|
||||
updatePayload={updatePayload!}
|
||||
uniqueIdentifier={uniqueIdentifier}
|
||||
payload={manifest}
|
||||
repoUrl={state.repoUrl}
|
||||
selectedVersion={state.selectedVersion}
|
||||
selectedPackage={state.selectedPackage}
|
||||
onBack={handleBack}
|
||||
onStartToInstall={handleStartToInstall}
|
||||
onInstalled={handleInstalled}
|
||||
onFailed={handleFailed}
|
||||
/>
|
||||
)}
|
||||
</DialogBody>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default InstallFromGitHub
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
'use client'
|
||||
|
||||
import type { Plugin, PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import * as React from 'react'
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
|
||||
import { updateFromGitHub } from '@/service/plugins'
|
||||
import { useInstallPackageFromGitHub, usePluginTaskList } from '@/service/use-plugins'
|
||||
import Card from '../../../card'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import checkTaskStatus from '../../base/check-task-status'
|
||||
import Version from '../../base/version'
|
||||
import { parseGitHubUrl, pluginManifestToCardPluginProps } from '../../utils'
|
||||
|
||||
type LoadedProps = {
|
||||
updatePayload?: UpdateFromGitHubPayload
|
||||
uniqueIdentifier: string
|
||||
payload: PluginDeclaration | Plugin
|
||||
repoUrl: string
|
||||
selectedVersion: string
|
||||
selectedPackage: string
|
||||
onBack: () => void
|
||||
onStartToInstall?: () => void
|
||||
onInstalled: (notRefresh?: boolean) => void | Promise<void>
|
||||
onFailed: (message?: string) => void
|
||||
}
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
const Loaded: React.FC<LoadedProps> = ({
|
||||
updatePayload,
|
||||
uniqueIdentifier,
|
||||
payload,
|
||||
repoUrl,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
onBack,
|
||||
onStartToInstall,
|
||||
onInstalled,
|
||||
onFailed,
|
||||
}) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const installButtonLabelId = React.useId()
|
||||
const toInstallVersion = payload.version
|
||||
const pluginId = (payload as Plugin).plugin_id
|
||||
const { installedInfo, isLoading } = useCheckInstalled({
|
||||
pluginIds: [pluginId],
|
||||
enabled: !!pluginId,
|
||||
})
|
||||
const installedInfoPayload = installedInfo?.[pluginId]
|
||||
const installedVersion = installedInfoPayload?.installedVersion
|
||||
const hasInstalled = !!installedVersion
|
||||
|
||||
const [isInstalling, setIsInstalling] = React.useState(false)
|
||||
const { mutateAsync: installPackageFromGitHub } = useInstallPackageFromGitHub()
|
||||
const { handleInstallTaskStart } = usePluginTaskList(payload.category)
|
||||
const { check } = checkTaskStatus()
|
||||
|
||||
useEffect(() => {
|
||||
if (hasInstalled && uniqueIdentifier === installedInfoPayload.uniqueIdentifier) onInstalled()
|
||||
}, [hasInstalled])
|
||||
|
||||
const handleInstall = async () => {
|
||||
if (isInstalling) return
|
||||
setIsInstalling(true)
|
||||
onStartToInstall?.()
|
||||
|
||||
try {
|
||||
const { owner, repo } = parseGitHubUrl(repoUrl)
|
||||
let taskId
|
||||
let isInstalled
|
||||
if (updatePayload) {
|
||||
const response = await updateFromGitHub(
|
||||
`${owner}/${repo}`,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
updatePayload.originalPackageInfo.id,
|
||||
uniqueIdentifier,
|
||||
)
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
} else {
|
||||
if (hasInstalled) {
|
||||
const response = await updateFromGitHub(
|
||||
`${owner}/${repo}`,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
installedInfoPayload.uniqueIdentifier,
|
||||
uniqueIdentifier,
|
||||
)
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
} else {
|
||||
const response = await installPackageFromGitHub({
|
||||
repoUrl: `${owner}/${repo}`,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
uniqueIdentifier,
|
||||
})
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
}
|
||||
}
|
||||
if (isInstalled) {
|
||||
await onInstalled()
|
||||
return
|
||||
}
|
||||
|
||||
const { status, error } = await check({
|
||||
taskId,
|
||||
pluginUniqueIdentifier: uniqueIdentifier,
|
||||
})
|
||||
if (status === TaskStatus.failed) {
|
||||
onFailed(error)
|
||||
return
|
||||
}
|
||||
await onInstalled(true)
|
||||
} catch (e) {
|
||||
if (typeof e === 'string') {
|
||||
onFailed(e)
|
||||
return
|
||||
}
|
||||
onFailed()
|
||||
} finally {
|
||||
setIsInstalling(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="system-md-regular text-text-secondary">
|
||||
<p>{t(($) => $[`${i18nPrefix}.readyToInstall`], { ns: 'plugin' })}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
|
||||
<Card
|
||||
className="w-full"
|
||||
payload={pluginManifestToCardPluginProps(payload as PluginDeclaration)}
|
||||
titleLeft={
|
||||
!isLoading && (
|
||||
<Version
|
||||
hasInstalled={hasInstalled}
|
||||
installedVersion={installedVersion}
|
||||
toInstallVersion={toInstallVersion}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-end gap-2 self-stretch">
|
||||
{!isInstalling && (
|
||||
<Button variant="secondary" className="min-w-18" onClick={onBack}>
|
||||
{t(($) => $['installModal.back'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="min-w-18"
|
||||
onClick={handleInstall}
|
||||
disabled={isLoading}
|
||||
loading={isInstalling}
|
||||
aria-labelledby={installButtonLabelId}
|
||||
>
|
||||
<span id={installButtonLabelId}>
|
||||
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
|
||||
ns: 'plugin',
|
||||
})}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Loaded
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
'use client'
|
||||
|
||||
import type { PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Field } from '@langgenius/dify-ui/field'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectItemIndicator,
|
||||
SelectItemText,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
} from '@langgenius/dify-ui/select'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Badge from '@/app/components/base/badge'
|
||||
import { handleUpload } from '../../hooks'
|
||||
|
||||
const i18nPrefix = 'installFromGitHub'
|
||||
|
||||
type SelectOption = {
|
||||
value: string
|
||||
name: string
|
||||
}
|
||||
|
||||
type SelectPackageProps = {
|
||||
updatePayload: UpdateFromGitHubPayload
|
||||
repoUrl: string
|
||||
selectedVersion: string
|
||||
versions: SelectOption[]
|
||||
onSelectVersion: (item: SelectOption) => void
|
||||
selectedPackage: string
|
||||
packages: SelectOption[]
|
||||
onSelectPackage: (item: SelectOption) => void
|
||||
onUploaded: (result: { uniqueIdentifier: string; manifest: PluginDeclaration }) => void
|
||||
onFailed: (errorMsg: string) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
const SelectPackage: React.FC<SelectPackageProps> = ({
|
||||
updatePayload,
|
||||
repoUrl,
|
||||
selectedVersion,
|
||||
versions,
|
||||
onSelectVersion,
|
||||
selectedPackage,
|
||||
packages,
|
||||
onSelectPackage,
|
||||
onUploaded,
|
||||
onFailed,
|
||||
onBack,
|
||||
}) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const isEdit = Boolean(updatePayload)
|
||||
const [isUploading, setIsUploading] = React.useState(false)
|
||||
const selectedVersionOption = versions.find((item) => item.value === selectedVersion) ?? null
|
||||
const selectedPackageOption = packages.find((item) => item.value === selectedPackage) ?? null
|
||||
|
||||
const handleUploadPackage = async () => {
|
||||
if (isUploading) return
|
||||
setIsUploading(true)
|
||||
try {
|
||||
const repo = repoUrl.replace('https://github.com/', '')
|
||||
await handleUpload(repo, selectedVersion, selectedPackage, (GitHubPackage) => {
|
||||
onUploaded({
|
||||
uniqueIdentifier: GitHubPackage.unique_identifier,
|
||||
manifest: GitHubPackage.manifest,
|
||||
})
|
||||
})
|
||||
} catch (e) {
|
||||
if (e instanceof Error && e.message) onFailed(e.message)
|
||||
else onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Field name="version" className="gap-4 self-stretch">
|
||||
<Select
|
||||
value={selectedVersionOption?.value ?? null}
|
||||
onValueChange={(value) => {
|
||||
if (value == null) return
|
||||
const selectedItem = versions.find((item) => item.value === value)
|
||||
if (selectedItem) onSelectVersion(selectedItem)
|
||||
}}
|
||||
>
|
||||
<SelectLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
|
||||
<span className="system-sm-semibold">
|
||||
{t(($) => $[`${i18nPrefix}.selectVersion`], { ns: 'plugin' })}
|
||||
</span>
|
||||
</SelectLabel>
|
||||
<SelectTrigger className="h-9 text-components-input-text-filled">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="truncate">
|
||||
{selectedVersionOption?.name ??
|
||||
t(($) => $[`${i18nPrefix}.selectVersionPlaceholder`], { ns: 'plugin' }) ??
|
||||
''}
|
||||
</span>
|
||||
{!!(
|
||||
updatePayload?.originalPackageInfo.version &&
|
||||
selectedVersionOption &&
|
||||
selectedVersionOption.value !== updatePayload.originalPackageInfo.version
|
||||
) && (
|
||||
<Badge>
|
||||
{updatePayload.originalPackageInfo.version} {'->'} {selectedVersionOption.value}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="w-lg">
|
||||
{versions.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>
|
||||
<SelectItemText>{item.name}</SelectItemText>
|
||||
{item.value === updatePayload?.originalPackageInfo.version && (
|
||||
<Badge uppercase={true} className="ml-1 shrink-0">
|
||||
INSTALLED
|
||||
</Badge>
|
||||
)}
|
||||
<SelectItemIndicator />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field name="package" className="gap-4 self-stretch">
|
||||
<Select
|
||||
value={selectedPackageOption?.value ?? null}
|
||||
disabled={!selectedVersion}
|
||||
onValueChange={(value) => {
|
||||
if (value == null) return
|
||||
const selectedItem = packages.find((item) => item.value === value)
|
||||
if (selectedItem) onSelectPackage(selectedItem)
|
||||
}}
|
||||
>
|
||||
<SelectLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
|
||||
<span className="system-sm-semibold">
|
||||
{t(($) => $[`${i18nPrefix}.selectPackage`], { ns: 'plugin' })}
|
||||
</span>
|
||||
</SelectLabel>
|
||||
<SelectTrigger className="h-9 text-components-input-text-filled">
|
||||
{selectedPackageOption?.name ??
|
||||
t(($) => $[`${i18nPrefix}.selectPackagePlaceholder`], { ns: 'plugin' }) ??
|
||||
''}
|
||||
</SelectTrigger>
|
||||
<SelectContent className="w-lg">
|
||||
{packages.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>
|
||||
<SelectItemText>{item.name}</SelectItemText>
|
||||
<SelectItemIndicator />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<div className="mt-4 flex items-center justify-end gap-2 self-stretch">
|
||||
{!isEdit && (
|
||||
<Button variant="secondary" className="min-w-18" onClick={onBack} disabled={isUploading}>
|
||||
{t(($) => $['installModal.back'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="min-w-18"
|
||||
onClick={handleUploadPackage}
|
||||
disabled={!selectedVersion || !selectedPackage || isUploading}
|
||||
>
|
||||
{t(($) => $['installModal.next'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default SelectPackage
|
||||
Reference in new issue
Block a user