chore: install package from GitHub

This commit is contained in:
Yi 2024-11-01 14:55:56 +08:00
parent b5be6bacef
commit c503e8ebc9
10 changed files with 239 additions and 139 deletions

View File

@ -6,15 +6,12 @@ import { RiArrowDownSLine } from '@remixicon/react'
import cn from '@/utils/classnames'
import { switchWorkspace } from '@/service/common'
import { useWorkspacesContext } from '@/context/workspace-context'
import HeaderBillingBtn from '@/app/components/billing/header-billing-btn'
import { useProviderContext } from '@/context/provider-context'
import { ToastContext } from '@/app/components/base/toast'
const WorkplaceSelector = () => {
const { t } = useTranslation()
const { notify } = useContext(ToastContext)
const { workspaces } = useWorkspacesContext()
const { enableBilling } = useProviderContext()
const currentWorkspace = workspaces.find(v => v.current)
const handleSwitchWorkspace = async (tenant_id: string) => {
try {
@ -69,11 +66,6 @@ const WorkplaceSelector = () => {
<div className='flex py-1 pl-3 pr-2 items-center gap-2 self-stretch hover:bg-state-base-hover rounded-lg' key={workspace.id} onClick={() => handleSwitchWorkspace(workspace.id)}>
<div className='flex items-center justify-center w-7 h-7 bg-[#EFF4FF] rounded-md text-xs font-medium text-primary-600'>{workspace.name[0].toLocaleUpperCase()}</div>
<div className='line-clamp-1 flex-grow overflow-hidden text-text-secondary text-ellipsis system-md-regular'>{workspace.name}</div>
{enableBilling && (
<div className='select-none'>
<HeaderBillingBtn isDisplayOnly={true} />
</div>
)}
</div>
))
}

View File

@ -0,0 +1,68 @@
import { useState } from 'react'
import Toast from '@/app/components/base/toast'
import { uploadGitHub } from '@/service/plugins'
export const useGitHubReleases = () => {
const fetchReleases = async (owner: string, repo: string, setReleases: (releases: any) => void) => {
try {
const res = await fetch(`https://api.github.com/repos/${owner}/${repo}/releases`)
if (!res.ok) throw new Error('Failed to fetch releases')
const data = await res.json()
const formattedReleases = data.map((release: any) => ({
tag_name: release.tag_name,
assets: release.assets.map((asset: any) => ({
browser_download_url: asset.browser_download_url,
name: asset.name,
})),
}))
setReleases(formattedReleases)
}
catch (error) {
Toast.notify({
type: 'error',
message: 'Failed to fetch repository releases',
})
}
}
return { fetchReleases }
}
export const useGitHubUpload = () => {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleUpload = async (
repoUrl: string,
selectedVersion: string,
selectedPackage: string,
onSuccess?: (GitHubPackage: { manifest: any; uniqueIdentifier: string }) => void,
) => {
setIsLoading(true)
setError(null)
try {
const response = await uploadGitHub(repoUrl, selectedVersion, selectedPackage)
const GitHubPackage = {
manifest: response.manifest,
uniqueIdentifier: response.plugin_unique_identifier,
}
if (onSuccess) onSuccess(GitHubPackage)
return GitHubPackage
}
catch (error) {
setError('Error installing package')
Toast.notify({
type: 'error',
message: 'Error installing package',
})
}
finally {
setIsLoading(false)
}
}
return { handleUpload, isLoading, error }
}

View File

@ -3,13 +3,16 @@
import React, { useState } from 'react'
import Modal from '@/app/components/base/modal'
import type { Item } from '@/app/components/base/select'
import type { GitHubUrlInfo, InstallState } from '@/app/components/plugins/types'
import type { InstallState } from '@/app/components/plugins/types'
import { useGitHubReleases, useGitHubUpload } from '../hooks'
import { parseGitHubUrl } from '../utils'
import type { PluginDeclaration } from '../../types'
import { InstallStepFromGitHub } from '../../types'
import Toast from '@/app/components/base/toast'
import SetURL from './steps/setURL'
import SetVersion from './steps/setVersion'
import SetPackage from './steps/setPackage'
import SelectPackage from './steps/selectPackage'
import Installed from './steps/installed'
import Loaded from './steps/loaded'
import { useTranslation } from 'react-i18next'
type InstallFromGitHubProps = {
@ -25,6 +28,8 @@ const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({ onClose }) => {
selectedPackage: '',
releases: [],
})
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
const [manifest, setManifest] = useState<PluginDeclaration | null>(null)
const versions: Item[] = state.releases.map(release => ({
value: release.tag_name,
@ -36,41 +41,16 @@ const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({ onClose }) => {
.find(release => release.tag_name === state.selectedVersion)
?.assets
.map(asset => ({
value: asset.browser_download_url,
value: asset.name,
name: asset.name,
})) || [])
: []
const parseGitHubUrl = (url: string): GitHubUrlInfo => {
const githubUrlRegex = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/?$/
const match = url.match(githubUrlRegex)
if (match) {
return {
isValid: true,
owner: match[1],
repo: match[2],
}
}
return { isValid: false }
}
const { isLoading, handleUpload, error } = useGitHubUpload()
const { fetchReleases } = useGitHubReleases()
const handleInstall = async () => {
// try {
// const response = await installPackageFromGitHub({ repo: state.repoUrl, version: state.selectedVersion, package: state.selectedPackage })
// if (response.plugin_unique_identifier) {
// setState(prevState => ({...prevState, step: InstallStep.installed}))
// console.log('Package installed:')
// }
// else {
// console.error('Failed to install package:')
// }
// }
// catch (error) {
// console.error('Error installing package:')
// }
setState(prevState => ({ ...prevState, step: InstallStepFromGitHub.installed }))
}
const handleNext = async () => {
@ -84,45 +64,48 @@ const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({ onClose }) => {
})
break
}
try {
const res = await fetch(`https://api.github.com/repos/${owner}/${repo}/releases`)
if (!res.ok)
throw new Error('Failed to fetch releases')
const data = await res.json()
const formattedReleases = data.map((release: any) => ({
tag_name: release.tag_name,
assets: release.assets.map((asset: any) => ({
browser_download_url: asset.browser_download_url,
id: asset.id,
name: asset.name,
})),
await fetchReleases(owner, repo, (fetchedReleases) => {
setState(prevState => ({
...prevState,
releases: fetchedReleases,
step: InstallStepFromGitHub.selectPackage,
}))
setState(prevState => ({ ...prevState, releases: formattedReleases, step: InstallStepFromGitHub.setVersion }))
}
catch (error) {
})
break
}
case InstallStepFromGitHub.selectPackage: {
const repo = state.repoUrl.replace('https://github.com/', '')
if (error) {
Toast.notify({
type: 'error',
message: 'Failed to fetch repository release',
message: error,
})
}
else {
await handleUpload(repo, state.selectedVersion, state.selectedPackage, (GitHubPackage) => {
setManifest(GitHubPackage.manifest)
setUniqueIdentifier(GitHubPackage.uniqueIdentifier)
setState(prevState => ({ ...prevState, step: InstallStepFromGitHub.loaded }))
})
}
break
}
case InstallStepFromGitHub.setVersion:
setState(prevState => ({ ...prevState, step: InstallStepFromGitHub.setPackage }))
break
case InstallStepFromGitHub.setPackage:
case InstallStepFromGitHub.loaded:
setState(prevState => ({ ...prevState, step: InstallStepFromGitHub.installed }))
handleInstall()
break
case InstallStepFromGitHub.installed:
break
}
}
const handleBack = () => {
setState((prevState) => {
switch (prevState.step) {
case InstallStepFromGitHub.setVersion:
case InstallStepFromGitHub.selectPackage:
return { ...prevState, step: InstallStepFromGitHub.setUrl }
case InstallStepFromGitHub.setPackage:
return { ...prevState, step: InstallStepFromGitHub.setVersion }
case InstallStepFromGitHub.loaded:
return { ...prevState, step: InstallStepFromGitHub.selectPackage }
default:
return prevState
}
@ -155,22 +138,24 @@ const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({ onClose }) => {
onCancel={onClose}
/>
)}
{state.step === InstallStepFromGitHub.setVersion && (
<SetVersion
{state.step === InstallStepFromGitHub.selectPackage && (
<SelectPackage
selectedVersion={state.selectedVersion}
versions={versions}
onSelect={item => setState(prevState => ({ ...prevState, selectedVersion: item.value as string }))}
onSelectVersion={item => setState(prevState => ({ ...prevState, selectedVersion: item.value as string }))}
selectedPackage={state.selectedPackage}
packages={packages}
onSelectPackage={item => setState(prevState => ({ ...prevState, selectedPackage: item.value as string }))}
onNext={handleNext}
onBack={handleBack}
/>
)}
{state.step === InstallStepFromGitHub.setPackage && (
<SetPackage
selectedPackage={state.selectedPackage}
packages={packages}
onSelect={item => setState(prevState => ({ ...prevState, selectedPackage: item.value as string }))}
onInstall={handleInstall}
{state.step === InstallStepFromGitHub.loaded && (
<Loaded
isLoading={isLoading}
payload={manifest as any}
onBack={handleBack}
onInstall={handleNext}
/>
)}
{state.step === InstallStepFromGitHub.installed && (

View File

@ -0,0 +1,55 @@
'use client'
import React from 'react'
import Button from '@/app/components/base/button'
import type { PluginDeclaration } from '../../../types'
import Card from '../../../card'
import Badge, { BadgeState } from '@/app/components/base/badge/index'
import { pluginManifestToCardPluginProps } from '../../utils'
import { useTranslation } from 'react-i18next'
type LoadedProps = {
isLoading: boolean
payload: PluginDeclaration
onBack: () => void
onInstall: () => void
}
const i18nPrefix = 'plugin.installModal'
const Loaded: React.FC<LoadedProps> = ({ isLoading, payload, onBack, onInstall }) => {
const { t } = useTranslation()
return (
<>
<div className='text-text-secondary system-md-regular'>
<p>{t(`${i18nPrefix}.readyToInstall`)}</p>
</div>
<div className='flex p-2 items-start content-start gap-1 self-stretch flex-wrap rounded-2xl bg-background-section-burn'>
<Card
className='w-full'
payload={pluginManifestToCardPluginProps(payload)}
titleLeft={<Badge className='mx-1' size="s" state={BadgeState.Default}>{payload.version}</Badge>}
/>
</div>
<div className='flex justify-end items-center gap-2 self-stretch mt-4'>
<Button
variant='secondary'
className='min-w-[72px]'
onClick={onBack}
>
{t('plugin.installModal.back')}
</Button>
<Button
variant='primary'
className='min-w-[72px]'
onClick={onInstall}
disabled={isLoading}
>
{t('plugin.installModal.next')}
</Button>
</div>
</>
)
}
export default Loaded

View File

@ -1,18 +1,32 @@
'use client'
import React from 'react'
import type { Item } from '@/app/components/base/select'
import { PortalSelect } from '@/app/components/base/select'
import Button from '@/app/components/base/button'
import { useTranslation } from 'react-i18next'
type SetVersionProps = {
type SelectPackageProps = {
selectedVersion: string
versions: Item[]
onSelect: (item: Item) => void
onSelectVersion: (item: Item) => void
selectedPackage: string
packages: Item[]
onSelectPackage: (item: Item) => void
onNext: () => void
onBack: () => void
}
const SetVersion: React.FC<SetVersionProps> = ({ selectedVersion, versions, onSelect, onNext, onBack }) => {
const SelectPackage: React.FC<SelectPackageProps> = ({
selectedVersion,
versions,
onSelectVersion,
selectedPackage,
packages,
onSelectPackage,
onNext,
onBack,
}) => {
const { t } = useTranslation()
return (
<>
@ -24,11 +38,24 @@ const SetVersion: React.FC<SetVersionProps> = ({ selectedVersion, versions, onSe
</label>
<PortalSelect
value={selectedVersion}
onSelect={onSelect}
onSelect={onSelectVersion}
items={versions}
placeholder={t('plugin.installFromGitHub.selectVersionPlaceholder') || ''}
popupClassName='w-[432px] z-[1001]'
/>
<label
htmlFor='package'
className='flex flex-col justify-center items-start self-stretch text-text-secondary'
>
<span className='system-sm-semibold'>{t('plugin.installFromGitHub.selectPackage')}</span>
</label>
<PortalSelect
value={selectedPackage}
onSelect={onSelectPackage}
items={packages}
placeholder={t('plugin.installFromGitHub.selectPackagePlaceholder') || ''}
popupClassName='w-[432px] z-[1001]'
/>
<div className='flex justify-end items-center gap-2 self-stretch mt-4'>
<Button
variant='secondary'
@ -41,7 +68,7 @@ const SetVersion: React.FC<SetVersionProps> = ({ selectedVersion, versions, onSe
variant='primary'
className='min-w-[72px]'
onClick={onNext}
disabled={!selectedVersion}
disabled={!selectedVersion || !selectedPackage}
>
{t('plugin.installModal.next')}
</Button>
@ -50,4 +77,4 @@ const SetVersion: React.FC<SetVersionProps> = ({ selectedVersion, versions, onSe
)
}
export default SetVersion
export default SelectPackage

View File

@ -1,53 +0,0 @@
import React from 'react'
import type { Item } from '@/app/components/base/select'
import { PortalSelect } from '@/app/components/base/select'
import Button from '@/app/components/base/button'
import { useTranslation } from 'react-i18next'
type SetPackageProps = {
selectedPackage: string
packages: Item[]
onSelect: (item: Item) => void
onInstall: () => void
onBack: () => void
}
const SetPackage: React.FC<SetPackageProps> = ({ selectedPackage, packages, onSelect, onInstall, onBack }) => {
const { t } = useTranslation()
return (
<>
<label
htmlFor='package'
className='flex flex-col justify-center items-start self-stretch text-text-secondary'
>
<span className='system-sm-semibold'>{t('plugin.installFromGitHub.selectPackage')}</span>
</label>
<PortalSelect
value={selectedPackage}
onSelect={onSelect}
items={packages}
placeholder={t('plugin.installFromGitHub.selectPackagePlaceholder') || ''}
popupClassName='w-[432px] z-[1001]'
/>
<div className='flex justify-end items-center gap-2 self-stretch mt-4'>
<Button
variant='secondary'
className='min-w-[72px]'
onClick={onBack}
>
{t('plugin.installModal.back')}
</Button>
<Button
variant='primary'
className='min-w-[72px]'
onClick={onInstall}
disabled={!selectedPackage}
>
{t('plugin.installModal.install')}
</Button>
</div>
</>
)
}
export default SetPackage

View File

@ -1,3 +1,5 @@
'use client'
import React from 'react'
import Button from '@/app/components/base/button'
import { useTranslation } from 'react-i18next'

View File

@ -1,4 +1,5 @@
import type { Plugin, PluginDeclaration, PluginManifestInMarket } from '../types'
import type { GitHubUrlInfo } from '@/app/components/plugins/types'
export const pluginManifestToCardPluginProps = (pluginManifest: PluginDeclaration): Plugin => {
return {
@ -18,6 +19,7 @@ export const pluginManifestToCardPluginProps = (pluginManifest: PluginDeclaratio
endpoint: {
settings: [],
},
tags: [],
}
}
@ -39,5 +41,11 @@ export const pluginManifestInMarketToPluginProps = (pluginManifest: PluginManife
endpoint: {
settings: [],
},
tags: [],
}
}
export const parseGitHubUrl = (url: string): GitHubUrlInfo => {
const match = url.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/?$/)
return match ? { isValid: true, owner: match[1], repo: match[2] } : { isValid: false }
}

View File

@ -133,8 +133,8 @@ export type Permissions = {
export enum InstallStepFromGitHub {
setUrl = 'url',
setVersion = 'version',
setPackage = 'package',
selectPackage = 'selecting',
loaded = 'loaded',
installed = 'installed',
}
@ -205,6 +205,11 @@ export type InstallPackageResponse = {
task_id: string
}
export type uploadGitHubResponse = {
plugin_unique_identifier: string
manifest: PluginDeclaration
}
export type DebugInfo = {
key: string
host: string

View File

@ -14,6 +14,7 @@ import type {
TaskStatusResponse,
UninstallPluginResponse,
UpdateEndpointRequest,
uploadGitHubResponse,
} from '@/app/components/plugins/types'
import type { DebugInfo as DebugInfoTypes } from '@/app/components/plugins/types'
import type {
@ -51,12 +52,6 @@ export const disableEndpoint: Fetcher<EndpointOperationResponse, { url: string;
return post<EndpointOperationResponse>(url, { body: { endpoint_id: endpointID } })
}
export const installPackageFromGitHub: Fetcher<InstallPackageResponse, { repo: string; version: string; package: string }> = ({ repo, version, package: packageName }) => {
return post<InstallPackageResponse>('/workspaces/current/plugin/upload/github', {
body: { repo, version, package: packageName },
})
}
export const fetchDebugKey = async () => {
return get<DebugInfoTypes>('/workspaces/current/plugin/debugging-key')
}
@ -76,6 +71,22 @@ export const installPackageFromLocal = async (uniqueIdentifier: string) => {
})
}
export const uploadGitHub = async (repoUrl: string, selectedVersion: string, selectedPackage: string) => {
return post<uploadGitHubResponse>('/workspaces/current/plugin/upload/github', {
body: {
repo: repoUrl,
version: selectedVersion,
package: selectedPackage,
},
})
}
export const installPackageFromGitHub = async (uniqueIdentifier: string) => {
return post<InstallPackageResponse>('/workspaces/current/plugin/install/github', {
body: { plugin_unique_identifiers: [uniqueIdentifier] },
})
}
export const fetchIcon = (tenantId: string, fileName: string) => {
return get(`workspaces/current/plugin/icon?tenant_id=${tenantId}&filename=${fileName}`)
}