pull/12372/head
StyleZhang 2 years ago
commit ba53900ec4

@ -47,7 +47,7 @@ const PluginList = () => {
{ {
type: 'marketplace', type: 'marketplace',
value: { value: {
plugin_unique_identifier: 'langgenius/openai:0.0.1@f88fdb98d104466db16a425bfe3af8c1bcad45047a40fb802d98a989ac57a5a3', plugin_unique_identifier: 'langgenius/openai:0.0.2@7baee9635a07573ea192621ebfdacb39db466fa691e75255beaf48bf41d44375',
}, },
}, },
]} /> ]} />

@ -3,7 +3,7 @@ import cn from '@/utils/classnames'
type BadgeProps = { type BadgeProps = {
className?: string className?: string
text: string text: string | React.ReactNode
uppercase?: boolean uppercase?: boolean
hasRedCornerMark?: boolean hasRedCornerMark?: boolean
} }

@ -0,0 +1,25 @@
export const tagKeys = [
'search',
'image',
'videos',
'weather',
'finance',
'design',
'travel',
'social',
'news',
'medical',
'productivity',
'education',
'business',
'entertainment',
'utilities',
'other',
]
export const categoryKeys = [
'model',
'tool',
'extension',
'bundle',
]

@ -1,5 +1,9 @@
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import type { TFunction } from 'i18next' import type { TFunction } from 'i18next'
import {
categoryKeys,
tagKeys,
} from './constants'
type Tag = { type Tag = {
name: string name: string
@ -10,72 +14,12 @@ export const useTags = (translateFromOut?: TFunction) => {
const { t: translation } = useTranslation() const { t: translation } = useTranslation()
const t = translateFromOut || translation const t = translateFromOut || translation
const tags = [ const tags = tagKeys.map((tag) => {
{ return {
name: 'search', name: tag,
label: t('pluginTags.tags.search'), label: t(`pluginTags.tags.${tag}`),
}, }
{ })
name: 'image',
label: t('pluginTags.tags.image'),
},
{
name: 'videos',
label: t('pluginTags.tags.videos'),
},
{
name: 'weather',
label: t('pluginTags.tags.weather'),
},
{
name: 'finance',
label: t('pluginTags.tags.finance'),
},
{
name: 'design',
label: t('pluginTags.tags.design'),
},
{
name: 'travel',
label: t('pluginTags.tags.travel'),
},
{
name: 'social',
label: t('pluginTags.tags.social'),
},
{
name: 'news',
label: t('pluginTags.tags.news'),
},
{
name: 'medical',
label: t('pluginTags.tags.medical'),
},
{
name: 'productivity',
label: t('pluginTags.tags.productivity'),
},
{
name: 'education',
label: t('pluginTags.tags.education'),
},
{
name: 'business',
label: t('pluginTags.tags.business'),
},
{
name: 'entertainment',
label: t('pluginTags.tags.entertainment'),
},
{
name: 'utilities',
label: t('pluginTags.tags.utilities'),
},
{
name: 'other',
label: t('pluginTags.tags.other'),
},
]
const tagsMap = tags.reduce((acc, tag) => { const tagsMap = tags.reduce((acc, tag) => {
acc[tag.name] = tag acc[tag.name] = tag
@ -97,24 +41,12 @@ export const useCategories = (translateFromOut?: TFunction) => {
const { t: translation } = useTranslation() const { t: translation } = useTranslation()
const t = translateFromOut || translation const t = translateFromOut || translation
const categories = [ const categories = categoryKeys.map((category) => {
{ return {
name: 'model', name: category,
label: t('plugin.category.models'), label: t(`plugin.category.${category}s`),
}, }
{ })
name: 'tool',
label: t('plugin.category.tools'),
},
{
name: 'extension',
label: t('plugin.category.extensions'),
},
{
name: 'bundle',
label: t('plugin.category.bundles'),
},
]
const categoriesMap = categories.reduce((acc, category) => { const categoriesMap = categories.reduce((acc, category) => {
acc[category.name] = category acc[category.name] = category

@ -1,24 +1,16 @@
import Toast from '@/app/components/base/toast' import Toast, { type IToastProps } from '@/app/components/base/toast'
import { uploadGitHub } from '@/service/plugins' import { uploadGitHub } from '@/service/plugins'
import { Octokit } from '@octokit/core' import { compareVersion, getLatestVersion } from '@/utils/semver'
import { GITHUB_ACCESS_TOKEN } from '@/config' import type { GitHubRepoReleaseResponse } from '../types'
export const useGitHubReleases = () => { export const useGitHubReleases = () => {
const fetchReleases = async (owner: string, repo: string) => { const fetchReleases = async (owner: string, repo: string) => {
try { try {
const octokit = new Octokit({ const res = await fetch(`/repos/${owner}/${repo}/releases`)
auth: GITHUB_ACCESS_TOKEN, const bodyJson = await res.json()
}) if (bodyJson.status !== 200) throw new Error(bodyJson.data.message)
const res = await octokit.request('GET /repos/{owner}/{repo}/releases', {
owner,
repo,
headers: {
'X-GitHub-Api-Version': '2022-11-28',
},
})
if (res.status !== 200) throw new Error('Failed to fetch releases')
const formattedReleases = res.data.map((release: any) => ({ const formattedReleases = bodyJson.data.map((release: any) => ({
tag_name: release.tag_name, tag_name: release.tag_name,
assets: release.assets.map((asset: any) => ({ assets: release.assets.map((asset: any) => ({
browser_download_url: asset.browser_download_url, browser_download_url: asset.browser_download_url,
@ -29,15 +21,49 @@ export const useGitHubReleases = () => {
return formattedReleases return formattedReleases
} }
catch (error) { catch (error) {
if (error instanceof Error) {
Toast.notify({
type: 'error',
message: error.message,
})
}
else {
Toast.notify({ Toast.notify({
type: 'error', type: 'error',
message: 'Failed to fetch repository releases', message: 'Failed to fetch repository releases',
}) })
}
return [] return []
} }
} }
return { fetchReleases } const checkForUpdates = (fetchedReleases: GitHubRepoReleaseResponse[], currentVersion: string) => {
let needUpdate = false
const toastProps: IToastProps = {
type: 'info',
message: 'No new version available',
}
if (fetchedReleases.length === 0) {
toastProps.type = 'error'
toastProps.message = 'Input releases is empty'
return { needUpdate, toastProps }
}
const versions = fetchedReleases.map(release => release.tag_name)
const latestVersion = getLatestVersion(versions)
try {
needUpdate = compareVersion(latestVersion, currentVersion) === 1
if (needUpdate)
toastProps.message = `New version available: ${latestVersion}`
}
catch {
needUpdate = false
toastProps.type = 'error'
toastProps.message = 'Fail to compare versions, please check the version format'
}
return { needUpdate, toastProps }
}
return { fetchReleases, checkForUpdates }
} }
export const useGitHubUpload = () => { export const useGitHubUpload = () => {

@ -3,9 +3,8 @@ import type { FC } from 'react'
import Modal from '@/app/components/base/modal' import Modal from '@/app/components/base/modal'
import React, { useCallback, useState } from 'react' import React, { useCallback, useState } from 'react'
import { InstallStep } from '../../types' import { InstallStep } from '../../types'
import type { Dependency, InstallStatusResponse, Plugin } from '../../types' import type { Dependency } from '../../types'
import Install from './steps/install' import ReadyToInstall from './ready-to-install'
import Installed from './steps/installed'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
const i18nPrefix = 'plugin.installModal' const i18nPrefix = 'plugin.installModal'
@ -30,8 +29,7 @@ const InstallBundle: FC<Props> = ({
}) => { }) => {
const { t } = useTranslation() const { t } = useTranslation()
const [step, setStep] = useState<InstallStep>(installType === InstallType.fromMarketplace ? InstallStep.readyToInstall : InstallStep.uploading) const [step, setStep] = useState<InstallStep>(installType === InstallType.fromMarketplace ? InstallStep.readyToInstall : InstallStep.uploading)
const [installedPlugins, setInstalledPlugins] = useState<Plugin[]>([])
const [installStatus, setInstallStatus] = useState<InstallStatusResponse[]>([])
const getTitle = useCallback(() => { const getTitle = useCallback(() => {
if (step === InstallStep.uploadFailed) if (step === InstallStep.uploadFailed)
return t(`${i18nPrefix}.uploadFailed`) return t(`${i18nPrefix}.uploadFailed`)
@ -43,12 +41,6 @@ const InstallBundle: FC<Props> = ({
return t(`${i18nPrefix}.installPlugin`) return t(`${i18nPrefix}.installPlugin`)
}, [step, t]) }, [step, t])
const handleInstalled = useCallback((plugins: Plugin[], installStatus: InstallStatusResponse[]) => {
setInstallStatus(installStatus)
setInstalledPlugins(plugins)
setStep(InstallStep.installed)
}, [])
return ( return (
<Modal <Modal
isShow={true} isShow={true}
@ -61,20 +53,12 @@ const InstallBundle: FC<Props> = ({
{getTitle()} {getTitle()}
</div> </div>
</div> </div>
{step === InstallStep.readyToInstall && ( <ReadyToInstall
<Install step={step}
fromDSLPayload={fromDSLPayload} onStepChange={setStep}
onCancel={onClose} dependencies={fromDSLPayload}
onInstalled={handleInstalled} onClose={onClose}
/>
)}
{step === InstallStep.installed && (
<Installed
list={installedPlugins}
installStatus={installStatus}
onCancel={onClose}
/> />
)}
</Modal> </Modal>
) )
} }

@ -0,0 +1,48 @@
'use client'
import type { FC } from 'react'
import React, { useCallback, useState } from 'react'
import { InstallStep } from '../../types'
import Install from './steps/install'
import Installed from './steps/installed'
import type { Dependency, InstallStatusResponse, Plugin } from '../../types'
type Props = {
step: InstallStep
onStepChange: (step: InstallStep) => void,
dependencies: Dependency[]
onClose: () => void
}
const ReadyToInstall: FC<Props> = ({
step,
onStepChange,
dependencies,
onClose,
}) => {
const [installedPlugins, setInstalledPlugins] = useState<Plugin[]>([])
const [installStatus, setInstallStatus] = useState<InstallStatusResponse[]>([])
const handleInstalled = useCallback((plugins: Plugin[], installStatus: InstallStatusResponse[]) => {
setInstallStatus(installStatus)
setInstalledPlugins(plugins)
onStepChange(InstallStep.installed)
}, [onStepChange])
return (
<>
{step === InstallStep.readyToInstall && (
<Install
fromDSLPayload={dependencies}
onCancel={onClose}
onInstalled={handleInstalled}
/>
)}
{step === InstallStep.installed && (
<Installed
list={installedPlugins}
installStatus={installStatus}
onCancel={onClose}
/>
)}
</>
)
}
export default React.memo(ReadyToInstall)

@ -1,7 +1,7 @@
'use client' 'use client'
import type { FC } from 'react' import type { FC } from 'react'
import React from 'react' import React from 'react'
import type { Plugin } from '../../../types' import type { InstallStatusResponse, Plugin } from '../../../types'
import Card from '@/app/components/plugins/card' import Card from '@/app/components/plugins/card'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@ -11,7 +11,7 @@ import { MARKETPLACE_API_PREFIX } from '@/config'
type Props = { type Props = {
list: Plugin[] list: Plugin[]
installStatus: { success: boolean, isFromMarketPlace: boolean }[] installStatus: InstallStatusResponse[]
onCancel: () => void onCancel: () => void
} }

@ -2,14 +2,13 @@
import React, { useCallback, useState } from 'react' import React, { useCallback, useState } from 'react'
import Modal from '@/app/components/base/modal' import Modal from '@/app/components/base/modal'
import type { PluginDeclaration } from '../../types' import type { Dependency, PluginDeclaration } from '../../types'
import { InstallStep } from '../../types' import { InstallStep } from '../../types'
import Uploading from './steps/uploading' import Uploading from './steps/uploading'
import Install from './steps/install'
import Installed from '../base/installed'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon' import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins' import ReadyToInstallPackage from './ready-to-install'
import ReadyToInstallBundle from '../install-bundle/ready-to-install'
const i18nPrefix = 'plugin.installModal' const i18nPrefix = 'plugin.installModal'
@ -29,7 +28,8 @@ const InstallFromLocalPackage: React.FC<InstallFromLocalPackageProps> = ({
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null) const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
const [manifest, setManifest] = useState<PluginDeclaration | null>(null) const [manifest, setManifest] = useState<PluginDeclaration | null>(null)
const [errorMsg, setErrorMsg] = useState<string | null>(null) const [errorMsg, setErrorMsg] = useState<string | null>(null)
const invalidateInstalledPluginList = useInvalidateInstalledPluginList() const isBundle = file.name.endsWith('.bundle')
const [dependencies, setDependencies] = useState<Dependency[]>([])
const getTitle = useCallback(() => { const getTitle = useCallback(() => {
if (step === InstallStep.uploadFailed) if (step === InstallStep.uploadFailed)
@ -44,7 +44,7 @@ const InstallFromLocalPackage: React.FC<InstallFromLocalPackageProps> = ({
const { getIconUrl } = useGetIcon() const { getIconUrl } = useGetIcon()
const handleUploaded = useCallback(async (result: { const handlePackageUploaded = useCallback(async (result: {
uniqueIdentifier: string uniqueIdentifier: string
manifest: PluginDeclaration manifest: PluginDeclaration
}) => { }) => {
@ -61,20 +61,14 @@ const InstallFromLocalPackage: React.FC<InstallFromLocalPackageProps> = ({
setStep(InstallStep.readyToInstall) setStep(InstallStep.readyToInstall)
}, [getIconUrl]) }, [getIconUrl])
const handleUploadFail = useCallback((errorMsg: string) => { const handleBundleUploaded = useCallback((result: Dependency[]) => {
setErrorMsg(errorMsg) setDependencies(result)
setStep(InstallStep.uploadFailed) setStep(InstallStep.readyToInstall)
}, []) }, [])
const handleInstalled = useCallback(() => { const handleUploadFail = useCallback((errorMsg: string) => {
invalidateInstalledPluginList()
setStep(InstallStep.installed)
}, [invalidateInstalledPluginList])
const handleFailed = useCallback((errorMsg?: string) => {
setStep(InstallStep.installFailed)
if (errorMsg)
setErrorMsg(errorMsg) setErrorMsg(errorMsg)
setStep(InstallStep.uploadFailed)
}, []) }, [])
return ( return (
@ -91,33 +85,32 @@ const InstallFromLocalPackage: React.FC<InstallFromLocalPackageProps> = ({
</div> </div>
{step === InstallStep.uploading && ( {step === InstallStep.uploading && (
<Uploading <Uploading
isBundle={isBundle}
file={file} file={file}
onCancel={onClose} onCancel={onClose}
onUploaded={handleUploaded} onPackageUploaded={handlePackageUploaded}
onBundleUploaded={handleBundleUploaded}
onFailed={handleUploadFail} onFailed={handleUploadFail}
/> />
)} )}
{ {isBundle ? (
step === InstallStep.readyToInstall && ( <ReadyToInstallBundle
<Install step={step}
uniqueIdentifier={uniqueIdentifier!} onStepChange={setStep}
payload={manifest!} onClose={onClose}
onCancel={onClose} dependencies={dependencies}
onInstalled={handleInstalled}
onFailed={handleFailed}
/> />
) ) : (
} <ReadyToInstallPackage
{ step={step}
([InstallStep.uploadFailed, InstallStep.installed, InstallStep.installFailed].includes(step)) && ( onStepChange={setStep}
<Installed onClose={onClose}
payload={manifest} uniqueIdentifier={uniqueIdentifier}
isFailed={[InstallStep.uploadFailed, InstallStep.installFailed].includes(step)} manifest={manifest}
errMsg={errorMsg} errorMsg={errorMsg}
onCancel={onClose} onError={setErrorMsg}
/> />
) )}
}
</Modal> </Modal>
) )
} }

@ -0,0 +1,68 @@
'use client'
import type { FC } from 'react'
import React, { useCallback } from 'react'
import type { PluginDeclaration } from '../../types'
import { InstallStep } from '../../types'
import Install from './steps/install'
import Installed from '../base/installed'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
type Props = {
step: InstallStep
onStepChange: (step: InstallStep) => void,
onClose: () => void
uniqueIdentifier: string | null,
manifest: PluginDeclaration | null,
errorMsg: string | null,
onError: (errorMsg: string) => void,
}
const ReadyToInstall: FC<Props> = ({
step,
onStepChange,
onClose,
uniqueIdentifier,
manifest,
errorMsg,
onError,
}) => {
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
const handleInstalled = useCallback(() => {
invalidateInstalledPluginList()
onStepChange(InstallStep.installed)
}, [invalidateInstalledPluginList, onStepChange])
const handleFailed = useCallback((errorMsg?: string) => {
onStepChange(InstallStep.installFailed)
if (errorMsg)
onError(errorMsg)
}, [onError, onStepChange])
return (
<>
{
step === InstallStep.readyToInstall && (
<Install
uniqueIdentifier={uniqueIdentifier!}
payload={manifest!}
onCancel={onClose}
onInstalled={handleInstalled}
onFailed={handleFailed}
/>
)
}
{
([InstallStep.uploadFailed, InstallStep.installed, InstallStep.installFailed].includes(step)) && (
<Installed
payload={manifest}
isFailed={[InstallStep.uploadFailed, InstallStep.installFailed].includes(step)}
errMsg={errorMsg}
onCancel={onClose}
/>
)
}
</>
)
}
export default React.memo(ReadyToInstall)

@ -3,34 +3,37 @@ import type { FC } from 'react'
import React from 'react' import React from 'react'
import { RiLoader2Line } from '@remixicon/react' import { RiLoader2Line } from '@remixicon/react'
import Card from '../../../card' import Card from '../../../card'
import type { PluginDeclaration } from '../../../types' import type { Dependency, PluginDeclaration } from '../../../types'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { uploadPackageFile } from '@/service/plugins' import { uploadFile } from '@/service/plugins'
const i18nPrefix = 'plugin.installModal' const i18nPrefix = 'plugin.installModal'
type Props = { type Props = {
isBundle: boolean
file: File file: File
onCancel: () => void onCancel: () => void
onUploaded: (result: { onPackageUploaded: (result: {
uniqueIdentifier: string uniqueIdentifier: string
manifest: PluginDeclaration manifest: PluginDeclaration
}) => void }) => void
onBundleUploaded: (result: Dependency[]) => void
onFailed: (errorMsg: string) => void onFailed: (errorMsg: string) => void
} }
const Uploading: FC<Props> = ({ const Uploading: FC<Props> = ({
isBundle,
file, file,
onCancel, onCancel,
onUploaded, onPackageUploaded,
onBundleUploaded,
onFailed, onFailed,
}) => { }) => {
const { t } = useTranslation() const { t } = useTranslation()
const fileName = file.name const fileName = file.name
const handleUpload = async () => { const handleUpload = async () => {
try { try {
const res = await uploadPackageFile(file) await uploadFile(file, isBundle)
onUploaded(res)
} }
catch (e: any) { catch (e: any) {
if (e.response?.message) { if (e.response?.message) {
@ -38,7 +41,11 @@ const Uploading: FC<Props> = ({
} }
else { // Why it would into this branch? else { // Why it would into this branch?
const res = e.response const res = e.response
onUploaded({ if (isBundle) {
onBundleUploaded(res)
return
}
onPackageUploaded({
uniqueIdentifier: res.unique_identifier, uniqueIdentifier: res.unique_identifier,
manifest: res.manifest, manifest: res.manifest,
}) })

@ -5,6 +5,7 @@ import type {
} from 'react' } from 'react'
import { import {
useCallback, useCallback,
useEffect,
useRef, useRef,
useState, useState,
} from 'react' } from 'react'
@ -14,9 +15,14 @@ import {
} from 'use-context-selector' } from 'use-context-selector'
import { PLUGIN_TYPE_SEARCH_MAP } from './plugin-type-switch' import { PLUGIN_TYPE_SEARCH_MAP } from './plugin-type-switch'
import type { Plugin } from '../types' import type { Plugin } from '../types'
import {
getValidCategoryKeys,
getValidTagKeys,
} from '../utils'
import type { import type {
MarketplaceCollection, MarketplaceCollection,
PluginsSort, PluginsSort,
SearchParams,
} from './types' } from './types'
import { DEFAULT_SORT } from './constants' import { DEFAULT_SORT } from './constants'
import { import {
@ -66,6 +72,7 @@ export const MarketplaceContext = createContext<MarketplaceContextValue>({
type MarketplaceContextProviderProps = { type MarketplaceContextProviderProps = {
children: ReactNode children: ReactNode
searchParams?: SearchParams
} }
export function useMarketplaceContext(selector: (value: MarketplaceContextValue) => any) { export function useMarketplaceContext(selector: (value: MarketplaceContextValue) => any) {
@ -74,13 +81,19 @@ export function useMarketplaceContext(selector: (value: MarketplaceContextValue)
export const MarketplaceContextProvider = ({ export const MarketplaceContextProvider = ({
children, children,
searchParams,
}: MarketplaceContextProviderProps) => { }: MarketplaceContextProviderProps) => {
const queryFromSearchParams = searchParams?.q || ''
const tagsFromSearchParams = searchParams?.tags ? getValidTagKeys(searchParams.tags.split(',')) : []
const hasValidTags = !!tagsFromSearchParams.length
const hasValidCategory = getValidCategoryKeys(searchParams?.category)
const categoryFromSearchParams = hasValidCategory || PLUGIN_TYPE_SEARCH_MAP.all
const [intersected, setIntersected] = useState(true) const [intersected, setIntersected] = useState(true)
const [searchPluginText, setSearchPluginText] = useState('') const [searchPluginText, setSearchPluginText] = useState(queryFromSearchParams)
const searchPluginTextRef = useRef(searchPluginText) const searchPluginTextRef = useRef(searchPluginText)
const [filterPluginTags, setFilterPluginTags] = useState<string[]>([]) const [filterPluginTags, setFilterPluginTags] = useState<string[]>(tagsFromSearchParams)
const filterPluginTagsRef = useRef(filterPluginTags) const filterPluginTagsRef = useRef(filterPluginTags)
const [activePluginType, setActivePluginType] = useState(PLUGIN_TYPE_SEARCH_MAP.all) const [activePluginType, setActivePluginType] = useState(categoryFromSearchParams)
const activePluginTypeRef = useRef(activePluginType) const activePluginTypeRef = useRef(activePluginType)
const [sort, setSort] = useState(DEFAULT_SORT) const [sort, setSort] = useState(DEFAULT_SORT)
const sortRef = useRef(sort) const sortRef = useRef(sort)
@ -100,6 +113,20 @@ export const MarketplaceContextProvider = ({
isLoading: isPluginsLoading, isLoading: isPluginsLoading,
} = useMarketplacePlugins() } = useMarketplacePlugins()
useEffect(() => {
if (queryFromSearchParams || hasValidTags || hasValidCategory) {
queryPlugins({
query: queryFromSearchParams,
category: hasValidCategory,
tags: hasValidTags ? tagsFromSearchParams : [],
sortBy: sortRef.current.sortBy,
sortOrder: sortRef.current.sortOrder,
})
history.pushState({}, '', `/${searchParams?.language ? `?language=${searchParams?.language}` : ''}`)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [queryPlugins])
const handleSearchPluginTextChange = useCallback((text: string) => { const handleSearchPluginTextChange = useCallback((text: string) => {
setSearchPluginText(text) setSearchPluginText(text)
searchPluginTextRef.current = text searchPluginTextRef.current = text

@ -4,22 +4,25 @@ import IntersectionLine from './intersection-line'
import SearchBoxWrapper from './search-box/search-box-wrapper' import SearchBoxWrapper from './search-box/search-box-wrapper'
import PluginTypeSwitch from './plugin-type-switch' import PluginTypeSwitch from './plugin-type-switch'
import ListWrapper from './list/list-wrapper' import ListWrapper from './list/list-wrapper'
import type { SearchParams } from './types'
import { getMarketplaceCollectionsAndPlugins } from './utils' import { getMarketplaceCollectionsAndPlugins } from './utils'
import { TanstackQueryIniter } from '@/context/query-client' import { TanstackQueryIniter } from '@/context/query-client'
type MarketplaceProps = { type MarketplaceProps = {
locale?: string locale?: string
showInstallButton?: boolean showInstallButton?: boolean
searchParams?: SearchParams
} }
const Marketplace = async ({ const Marketplace = async ({
locale, locale,
showInstallButton = true, showInstallButton = true,
searchParams,
}: MarketplaceProps) => { }: MarketplaceProps) => {
const { marketplaceCollections, marketplaceCollectionPluginsMap } = await getMarketplaceCollectionsAndPlugins() const { marketplaceCollections, marketplaceCollectionPluginsMap } = await getMarketplaceCollectionsAndPlugins()
return ( return (
<TanstackQueryIniter> <TanstackQueryIniter>
<MarketplaceContextProvider> <MarketplaceContextProvider searchParams={searchParams}>
<Description locale={locale} /> <Description locale={locale} />
<IntersectionLine /> <IntersectionLine />
<SearchBoxWrapper locale={locale} /> <SearchBoxWrapper locale={locale} />

@ -36,3 +36,10 @@ export type PluginsSort = {
export type CollectionsAndPluginsSearchParams = { export type CollectionsAndPluginsSearchParams = {
category?: string category?: string
} }
export type SearchParams = {
language?: string
q?: string
tags?: string
category?: string
}

@ -33,7 +33,7 @@ const AppInputsPanel = ({
const isBasicApp = appDetail.mode !== 'advanced-chat' && appDetail.mode !== 'workflow' const isBasicApp = appDetail.mode !== 'advanced-chat' && appDetail.mode !== 'workflow'
const { data: fileUploadConfig } = useFileUploadConfig() const { data: fileUploadConfig } = useFileUploadConfig()
const { data: currentApp, isFetching: isAppLoading } = useAppDetail(appDetail.id) const { data: currentApp, isFetching: isAppLoading } = useAppDetail(appDetail.id)
const { data: currentWorkflow, isFetching: isWorkflowLoading } = useAppWorkflow(isBasicApp ? 'empty' : appDetail.id) const { data: currentWorkflow, isFetching: isWorkflowLoading } = useAppWorkflow(isBasicApp ? '' : appDetail.id)
const isLoading = isAppLoading || isWorkflowLoading const isLoading = isAppLoading || isWorkflowLoading
const basicAppFileConfig = useMemo(() => { const basicAppFileConfig = useMemo(() => {

@ -1,7 +1,8 @@
import React, { useCallback, useMemo } from 'react' import React, { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useBoolean } from 'ahooks' import { useBoolean } from 'ahooks'
import { import {
RiArrowLeftRightLine,
RiBugLine, RiBugLine,
RiCloseLine, RiCloseLine,
RiHardDrive3Line, RiHardDrive3Line,
@ -14,8 +15,9 @@ import Icon from '../card/base/card-icon'
import Title from '../card/base/title' import Title from '../card/base/title'
import OrgInfo from '../card/base/org-info' import OrgInfo from '../card/base/org-info'
import { useGitHubReleases } from '../install-plugin/hooks' import { useGitHubReleases } from '../install-plugin/hooks'
import { compareVersion, getLatestVersion } from '@/utils/semver' import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'
import OperationDropdown from './operation-dropdown' import UpdateFromMarketplace from '@/app/components/plugins/update-plugin/from-market-place'
import OperationDropdown from '@/app/components/plugins/plugin-detail-panel/operation-dropdown'
import PluginInfo from '@/app/components/plugins/plugin-page/plugin-info' import PluginInfo from '@/app/components/plugins/plugin-page/plugin-info'
import ActionButton from '@/app/components/base/action-button' import ActionButton from '@/app/components/base/action-button'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
@ -28,7 +30,6 @@ import { Github } from '@/app/components/base/icons/src/public/common'
import { uninstallPlugin } from '@/service/plugins' import { uninstallPlugin } from '@/service/plugins'
import { useGetLanguage } from '@/context/i18n' import { useGetLanguage } from '@/context/i18n'
import { useModalContext } from '@/context/modal-context' import { useModalContext } from '@/context/modal-context'
import UpdateFromMarketplace from '@/app/components/plugins/update-plugin/from-market-place'
import { API_PREFIX, MARKETPLACE_URL_PREFIX } from '@/config' import { API_PREFIX, MARKETPLACE_URL_PREFIX } from '@/config'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
@ -47,7 +48,7 @@ const DetailHeader = ({
}: Props) => { }: Props) => {
const { t } = useTranslation() const { t } = useTranslation()
const locale = useGetLanguage() const locale = useGetLanguage()
const { fetchReleases } = useGitHubReleases() const { checkForUpdates, fetchReleases } = useGitHubReleases()
const { setShowUpdatePluginModal } = useModalContext() const { setShowUpdatePluginModal } = useModalContext()
const { const {
@ -58,20 +59,23 @@ const DetailHeader = ({
latest_unique_identifier, latest_unique_identifier,
latest_version, latest_version,
meta, meta,
plugin_id,
} = detail } = detail
const { author, name, label, description, icon, verified } = detail.declaration const { author, name, label, description, icon, verified } = detail.declaration
const isFromGitHub = source === PluginSource.github const isFromGitHub = source === PluginSource.github
const isFromMarketplace = source === PluginSource.marketplace const isFromMarketplace = source === PluginSource.marketplace
const [isShow, setIsShow] = useState(false)
const [targetVersion, setTargetVersion] = useState({
version: latest_version,
unique_identifier: latest_unique_identifier,
})
const hasNewVersion = useMemo(() => { const hasNewVersion = useMemo(() => {
if (isFromGitHub)
return latest_version !== version
if (isFromMarketplace) if (isFromMarketplace)
return !!latest_version && latest_version !== version return !!latest_version && latest_version !== version
return false return false
}, [isFromGitHub, isFromMarketplace, latest_version, version]) }, [isFromMarketplace, latest_version, version])
const [isShowUpdateModal, { const [isShowUpdateModal, {
setTrue: showUpdateModal, setTrue: showUpdateModal,
@ -84,13 +88,11 @@ const DetailHeader = ({
return return
} }
try {
const fetchedReleases = await fetchReleases(author, name) const fetchedReleases = await fetchReleases(author, name)
if (fetchedReleases.length === 0) if (fetchedReleases.length === 0) return
return const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta!.version)
const versions = fetchedReleases.map(release => release.tag_name) Toast.notify(toastProps)
const latestVersion = getLatestVersion(versions) if (needUpdate) {
if (compareVersion(latestVersion, version) === 1) {
setShowUpdatePluginModal({ setShowUpdatePluginModal({
onSaveCallback: () => { onSaveCallback: () => {
onUpdate() onUpdate()
@ -99,7 +101,7 @@ const DetailHeader = ({
type: PluginSource.github, type: PluginSource.github,
github: { github: {
originalPackageInfo: { originalPackageInfo: {
id: installation_id, id: detail.plugin_unique_identifier,
repo: meta!.repo, repo: meta!.repo,
version: meta!.version, version: meta!.version,
package: meta!.package, package: meta!.package,
@ -109,19 +111,6 @@ const DetailHeader = ({
}, },
}) })
} }
else {
Toast.notify({
type: 'info',
message: 'No new version available',
})
}
}
catch {
Toast.notify({
type: 'error',
message: 'Failed to compare versions',
})
}
} }
const handleUpdatedFromMarketplace = () => { const handleUpdatedFromMarketplace = () => {
@ -167,12 +156,35 @@ const DetailHeader = ({
<div className="flex items-center h-5"> <div className="flex items-center h-5">
<Title title={label[locale]} /> <Title title={label[locale]} />
{verified && <RiVerifiedBadgeLine className="shrink-0 ml-0.5 w-4 h-4 text-text-accent" />} {verified && <RiVerifiedBadgeLine className="shrink-0 ml-0.5 w-4 h-4 text-text-accent" />}
<PluginVersionPicker
disabled={!isFromMarketplace || !hasNewVersion}
isShow={isShow}
onShowChange={setIsShow}
pluginID={plugin_id}
currentVersion={version}
onSelect={(state) => {
setTargetVersion(state)
handleUpdate()
}}
trigger={
<Badge <Badge
className='mx-1' className={cn(
text={version} 'mx-1',
isShow && 'bg-state-base-hover',
(isShow || isFromMarketplace) && 'hover:bg-state-base-hover',
)}
uppercase={false}
text={
<>
<div>{isFromGitHub ? meta!.version : version}</div>
{isFromMarketplace && <RiArrowLeftRightLine className='ml-1 w-3 h-3 text-text-tertiary' />}
</>
}
hasRedCornerMark={hasNewVersion} hasRedCornerMark={hasNewVersion}
/> />
{hasNewVersion && ( }
/>
{(hasNewVersion || isFromGitHub) && (
<Button variant='secondary-accent' size='small' className='!h-5' onClick={handleUpdate}>{t('plugin.detailPanel.operation.update')}</Button> <Button variant='secondary-accent' size='small' className='!h-5' onClick={handleUpdate}>{t('plugin.detailPanel.operation.update')}</Button>
)} )}
</div> </div>
@ -254,8 +266,8 @@ const DetailHeader = ({
payload: detail.declaration, payload: detail.declaration,
}, },
targetPackageInfo: { targetPackageInfo: {
id: latest_unique_identifier, id: targetVersion.unique_identifier,
version: latest_version, version: targetVersion.version,
}, },
}} }}
onCancel={hideUpdateModal} onCancel={hideUpdateModal}

@ -1,7 +1,11 @@
import React, { useMemo } from 'react' import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useBoolean } from 'ahooks' import { useBoolean } from 'ahooks'
import { RiAddLine } from '@remixicon/react' import {
RiAddLine,
RiApps2AddLine,
RiBookOpenLine,
} from '@remixicon/react'
import EndpointModal from './endpoint-modal' import EndpointModal from './endpoint-modal'
import EndpointCard from './endpoint-card' import EndpointCard from './endpoint-card'
import { NAME_FIELD } from './utils' import { NAME_FIELD } from './utils'
@ -61,8 +65,27 @@ const EndpointList = ({ showTopBorder }: Props) => {
<div className='flex items-center gap-0.5'> <div className='flex items-center gap-0.5'>
{t('plugin.detailPanel.endpoints')} {t('plugin.detailPanel.endpoints')}
<Tooltip <Tooltip
position='right'
needsDelay
popupClassName='w-[240px] p-4 rounded-xl bg-components-panel-bg-blur border-[0.5px] border-components-panel-border'
popupContent={ popupContent={
<div className='w-[180px]'>TODO</div> <div className='flex flex-col gap-2'>
<div className='w-8 h-8 flex items-center justify-center bg-background-default-subtle rounded-lg border-[0.5px] border-components-panel-border-subtle'>
<RiApps2AddLine className='w-4 h-4 text-text-tertiary' />
</div>
<div className='text-text-tertiary system-xs-regular'>{t('plugin.detailPanel.endpointsTip')}</div>
{/* TODO endpoints doc link */}
<a
href=''
target='_blank'
rel='noopener noreferrer'
>
<div className='inline-flex items-center gap-1 text-text-accent system-xs-regular cursor-pointer'>
<RiBookOpenLine className='w-3 h-3' />
{t('plugin.detailPanel.endpointsDocLink')}
</div>
</a>
</div>
} }
/> />
</div> </div>

@ -11,7 +11,6 @@ import Tooltip from '../../base/tooltip'
import Confirm from '../../base/confirm' import Confirm from '../../base/confirm'
import { uninstallPlugin } from '@/service/plugins' import { uninstallPlugin } from '@/service/plugins'
import { useGitHubReleases } from '../install-plugin/hooks' import { useGitHubReleases } from '../install-plugin/hooks'
import { compareVersion, getLatestVersion } from '@/utils/semver'
import Toast from '@/app/components/base/toast' import Toast from '@/app/components/base/toast'
import { useModalContext } from '@/context/modal-context' import { useModalContext } from '@/context/modal-context'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins' import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
@ -50,18 +49,16 @@ const Action: FC<Props> = ({
setTrue: showDeleting, setTrue: showDeleting,
setFalse: hideDeleting, setFalse: hideDeleting,
}] = useBoolean(false) }] = useBoolean(false)
const { fetchReleases } = useGitHubReleases() const { checkForUpdates, fetchReleases } = useGitHubReleases()
const { setShowUpdatePluginModal } = useModalContext() const { setShowUpdatePluginModal } = useModalContext()
const invalidateInstalledPluginList = useInvalidateInstalledPluginList() const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
const handleFetchNewVersion = async () => { const handleFetchNewVersion = async () => {
try {
const fetchedReleases = await fetchReleases(author, pluginName) const fetchedReleases = await fetchReleases(author, pluginName)
if (fetchedReleases.length === 0) if (fetchReleases.length === 0) return
return const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta!.version)
const versions = fetchedReleases.map(release => release.tag_name) Toast.notify(toastProps)
const latestVersion = getLatestVersion(versions) if (needUpdate) {
if (compareVersion(latestVersion, meta!.version) === 1) {
setShowUpdatePluginModal({ setShowUpdatePluginModal({
onSaveCallback: () => { onSaveCallback: () => {
invalidateInstalledPluginList() invalidateInstalledPluginList()
@ -80,19 +77,6 @@ const Action: FC<Props> = ({
}, },
}) })
} }
else {
Toast.notify({
type: 'info',
message: 'No new version available',
})
}
}
catch {
Toast.notify({
type: 'error',
message: 'Failed to compare versions',
})
}
} }
const [isShowDeleteConfirm, { const [isShowDeleteConfirm, {
@ -108,6 +92,7 @@ const Action: FC<Props> = ({
hideDeleteConfirm() hideDeleteConfirm()
onDelete() onDelete()
} }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [installationId, onDelete]) }, [installationId, onDelete])
return ( return (
<div className='flex space-x-1'> <div className='flex space-x-1'>

@ -82,7 +82,7 @@ const PluginItem: FC<Props> = ({
<div className="flex items-center h-5"> <div className="flex items-center h-5">
<Title title={label[locale]} /> <Title title={label[locale]} />
{verified && <RiVerifiedBadgeLine className="shrink-0 ml-0.5 w-4 h-4 text-text-accent" />} {verified && <RiVerifiedBadgeLine className="shrink-0 ml-0.5 w-4 h-4 text-text-accent" />}
<Badge className='ml-1' text={plugin.version} /> <Badge className='ml-1' text={source === PluginSource.github ? plugin.meta!.version : plugin.version} />
</div> </div>
<div className='flex items-center justify-between'> <div className='flex items-center justify-between'>
<Description text={description[locale]} descriptionLineRows={1}></Description> <Description text={description[locale]} descriptionLineRows={1}></Description>

@ -10,6 +10,7 @@ import { useSelector as useAppContextSelector } from '@/context/app-context'
import Line from '../../marketplace/empty/line' import Line from '../../marketplace/empty/line'
import { useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins' import { useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
const Empty = () => { const Empty = () => {
const { t } = useTranslation() const { t } = useTranslation()
@ -66,7 +67,7 @@ const Empty = () => {
ref={fileInputRef} ref={fileInputRef}
style={{ display: 'none' }} style={{ display: 'none' }}
onChange={handleFileChange} onChange={handleFileChange}
accept='.difypkg' accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
/> />
<div className='w-full flex flex-col gap-y-1'> <div className='w-full flex flex-col gap-y-1'>
{[ {[

@ -32,6 +32,7 @@ import type { PluginDeclaration, PluginManifestInMarket } from '../types'
import { sleep } from '@/utils' import { sleep } from '@/utils'
import { fetchManifestFromMarketPlace } from '@/service/plugins' import { fetchManifestFromMarketPlace } from '@/service/plugins'
import { marketplaceApiPrefix } from '@/config' import { marketplaceApiPrefix } from '@/config'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
const PACKAGE_IDS_KEY = 'package-ids' const PACKAGE_IDS_KEY = 'package-ids'
@ -186,7 +187,7 @@ const PluginPage = ({
className="hidden" className="hidden"
type="file" type="file"
id="fileUploader" id="fileUploader"
accept='.difypkg' accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
onChange={fileChangeHandle ?? (() => { })} onChange={fileChangeHandle ?? (() => { })}
/> />
</> </>

@ -17,6 +17,7 @@ import {
import { useSelector as useAppContextSelector } from '@/context/app-context' import { useSelector as useAppContextSelector } from '@/context/app-context'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins' import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
type Props = { type Props = {
onSwitchToMarketplaceTab: () => void onSwitchToMarketplaceTab: () => void
@ -81,7 +82,7 @@ const InstallPluginDropdown = ({
ref={fileInputRef} ref={fileInputRef}
style={{ display: 'none' }} style={{ display: 'none' }}
onChange={handleFileChange} onChange={handleFileChange}
accept='.difypkg' accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
/> />
<div className='w-full'> <div className='w-full'>
{[ {[

@ -322,3 +322,17 @@ export type Dependency = {
plugin_unique_identifier?: string plugin_unique_identifier?: string
} }
} }
export type Version = {
plugin_org: string
plugin_name: string
version: string
file_name: string
checksum: string
created_at: string
unique_identifier: string
}
export type VersionListResponse = {
versions: Version[]
}

@ -0,0 +1,118 @@
'use client'
import type { FC } from 'react'
import React, { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import Badge from '@/app/components/base/badge'
import type {
OffsetOptions,
Placement,
} from '@floating-ui/react'
import { useVersionListOfPlugin } from '@/service/use-plugins'
import useTimestamp from '@/hooks/use-timestamp'
import cn from '@/utils/classnames'
type Props = {
disabled?: boolean
isShow: boolean
onShowChange: (isShow: boolean) => void
pluginID: string
currentVersion: string
trigger: React.ReactNode
placement?: Placement
offset?: OffsetOptions
onSelect: ({
version,
unique_identifier,
}: {
version: string
unique_identifier: string
}) => void
}
const PluginVersionPicker: FC<Props> = ({
disabled = false,
isShow,
onShowChange,
pluginID,
currentVersion,
trigger,
placement = 'bottom-start',
offset = {
mainAxis: 4,
crossAxis: -16,
},
onSelect,
}) => {
const { t } = useTranslation()
const format = t('appLog.dateTimeFormat').split(' ')[0]
const { formatDate } = useTimestamp()
const handleTriggerClick = () => {
if (disabled) return
onShowChange(true)
}
const { data: res } = useVersionListOfPlugin(pluginID)
const handleSelect = useCallback(({ version, unique_identifier }: {
version: string
unique_identifier: string
}) => {
if (currentVersion === version)
return
onSelect({ version, unique_identifier })
onShowChange(false)
}, [currentVersion, onSelect])
return (
<PortalToFollowElem
placement={placement}
offset={offset}
open={isShow}
onOpenChange={onShowChange}
>
<PortalToFollowElemTrigger
className={cn('inline-flex items-center cursor-pointer', disabled && 'cursor-default')}
onClick={handleTriggerClick}
>
{trigger}
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1000]'>
<div className="relative w-[209px] p-1 rounded-xl bg-components-panel-bg-blur border-[0.5px] border-components-panel-border shadow-lg">
<div className='px-3 pt-1 pb-0.5 text-text-tertiary system-xs-medium-uppercase'>
{t('plugin.detailPanel.switchVersion')}
</div>
<div className='relative'>
{res?.data.versions.map(version => (
<div
key={version.unique_identifier}
className={cn(
'h-7 px-3 py-1 flex items-center gap-1 rounded-lg hover:bg-state-base-hover cursor-pointer',
currentVersion === version.version && 'opacity-30 cursor-default hover:bg-transparent',
)}
onClick={() => handleSelect({
version: version.version,
unique_identifier: version.unique_identifier,
})}
>
<div className='grow flex items-center'>
<div className='text-text-secondary system-sm-medium'>{version.version}</div>
{currentVersion === version.version && <Badge className='ml-1' text='CURRENT'/>}
</div>
<div className='shrink-0 text-text-tertiary system-xs-regular'>{formatDate(version.created_at, format)}</div>
</div>
))}
</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default React.memo(PluginVersionPicker)

@ -0,0 +1,13 @@
import {
categoryKeys,
tagKeys,
} from './constants'
export const getValidTagKeys = (tags: string[]) => {
return tags.filter(tag => tagKeys.includes(tag))
}
export const getValidCategoryKeys = (category?: string) => {
const currentCategory = categoryKeys.find(key => key === category)
return currentCategory ? `${currentCategory}s` : ''
}

@ -57,7 +57,7 @@ const Marketplace = ({
</span> </span>
{t('common.operation.in')} {t('common.operation.in')}
<a <a
href={`${MARKETPLACE_URL_PREFIX}?language=${locale}`} href={`${MARKETPLACE_URL_PREFIX}?language=${locale}&q=${searchPluginText}&tags=${filterPluginTags.join(',')}`}
className='flex items-center ml-1 system-sm-medium text-text-accent' className='flex items-center ml-1 system-sm-medium text-text-accent'
target='_blank' target='_blank'
> >

@ -26,7 +26,7 @@ const List = ({
const { t } = useTranslation() const { t } = useTranslation()
const hasFilter = !searchText const hasFilter = !searchText
const hasRes = list.length > 0 const hasRes = list.length > 0
const urlWithSearchText = `${marketplaceUrlPrefix}/marketplace?q=${searchText}&tags=${tags.join(',')}` const urlWithSearchText = `${marketplaceUrlPrefix}/?q=${searchText}&tags=${tags.join(',')}`
const nextToStickyELemRef = useRef<HTMLDivElement>(null) const nextToStickyELemRef = useRef<HTMLDivElement>(null)
const { handleScroll, scrollPosition } = useStickyScroll({ const { handleScroll, scrollPosition } = useStickyScroll({
@ -65,7 +65,7 @@ const List = ({
return ( return (
<Link <Link
className='sticky bottom-0 z-10 flex h-8 px-4 py-1 system-sm-medium items-center border-t border-[0.5px] border-components-panel-border bg-components-panel-bg-blur rounded-b-lg shadow-lg text-text-accent-light-mode-only cursor-pointer' className='sticky bottom-0 z-10 flex h-8 px-4 py-1 system-sm-medium items-center border-t border-[0.5px] border-components-panel-border bg-components-panel-bg-blur rounded-b-lg shadow-lg text-text-accent-light-mode-only cursor-pointer'
href={`${marketplaceUrlPrefix}/plugins`} href={`${marketplaceUrlPrefix}/`}
target='_blank' target='_blank'
> >
<span>{t('plugin.findMoreInMarketplace')}</span> <span>{t('plugin.findMoreInMarketplace')}</span>

@ -0,0 +1,36 @@
import { type NextRequest, NextResponse } from 'next/server'
import { Octokit } from '@octokit/core'
import { RequestError } from '@octokit/request-error'
import { GITHUB_ACCESS_TOKEN } from '@/config'
type Params = {
owner: string,
repo: string,
}
const octokit = new Octokit({
auth: GITHUB_ACCESS_TOKEN,
})
export async function GET(
request: NextRequest,
{ params }: { params: Promise<Params> },
) {
const { owner, repo } = (await params)
try {
const releasesRes = await octokit.request('GET /repos/{owner}/{repo}/releases', {
owner,
repo,
headers: {
'X-GitHub-Api-Version': '2022-11-28',
},
})
return NextResponse.json(releasesRes)
}
catch (error) {
if (error instanceof RequestError)
return NextResponse.json(error.response)
else
throw error
}
}

@ -273,3 +273,5 @@ export const TEXT_GENERATION_TIMEOUT_MS = textGenerationTimeoutMs
export const DISABLE_UPLOAD_IMAGE_AS_ICON = process.env.NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON === 'true' export const DISABLE_UPLOAD_IMAGE_AS_ICON = process.env.NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON === 'true'
export const GITHUB_ACCESS_TOKEN = process.env.NEXT_PUBLIC_GITHUB_ACCESS_TOKEN || globalThis.document?.body?.getAttribute('data-public-github-access-token') || '' export const GITHUB_ACCESS_TOKEN = process.env.NEXT_PUBLIC_GITHUB_ACCESS_TOKEN || globalThis.document?.body?.getAttribute('data-public-github-access-token') || ''
export const SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS = '.difypkg,.bundle'

@ -15,7 +15,11 @@ const useTimestamp = () => {
return dayjs.unix(value).tz(timezone).format(format) return dayjs.unix(value).tz(timezone).format(format)
}, [timezone]) }, [timezone])
return { formatTime } const formatDate = useCallback((value: string, format: string) => {
return dayjs(value).tz(timezone).format(format)
}, [timezone])
return { formatTime, formatDate }
} }
export default useTimestamp export default useTimestamp

@ -33,6 +33,7 @@ const translation = {
local: 'Local Package File', local: 'Local Package File',
}, },
detailPanel: { detailPanel: {
switchVersion: 'Switch Version',
categoryTip: { categoryTip: {
marketplace: 'Installed from Marketplace', marketplace: 'Installed from Marketplace',
github: 'Installed from Github', github: 'Installed from Github',
@ -50,6 +51,8 @@ const translation = {
}, },
actionNum: '{{num}} ACTIONS INCLUDED', actionNum: '{{num}} ACTIONS INCLUDED',
endpoints: 'Endpoints', endpoints: 'Endpoints',
endpointsTip: 'This plugin provides specific functionalities via endpoints, and you can configure multiple endpoint sets for current workspace.',
endpointsDocLink: 'View the document',
endpointsEmpty: 'Click the \'+\' button to add an endpoint', endpointsEmpty: 'Click the \'+\' button to add an endpoint',
endpointDisableTip: 'Disable Endpoint', endpointDisableTip: 'Disable Endpoint',
endpointDisableContent: 'Would you like to disable {{name}}? ', endpointDisableContent: 'Would you like to disable {{name}}? ',

@ -33,6 +33,7 @@ const translation = {
local: '本地插件', local: '本地插件',
}, },
detailPanel: { detailPanel: {
switchVersion: '切换版本',
categoryTip: { categoryTip: {
marketplace: '从 Marketplace 安装', marketplace: '从 Marketplace 安装',
github: '从 Github 安装', github: '从 Github 安装',
@ -49,14 +50,16 @@ const translation = {
remove: '移除', remove: '移除',
}, },
actionNum: '{{num}} ACTIONS 已包含', actionNum: '{{num}} ACTIONS 已包含',
endpoints: 'Endpoints', endpoints: 'API 端点',
endpointsEmpty: '点击 \'+\' 按钮添加 Endpoint', endpointsTip: '此插件通过 API 端点提供特定功能,您可以为当前工作区配置多个 API 端点集。',
endpointDisableTip: '停用 Endpoint', endpointsDocLink: '查看文档',
endpointDisableContent: '是否要停用 {{name}} 的 Endpoint ', endpointsEmpty: '点击 \'+\' 按钮添加 API 端点',
endpointDeleteTip: '移除 Endpoint', endpointDisableTip: '停用 API 端点',
endpointDisableContent: '是否要停用 {{name}} 的 API 端点 ',
endpointDeleteTip: '移除 API 端点',
endpointDeleteContent: '是否要移除 {{name}} ', endpointDeleteContent: '是否要移除 {{name}} ',
endpointModalTitle: '设置 Endpoint', endpointModalTitle: '设置 API 端点',
endpointModalDesc: '配置表单后,工作区内的所有成员都可以在编排应用时使用此端点。', endpointModalDesc: '配置表单后,工作区内的所有成员都可以在编排应用时使用此 API 端点。',
serviceOk: '服务正常', serviceOk: '服务正常',
disabled: '停用', disabled: '停用',
modelNum: '{{num}} 模型已包含', modelNum: '{{num}} 模型已包含',

@ -38,6 +38,7 @@
"@monaco-editor/react": "^4.6.0", "@monaco-editor/react": "^4.6.0",
"@next/mdx": "^14.0.4", "@next/mdx": "^14.0.4",
"@octokit/core": "^6.1.2", "@octokit/core": "^6.1.2",
"@octokit/request-error": "^6.1.5",
"@remixicon/react": "^4.3.0", "@remixicon/react": "^4.3.0",
"@sentry/react": "^7.54.0", "@sentry/react": "^7.54.0",
"@sentry/utils": "^7.54.0", "@sentry/utils": "^7.54.0",

File diff suppressed because it is too large Load Diff

@ -16,13 +16,13 @@ import type {
MarketplaceCollectionsResponse, MarketplaceCollectionsResponse,
} from '@/app/components/plugins/marketplace/types' } from '@/app/components/plugins/marketplace/types'
export const uploadPackageFile = async (file: File) => { export const uploadFile = async (file: File, isBundle: boolean) => {
const formData = new FormData() const formData = new FormData()
formData.append('pkg', file) formData.append(isBundle ? 'bundle' : 'pkg', file)
return upload({ return upload({
xhr: new XMLHttpRequest(), xhr: new XMLHttpRequest(),
data: formData, data: formData,
}, false, '/workspaces/current/plugin/upload/pkg') }, false, `/workspaces/current/plugin/upload/${isBundle ? 'bundle' : 'pkg'}`)
} }
export const updateFromMarketPlace = async (body: Record<string, string>) => { export const updateFromMarketPlace = async (body: Record<string, string>) => {

@ -7,13 +7,14 @@ import type {
Permissions, Permissions,
PluginTask, PluginTask,
PluginsFromMarketplaceResponse, PluginsFromMarketplaceResponse,
VersionListResponse,
uploadGitHubResponse, uploadGitHubResponse,
} from '@/app/components/plugins/types' } from '@/app/components/plugins/types'
import { TaskStatus } from '@/app/components/plugins/types' import { TaskStatus } from '@/app/components/plugins/types'
import type { import type {
PluginsSearchParams, PluginsSearchParams,
} from '@/app/components/plugins/marketplace/types' } from '@/app/components/plugins/marketplace/types'
import { get, post, postMarketplace } from './base' import { get, getMarketplace, post, postMarketplace } from './base'
import { import {
useMutation, useMutation,
useQuery, useQuery,
@ -52,6 +53,19 @@ export const useInstallPackageFromMarketPlace = () => {
}) })
} }
export const useVersionListOfPlugin = (pluginID: string) => {
return useQuery<{ data: VersionListResponse }>({
queryKey: [NAME_SPACE, 'versions', pluginID],
queryFn: () => getMarketplace<{ data: VersionListResponse }>(`/plugins/${pluginID}/versions`, { params: { page: 1, page_size: 100 } }),
})
}
export const useInvalidateVersionListOfPlugin = () => {
const queryClient = useQueryClient()
return (pluginID: string) => {
queryClient.invalidateQueries({ queryKey: [NAME_SPACE, 'versions', pluginID] })
}
}
export const useInstallPackageFromLocal = () => { export const useInstallPackageFromLocal = () => {
return useMutation({ return useMutation({
mutationFn: (uniqueIdentifier: string) => { mutationFn: (uniqueIdentifier: string) => {

@ -8,11 +8,8 @@ const NAME_SPACE = 'workflow'
export const useAppWorkflow = (appID: string) => { export const useAppWorkflow = (appID: string) => {
return useQuery<FetchWorkflowDraftResponse>({ return useQuery<FetchWorkflowDraftResponse>({
enabled: !!appID,
queryKey: [NAME_SPACE, 'publish', appID], queryKey: [NAME_SPACE, 'publish', appID],
queryFn: () => { queryFn: () => get<FetchWorkflowDraftResponse>(`/apps/${appID}/workflows/publish`),
if (appID === 'empty')
return Promise.resolve({} as unknown as FetchWorkflowDraftResponse)
return get<FetchWorkflowDraftResponse>(`/apps/${appID}/workflows/publish`)
},
}) })
} }

Loading…
Cancel
Save