FEAT: NEW WORKFLOW ENGINE (#3160)
Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: Yeuoly <admin@srmxy.cn> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: StyleZhang <jasonapring2015@outlook.com> Co-authored-by: jyong <jyong@dify.ai> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: jyong <718720800@qq.com>
This commit is contained in:
parent
2fb9850af5
commit
7753ba2d37
1161 changed files with 103836 additions and 10327 deletions
119
web/app/components/workflow/block-icon.tsx
Normal file
119
web/app/components/workflow/block-icon.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import type { FC } from 'react'
|
||||
import { memo } from 'react'
|
||||
import { BlockEnum } from './types'
|
||||
import {
|
||||
Answer,
|
||||
Code,
|
||||
End,
|
||||
Home,
|
||||
Http,
|
||||
IfElse,
|
||||
KnowledgeRetrieval,
|
||||
Llm,
|
||||
QuestionClassifier,
|
||||
TemplatingTransform,
|
||||
VariableX,
|
||||
} from '@/app/components/base/icons/src/vender/workflow'
|
||||
import AppIcon from '@/app/components/base/app-icon'
|
||||
|
||||
type BlockIconProps = {
|
||||
type: BlockEnum
|
||||
size?: string
|
||||
className?: string
|
||||
toolIcon?: string | { content: string; background: string }
|
||||
}
|
||||
const ICON_CONTAINER_CLASSNAME_SIZE_MAP: Record<string, string> = {
|
||||
xs: 'w-4 h-4 rounded-[5px] shadow-xs',
|
||||
sm: 'w-5 h-5 rounded-md shadow-xs',
|
||||
md: 'w-6 h-6 rounded-lg shadow-md',
|
||||
}
|
||||
const getIcon = (type: BlockEnum, className: string) => {
|
||||
return {
|
||||
[BlockEnum.Start]: <Home className={className} />,
|
||||
[BlockEnum.LLM]: <Llm className={className} />,
|
||||
[BlockEnum.Code]: <Code className={className} />,
|
||||
[BlockEnum.End]: <End className={className} />,
|
||||
[BlockEnum.IfElse]: <IfElse className={className} />,
|
||||
[BlockEnum.HttpRequest]: <Http className={className} />,
|
||||
[BlockEnum.Answer]: <Answer className={className} />,
|
||||
[BlockEnum.KnowledgeRetrieval]: <KnowledgeRetrieval className={className} />,
|
||||
[BlockEnum.QuestionClassifier]: <QuestionClassifier className={className} />,
|
||||
[BlockEnum.TemplateTransform]: <TemplatingTransform className={className} />,
|
||||
[BlockEnum.VariableAssigner]: <VariableX className={className} />,
|
||||
[BlockEnum.Tool]: <VariableX className={className} />,
|
||||
}[type]
|
||||
}
|
||||
const ICON_CONTAINER_BG_COLOR_MAP: Record<string, string> = {
|
||||
[BlockEnum.Start]: 'bg-primary-500',
|
||||
[BlockEnum.LLM]: 'bg-[#6172F3]',
|
||||
[BlockEnum.Code]: 'bg-[#2E90FA]',
|
||||
[BlockEnum.End]: 'bg-[#F79009]',
|
||||
[BlockEnum.IfElse]: 'bg-[#06AED4]',
|
||||
[BlockEnum.HttpRequest]: 'bg-[#875BF7]',
|
||||
[BlockEnum.Answer]: 'bg-[#F79009]',
|
||||
[BlockEnum.KnowledgeRetrieval]: 'bg-[#16B364]',
|
||||
[BlockEnum.QuestionClassifier]: 'bg-[#16B364]',
|
||||
[BlockEnum.TemplateTransform]: 'bg-[#2E90FA]',
|
||||
[BlockEnum.VariableAssigner]: 'bg-[#2E90FA]',
|
||||
}
|
||||
const BlockIcon: FC<BlockIconProps> = ({
|
||||
type,
|
||||
size = 'sm',
|
||||
className,
|
||||
toolIcon,
|
||||
}) => {
|
||||
return (
|
||||
<div className={`
|
||||
flex items-center justify-center border-[0.5px] border-white/[0.02] text-white
|
||||
${ICON_CONTAINER_CLASSNAME_SIZE_MAP[size]}
|
||||
${ICON_CONTAINER_BG_COLOR_MAP[type]}
|
||||
${toolIcon && '!shadow-none'}
|
||||
${className}
|
||||
`}
|
||||
>
|
||||
{
|
||||
type !== BlockEnum.Tool && (
|
||||
getIcon(type, size === 'xs' ? 'w-3 h-3' : 'w-3.5 h-3.5')
|
||||
)
|
||||
}
|
||||
{
|
||||
type === BlockEnum.Tool && toolIcon && (
|
||||
<>
|
||||
{
|
||||
typeof toolIcon === 'string'
|
||||
? (
|
||||
<div
|
||||
className='shrink-0 w-full h-full bg-cover bg-center rounded-md'
|
||||
style={{
|
||||
backgroundImage: `url(${toolIcon})`,
|
||||
}}
|
||||
></div>
|
||||
)
|
||||
: (
|
||||
<AppIcon
|
||||
className='shrink-0 !w-full !h-full'
|
||||
size='tiny'
|
||||
icon={toolIcon?.content}
|
||||
background={toolIcon?.background}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const VarBlockIcon: FC<BlockIconProps> = ({
|
||||
type,
|
||||
className,
|
||||
}) => {
|
||||
return (
|
||||
<>
|
||||
{getIcon(type, `w-3 h-3 ${className}`)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(BlockIcon)
|
||||
120
web/app/components/workflow/block-selector/blocks.tsx
Normal file
120
web/app/components/workflow/block-selector/blocks.tsx
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useMemo,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { groupBy } from 'lodash-es'
|
||||
import BlockIcon from '../block-icon'
|
||||
import { BlockEnum } from '../types'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useNodesExtraData,
|
||||
} from '../hooks'
|
||||
import { BLOCK_CLASSIFICATIONS } from './constants'
|
||||
import { useBlocks } from './hooks'
|
||||
import type { ToolDefaultValue } from './types'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
|
||||
type BlocksProps = {
|
||||
searchText: string
|
||||
onSelect: (type: BlockEnum, tool?: ToolDefaultValue) => void
|
||||
availableBlocksTypes?: BlockEnum[]
|
||||
}
|
||||
const Blocks = ({
|
||||
searchText,
|
||||
onSelect,
|
||||
availableBlocksTypes = [],
|
||||
}: BlocksProps) => {
|
||||
const { t } = useTranslation()
|
||||
const isChatMode = useIsChatMode()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const blocks = useBlocks()
|
||||
|
||||
const groups = useMemo(() => {
|
||||
return BLOCK_CLASSIFICATIONS.reduce((acc, classification) => {
|
||||
const list = groupBy(blocks, 'classification')[classification].filter((block) => {
|
||||
if (block.type === BlockEnum.Answer && !isChatMode)
|
||||
return false
|
||||
|
||||
return block.title.toLowerCase().includes(searchText.toLowerCase()) && availableBlocksTypes.includes(block.type)
|
||||
})
|
||||
|
||||
return {
|
||||
...acc,
|
||||
[classification]: list,
|
||||
}
|
||||
}, {} as Record<string, typeof blocks>)
|
||||
}, [blocks, isChatMode, searchText, availableBlocksTypes])
|
||||
const isEmpty = Object.values(groups).every(list => !list.length)
|
||||
|
||||
const renderGroup = useCallback((classification: string) => {
|
||||
const list = groups[classification]
|
||||
|
||||
return (
|
||||
<div
|
||||
key={classification}
|
||||
className='mb-1 last-of-type:mb-0'
|
||||
>
|
||||
{
|
||||
classification !== '-' && !!list.length && (
|
||||
<div className='flex items-start px-3 h-[22px] text-xs font-medium text-gray-500'>
|
||||
{t(`workflow.tabs.${classification}`)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
list.map(block => (
|
||||
<Tooltip
|
||||
key={block.type}
|
||||
selector={`workflow-block-${block.type}`}
|
||||
position='right'
|
||||
className='!p-0 !px-3 !py-2.5 !w-[200px] !leading-[18px] !text-xs !text-gray-700 !border-[0.5px] !border-black/5 !bg-transparent !rounded-xl !shadow-lg'
|
||||
htmlContent={(
|
||||
<div>
|
||||
<div className='flex items-center mb-2'>
|
||||
<BlockIcon
|
||||
size='md'
|
||||
className='mr-2'
|
||||
type={block.type}
|
||||
/>
|
||||
<div className='text-sm text-gray-900'>{block.title}</div>
|
||||
</div>
|
||||
{nodesExtraData[block.type].about}
|
||||
</div>
|
||||
)}
|
||||
noArrow
|
||||
>
|
||||
<div
|
||||
key={block.type}
|
||||
className='flex items-center px-3 w-full h-8 rounded-lg hover:bg-gray-50 cursor-pointer'
|
||||
onClick={() => onSelect(block.type)}
|
||||
>
|
||||
<BlockIcon
|
||||
className='mr-2'
|
||||
type={block.type}
|
||||
/>
|
||||
<div className='text-sm text-gray-900'>{block.title}</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}, [groups, nodesExtraData, onSelect, t])
|
||||
|
||||
return (
|
||||
<div className='p-1'>
|
||||
{
|
||||
isEmpty && (
|
||||
<div className='flex items-center px-3 h-[22px] text-xs font-medium text-gray-500'>{t('workflow.tabs.noResult')}</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
!isEmpty && BLOCK_CLASSIFICATIONS.map(renderGroup)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Blocks)
|
||||
70
web/app/components/workflow/block-selector/constants.tsx
Normal file
70
web/app/components/workflow/block-selector/constants.tsx
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import type { Block } from '../types'
|
||||
import { BlockEnum } from '../types'
|
||||
import { BlockClassificationEnum } from './types'
|
||||
|
||||
export const BLOCKS: Block[] = [
|
||||
{
|
||||
classification: BlockClassificationEnum.Default,
|
||||
type: BlockEnum.Start,
|
||||
title: 'Start',
|
||||
description: '',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Default,
|
||||
type: BlockEnum.LLM,
|
||||
title: 'LLM',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Default,
|
||||
type: BlockEnum.KnowledgeRetrieval,
|
||||
title: 'Knowledge Retrieval',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Default,
|
||||
type: BlockEnum.End,
|
||||
title: 'End',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Default,
|
||||
type: BlockEnum.Answer,
|
||||
title: 'Direct Answer',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.QuestionUnderstand,
|
||||
type: BlockEnum.QuestionClassifier,
|
||||
title: 'Question Classifier',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Logic,
|
||||
type: BlockEnum.IfElse,
|
||||
title: 'IF/ELSE',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Transform,
|
||||
type: BlockEnum.Code,
|
||||
title: 'Code',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Transform,
|
||||
type: BlockEnum.TemplateTransform,
|
||||
title: 'Templating Transform',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Transform,
|
||||
type: BlockEnum.VariableAssigner,
|
||||
title: 'Variable Assigner',
|
||||
},
|
||||
{
|
||||
classification: BlockClassificationEnum.Utilities,
|
||||
type: BlockEnum.HttpRequest,
|
||||
title: 'HTTP Request',
|
||||
},
|
||||
]
|
||||
|
||||
export const BLOCK_CLASSIFICATIONS: string[] = [
|
||||
BlockClassificationEnum.Default,
|
||||
BlockClassificationEnum.QuestionUnderstand,
|
||||
BlockClassificationEnum.Logic,
|
||||
BlockClassificationEnum.Transform,
|
||||
BlockClassificationEnum.Utilities,
|
||||
]
|
||||
33
web/app/components/workflow/block-selector/hooks.ts
Normal file
33
web/app/components/workflow/block-selector/hooks.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { BLOCKS } from './constants'
|
||||
import { TabsEnum } from './types'
|
||||
|
||||
export const useBlocks = () => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return BLOCKS.map((block) => {
|
||||
return {
|
||||
...block,
|
||||
title: t(`workflow.blocks.${block.type}`),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useTabs = () => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return [
|
||||
{
|
||||
key: TabsEnum.Blocks,
|
||||
name: t('workflow.tabs.blocks'),
|
||||
},
|
||||
{
|
||||
key: TabsEnum.BuiltInTool,
|
||||
name: t('workflow.tabs.builtInTool'),
|
||||
},
|
||||
{
|
||||
key: TabsEnum.CustomTool,
|
||||
name: t('workflow.tabs.customTool'),
|
||||
},
|
||||
]
|
||||
}
|
||||
146
web/app/components/workflow/block-selector/index.tsx
Normal file
146
web/app/components/workflow/block-selector/index.tsx
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import type {
|
||||
FC,
|
||||
MouseEventHandler,
|
||||
} from 'react'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type {
|
||||
OffsetOptions,
|
||||
Placement,
|
||||
} from '@floating-ui/react'
|
||||
import type { BlockEnum, OnSelectBlock } from '../types'
|
||||
import Tabs from './tabs'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import {
|
||||
Plus02,
|
||||
SearchLg,
|
||||
} from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'
|
||||
|
||||
type NodeSelectorProps = {
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
onSelect: OnSelectBlock
|
||||
trigger?: (open: boolean) => React.ReactNode
|
||||
placement?: Placement
|
||||
offset?: OffsetOptions
|
||||
triggerStyle?: React.CSSProperties
|
||||
triggerClassName?: (open: boolean) => string
|
||||
triggerInnerClassName?: string
|
||||
popupClassName?: string
|
||||
asChild?: boolean
|
||||
availableBlocksTypes?: BlockEnum[]
|
||||
disabled?: boolean
|
||||
}
|
||||
const NodeSelector: FC<NodeSelectorProps> = ({
|
||||
open: openFromProps,
|
||||
onOpenChange,
|
||||
onSelect,
|
||||
trigger,
|
||||
placement = 'right',
|
||||
offset = 6,
|
||||
triggerClassName,
|
||||
triggerInnerClassName,
|
||||
triggerStyle,
|
||||
popupClassName,
|
||||
asChild,
|
||||
availableBlocksTypes,
|
||||
disabled,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const [localOpen, setLocalOpen] = useState(false)
|
||||
const open = openFromProps === undefined ? localOpen : openFromProps
|
||||
const handleOpenChange = useCallback((newOpen: boolean) => {
|
||||
setLocalOpen(newOpen)
|
||||
|
||||
if (onOpenChange)
|
||||
onOpenChange(newOpen)
|
||||
}, [onOpenChange])
|
||||
const handleTrigger = useCallback<MouseEventHandler<HTMLDivElement>>((e) => {
|
||||
if (disabled)
|
||||
return
|
||||
e.stopPropagation()
|
||||
handleOpenChange(!open)
|
||||
}, [handleOpenChange, open, disabled])
|
||||
const handleSelect = useCallback<OnSelectBlock>((type, toolDefaultValue) => {
|
||||
handleOpenChange(false)
|
||||
onSelect(type, toolDefaultValue)
|
||||
}, [handleOpenChange, onSelect])
|
||||
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
placement={placement}
|
||||
offset={offset}
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
>
|
||||
<PortalToFollowElemTrigger
|
||||
asChild={asChild}
|
||||
onClick={handleTrigger}
|
||||
className={triggerInnerClassName}
|
||||
>
|
||||
{
|
||||
trigger
|
||||
? trigger(open)
|
||||
: (
|
||||
<div
|
||||
className={`
|
||||
flex items-center justify-center
|
||||
w-4 h-4 rounded-full bg-primary-600 cursor-pointer z-10
|
||||
${triggerClassName?.(open)}
|
||||
`}
|
||||
style={triggerStyle}
|
||||
>
|
||||
<Plus02 className='w-2.5 h-2.5 text-white' />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-[1000]'>
|
||||
<div className={`rounded-lg border-[0.5px] border-gray-200 bg-white shadow-lg ${popupClassName}`}>
|
||||
<div className='px-2 pt-2'>
|
||||
<div
|
||||
className='flex items-center px-2 rounded-lg bg-gray-100'
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<SearchLg className='shrink-0 ml-[1px] mr-[5px] w-3.5 h-3.5 text-gray-400' />
|
||||
<input
|
||||
value={searchText}
|
||||
className='grow px-0.5 py-[7px] text-[13px] text-gray-700 bg-transparent appearance-none outline-none caret-primary-600 placeholder:text-gray-400'
|
||||
placeholder={t('workflow.tabs.searchBlock') || ''}
|
||||
onChange={e => setSearchText(e.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
{
|
||||
searchText && (
|
||||
<div
|
||||
className='flex items-center justify-center ml-[5px] w-[18px] h-[18px] cursor-pointer'
|
||||
onClick={() => setSearchText('')}
|
||||
>
|
||||
<XCircle className='w-[14px] h-[14px] text-gray-400' />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<Tabs
|
||||
onSelect={handleSelect}
|
||||
searchText={searchText}
|
||||
availableBlocksTypes={availableBlocksTypes}
|
||||
/>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(NodeSelector)
|
||||
76
web/app/components/workflow/block-selector/tabs.tsx
Normal file
76
web/app/components/workflow/block-selector/tabs.tsx
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import type { FC } from 'react'
|
||||
import {
|
||||
memo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import type { BlockEnum } from '../types'
|
||||
import { useTabs } from './hooks'
|
||||
import type { ToolDefaultValue } from './types'
|
||||
import { TabsEnum } from './types'
|
||||
import Tools from './tools'
|
||||
import Blocks from './blocks'
|
||||
|
||||
export type TabsProps = {
|
||||
searchText: string
|
||||
onSelect: (type: BlockEnum, tool?: ToolDefaultValue) => void
|
||||
availableBlocksTypes?: BlockEnum[]
|
||||
}
|
||||
const Tabs: FC<TabsProps> = ({
|
||||
searchText,
|
||||
onSelect,
|
||||
availableBlocksTypes,
|
||||
}) => {
|
||||
const tabs = useTabs()
|
||||
const [activeTab, setActiveTab] = useState(tabs[0].key)
|
||||
|
||||
return (
|
||||
<div onClick={e => e.stopPropagation()}>
|
||||
<div className='flex items-center px-3 border-b-[0.5px] border-b-black/5'>
|
||||
{
|
||||
tabs.map(tab => (
|
||||
<div
|
||||
key={tab.key}
|
||||
className={`
|
||||
relative mr-4 h-[34px] leading-[34px] text-[13px] font-medium cursor-pointer
|
||||
${activeTab === tab.key
|
||||
? 'text-gray-700 after:absolute after:bottom-0 after:left-0 after:h-0.5 after:w-full after:bg-primary-600'
|
||||
: 'text-gray-500'}
|
||||
`}
|
||||
onClick={() => setActiveTab(tab.key)}
|
||||
>
|
||||
{tab.name}
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
{
|
||||
activeTab === TabsEnum.Blocks && (
|
||||
<Blocks
|
||||
searchText={searchText}
|
||||
onSelect={onSelect}
|
||||
availableBlocksTypes={availableBlocksTypes}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
activeTab === TabsEnum.BuiltInTool && (
|
||||
<Tools
|
||||
onSelect={onSelect}
|
||||
searchText={searchText}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
activeTab === TabsEnum.CustomTool && (
|
||||
<Tools
|
||||
isCustom
|
||||
searchText={searchText}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Tabs)
|
||||
113
web/app/components/workflow/block-selector/tools.tsx
Normal file
113
web/app/components/workflow/block-selector/tools.tsx
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useMemo,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import BlockIcon from '../block-icon'
|
||||
import { BlockEnum } from '../types'
|
||||
import type { ToolWithProvider } from '../types'
|
||||
import { useStore } from '../store'
|
||||
import type { ToolDefaultValue } from './types'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
import { useGetLanguage } from '@/context/i18n'
|
||||
|
||||
type ToolsProps = {
|
||||
isCustom?: boolean
|
||||
onSelect: (type: BlockEnum, tool?: ToolDefaultValue) => void
|
||||
searchText: string
|
||||
}
|
||||
const Blocks = ({
|
||||
isCustom,
|
||||
searchText,
|
||||
onSelect,
|
||||
}: ToolsProps) => {
|
||||
const { t } = useTranslation()
|
||||
const language = useGetLanguage()
|
||||
const buildInTools = useStore(s => s.buildInTools)
|
||||
const customTools = useStore(s => s.customTools)
|
||||
|
||||
const tools = useMemo(() => {
|
||||
const currentTools = isCustom ? customTools : buildInTools
|
||||
|
||||
return currentTools.filter((toolWithProvider) => {
|
||||
return toolWithProvider.tools.some((tool) => {
|
||||
return tool.label[language].toLowerCase().includes(searchText.toLowerCase())
|
||||
})
|
||||
})
|
||||
}, [isCustom, customTools, buildInTools, searchText, language])
|
||||
|
||||
const renderGroup = useCallback((toolWithProvider: ToolWithProvider) => {
|
||||
const list = toolWithProvider.tools
|
||||
|
||||
return (
|
||||
<div
|
||||
key={toolWithProvider.id}
|
||||
className='mb-1 last-of-type:mb-0'
|
||||
>
|
||||
<div className='flex items-start px-3 h-[22px] text-xs font-medium text-gray-500'>
|
||||
{toolWithProvider.label[language]}
|
||||
</div>
|
||||
{
|
||||
list.map(tool => (
|
||||
<Tooltip
|
||||
key={tool.name}
|
||||
selector={`workflow-block-tool-${tool.name}`}
|
||||
position='right'
|
||||
className='!p-0 !px-3 !py-2.5 !w-[200px] !leading-[18px] !text-xs !text-gray-700 !border-[0.5px] !border-black/5 !bg-transparent !rounded-xl !shadow-lg'
|
||||
htmlContent={(
|
||||
<div>
|
||||
<div className='flex items-center mb-2'>
|
||||
<BlockIcon
|
||||
size='md'
|
||||
className='mr-2'
|
||||
type={BlockEnum.Tool}
|
||||
toolIcon={toolWithProvider.icon}
|
||||
/>
|
||||
<div className='text-sm text-gray-900'>{tool.label[language]}</div>
|
||||
</div>
|
||||
{tool.description[language]}
|
||||
</div>
|
||||
)}
|
||||
noArrow
|
||||
>
|
||||
<div
|
||||
className='flex items-center px-3 w-full h-8 rounded-lg hover:bg-gray-50 cursor-pointer'
|
||||
onClick={() => onSelect(BlockEnum.Tool, {
|
||||
provider_id: toolWithProvider.id,
|
||||
provider_type: toolWithProvider.type,
|
||||
provider_name: toolWithProvider.name,
|
||||
tool_name: tool.name,
|
||||
tool_label: tool.label[language],
|
||||
title: tool.label[language],
|
||||
})}
|
||||
>
|
||||
<BlockIcon
|
||||
className='mr-2'
|
||||
type={BlockEnum.Tool}
|
||||
toolIcon={toolWithProvider.icon}
|
||||
/>
|
||||
<div className='text-sm text-gray-900'>{tool.label[language]}</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}, [onSelect, language])
|
||||
|
||||
return (
|
||||
<div className='p-1 max-h-[464px] overflow-y-auto'>
|
||||
{
|
||||
!tools.length && (
|
||||
<div className='flex items-center px-3 h-[22px] text-xs font-medium text-gray-500'>{t('workflow.tabs.noResult')}</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
!!tools.length && tools.map(renderGroup)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Blocks)
|
||||
22
web/app/components/workflow/block-selector/types.ts
Normal file
22
web/app/components/workflow/block-selector/types.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
export enum TabsEnum {
|
||||
Blocks = 'blocks',
|
||||
BuiltInTool = 'built-in-tool',
|
||||
CustomTool = 'custom-tool',
|
||||
}
|
||||
|
||||
export enum BlockClassificationEnum {
|
||||
Default = '-',
|
||||
QuestionUnderstand = 'question-understand',
|
||||
Logic = 'logic',
|
||||
Transform = 'transform',
|
||||
Utilities = 'utilities',
|
||||
}
|
||||
|
||||
export type ToolDefaultValue = {
|
||||
provider_id: string
|
||||
provider_type: string
|
||||
provider_name: string
|
||||
tool_name: string
|
||||
tool_label: string
|
||||
title: string
|
||||
}
|
||||
404
web/app/components/workflow/constants.ts
Normal file
404
web/app/components/workflow/constants.ts
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
import type { Var } from './types'
|
||||
import { BlockEnum, VarType } from './types'
|
||||
import StartNodeDefault from './nodes/start/default'
|
||||
import AnswerDefault from './nodes/answer/default'
|
||||
import LLMDefault from './nodes/llm/default'
|
||||
import KnowledgeRetrievalDefault from './nodes/knowledge-retrieval/default'
|
||||
import QuestionClassifierDefault from './nodes/question-classifier/default'
|
||||
import IfElseDefault from './nodes/if-else/default'
|
||||
import CodeDefault from './nodes/code/default'
|
||||
import TemplateTransformDefault from './nodes/template-transform/default'
|
||||
import HttpRequestDefault from './nodes/http/default'
|
||||
import ToolDefault from './nodes/tool/default'
|
||||
import VariableAssignerDefault from './nodes/variable-assigner/default'
|
||||
import EndNodeDefault from './nodes/end/default'
|
||||
|
||||
type NodesExtraData = {
|
||||
author: string
|
||||
about: string
|
||||
availablePrevNodes: BlockEnum[]
|
||||
availableNextNodes: BlockEnum[]
|
||||
getAvailablePrevNodes: (isChatMode: boolean) => BlockEnum[]
|
||||
getAvailableNextNodes: (isChatMode: boolean) => BlockEnum[]
|
||||
checkValid: any
|
||||
}
|
||||
export const NODES_EXTRA_DATA: Record<BlockEnum, NodesExtraData> = {
|
||||
[BlockEnum.Start]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: StartNodeDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: StartNodeDefault.getAvailableNextNodes,
|
||||
checkValid: StartNodeDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.End]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: EndNodeDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: EndNodeDefault.getAvailableNextNodes,
|
||||
checkValid: EndNodeDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.Answer]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: AnswerDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: AnswerDefault.getAvailableNextNodes,
|
||||
checkValid: AnswerDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.LLM]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: LLMDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: LLMDefault.getAvailableNextNodes,
|
||||
checkValid: LLMDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.KnowledgeRetrieval]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: KnowledgeRetrievalDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: KnowledgeRetrievalDefault.getAvailableNextNodes,
|
||||
checkValid: KnowledgeRetrievalDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.IfElse]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: IfElseDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: IfElseDefault.getAvailableNextNodes,
|
||||
checkValid: IfElseDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.Code]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: CodeDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: CodeDefault.getAvailableNextNodes,
|
||||
checkValid: CodeDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.TemplateTransform]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: TemplateTransformDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: TemplateTransformDefault.getAvailableNextNodes,
|
||||
checkValid: TemplateTransformDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.QuestionClassifier]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: QuestionClassifierDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: QuestionClassifierDefault.getAvailableNextNodes,
|
||||
checkValid: QuestionClassifierDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.HttpRequest]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: HttpRequestDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: HttpRequestDefault.getAvailableNextNodes,
|
||||
checkValid: HttpRequestDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.VariableAssigner]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: VariableAssignerDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: VariableAssignerDefault.getAvailableNextNodes,
|
||||
checkValid: VariableAssignerDefault.checkValid,
|
||||
},
|
||||
[BlockEnum.Tool]: {
|
||||
author: 'Dify',
|
||||
about: '',
|
||||
availablePrevNodes: [],
|
||||
availableNextNodes: [],
|
||||
getAvailablePrevNodes: ToolDefault.getAvailablePrevNodes,
|
||||
getAvailableNextNodes: ToolDefault.getAvailableNextNodes,
|
||||
checkValid: ToolDefault.checkValid,
|
||||
},
|
||||
}
|
||||
|
||||
export const ALL_CHAT_AVAILABLE_BLOCKS = Object.keys(NODES_EXTRA_DATA).filter(key => key !== BlockEnum.End && key !== BlockEnum.Start) as BlockEnum[]
|
||||
export const ALL_COMPLETION_AVAILABLE_BLOCKS = Object.keys(NODES_EXTRA_DATA).filter(key => key !== BlockEnum.Answer && key !== BlockEnum.Start) as BlockEnum[]
|
||||
|
||||
export const NODES_INITIAL_DATA = {
|
||||
[BlockEnum.Start]: {
|
||||
type: BlockEnum.Start,
|
||||
title: '',
|
||||
desc: '',
|
||||
...StartNodeDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.End]: {
|
||||
type: BlockEnum.End,
|
||||
title: '',
|
||||
desc: '',
|
||||
...EndNodeDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.Answer]: {
|
||||
type: BlockEnum.Answer,
|
||||
title: '',
|
||||
desc: '',
|
||||
...AnswerDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.LLM]: {
|
||||
type: BlockEnum.LLM,
|
||||
title: '',
|
||||
desc: '',
|
||||
variables: [],
|
||||
...LLMDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.KnowledgeRetrieval]: {
|
||||
type: BlockEnum.KnowledgeRetrieval,
|
||||
title: '',
|
||||
desc: '',
|
||||
query_variable_selector: [],
|
||||
dataset_ids: [],
|
||||
retrieval_mode: 'single',
|
||||
...KnowledgeRetrievalDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.IfElse]: {
|
||||
type: BlockEnum.IfElse,
|
||||
title: '',
|
||||
desc: '',
|
||||
...IfElseDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.Code]: {
|
||||
type: BlockEnum.Code,
|
||||
title: '',
|
||||
desc: '',
|
||||
variables: [],
|
||||
code_language: 'python3',
|
||||
code: '',
|
||||
outputs: [],
|
||||
...CodeDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.TemplateTransform]: {
|
||||
type: BlockEnum.TemplateTransform,
|
||||
title: '',
|
||||
desc: '',
|
||||
variables: [],
|
||||
template: '',
|
||||
...TemplateTransformDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.QuestionClassifier]: {
|
||||
type: BlockEnum.QuestionClassifier,
|
||||
title: '',
|
||||
desc: '',
|
||||
query_variable_selector: [],
|
||||
topics: [],
|
||||
...QuestionClassifierDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.HttpRequest]: {
|
||||
type: BlockEnum.HttpRequest,
|
||||
title: '',
|
||||
desc: '',
|
||||
variables: [],
|
||||
...HttpRequestDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.VariableAssigner]: {
|
||||
type: BlockEnum.VariableAssigner,
|
||||
title: '',
|
||||
desc: '',
|
||||
variables: [],
|
||||
output_type: '',
|
||||
...VariableAssignerDefault.defaultValue,
|
||||
},
|
||||
[BlockEnum.Tool]: {
|
||||
type: BlockEnum.Tool,
|
||||
title: '',
|
||||
desc: '',
|
||||
...ToolDefault.defaultValue,
|
||||
},
|
||||
}
|
||||
|
||||
export const NODE_WIDTH = 240
|
||||
export const X_OFFSET = 60
|
||||
export const NODE_WIDTH_X_OFFSET = NODE_WIDTH + X_OFFSET
|
||||
export const Y_OFFSET = 39
|
||||
export const MAX_TREE_DEEPTH = 30
|
||||
export const START_INITIAL_POSITION = { x: 80, y: 282 }
|
||||
export const AUTO_LAYOUT_OFFSET = {
|
||||
x: -42,
|
||||
y: 243,
|
||||
}
|
||||
|
||||
export const RETRIEVAL_OUTPUT_STRUCT = `{
|
||||
"content": "",
|
||||
"title": "",
|
||||
"url": "",
|
||||
"icon": "",
|
||||
"metadata": {
|
||||
"dataset_id": "",
|
||||
"dataset_name": "",
|
||||
"document_id": [],
|
||||
"document_name": "",
|
||||
"document_data_source_type": "",
|
||||
"segment_id": "",
|
||||
"segment_position": "",
|
||||
"segment_word_count": "",
|
||||
"segment_hit_count": "",
|
||||
"segment_index_node_hash": "",
|
||||
"score": ""
|
||||
}
|
||||
}`
|
||||
|
||||
export const SUPPORT_OUTPUT_VARS_NODE = [
|
||||
BlockEnum.Start, BlockEnum.LLM, BlockEnum.KnowledgeRetrieval, BlockEnum.Code, BlockEnum.TemplateTransform,
|
||||
BlockEnum.HttpRequest, BlockEnum.Tool, BlockEnum.VariableAssigner,
|
||||
]
|
||||
|
||||
const USAGE = {
|
||||
variable: 'usage',
|
||||
type: VarType.object,
|
||||
children: [
|
||||
{
|
||||
variable: 'prompt_tokens',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'prompt_unit_price',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'prompt_price_unit',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'prompt_price',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'completion_tokens',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'completion_unit_price',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'completion_price_unit',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'completion_unit_price',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'completion_price',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'total_tokens',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'total_price',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'currency',
|
||||
type: VarType.string,
|
||||
},
|
||||
{
|
||||
variable: 'latency',
|
||||
type: VarType.number,
|
||||
},
|
||||
],
|
||||
}
|
||||
export const LLM_OUTPUT_STRUCT: Var[] = [
|
||||
{
|
||||
variable: 'text',
|
||||
type: VarType.string,
|
||||
},
|
||||
]
|
||||
|
||||
export const KNOWLEDGE_RETRIEVAL_OUTPUT_STRUCT: Var[] = [
|
||||
{
|
||||
variable: 'result',
|
||||
type: VarType.arrayObject,
|
||||
},
|
||||
]
|
||||
|
||||
export const TEMPLATE_TRANSFORM_OUTPUT_STRUCT: Var[] = [
|
||||
{
|
||||
variable: 'output',
|
||||
type: VarType.string,
|
||||
},
|
||||
]
|
||||
|
||||
const QUESTION_CLASSIFIER_OUTPUT_STRUCT_COMMON: Var[] = [
|
||||
USAGE,
|
||||
{
|
||||
variable: 'topic',
|
||||
type: VarType.string,
|
||||
},
|
||||
]
|
||||
|
||||
export const CHAT_QUESTION_CLASSIFIER_OUTPUT_STRUCT = [
|
||||
{
|
||||
variable: 'model_mode',
|
||||
type: VarType.string,
|
||||
},
|
||||
{
|
||||
variable: 'messages',
|
||||
type: VarType.arrayObject,
|
||||
},
|
||||
...QUESTION_CLASSIFIER_OUTPUT_STRUCT_COMMON,
|
||||
]
|
||||
|
||||
export const COMPLETION_QUESTION_CLASSIFIER_OUTPUT_STRUCT = [
|
||||
{
|
||||
variable: 'model_mode',
|
||||
type: VarType.string,
|
||||
},
|
||||
{
|
||||
variable: 'text',
|
||||
type: VarType.string,
|
||||
},
|
||||
...QUESTION_CLASSIFIER_OUTPUT_STRUCT_COMMON,
|
||||
]
|
||||
|
||||
export const HTTP_REQUEST_OUTPUT_STRUCT: Var[] = [
|
||||
{
|
||||
variable: 'body',
|
||||
type: VarType.string,
|
||||
},
|
||||
{
|
||||
variable: 'status_code',
|
||||
type: VarType.number,
|
||||
},
|
||||
{
|
||||
variable: 'headers',
|
||||
type: VarType.string,
|
||||
},
|
||||
{
|
||||
variable: 'files',
|
||||
type: VarType.arrayFile,
|
||||
},
|
||||
]
|
||||
|
||||
export const TOOL_OUTPUT_STRUCT: Var[] = [
|
||||
{
|
||||
variable: 'text',
|
||||
type: VarType.string,
|
||||
},
|
||||
{
|
||||
variable: 'files',
|
||||
type: VarType.arrayFile,
|
||||
},
|
||||
]
|
||||
24
web/app/components/workflow/context.tsx
Normal file
24
web/app/components/workflow/context.tsx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import {
|
||||
createContext,
|
||||
useRef,
|
||||
} from 'react'
|
||||
import { createWorkflowStore } from './store'
|
||||
|
||||
type WorkflowStore = ReturnType<typeof createWorkflowStore>
|
||||
export const WorkflowContext = createContext<WorkflowStore | null>(null)
|
||||
|
||||
type WorkflowProviderProps = {
|
||||
children: React.ReactNode
|
||||
}
|
||||
export const WorkflowContextProvider = ({ children }: WorkflowProviderProps) => {
|
||||
const storeRef = useRef<WorkflowStore>()
|
||||
|
||||
if (!storeRef.current)
|
||||
storeRef.current = createWorkflowStore()
|
||||
|
||||
return (
|
||||
<WorkflowContext.Provider value={storeRef.current}>
|
||||
{children}
|
||||
</WorkflowContext.Provider>
|
||||
)
|
||||
}
|
||||
39
web/app/components/workflow/custom-connection-line.tsx
Normal file
39
web/app/components/workflow/custom-connection-line.tsx
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { memo } from 'react'
|
||||
import type { ConnectionLineComponentProps } from 'reactflow'
|
||||
import {
|
||||
Position,
|
||||
getSimpleBezierPath,
|
||||
} from 'reactflow'
|
||||
|
||||
const CustomConnectionLine = ({ fromX, fromY, toX, toY }: ConnectionLineComponentProps) => {
|
||||
const [
|
||||
edgePath,
|
||||
] = getSimpleBezierPath({
|
||||
sourceX: fromX,
|
||||
sourceY: fromY,
|
||||
sourcePosition: Position.Right,
|
||||
targetX: toX,
|
||||
targetY: toY,
|
||||
targetPosition: Position.Left,
|
||||
})
|
||||
|
||||
return (
|
||||
<g>
|
||||
<path
|
||||
fill="none"
|
||||
stroke='#D0D5DD'
|
||||
strokeWidth={2}
|
||||
d={edgePath}
|
||||
/>
|
||||
<rect
|
||||
x={toX}
|
||||
y={toY - 4}
|
||||
width={2}
|
||||
height={8}
|
||||
fill='#2970FF'
|
||||
/>
|
||||
</g>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(CustomConnectionLine)
|
||||
110
web/app/components/workflow/custom-edge.tsx
Normal file
110
web/app/components/workflow/custom-edge.tsx
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { intersection } from 'lodash-es'
|
||||
import type { EdgeProps } from 'reactflow'
|
||||
import {
|
||||
BaseEdge,
|
||||
EdgeLabelRenderer,
|
||||
Position,
|
||||
getSimpleBezierPath,
|
||||
} from 'reactflow'
|
||||
import {
|
||||
useNodesExtraData,
|
||||
useNodesInteractions,
|
||||
} from './hooks'
|
||||
import BlockSelector from './block-selector'
|
||||
import type {
|
||||
Edge,
|
||||
OnSelectBlock,
|
||||
} from './types'
|
||||
|
||||
const CustomEdge = ({
|
||||
id,
|
||||
data,
|
||||
source,
|
||||
sourceHandleId,
|
||||
target,
|
||||
targetHandleId,
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
selected,
|
||||
}: EdgeProps) => {
|
||||
const [
|
||||
edgePath,
|
||||
labelX,
|
||||
labelY,
|
||||
] = getSimpleBezierPath({
|
||||
sourceX: sourceX - 8,
|
||||
sourceY,
|
||||
sourcePosition: Position.Right,
|
||||
targetX: targetX + 8,
|
||||
targetY,
|
||||
targetPosition: Position.Left,
|
||||
})
|
||||
const [open, setOpen] = useState(false)
|
||||
const { handleNodeAdd } = useNodesInteractions()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const availablePrevNodes = nodesExtraData[(data as Edge['data'])!.targetType]?.availablePrevNodes || []
|
||||
const availableNextNodes = nodesExtraData[(data as Edge['data'])!.sourceType]?.availableNextNodes || []
|
||||
const handleOpenChange = useCallback((v: boolean) => {
|
||||
setOpen(v)
|
||||
}, [])
|
||||
|
||||
const handleInsert = useCallback<OnSelectBlock>((nodeType, toolDefaultValue) => {
|
||||
handleNodeAdd(
|
||||
{
|
||||
nodeType,
|
||||
toolDefaultValue,
|
||||
},
|
||||
{
|
||||
prevNodeId: source,
|
||||
prevNodeSourceHandle: sourceHandleId || 'source',
|
||||
nextNodeId: target,
|
||||
nextNodeTargetHandle: targetHandleId || 'target',
|
||||
},
|
||||
)
|
||||
}, [handleNodeAdd, source, sourceHandleId, target, targetHandleId])
|
||||
|
||||
return (
|
||||
<>
|
||||
<BaseEdge
|
||||
id={id}
|
||||
path={edgePath}
|
||||
style={{
|
||||
stroke: (selected || data?._connectedNodeIsHovering || data?._runned) ? '#2970FF' : '#D0D5DD',
|
||||
strokeWidth: 2,
|
||||
}}
|
||||
/>
|
||||
<EdgeLabelRenderer>
|
||||
<div
|
||||
className={`
|
||||
nopan nodrag hover:scale-125
|
||||
${data?._hovering ? 'block' : 'hidden'}
|
||||
${open && '!block'}
|
||||
`}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
|
||||
pointerEvents: 'all',
|
||||
}}
|
||||
>
|
||||
<BlockSelector
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
asChild
|
||||
onSelect={handleInsert}
|
||||
availableBlocksTypes={intersection(availablePrevNodes, availableNextNodes)}
|
||||
triggerClassName={() => 'hover:scale-150 transition-all'}
|
||||
/>
|
||||
</div>
|
||||
</EdgeLabelRenderer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(CustomEdge)
|
||||
66
web/app/components/workflow/features.tsx
Normal file
66
web/app/components/workflow/features.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStore } from './store'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useNodesReadOnly,
|
||||
useNodesSyncDraft,
|
||||
} from './hooks'
|
||||
import { XClose } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import {
|
||||
FeaturesChoose,
|
||||
FeaturesPanel,
|
||||
} from '@/app/components/base/features'
|
||||
|
||||
const Features = () => {
|
||||
const { t } = useTranslation()
|
||||
const isChatMode = useIsChatMode()
|
||||
const setShowFeaturesPanel = useStore(s => s.setShowFeaturesPanel)
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
|
||||
const handleFeaturesChange = useCallback(() => {
|
||||
handleSyncWorkflowDraft()
|
||||
}, [handleSyncWorkflowDraft])
|
||||
|
||||
return (
|
||||
<div className='fixed top-16 left-2 bottom-2 w-[600px] rounded-2xl border-[0.5px] border-gray-200 bg-white shadow-xl z-10'>
|
||||
<div className='flex items-center justify-between px-4 pt-3'>
|
||||
{t('workflow.common.features')}
|
||||
<div className='flex items-center'>
|
||||
{
|
||||
isChatMode && (
|
||||
<>
|
||||
<FeaturesChoose
|
||||
disabled={nodesReadOnly}
|
||||
onChange={handleFeaturesChange}
|
||||
/>
|
||||
<div className='mx-3 w-[1px] h-[14px] bg-gray-200'></div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
<div
|
||||
className='flex items-center justify-center w-6 h-6 cursor-pointer'
|
||||
onClick={() => setShowFeaturesPanel(false)}
|
||||
>
|
||||
<XClose className='w-4 h-4 text-gray-500' />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='p-4'>
|
||||
<FeaturesPanel
|
||||
disabled={nodesReadOnly}
|
||||
onChange={handleFeaturesChange}
|
||||
openingStatementProps={{
|
||||
onAutoAddPromptVariable: () => {},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Features)
|
||||
158
web/app/components/workflow/header/checklist.tsx
Normal file
158
web/app/components/workflow/header/checklist.tsx
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import {
|
||||
memo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
useEdges,
|
||||
useNodes,
|
||||
} from 'reactflow'
|
||||
import BlockIcon from '../block-icon'
|
||||
import {
|
||||
useChecklist,
|
||||
useNodesInteractions,
|
||||
} from '../hooks'
|
||||
import type {
|
||||
CommonEdgeType,
|
||||
CommonNodeType,
|
||||
} from '../types'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import {
|
||||
Checklist,
|
||||
ChecklistSquare,
|
||||
XClose,
|
||||
} from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'
|
||||
|
||||
const WorkflowChecklist = () => {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const nodes = useNodes<CommonNodeType>()
|
||||
const edges = useEdges<CommonEdgeType>()
|
||||
const needWarningNodes = useChecklist(nodes, edges)
|
||||
const { handleNodeSelect } = useNodesInteractions()
|
||||
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
placement='bottom-end'
|
||||
offset={{
|
||||
mainAxis: 12,
|
||||
crossAxis: 4,
|
||||
}}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)}>
|
||||
<div className='relative flex items-center justify-center p-0.5 w-8 h-8 rounded-lg border-[0.5px] border-gray-200 bg-white shadow-xs'>
|
||||
<div
|
||||
className={`
|
||||
group flex items-center justify-center w-full h-full rounded-md cursor-pointer
|
||||
hover:bg-primary-50
|
||||
${open && 'bg-primary-50'}
|
||||
`}
|
||||
>
|
||||
<Checklist
|
||||
className={`
|
||||
w-4 h-4 group-hover:text-primary-600
|
||||
${open ? 'text-primary-600' : 'text-gray-500'}`
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{
|
||||
!!needWarningNodes.length && (
|
||||
<div className='absolute -right-1.5 -top-1.5 flex items-center justify-center min-w-[18px] h-[18px] rounded-full border border-gray-100 text-white text-[11px] font-semibold bg-[#F79009]'>
|
||||
{needWarningNodes.length}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-[12]'>
|
||||
<div
|
||||
className='w-[420px] rounded-2xl bg-white border-[0.5px] border-black/5 shadow-lg overflow-y-auto'
|
||||
style={{
|
||||
maxHeight: 'calc(2 / 3 * 100vh)',
|
||||
}}
|
||||
>
|
||||
<div className='sticky top-0 bg-white flex items-center pl-4 pr-3 pt-3 h-[44px] text-md font-semibold text-gray-900 z-[1]'>
|
||||
<div className='grow'>{t('workflow.panel.checklist')}{needWarningNodes.length ? `(${needWarningNodes.length})` : ''}</div>
|
||||
<div
|
||||
className='shrink-0 flex items-center justify-center w-6 h-6 cursor-pointer'
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
<XClose className='w-4 h-4 text-gray-500' />
|
||||
</div>
|
||||
</div>
|
||||
<div className='py-2'>
|
||||
{
|
||||
!!needWarningNodes.length && (
|
||||
<>
|
||||
<div className='px-4 text-xs text-gray-400'>{t('workflow.panel.checklistTip')}</div>
|
||||
<div className='px-4 py-2'>
|
||||
{
|
||||
needWarningNodes.map(node => (
|
||||
<div
|
||||
key={node.id}
|
||||
className='mb-2 last-of-type:mb-0 border-[0.5px] border-gray-200 bg-white shadow-xs rounded-lg cursor-pointer'
|
||||
onClick={() => {
|
||||
handleNodeSelect(node.id)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center p-2 h-9 text-xs font-medium text-gray-700'>
|
||||
<BlockIcon
|
||||
type={node.type}
|
||||
className='mr-1.5'
|
||||
toolIcon={node.toolIcon}
|
||||
/>
|
||||
{node.title}
|
||||
</div>
|
||||
<div className='border-t-[0.5px] border-t-black/[0.02]'>
|
||||
{
|
||||
node.unConnected && (
|
||||
<div className='px-3 py-2 bg-gray-25 rounded-b-lg'>
|
||||
<div className='flex text-xs leading-[18px] text-gray-500'>
|
||||
<AlertTriangle className='mt-[3px] mr-2 w-3 h-3 text-[#F79009]' />
|
||||
{t('workflow.common.needConnecttip')}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
node.errorMessage && (
|
||||
<div className='px-3 py-2 bg-gray-25 rounded-b-lg'>
|
||||
<div className='flex text-xs leading-[18px] text-gray-500'>
|
||||
<AlertTriangle className='mt-[3px] mr-2 w-3 h-3 text-[#F79009]' />
|
||||
{node.errorMessage}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
{
|
||||
!needWarningNodes.length && (
|
||||
<div className='mx-4 mb-3 py-4 rounded-lg bg-gray-50 text-gray-400 text-xs text-center'>
|
||||
<ChecklistSquare className='mx-auto mb-[5px] w-8 h-8 text-gray-300' />
|
||||
{t('workflow.panel.checklistResolved')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(WorkflowChecklist)
|
||||
36
web/app/components/workflow/header/editing-title.tsx
Normal file
36
web/app/components/workflow/header/editing-title.tsx
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { memo } from 'react'
|
||||
import dayjs from 'dayjs'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useWorkflow } from '../hooks'
|
||||
import { Edit03 } from '@/app/components/base/icons/src/vender/solid/general'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
|
||||
const EditingTitle = () => {
|
||||
const { t } = useTranslation()
|
||||
const { formatTimeFromNow } = useWorkflow()
|
||||
const draftUpdatedAt = useStore(state => state.draftUpdatedAt)
|
||||
const publishedAt = useStore(state => state.publishedAt)
|
||||
|
||||
return (
|
||||
<div className='flex items-center h-[18px] text-xs text-gray-500'>
|
||||
<Edit03 className='mr-1 w-3 h-3 text-gray-400' />
|
||||
{t('workflow.common.editing')}
|
||||
{
|
||||
!!draftUpdatedAt && (
|
||||
<>
|
||||
<span className='flex items-center mx-1'>·</span>
|
||||
{t('workflow.common.autoSaved')} {dayjs(draftUpdatedAt).format('HH:mm:ss')}
|
||||
</>
|
||||
)
|
||||
}
|
||||
<span className='flex items-center mx-1'>·</span>
|
||||
{
|
||||
publishedAt
|
||||
? `${t('workflow.common.published')} ${formatTimeFromNow(publishedAt)}`
|
||||
: t('workflow.common.unpublished')
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(EditingTitle)
|
||||
213
web/app/components/workflow/header/index.tsx
Normal file
213
web/app/components/workflow/header/index.tsx
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
import type { FC } from 'react'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useContext } from 'use-context-selector'
|
||||
import {
|
||||
useStore,
|
||||
useWorkflowStore,
|
||||
} from '../store'
|
||||
import {
|
||||
useChecklistBeforePublish,
|
||||
useNodesReadOnly,
|
||||
useNodesSyncDraft,
|
||||
useWorkflowRun,
|
||||
} from '../hooks'
|
||||
import AppPublisher from '../../app/app-publisher'
|
||||
import { ToastContext } from '../../base/toast'
|
||||
import RunAndHistory from './run-and-history'
|
||||
import EditingTitle from './editing-title'
|
||||
import RunningTitle from './running-title'
|
||||
import RestoringTitle from './restoring-title'
|
||||
import Checklist from './checklist'
|
||||
import { Grid01 } from '@/app/components/base/icons/src/vender/line/layout'
|
||||
import Button from '@/app/components/base/button'
|
||||
import { ArrowNarrowLeft } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import { publishWorkflow } from '@/service/workflow'
|
||||
|
||||
const Header: FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const appDetail = useAppStore(s => s.appDetail)
|
||||
const appSidebarExpand = useAppStore(s => s.appSidebarExpand)
|
||||
const appID = useAppStore(state => state.appDetail?.id)
|
||||
const {
|
||||
nodesReadOnly,
|
||||
getNodesReadOnly,
|
||||
} = useNodesReadOnly()
|
||||
const isRestoring = useStore(s => s.isRestoring)
|
||||
const publishedAt = useStore(s => s.publishedAt)
|
||||
const draftUpdatedAt = useStore(s => s.draftUpdatedAt)
|
||||
const {
|
||||
handleLoadBackupDraft,
|
||||
handleRunSetting,
|
||||
handleBackupDraft,
|
||||
handleRestoreFromPublishedWorkflow,
|
||||
} = useWorkflowRun()
|
||||
const { handleCheckBeforePublish } = useChecklistBeforePublish()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
const { notify } = useContext(ToastContext)
|
||||
|
||||
const handleShowFeatures = useCallback(() => {
|
||||
const {
|
||||
isRestoring,
|
||||
setShowFeaturesPanel,
|
||||
} = workflowStore.getState()
|
||||
if (getNodesReadOnly() && !isRestoring)
|
||||
return
|
||||
|
||||
setShowFeaturesPanel(true)
|
||||
}, [workflowStore, getNodesReadOnly])
|
||||
|
||||
const handleGoBackToEdit = useCallback(() => {
|
||||
handleRunSetting(true)
|
||||
}, [handleRunSetting])
|
||||
|
||||
const handleCancelRestore = useCallback(() => {
|
||||
handleLoadBackupDraft()
|
||||
workflowStore.setState({ isRestoring: false })
|
||||
}, [workflowStore, handleLoadBackupDraft])
|
||||
|
||||
const handleRestore = useCallback(() => {
|
||||
workflowStore.setState({ isRestoring: false })
|
||||
handleSyncWorkflowDraft(true)
|
||||
}, [handleSyncWorkflowDraft, workflowStore])
|
||||
|
||||
const onPublish = useCallback(async () => {
|
||||
if (handleCheckBeforePublish()) {
|
||||
const res = await publishWorkflow(`/apps/${appID}/workflows/publish`)
|
||||
|
||||
if (res) {
|
||||
notify({ type: 'success', message: t('common.api.actionSuccess') })
|
||||
workflowStore.getState().setPublishedAt(res.created_at)
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error('Checklist failed')
|
||||
}
|
||||
}, [appID, handleCheckBeforePublish, notify, t, workflowStore])
|
||||
|
||||
const onStartRestoring = useCallback(() => {
|
||||
workflowStore.setState({ isRestoring: true })
|
||||
handleBackupDraft()
|
||||
handleRestoreFromPublishedWorkflow()
|
||||
}, [handleBackupDraft, handleRestoreFromPublishedWorkflow, workflowStore])
|
||||
|
||||
const onPublisherToggle = useCallback((state: boolean) => {
|
||||
if (state)
|
||||
handleSyncWorkflowDraft(true)
|
||||
}, [handleSyncWorkflowDraft])
|
||||
|
||||
return (
|
||||
<div
|
||||
className='absolute top-0 left-0 z-10 flex items-center justify-between w-full px-3 h-14'
|
||||
style={{
|
||||
background: 'linear-gradient(180deg, #F9FAFB 0%, rgba(249, 250, 251, 0.00) 100%)',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
{
|
||||
appSidebarExpand === 'collapse' && (
|
||||
<div className='text-xs font-medium text-gray-700'>{appDetail?.name}</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
!nodesReadOnly && !isRestoring && <EditingTitle />
|
||||
}
|
||||
{
|
||||
nodesReadOnly && !isRestoring && <RunningTitle />
|
||||
}
|
||||
{
|
||||
isRestoring && <RestoringTitle />
|
||||
}
|
||||
</div>
|
||||
{
|
||||
!isRestoring && (
|
||||
<div className='flex items-center'>
|
||||
{
|
||||
nodesReadOnly && (
|
||||
<Button
|
||||
className={`
|
||||
mr-2 px-3 py-0 h-8 bg-white text-[13px] font-medium text-primary-600
|
||||
border-[0.5px] border-gray-200 shadow-xs
|
||||
`}
|
||||
onClick={handleGoBackToEdit}
|
||||
>
|
||||
<ArrowNarrowLeft className='w-4 h-4 mr-1' />
|
||||
{t('workflow.common.goBackToEdit')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
<RunAndHistory />
|
||||
<div className='mx-2 w-[1px] h-3.5 bg-gray-200'></div>
|
||||
<Button
|
||||
className={`
|
||||
mr-2 px-3 py-0 h-8 bg-white text-[13px] font-medium text-gray-700
|
||||
border-[0.5px] border-gray-200 shadow-xs
|
||||
${nodesReadOnly && !isRestoring && 'opacity-50 !cursor-not-allowed'}
|
||||
`}
|
||||
onClick={handleShowFeatures}
|
||||
>
|
||||
<Grid01 className='w-4 h-4 mr-1 text-gray-500' />
|
||||
{t('workflow.common.features')}
|
||||
</Button>
|
||||
<AppPublisher
|
||||
{...{
|
||||
publishedAt,
|
||||
draftUpdatedAt,
|
||||
disabled: Boolean(getNodesReadOnly()),
|
||||
onPublish,
|
||||
onRestore: onStartRestoring,
|
||||
onToggle: onPublisherToggle,
|
||||
crossAxisOffset: 53,
|
||||
}}
|
||||
/>
|
||||
{
|
||||
!nodesReadOnly && (
|
||||
<>
|
||||
<div className='mx-2 w-[1px] h-3.5 bg-gray-200'></div>
|
||||
<Checklist />
|
||||
</>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
isRestoring && (
|
||||
<div className='flex items-center'>
|
||||
<Button
|
||||
className={`
|
||||
px-3 py-0 h-8 bg-white text-[13px] font-medium text-gray-700
|
||||
border-[0.5px] border-gray-200 shadow-xs
|
||||
`}
|
||||
onClick={handleShowFeatures}
|
||||
>
|
||||
<Grid01 className='w-4 h-4 mr-1 text-gray-500' />
|
||||
{t('workflow.common.features')}
|
||||
</Button>
|
||||
<div className='mx-2 w-[1px] h-3.5 bg-gray-200'></div>
|
||||
<Button
|
||||
className='mr-2 px-3 py-0 h-8 bg-white text-[13px] text-gray-700 font-medium border-[0.5px] border-gray-200 shadow-xs'
|
||||
onClick={handleCancelRestore}
|
||||
>
|
||||
{t('common.operation.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
className='px-3 py-0 h-8 text-[13px] font-medium shadow-xs'
|
||||
onClick={handleRestore}
|
||||
type='primary'
|
||||
>
|
||||
{t('workflow.common.restore')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Header)
|
||||
21
web/app/components/workflow/header/restoring-title.tsx
Normal file
21
web/app/components/workflow/header/restoring-title.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useWorkflow } from '../hooks'
|
||||
import { useStore } from '../store'
|
||||
import { ClockRefresh } from '@/app/components/base/icons/src/vender/line/time'
|
||||
|
||||
const RestoringTitle = () => {
|
||||
const { t } = useTranslation()
|
||||
const { formatTimeFromNow } = useWorkflow()
|
||||
const publishedAt = useStore(state => state.publishedAt)
|
||||
|
||||
return (
|
||||
<div className='flex items-center h-[18px] text-xs text-gray-500'>
|
||||
<ClockRefresh className='mr-1 w-3 h-3 text-gray-500' />
|
||||
{t('workflow.common.latestPublished')}
|
||||
{formatTimeFromNow(publishedAt)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(RestoringTitle)
|
||||
179
web/app/components/workflow/header/run-and-history.tsx
Normal file
179
web/app/components/workflow/header/run-and-history.tsx
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
import type { FC } from 'react'
|
||||
import { memo, useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import {
|
||||
useStore,
|
||||
useWorkflowStore,
|
||||
} from '../store'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useNodesReadOnly,
|
||||
useNodesSyncDraft,
|
||||
useWorkflowRun,
|
||||
} from '../hooks'
|
||||
import {
|
||||
BlockEnum,
|
||||
WorkflowRunningStatus,
|
||||
} from '../types'
|
||||
import ViewHistory from './view-history'
|
||||
import {
|
||||
Play,
|
||||
StopCircle,
|
||||
} from '@/app/components/base/icons/src/vender/line/mediaAndDevices'
|
||||
import { Loading02 } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { useFeaturesStore } from '@/app/components/base/features/hooks'
|
||||
|
||||
const RunMode = memo(() => {
|
||||
const { t } = useTranslation()
|
||||
const store = useStoreApi()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const featuresStore = useFeaturesStore()
|
||||
const {
|
||||
handleStopRun,
|
||||
handleRunSetting,
|
||||
handleRun,
|
||||
} = useWorkflowRun()
|
||||
const {
|
||||
doSyncWorkflowDraft,
|
||||
handleSyncWorkflowDraft,
|
||||
} = useNodesSyncDraft()
|
||||
const workflowRunningData = useStore(s => s.workflowRunningData)
|
||||
const showInputsPanel = useStore(s => s.showInputsPanel)
|
||||
const isRunning = workflowRunningData?.result.status === WorkflowRunningStatus.Running
|
||||
|
||||
const handleClick = useCallback(async () => {
|
||||
const {
|
||||
workflowRunningData,
|
||||
} = workflowStore.getState()
|
||||
|
||||
if (workflowRunningData?.result.status === WorkflowRunningStatus.Running)
|
||||
return
|
||||
|
||||
const { getNodes } = store.getState()
|
||||
const nodes = getNodes()
|
||||
const startNode = nodes.find(node => node.data.type === BlockEnum.Start)
|
||||
const startVariables = startNode?.data.variables || []
|
||||
const fileSettings = featuresStore!.getState().features.file
|
||||
|
||||
if (!startVariables.length && !fileSettings?.image?.enabled) {
|
||||
await doSyncWorkflowDraft()
|
||||
handleRunSetting()
|
||||
handleRun({ inputs: {}, files: [] })
|
||||
}
|
||||
else {
|
||||
workflowStore.setState({
|
||||
historyWorkflowData: undefined,
|
||||
showInputsPanel: true,
|
||||
})
|
||||
handleSyncWorkflowDraft(true)
|
||||
}
|
||||
}, [
|
||||
workflowStore,
|
||||
handleSyncWorkflowDraft,
|
||||
handleRunSetting,
|
||||
handleRun,
|
||||
doSyncWorkflowDraft,
|
||||
store,
|
||||
featuresStore,
|
||||
])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`
|
||||
flex items-center px-1.5 h-7 rounded-md text-[13px] font-medium text-primary-600
|
||||
hover:bg-primary-50 cursor-pointer
|
||||
${showInputsPanel && 'bg-primary-50'}
|
||||
${isRunning && 'bg-primary-50 !cursor-not-allowed'}
|
||||
`}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{
|
||||
isRunning
|
||||
? (
|
||||
<>
|
||||
<Loading02 className='mr-1 w-4 h-4 animate-spin' />
|
||||
{t('workflow.common.running')}
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<Play className='mr-1 w-4 h-4' />
|
||||
{t('workflow.common.run')}
|
||||
</>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
{
|
||||
isRunning && (
|
||||
<div
|
||||
className='flex items-center justify-center ml-0.5 w-7 h-7 cursor-pointer hover:bg-black/5 rounded-md'
|
||||
onClick={() => handleStopRun(workflowRunningData?.task_id || '')}
|
||||
>
|
||||
<StopCircle className='w-4 h-4 text-gray-500' />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</>
|
||||
)
|
||||
})
|
||||
RunMode.displayName = 'RunMode'
|
||||
|
||||
const PreviewMode = memo(() => {
|
||||
const { t } = useTranslation()
|
||||
const { handleRunSetting } = useWorkflowRun()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
|
||||
const handleClick = () => {
|
||||
handleSyncWorkflowDraft(true)
|
||||
handleRunSetting()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
flex items-center px-1.5 h-7 rounded-md text-[13px] font-medium text-primary-600
|
||||
hover:bg-primary-50 cursor-pointer
|
||||
${nodesReadOnly && 'bg-primary-50 opacity-50 !cursor-not-allowed'}
|
||||
`}
|
||||
onClick={() => !nodesReadOnly && handleClick()}
|
||||
>
|
||||
{
|
||||
nodesReadOnly
|
||||
? (
|
||||
<>
|
||||
{t('workflow.common.inPreview')}
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<Play className='mr-1 w-4 h-4' />
|
||||
{t('workflow.common.preview')}
|
||||
</>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
PreviewMode.displayName = 'PreviewMode'
|
||||
|
||||
const RunAndHistory: FC = () => {
|
||||
const isChatMode = useIsChatMode()
|
||||
|
||||
return (
|
||||
<div className='flex items-center px-0.5 h-8 rounded-lg border-[0.5px] border-gray-200 bg-white shadow-xs'>
|
||||
{
|
||||
!isChatMode && <RunMode />
|
||||
}
|
||||
{
|
||||
isChatMode && <PreviewMode />
|
||||
}
|
||||
<div className='mx-0.5 w-[0.5px] h-8 bg-gray-200'></div>
|
||||
<ViewHistory />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(RunAndHistory)
|
||||
24
web/app/components/workflow/header/running-title.tsx
Normal file
24
web/app/components/workflow/header/running-title.tsx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import { Play } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
|
||||
|
||||
const RunningTitle = () => {
|
||||
const { t } = useTranslation()
|
||||
const appDetail = useAppStore(state => state.appDetail)
|
||||
|
||||
return (
|
||||
<div className='flex items-center h-[18px] text-xs text-primary-600'>
|
||||
<Play className='mr-1 w-3 h-3' />
|
||||
{
|
||||
appDetail?.mode === 'advanced-chat'
|
||||
? t('workflow.common.inPreviewMode')
|
||||
: t('workflow.common.inRunMode')
|
||||
}
|
||||
<span className='mx-1'>·</span>
|
||||
<span className='text-gray-500'>Test Run#2</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(RunningTitle)
|
||||
179
web/app/components/workflow/header/view-history.tsx
Normal file
179
web/app/components/workflow/header/view-history.tsx
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
import {
|
||||
memo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import cn from 'classnames'
|
||||
import useSWR from 'swr'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useWorkflow,
|
||||
useWorkflowRun,
|
||||
} from '../hooks'
|
||||
import { WorkflowRunningStatus } from '../types'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import TooltipPlus from '@/app/components/base/tooltip-plus'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import {
|
||||
ClockPlay,
|
||||
ClockPlaySlim,
|
||||
} from '@/app/components/base/icons/src/vender/line/time'
|
||||
import { CheckCircle, XClose } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { AlertCircle, AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'
|
||||
import {
|
||||
fetcChatRunHistory,
|
||||
fetchWorkflowRunHistory,
|
||||
} from '@/service/workflow'
|
||||
import Loading from '@/app/components/base/loading'
|
||||
import {
|
||||
useStore,
|
||||
useWorkflowStore,
|
||||
} from '@/app/components/workflow/store'
|
||||
|
||||
const ViewHistory = () => {
|
||||
const { t } = useTranslation()
|
||||
const isChatMode = useIsChatMode()
|
||||
const [open, setOpen] = useState(false)
|
||||
const { formatTimeFromNow } = useWorkflow()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const { appDetail, setCurrentLogItem, setShowMessageLogModal } = useAppStore()
|
||||
const historyWorkflowData = useStore(s => s.historyWorkflowData)
|
||||
const { handleBackupDraft } = useWorkflowRun()
|
||||
const { data: runList, isLoading: runListLoading } = useSWR((appDetail && !isChatMode && open) ? `/apps/${appDetail.id}/workflow-runs` : null, fetchWorkflowRunHistory)
|
||||
const { data: chatList, isLoading: chatListLoading } = useSWR((appDetail && isChatMode && open) ? `/apps/${appDetail.id}/advanced-chat/workflow-runs` : null, fetcChatRunHistory)
|
||||
|
||||
const data = isChatMode ? chatList : runList
|
||||
const isLoading = isChatMode ? chatListLoading : runListLoading
|
||||
|
||||
return (
|
||||
(
|
||||
<PortalToFollowElem
|
||||
placement='bottom-end'
|
||||
offset={{
|
||||
mainAxis: 4,
|
||||
crossAxis: 131,
|
||||
}}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)}>
|
||||
<TooltipPlus
|
||||
popupContent={t('workflow.common.viewRunHistory')}
|
||||
>
|
||||
<div
|
||||
className={`
|
||||
flex items-center justify-center w-7 h-7 rounded-md hover:bg-black/5 cursor-pointer
|
||||
${open && 'bg-primary-50'}
|
||||
`}
|
||||
onClick={() => {
|
||||
setCurrentLogItem()
|
||||
setShowMessageLogModal(false)
|
||||
}}
|
||||
>
|
||||
<ClockPlay className={`w-4 h-4 ${open ? 'text-primary-600' : 'text-gray-500'}`} />
|
||||
</div>
|
||||
</TooltipPlus>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-[12]'>
|
||||
<div
|
||||
className='flex flex-col ml-2 w-[240px] bg-white border-[0.5px] border-gray-200 shadow-xl rounded-xl overflow-y-auto'
|
||||
style={{
|
||||
maxHeight: 'calc(2 / 3 * 100vh)',
|
||||
}}
|
||||
>
|
||||
<div className='sticky top-0 bg-white flex items-center justify-between px-4 pt-3 text-base font-semibold text-gray-900'>
|
||||
<div className='grow'>{t('workflow.common.runHistory')}</div>
|
||||
<div
|
||||
className='shrink-0 flex items-center justify-center w-6 h-6 cursor-pointer'
|
||||
onClick={() => {
|
||||
setCurrentLogItem()
|
||||
setShowMessageLogModal(false)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<XClose className='w-4 h-4 text-gray-500' />
|
||||
</div>
|
||||
</div>
|
||||
{
|
||||
isLoading && (
|
||||
<div className='flex items-center justify-center h-10'>
|
||||
<Loading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
!isLoading && (
|
||||
<div className='p-2'>
|
||||
{
|
||||
!data?.data.length && (
|
||||
<div className='py-12'>
|
||||
<ClockPlaySlim className='mx-auto mb-2 w-8 h-8 text-gray-300' />
|
||||
<div className='text-center text-[13px] text-gray-400'>
|
||||
{t('workflow.common.notRunning')}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
data?.data.map(item => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={cn(
|
||||
'flex mb-0.5 px-2 py-[7px] rounded-lg hover:bg-primary-50 cursor-pointer',
|
||||
item.id === historyWorkflowData?.id && 'bg-primary-50',
|
||||
)}
|
||||
onClick={() => {
|
||||
workflowStore.setState({
|
||||
historyWorkflowData: item,
|
||||
showInputsPanel: false,
|
||||
})
|
||||
handleBackupDraft()
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
{
|
||||
!isChatMode && item.status === WorkflowRunningStatus.Stopped && (
|
||||
<AlertTriangle className='mt-0.5 mr-1.5 w-3.5 h-3.5 text-[#F79009]' />
|
||||
)
|
||||
}
|
||||
{
|
||||
!isChatMode && item.status === WorkflowRunningStatus.Failed && (
|
||||
<AlertCircle className='mt-0.5 mr-1.5 w-3.5 h-3.5 text-[#F04438]' />
|
||||
)
|
||||
}
|
||||
{
|
||||
!isChatMode && item.status === WorkflowRunningStatus.Succeeded && (
|
||||
<CheckCircle className='mt-0.5 mr-1.5 w-3.5 h-3.5 text-[#12B76A]' />
|
||||
)
|
||||
}
|
||||
<div>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center text-[13px] font-medium leading-[18px]',
|
||||
item.id === historyWorkflowData?.id && 'text-primary-600',
|
||||
)}
|
||||
>
|
||||
{`Test ${isChatMode ? 'Chat' : 'Run'}#${item.sequence_number}`}
|
||||
</div>
|
||||
<div className='flex items-center text-xs text-gray-500 leading-[18px]'>
|
||||
{item.created_by_account.name} · {formatTimeFromNow((item.finished_at || item.created_at) * 1000)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ViewHistory)
|
||||
72
web/app/components/workflow/help-line/index.tsx
Normal file
72
web/app/components/workflow/help-line/index.tsx
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { memo } from 'react'
|
||||
import { useViewport } from 'reactflow'
|
||||
import { useStore } from '../store'
|
||||
import type {
|
||||
HelpLineHorizontalPosition,
|
||||
HelpLineVerticalPosition,
|
||||
} from './types'
|
||||
|
||||
const HelpLineHorizontal = memo(({
|
||||
top,
|
||||
left,
|
||||
width,
|
||||
}: HelpLineHorizontalPosition) => {
|
||||
const { x, y, zoom } = useViewport()
|
||||
|
||||
return (
|
||||
<div
|
||||
className='absolute h-[1px] bg-primary-300 z-[9]'
|
||||
style={{
|
||||
top: top * zoom + y,
|
||||
left: left * zoom + x,
|
||||
width: width * zoom,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
HelpLineHorizontal.displayName = 'HelpLineBase'
|
||||
|
||||
const HelpLineVertical = memo(({
|
||||
top,
|
||||
left,
|
||||
height,
|
||||
}: HelpLineVerticalPosition) => {
|
||||
const { x, y, zoom } = useViewport()
|
||||
|
||||
return (
|
||||
<div
|
||||
className='absolute w-[1px] bg-primary-300 z-[9]'
|
||||
style={{
|
||||
top: top * zoom + y,
|
||||
left: left * zoom + x,
|
||||
height: height * zoom,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
HelpLineVertical.displayName = 'HelpLineVertical'
|
||||
|
||||
const HelpLine = () => {
|
||||
const helpLineHorizontal = useStore(s => s.helpLineHorizontal)
|
||||
const helpLineVertical = useStore(s => s.helpLineVertical)
|
||||
|
||||
if (!helpLineHorizontal && !helpLineVertical)
|
||||
return null
|
||||
|
||||
return (
|
||||
<>
|
||||
{
|
||||
helpLineHorizontal && (
|
||||
<HelpLineHorizontal {...helpLineHorizontal} />
|
||||
)
|
||||
}
|
||||
{
|
||||
helpLineVertical && (
|
||||
<HelpLineVertical {...helpLineVertical} />
|
||||
)
|
||||
}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(HelpLine)
|
||||
11
web/app/components/workflow/help-line/types.ts
Normal file
11
web/app/components/workflow/help-line/types.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
export type HelpLineHorizontalPosition = {
|
||||
top: number
|
||||
left: number
|
||||
width: number
|
||||
}
|
||||
|
||||
export type HelpLineVerticalPosition = {
|
||||
top: number
|
||||
left: number
|
||||
height: number
|
||||
}
|
||||
9
web/app/components/workflow/hooks/index.ts
Normal file
9
web/app/components/workflow/hooks/index.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
export * from './use-edges-interactions'
|
||||
export * from './use-node-data-update'
|
||||
export * from './use-nodes-interactions'
|
||||
export * from './use-nodes-data'
|
||||
export * from './use-nodes-sync-draft'
|
||||
export * from './use-workflow'
|
||||
export * from './use-workflow-run'
|
||||
export * from './use-workflow-template'
|
||||
export * from './use-checklist'
|
||||
152
web/app/components/workflow/hooks/use-checklist.ts
Normal file
152
web/app/components/workflow/hooks/use-checklist.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
import {
|
||||
useCallback,
|
||||
useMemo,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import type {
|
||||
Edge,
|
||||
Node,
|
||||
} from '../types'
|
||||
import { BlockEnum } from '../types'
|
||||
import { useStore } from '../store'
|
||||
import {
|
||||
getToolCheckParams,
|
||||
getValidTreeNodes,
|
||||
} from '../utils'
|
||||
import { MAX_TREE_DEEPTH } from '../constants'
|
||||
import type { ToolNodeType } from '../nodes/tool/types'
|
||||
import { useIsChatMode } from './use-workflow'
|
||||
import { useNodesExtraData } from './use-nodes-data'
|
||||
import { useToastContext } from '@/app/components/base/toast'
|
||||
import { CollectionType } from '@/app/components/tools/types'
|
||||
import { useGetLanguage } from '@/context/i18n'
|
||||
|
||||
export const useChecklist = (nodes: Node[], edges: Edge[]) => {
|
||||
const { t } = useTranslation()
|
||||
const language = useGetLanguage()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const isChatMode = useIsChatMode()
|
||||
const buildInTools = useStore(s => s.buildInTools)
|
||||
const customTools = useStore(s => s.customTools)
|
||||
|
||||
const needWarningNodes = useMemo(() => {
|
||||
const list = []
|
||||
const { validNodes } = getValidTreeNodes(nodes, edges)
|
||||
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i]
|
||||
let toolIcon
|
||||
let moreDataForCheckValid
|
||||
|
||||
if (node.data.type === BlockEnum.Tool) {
|
||||
const { provider_type } = node.data
|
||||
const isBuiltIn = provider_type === CollectionType.builtIn
|
||||
|
||||
moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, language)
|
||||
if (isBuiltIn)
|
||||
toolIcon = buildInTools.find(tool => tool.id === node.data.provider_id)?.icon
|
||||
|
||||
if (!isBuiltIn)
|
||||
toolIcon = customTools.find(tool => tool.id === node.data.provider_id)?.icon
|
||||
}
|
||||
const { errorMessage } = nodesExtraData[node.data.type].checkValid(node.data, t, moreDataForCheckValid)
|
||||
|
||||
if (errorMessage || !validNodes.find(n => n.id === node.id)) {
|
||||
list.push({
|
||||
id: node.id,
|
||||
type: node.data.type,
|
||||
title: node.data.title,
|
||||
toolIcon,
|
||||
unConnected: !validNodes.find(n => n.id === node.id),
|
||||
errorMessage,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (isChatMode && !nodes.find(node => node.data.type === BlockEnum.Answer)) {
|
||||
list.push({
|
||||
id: 'answer-need-added',
|
||||
type: BlockEnum.Answer,
|
||||
title: t('workflow.blocks.answer'),
|
||||
errorMessage: t('workflow.common.needAnswerNode'),
|
||||
})
|
||||
}
|
||||
|
||||
if (!isChatMode && !nodes.find(node => node.data.type === BlockEnum.End)) {
|
||||
list.push({
|
||||
id: 'end-need-added',
|
||||
type: BlockEnum.End,
|
||||
title: t('workflow.blocks.end'),
|
||||
errorMessage: t('workflow.common.needEndNode'),
|
||||
})
|
||||
}
|
||||
|
||||
return list
|
||||
}, [t, nodes, edges, nodesExtraData, buildInTools, customTools, language, isChatMode])
|
||||
|
||||
return needWarningNodes
|
||||
}
|
||||
|
||||
export const useChecklistBeforePublish = () => {
|
||||
const { t } = useTranslation()
|
||||
const language = useGetLanguage()
|
||||
const buildInTools = useStore(s => s.buildInTools)
|
||||
const customTools = useStore(s => s.customTools)
|
||||
const { notify } = useToastContext()
|
||||
const isChatMode = useIsChatMode()
|
||||
const store = useStoreApi()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
|
||||
const handleCheckBeforePublish = useCallback(() => {
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const {
|
||||
validNodes,
|
||||
maxDepth,
|
||||
} = getValidTreeNodes(nodes, edges)
|
||||
|
||||
if (maxDepth > MAX_TREE_DEEPTH) {
|
||||
notify({ type: 'error', message: t('workflow.common.maxTreeDepth', { depth: MAX_TREE_DEEPTH }) })
|
||||
return false
|
||||
}
|
||||
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i]
|
||||
let moreDataForCheckValid
|
||||
if (node.data.type === BlockEnum.Tool)
|
||||
moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, language)
|
||||
|
||||
const { errorMessage } = nodesExtraData[node.data.type as BlockEnum].checkValid(node.data, t, moreDataForCheckValid)
|
||||
|
||||
if (errorMessage) {
|
||||
notify({ type: 'error', message: `[${node.data.title}] ${errorMessage}` })
|
||||
return false
|
||||
}
|
||||
|
||||
if (!validNodes.find(n => n.id === node.id)) {
|
||||
notify({ type: 'error', message: `[${node.data.title}] ${t('workflow.common.needConnecttip')}` })
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (isChatMode && !nodes.find(node => node.data.type === BlockEnum.Answer)) {
|
||||
notify({ type: 'error', message: t('workflow.common.needAnswerNode') })
|
||||
return false
|
||||
}
|
||||
|
||||
if (!isChatMode && !nodes.find(node => node.data.type === BlockEnum.End)) {
|
||||
notify({ type: 'error', message: t('workflow.common.needEndNode') })
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}, [nodesExtraData, notify, t, store, isChatMode, buildInTools, customTools, language])
|
||||
|
||||
return {
|
||||
handleCheckBeforePublish,
|
||||
}
|
||||
}
|
||||
212
web/app/components/workflow/hooks/use-edges-interactions.ts
Normal file
212
web/app/components/workflow/hooks/use-edges-interactions.ts
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
import { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import type {
|
||||
EdgeMouseHandler,
|
||||
OnEdgesChange,
|
||||
} from 'reactflow'
|
||||
import {
|
||||
getConnectedEdges,
|
||||
useStoreApi,
|
||||
} from 'reactflow'
|
||||
import type {
|
||||
Edge,
|
||||
Node,
|
||||
} from '../types'
|
||||
import { BlockEnum } from '../types'
|
||||
import { getNodesConnectedSourceOrTargetHandleIdsMap } from '../utils'
|
||||
import { useNodesSyncDraft } from './use-nodes-sync-draft'
|
||||
import { useNodesReadOnly } from './use-workflow'
|
||||
|
||||
export const useEdgesInteractions = () => {
|
||||
const store = useStoreApi()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
const { getNodesReadOnly } = useNodesReadOnly()
|
||||
|
||||
const handleEdgeEnter = useCallback<EdgeMouseHandler>((_, edge) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
const currentEdge = draft.find(e => e.id === edge.id)!
|
||||
|
||||
currentEdge.data._hovering = true
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}, [store, getNodesReadOnly])
|
||||
|
||||
const handleEdgeLeave = useCallback<EdgeMouseHandler>((_, edge) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
const currentEdge = draft.find(e => e.id === edge.id)!
|
||||
|
||||
currentEdge.data._hovering = false
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}, [store, getNodesReadOnly])
|
||||
|
||||
const handleEdgeDeleteByDeleteBranch = useCallback((nodeId: string, branchId: string) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const currentEdgeIndex = edges.findIndex(edge => edge.source === nodeId && edge.sourceHandle === branchId)
|
||||
|
||||
if (currentEdgeIndex < 0)
|
||||
return
|
||||
|
||||
const currentEdge = edges[currentEdgeIndex]
|
||||
const newNodes = produce(getNodes(), (draft: Node[]) => {
|
||||
const sourceNode = draft.find(node => node.id === currentEdge.source)
|
||||
const targetNode = draft.find(node => node.id === currentEdge.target)
|
||||
|
||||
if (sourceNode)
|
||||
sourceNode.data._connectedSourceHandleIds = sourceNode.data._connectedSourceHandleIds?.filter(handleId => handleId !== currentEdge.sourceHandle)
|
||||
|
||||
if (targetNode)
|
||||
targetNode.data._connectedTargetHandleIds = targetNode.data._connectedTargetHandleIds?.filter(handleId => handleId !== currentEdge.targetHandle)
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.splice(currentEdgeIndex, 1)
|
||||
})
|
||||
setEdges(newEdges)
|
||||
handleSyncWorkflowDraft()
|
||||
}, [store, handleSyncWorkflowDraft, getNodesReadOnly])
|
||||
|
||||
const handleEdgeDelete = useCallback(() => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const currentEdgeIndex = edges.findIndex(edge => edge.selected)
|
||||
|
||||
if (currentEdgeIndex < 0)
|
||||
return
|
||||
const currentEdge = edges[currentEdgeIndex]
|
||||
const nodes = getNodes()
|
||||
const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
|
||||
[
|
||||
{ type: 'remove', edge: currentEdge },
|
||||
],
|
||||
nodes,
|
||||
)
|
||||
const newNodes = produce(nodes, (draft: Node[]) => {
|
||||
draft.forEach((node) => {
|
||||
if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.splice(currentEdgeIndex, 1)
|
||||
})
|
||||
setEdges(newEdges)
|
||||
handleSyncWorkflowDraft()
|
||||
}, [store, getNodesReadOnly, handleSyncWorkflowDraft])
|
||||
|
||||
const handleEdgesChange = useCallback<OnEdgesChange>((changes) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
changes.forEach((change) => {
|
||||
if (change.type === 'select')
|
||||
draft.find(edge => edge.id === change.id)!.selected = change.selected
|
||||
})
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}, [store, getNodesReadOnly])
|
||||
|
||||
const handleVariableAssignerEdgesChange = useCallback((nodeId: string, variables: any) => {
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const newEdgesTargetHandleIds = variables.map((item: any) => item[0])
|
||||
const connectedEdges = getConnectedEdges([{ id: nodeId } as Node], edges).filter(edge => edge.target === nodeId)
|
||||
const needDeleteEdges = connectedEdges.filter(edge => !newEdgesTargetHandleIds.includes(edge.targetHandle))
|
||||
const needAddEdgesTargetHandleIds = newEdgesTargetHandleIds.filter((targetHandle: string) => !connectedEdges.some(edge => edge.targetHandle === targetHandle))
|
||||
const needAddEdges = needAddEdgesTargetHandleIds.map((targetHandle: string) => {
|
||||
return {
|
||||
id: `${targetHandle}-${nodeId}`,
|
||||
type: 'custom',
|
||||
source: targetHandle,
|
||||
sourceHandle: 'source',
|
||||
target: nodeId,
|
||||
targetHandle,
|
||||
data: {
|
||||
sourceType: nodes.find(node => node.id === targetHandle)?.data.type,
|
||||
targetType: BlockEnum.VariableAssigner,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
|
||||
[
|
||||
...needDeleteEdges.map(edge => ({ type: 'remove', edge })),
|
||||
...needAddEdges.map((edge: Edge) => ({ type: 'add', edge })),
|
||||
],
|
||||
nodes,
|
||||
)
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((node) => {
|
||||
if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
const filtered = draft.filter(edge => !needDeleteEdges.map(needDeleteEdge => needDeleteEdge.id).includes(edge.id))
|
||||
|
||||
filtered.push(...needAddEdges)
|
||||
|
||||
return filtered
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}, [store])
|
||||
|
||||
return {
|
||||
handleEdgeEnter,
|
||||
handleEdgeLeave,
|
||||
handleEdgeDeleteByDeleteBranch,
|
||||
handleEdgeDelete,
|
||||
handleEdgesChange,
|
||||
handleVariableAssignerEdgesChange,
|
||||
}
|
||||
}
|
||||
42
web/app/components/workflow/hooks/use-node-data-update.ts
Normal file
42
web/app/components/workflow/hooks/use-node-data-update.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import { useNodesSyncDraft } from './use-nodes-sync-draft'
|
||||
import { useNodesReadOnly } from './use-workflow'
|
||||
|
||||
type NodeDataUpdatePayload = {
|
||||
id: string
|
||||
data: Record<string, any>
|
||||
}
|
||||
|
||||
export const useNodeDataUpdate = () => {
|
||||
const store = useStoreApi()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
const { getNodesReadOnly } = useNodesReadOnly()
|
||||
|
||||
const handleNodeDataUpdate = useCallback(({ id, data }: NodeDataUpdatePayload) => {
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
} = store.getState()
|
||||
const newNodes = produce(getNodes(), (draft) => {
|
||||
const currentNode = draft.find(node => node.id === id)!
|
||||
|
||||
currentNode.data = { ...currentNode.data, ...data }
|
||||
})
|
||||
setNodes(newNodes)
|
||||
}, [store])
|
||||
|
||||
const handleNodeDataUpdateWithSyncDraft = useCallback((payload: NodeDataUpdatePayload) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
handleNodeDataUpdate(payload)
|
||||
handleSyncWorkflowDraft()
|
||||
}, [handleSyncWorkflowDraft, handleNodeDataUpdate, getNodesReadOnly])
|
||||
|
||||
return {
|
||||
handleNodeDataUpdate,
|
||||
handleNodeDataUpdateWithSyncDraft,
|
||||
}
|
||||
}
|
||||
32
web/app/components/workflow/hooks/use-nodes-data.ts
Normal file
32
web/app/components/workflow/hooks/use-nodes-data.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import produce from 'immer'
|
||||
import type { BlockEnum } from '../types'
|
||||
import {
|
||||
NODES_EXTRA_DATA,
|
||||
NODES_INITIAL_DATA,
|
||||
} from '../constants'
|
||||
import { useIsChatMode } from './use-workflow'
|
||||
|
||||
export const useNodesInitialData = () => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMemo(() => produce(NODES_INITIAL_DATA, (draft) => {
|
||||
Object.keys(draft).forEach((key) => {
|
||||
draft[key as BlockEnum].title = t(`workflow.blocks.${key}`)
|
||||
})
|
||||
}), [t])
|
||||
}
|
||||
|
||||
export const useNodesExtraData = () => {
|
||||
const { t } = useTranslation()
|
||||
const isChatMode = useIsChatMode()
|
||||
|
||||
return useMemo(() => produce(NODES_EXTRA_DATA, (draft) => {
|
||||
Object.keys(draft).forEach((key) => {
|
||||
draft[key as BlockEnum].about = t(`workflow.blocksAbout.${key}`)
|
||||
draft[key as BlockEnum].availablePrevNodes = draft[key as BlockEnum].getAvailablePrevNodes(isChatMode)
|
||||
draft[key as BlockEnum].availableNextNodes = draft[key as BlockEnum].getAvailableNextNodes(isChatMode)
|
||||
})
|
||||
}), [t, isChatMode])
|
||||
}
|
||||
721
web/app/components/workflow/hooks/use-nodes-interactions.ts
Normal file
721
web/app/components/workflow/hooks/use-nodes-interactions.ts
Normal file
|
|
@ -0,0 +1,721 @@
|
|||
import { useCallback, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import produce from 'immer'
|
||||
import type {
|
||||
HandleType,
|
||||
NodeDragHandler,
|
||||
NodeMouseHandler,
|
||||
OnConnect,
|
||||
OnConnectStart,
|
||||
} from 'reactflow'
|
||||
import {
|
||||
getConnectedEdges,
|
||||
getOutgoers,
|
||||
useStoreApi,
|
||||
} from 'reactflow'
|
||||
import type { ToolDefaultValue } from '../block-selector/types'
|
||||
import type {
|
||||
Edge,
|
||||
Node,
|
||||
OnNodeAdd,
|
||||
} from '../types'
|
||||
import { BlockEnum } from '../types'
|
||||
import { useWorkflowStore } from '../store'
|
||||
import {
|
||||
NODES_INITIAL_DATA,
|
||||
NODE_WIDTH_X_OFFSET,
|
||||
Y_OFFSET,
|
||||
} from '../constants'
|
||||
import {
|
||||
generateNewNode,
|
||||
getNodesConnectedSourceOrTargetHandleIdsMap,
|
||||
} from '../utils'
|
||||
import { useNodesExtraData } from './use-nodes-data'
|
||||
import { useNodesSyncDraft } from './use-nodes-sync-draft'
|
||||
import {
|
||||
useNodesReadOnly,
|
||||
useWorkflow,
|
||||
} from './use-workflow'
|
||||
|
||||
export const useNodesInteractions = () => {
|
||||
const { t } = useTranslation()
|
||||
const store = useStoreApi()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
const { getAfterNodesInSameBranch } = useWorkflow()
|
||||
const { getNodesReadOnly } = useNodesReadOnly()
|
||||
const dragNodeStartPosition = useRef({ x: 0, y: 0 } as { x: number; y: number })
|
||||
const connectingNodeRef = useRef<{ nodeId: string; handleType: HandleType } | null>(null)
|
||||
|
||||
const handleNodeDragStart = useCallback<NodeDragHandler>((_, node) => {
|
||||
workflowStore.setState({ nodeAnimation: false })
|
||||
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
dragNodeStartPosition.current = { x: node.position.x, y: node.position.y }
|
||||
}, [workflowStore, getNodesReadOnly])
|
||||
|
||||
const handleNodeDrag = useCallback<NodeDragHandler>((e, node: Node) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
} = store.getState()
|
||||
const {
|
||||
setHelpLineHorizontal,
|
||||
setHelpLineVertical,
|
||||
} = workflowStore.getState()
|
||||
e.stopPropagation()
|
||||
|
||||
const nodes = getNodes()
|
||||
|
||||
const showHorizontalHelpLineNodes = nodes.filter((n) => {
|
||||
if (n.id === node.id)
|
||||
return false
|
||||
|
||||
const nY = Math.ceil(n.position.y)
|
||||
const nodeY = Math.ceil(node.position.y)
|
||||
|
||||
if (nY - nodeY < 5 && nY - nodeY > -5)
|
||||
return true
|
||||
|
||||
return false
|
||||
}).sort((a, b) => a.position.x - b.position.x)
|
||||
const showHorizontalHelpLineNodesLength = showHorizontalHelpLineNodes.length
|
||||
if (showHorizontalHelpLineNodesLength > 0) {
|
||||
const first = showHorizontalHelpLineNodes[0]
|
||||
const last = showHorizontalHelpLineNodes[showHorizontalHelpLineNodesLength - 1]
|
||||
|
||||
const helpLine = {
|
||||
top: first.position.y,
|
||||
left: first.position.x,
|
||||
width: last.position.x + last.width! - first.position.x,
|
||||
}
|
||||
|
||||
if (node.position.x < first.position.x) {
|
||||
helpLine.left = node.position.x
|
||||
helpLine.width = first.position.x + first.width! - node.position.x
|
||||
}
|
||||
|
||||
if (node.position.x > last.position.x)
|
||||
helpLine.width = node.position.x + node.width! - first.position.x
|
||||
|
||||
setHelpLineHorizontal(helpLine)
|
||||
}
|
||||
else {
|
||||
setHelpLineHorizontal()
|
||||
}
|
||||
|
||||
const showVerticalHelpLineNodes = nodes.filter((n) => {
|
||||
if (n.id === node.id)
|
||||
return false
|
||||
|
||||
const nX = Math.ceil(n.position.x)
|
||||
const nodeX = Math.ceil(node.position.x)
|
||||
|
||||
if (nX - nodeX < 5 && nX - nodeX > -5)
|
||||
return true
|
||||
|
||||
return false
|
||||
}).sort((a, b) => a.position.x - b.position.x)
|
||||
const showVerticalHelpLineNodesLength = showVerticalHelpLineNodes.length
|
||||
|
||||
if (showVerticalHelpLineNodesLength > 0) {
|
||||
const first = showVerticalHelpLineNodes[0]
|
||||
const last = showVerticalHelpLineNodes[showVerticalHelpLineNodesLength - 1]
|
||||
|
||||
const helpLine = {
|
||||
top: first.position.y,
|
||||
left: first.position.x,
|
||||
height: last.position.y + last.height! - first.position.y,
|
||||
}
|
||||
|
||||
if (node.position.y < first.position.y) {
|
||||
helpLine.top = node.position.y
|
||||
helpLine.height = first.position.y + first.height! - node.position.y
|
||||
}
|
||||
|
||||
if (node.position.y > last.position.y)
|
||||
helpLine.height = node.position.y + node.height! - first.position.y
|
||||
|
||||
setHelpLineVertical(helpLine)
|
||||
}
|
||||
else {
|
||||
setHelpLineVertical()
|
||||
}
|
||||
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
const currentNode = draft.find(n => n.id === node.id)!
|
||||
|
||||
currentNode.position = {
|
||||
x: showVerticalHelpLineNodesLength > 0 ? showVerticalHelpLineNodes[0].position.x : node.position.x,
|
||||
y: showHorizontalHelpLineNodesLength > 0 ? showHorizontalHelpLineNodes[0].position.y : node.position.y,
|
||||
}
|
||||
})
|
||||
|
||||
setNodes(newNodes)
|
||||
}, [store, workflowStore, getNodesReadOnly])
|
||||
|
||||
const handleNodeDragStop = useCallback<NodeDragHandler>((_, node) => {
|
||||
const {
|
||||
setHelpLineHorizontal,
|
||||
setHelpLineVertical,
|
||||
} = workflowStore.getState()
|
||||
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const { x, y } = dragNodeStartPosition.current
|
||||
if (!(x === node.position.x && y === node.position.y)) {
|
||||
setHelpLineHorizontal()
|
||||
setHelpLineVertical()
|
||||
handleSyncWorkflowDraft()
|
||||
}
|
||||
}, [handleSyncWorkflowDraft, workflowStore, getNodesReadOnly])
|
||||
|
||||
const handleNodeEnter = useCallback<NodeMouseHandler>((_, node) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
|
||||
if (connectingNodeRef.current && connectingNodeRef.current.nodeId !== node.id) {
|
||||
const connectingNode: Node = nodes.find(n => n.id === connectingNodeRef.current!.nodeId)!
|
||||
const handleType = connectingNodeRef.current.handleType
|
||||
const currentNodeIndex = nodes.findIndex(n => n.id === node.id)
|
||||
const availablePrevNodes = nodesExtraData[connectingNode.data.type].availablePrevNodes
|
||||
const availableNextNodes = nodesExtraData[connectingNode.data.type].availableNextNodes
|
||||
const availableNodes = handleType === 'source' ? availableNextNodes : [...availablePrevNodes, BlockEnum.Start]
|
||||
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
if (!availableNodes.includes(draft[currentNodeIndex].data.type))
|
||||
draft[currentNodeIndex].data._isInvalidConnection = true
|
||||
})
|
||||
setNodes(newNodes)
|
||||
}
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
const connectedEdges = getConnectedEdges([node], edges)
|
||||
|
||||
connectedEdges.forEach((edge) => {
|
||||
const currentEdge = draft.find(e => e.id === edge.id)
|
||||
if (currentEdge)
|
||||
currentEdge.data._connectedNodeIsHovering = true
|
||||
})
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}, [store, nodesExtraData, getNodesReadOnly])
|
||||
|
||||
const handleNodeLeave = useCallback<NodeMouseHandler>(() => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const newNodes = produce(getNodes(), (draft) => {
|
||||
draft.forEach((node) => {
|
||||
node.data._isInvalidConnection = false
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.forEach((edge) => {
|
||||
edge.data._connectedNodeIsHovering = false
|
||||
})
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}, [store, getNodesReadOnly])
|
||||
|
||||
const handleNodeSelect = useCallback((nodeId: string, cancelSelection?: boolean) => {
|
||||
if (getNodesReadOnly() && !workflowStore.getState().isRestoring)
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
|
||||
const nodes = getNodes()
|
||||
const selectedNode = nodes.find(node => node.data.selected)
|
||||
|
||||
if (!cancelSelection && selectedNode?.id === nodeId)
|
||||
return
|
||||
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((node) => {
|
||||
if (node.id === nodeId)
|
||||
node.data.selected = !cancelSelection
|
||||
else
|
||||
node.data.selected = false
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
|
||||
const connectedEdges = getConnectedEdges([{ id: nodeId } as Node], edges).map(edge => edge.id)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.forEach((edge) => {
|
||||
if (connectedEdges.includes(edge.id)) {
|
||||
edge.data = {
|
||||
...edge.data,
|
||||
_connectedNodeIsSelected: !cancelSelection,
|
||||
}
|
||||
}
|
||||
else {
|
||||
edge.data = {
|
||||
...edge.data,
|
||||
_connectedNodeIsSelected: false,
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
setEdges(newEdges)
|
||||
|
||||
handleSyncWorkflowDraft()
|
||||
}, [store, handleSyncWorkflowDraft, getNodesReadOnly, workflowStore])
|
||||
|
||||
const handleNodeClick = useCallback<NodeMouseHandler>((_, node) => {
|
||||
if (getNodesReadOnly() && !workflowStore.getState().isRestoring)
|
||||
return
|
||||
|
||||
handleNodeSelect(node.id)
|
||||
}, [handleNodeSelect, getNodesReadOnly, workflowStore])
|
||||
|
||||
const handleNodeConnect = useCallback<OnConnect>(({
|
||||
source,
|
||||
sourceHandle,
|
||||
target,
|
||||
targetHandle,
|
||||
}) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const needDeleteEdges = edges.filter((edge) => {
|
||||
if (edge.source === source) {
|
||||
if (edge.sourceHandle)
|
||||
return edge.sourceHandle === sourceHandle
|
||||
else
|
||||
return true
|
||||
}
|
||||
if (edge.target === target) {
|
||||
if (edge.targetHandle)
|
||||
return edge.targetHandle === targetHandle
|
||||
else
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
const needDeleteEdgesIds = needDeleteEdges.map(edge => edge.id)
|
||||
const newEdge = {
|
||||
id: `${source}-${target}`,
|
||||
type: 'custom',
|
||||
source: source!,
|
||||
target: target!,
|
||||
sourceHandle,
|
||||
targetHandle,
|
||||
data: {
|
||||
sourceType: nodes.find(node => node.id === source)!.data.type,
|
||||
targetType: nodes.find(node => node.id === target)!.data.type,
|
||||
},
|
||||
}
|
||||
const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
|
||||
[
|
||||
...needDeleteEdges.map(edge => ({ type: 'remove', edge })),
|
||||
{ type: 'add', edge: newEdge },
|
||||
],
|
||||
nodes,
|
||||
)
|
||||
const newNodes = produce(nodes, (draft: Node[]) => {
|
||||
draft.forEach((node) => {
|
||||
if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
const filtered = draft.filter(edge => !needDeleteEdgesIds.includes(edge.id))
|
||||
|
||||
filtered.push(newEdge)
|
||||
|
||||
return filtered
|
||||
})
|
||||
setEdges(newEdges)
|
||||
handleSyncWorkflowDraft()
|
||||
}, [store, handleSyncWorkflowDraft, getNodesReadOnly])
|
||||
|
||||
const handleNodeConnectStart = useCallback<OnConnectStart>((_, { nodeId, handleType }) => {
|
||||
if (nodeId && handleType) {
|
||||
connectingNodeRef.current = {
|
||||
nodeId,
|
||||
handleType,
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleNodeConnectEnd = useCallback(() => {
|
||||
connectingNodeRef.current = null
|
||||
}, [])
|
||||
|
||||
const handleNodeDelete = useCallback((nodeId: string) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
|
||||
const nodes = getNodes()
|
||||
const currentNodeIndex = nodes.findIndex(node => node.id === nodeId)
|
||||
const connectedEdges = getConnectedEdges([{ id: nodeId } as Node], edges)
|
||||
const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(connectedEdges.map(edge => ({ type: 'remove', edge })), nodes)
|
||||
const newNodes = produce(nodes, (draft: Node[]) => {
|
||||
draft.forEach((node) => {
|
||||
if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
|
||||
}
|
||||
}
|
||||
})
|
||||
draft.splice(currentNodeIndex, 1)
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
return draft.filter(edge => !connectedEdges.find(connectedEdge => connectedEdge.id === edge.id))
|
||||
})
|
||||
setEdges(newEdges)
|
||||
handleSyncWorkflowDraft()
|
||||
}, [store, handleSyncWorkflowDraft, getNodesReadOnly])
|
||||
|
||||
const handleNodeAdd = useCallback<OnNodeAdd>((
|
||||
{
|
||||
nodeType,
|
||||
sourceHandle = 'source',
|
||||
targetHandle = 'target',
|
||||
toolDefaultValue,
|
||||
},
|
||||
{
|
||||
prevNodeId,
|
||||
prevNodeSourceHandle,
|
||||
nextNodeId,
|
||||
nextNodeTargetHandle,
|
||||
},
|
||||
) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
if (nodeType === BlockEnum.VariableAssigner)
|
||||
targetHandle = 'varNotSet'
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const nodesWithSameType = nodes.filter(node => node.data.type === nodeType)
|
||||
const newNode = generateNewNode({
|
||||
data: {
|
||||
...NODES_INITIAL_DATA[nodeType],
|
||||
title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${nodeType}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${nodeType}`),
|
||||
...(toolDefaultValue || {}),
|
||||
selected: true,
|
||||
},
|
||||
position: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
})
|
||||
if (prevNodeId && !nextNodeId) {
|
||||
const prevNodeIndex = nodes.findIndex(node => node.id === prevNodeId)
|
||||
const prevNode = nodes[prevNodeIndex]
|
||||
const outgoers = getOutgoers(prevNode, nodes, edges).sort((a, b) => a.position.y - b.position.y)
|
||||
const lastOutgoer = outgoers[outgoers.length - 1]
|
||||
if (prevNode.data.type === BlockEnum.KnowledgeRetrieval)
|
||||
targetHandle = prevNodeId
|
||||
newNode.data._connectedTargetHandleIds = [targetHandle]
|
||||
newNode.data._connectedSourceHandleIds = []
|
||||
newNode.position = {
|
||||
x: lastOutgoer ? lastOutgoer.position.x : prevNode.position.x + NODE_WIDTH_X_OFFSET,
|
||||
y: lastOutgoer ? lastOutgoer.position.y + lastOutgoer.height! + Y_OFFSET : prevNode.position.y,
|
||||
}
|
||||
|
||||
const newEdge = {
|
||||
id: `${prevNodeId}-${newNode.id}`,
|
||||
type: 'custom',
|
||||
source: prevNodeId,
|
||||
sourceHandle: prevNodeSourceHandle,
|
||||
target: newNode.id,
|
||||
targetHandle,
|
||||
data: {
|
||||
sourceType: prevNode.data.type,
|
||||
targetType: newNode.data.type,
|
||||
_connectedNodeIsSelected: true,
|
||||
},
|
||||
}
|
||||
const newNodes = produce(nodes, (draft: Node[]) => {
|
||||
draft.forEach((node) => {
|
||||
node.data.selected = false
|
||||
|
||||
if (node.id === prevNode.id)
|
||||
node.data._connectedSourceHandleIds?.push(prevNodeSourceHandle!)
|
||||
})
|
||||
draft.push(newNode)
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.forEach((item) => {
|
||||
item.data = {
|
||||
...item.data,
|
||||
_connectedNodeIsSelected: false,
|
||||
}
|
||||
})
|
||||
draft.push(newEdge)
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}
|
||||
if (!prevNodeId && nextNodeId) {
|
||||
const nextNodeIndex = nodes.findIndex(node => node.id === nextNodeId)
|
||||
const nextNode = nodes[nextNodeIndex]!
|
||||
newNode.data._connectedSourceHandleIds = [sourceHandle]
|
||||
newNode.data._connectedTargetHandleIds = []
|
||||
newNode.position = {
|
||||
x: nextNode.position.x,
|
||||
y: nextNode.position.y,
|
||||
}
|
||||
|
||||
const newEdge = {
|
||||
id: `${newNode.id}-${nextNodeId}`,
|
||||
type: 'custom',
|
||||
source: newNode.id,
|
||||
sourceHandle,
|
||||
target: nextNodeId,
|
||||
targetHandle: nextNodeTargetHandle,
|
||||
data: {
|
||||
sourceType: newNode.data.type,
|
||||
targetType: nextNode.data.type,
|
||||
_connectedNodeIsSelected: true,
|
||||
},
|
||||
}
|
||||
const afterNodesInSameBranch = getAfterNodesInSameBranch(nextNodeId!)
|
||||
const afterNodesInSameBranchIds = afterNodesInSameBranch.map(node => node.id)
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((node) => {
|
||||
node.data.selected = false
|
||||
|
||||
if (afterNodesInSameBranchIds.includes(node.id))
|
||||
node.position.x += NODE_WIDTH_X_OFFSET
|
||||
|
||||
if (node.id === nextNodeId)
|
||||
node.data._connectedTargetHandleIds?.push(nextNodeTargetHandle!)
|
||||
})
|
||||
draft.push(newNode)
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.forEach((item) => {
|
||||
item.data = {
|
||||
...item.data,
|
||||
_connectedNodeIsSelected: false,
|
||||
}
|
||||
})
|
||||
draft.push(newEdge)
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}
|
||||
if (prevNodeId && nextNodeId) {
|
||||
const prevNode = nodes.find(node => node.id === prevNodeId)!
|
||||
const nextNode = nodes.find(node => node.id === nextNodeId)!
|
||||
if (prevNode.data.type === BlockEnum.KnowledgeRetrieval)
|
||||
targetHandle = prevNodeId
|
||||
newNode.data._connectedTargetHandleIds = [targetHandle]
|
||||
newNode.data._connectedSourceHandleIds = [sourceHandle]
|
||||
newNode.position = {
|
||||
x: nextNode.position.x,
|
||||
y: nextNode.position.y,
|
||||
}
|
||||
|
||||
const currentEdgeIndex = edges.findIndex(edge => edge.source === prevNodeId && edge.target === nextNodeId)
|
||||
const newPrevEdge = {
|
||||
id: `${prevNodeId}-${newNode.id}`,
|
||||
type: 'custom',
|
||||
source: prevNodeId,
|
||||
sourceHandle: prevNodeSourceHandle,
|
||||
target: newNode.id,
|
||||
targetHandle,
|
||||
data: {
|
||||
sourceType: prevNode.data.type,
|
||||
targetType: newNode.data.type,
|
||||
_connectedNodeIsSelected: true,
|
||||
},
|
||||
}
|
||||
let newNextEdge: Edge | null = null
|
||||
if (nodeType !== BlockEnum.IfElse && nodeType !== BlockEnum.QuestionClassifier) {
|
||||
newNextEdge = {
|
||||
id: `${newNode.id}-${nextNodeId}`,
|
||||
type: 'custom',
|
||||
source: newNode.id,
|
||||
sourceHandle,
|
||||
target: nextNodeId,
|
||||
targetHandle: nextNodeTargetHandle,
|
||||
data: {
|
||||
sourceType: newNode.data.type,
|
||||
targetType: nextNode.data.type,
|
||||
_connectedNodeIsSelected: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
|
||||
[
|
||||
{ type: 'remove', edge: edges[currentEdgeIndex] },
|
||||
{ type: 'add', edge: newPrevEdge },
|
||||
...(newNextEdge ? [{ type: 'add', edge: newNextEdge }] : []),
|
||||
],
|
||||
[...nodes, newNode],
|
||||
)
|
||||
|
||||
const afterNodesInSameBranch = getAfterNodesInSameBranch(nextNodeId!)
|
||||
const afterNodesInSameBranchIds = afterNodesInSameBranch.map(node => node.id)
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((node) => {
|
||||
node.data.selected = false
|
||||
|
||||
if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
|
||||
}
|
||||
}
|
||||
if (afterNodesInSameBranchIds.includes(node.id))
|
||||
node.position.x += NODE_WIDTH_X_OFFSET
|
||||
})
|
||||
draft.push(newNode)
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.splice(currentEdgeIndex, 1)
|
||||
draft.forEach((item) => {
|
||||
item.data = {
|
||||
...item.data,
|
||||
_connectedNodeIsSelected: false,
|
||||
}
|
||||
})
|
||||
draft.push(newPrevEdge)
|
||||
|
||||
if (newNextEdge)
|
||||
draft.push(newNextEdge)
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}
|
||||
handleSyncWorkflowDraft()
|
||||
}, [store, handleSyncWorkflowDraft, getAfterNodesInSameBranch, getNodesReadOnly, t])
|
||||
|
||||
const handleNodeChange = useCallback((
|
||||
currentNodeId: string,
|
||||
nodeType: BlockEnum,
|
||||
sourceHandle: string,
|
||||
toolDefaultValue?: ToolDefaultValue,
|
||||
) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const currentNode = nodes.find(node => node.id === currentNodeId)!
|
||||
const connectedEdges = getConnectedEdges([currentNode], edges)
|
||||
const nodesWithSameType = nodes.filter(node => node.data.type === nodeType)
|
||||
const newCurrentNode = generateNewNode({
|
||||
data: {
|
||||
...NODES_INITIAL_DATA[nodeType],
|
||||
title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${nodeType}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${nodeType}`),
|
||||
...(toolDefaultValue || {}),
|
||||
_connectedSourceHandleIds: [],
|
||||
_connectedTargetHandleIds: [],
|
||||
selected: currentNode.data.selected,
|
||||
},
|
||||
position: {
|
||||
x: currentNode.position.x,
|
||||
y: currentNode.position.y,
|
||||
},
|
||||
})
|
||||
const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
|
||||
[
|
||||
...connectedEdges.map(edge => ({ type: 'remove', edge })),
|
||||
],
|
||||
nodes,
|
||||
)
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((node) => {
|
||||
node.data.selected = false
|
||||
|
||||
if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
|
||||
}
|
||||
}
|
||||
})
|
||||
const index = draft.findIndex(node => node.id === currentNodeId)
|
||||
|
||||
draft.splice(index, 1, newCurrentNode)
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
const filtered = draft.filter(edge => !connectedEdges.find(connectedEdge => connectedEdge.id === edge.id))
|
||||
|
||||
return filtered
|
||||
})
|
||||
setEdges(newEdges)
|
||||
handleSyncWorkflowDraft()
|
||||
}, [store, handleSyncWorkflowDraft, getNodesReadOnly, t])
|
||||
|
||||
return {
|
||||
handleNodeDragStart,
|
||||
handleNodeDrag,
|
||||
handleNodeDragStop,
|
||||
handleNodeEnter,
|
||||
handleNodeLeave,
|
||||
handleNodeSelect,
|
||||
handleNodeClick,
|
||||
handleNodeConnect,
|
||||
handleNodeConnectStart,
|
||||
handleNodeConnectEnd,
|
||||
handleNodeDelete,
|
||||
handleNodeChange,
|
||||
handleNodeAdd,
|
||||
}
|
||||
}
|
||||
118
web/app/components/workflow/hooks/use-nodes-sync-draft.ts
Normal file
118
web/app/components/workflow/hooks/use-nodes-sync-draft.ts
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import { useParams } from 'next/navigation'
|
||||
import {
|
||||
useStore,
|
||||
useWorkflowStore,
|
||||
} from '../store'
|
||||
import { BlockEnum } from '../types'
|
||||
import { useNodesReadOnly } from './use-workflow'
|
||||
import { syncWorkflowDraft } from '@/service/workflow'
|
||||
import { useFeaturesStore } from '@/app/components/base/features/hooks'
|
||||
import { API_PREFIX } from '@/config'
|
||||
|
||||
export const useNodesSyncDraft = () => {
|
||||
const store = useStoreApi()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const featuresStore = useFeaturesStore()
|
||||
const { getNodesReadOnly } = useNodesReadOnly()
|
||||
const debouncedSyncWorkflowDraft = useStore(s => s.debouncedSyncWorkflowDraft)
|
||||
const params = useParams()
|
||||
|
||||
const getPostParams = useCallback((appIdParams?: string) => {
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
transform,
|
||||
} = store.getState()
|
||||
const [x, y, zoom] = transform
|
||||
const appId = workflowStore.getState().appId
|
||||
|
||||
if (appId || appIdParams) {
|
||||
const nodes = getNodes()
|
||||
const hasStartNode = nodes.find(node => node.data.type === BlockEnum.Start)
|
||||
|
||||
if (!hasStartNode)
|
||||
return
|
||||
|
||||
const features = featuresStore!.getState().features
|
||||
const producedNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((node) => {
|
||||
Object.keys(node.data).forEach((key) => {
|
||||
if (key.startsWith('_'))
|
||||
delete node.data[key]
|
||||
})
|
||||
})
|
||||
})
|
||||
const producedEdges = produce(edges, (draft) => {
|
||||
draft.forEach((edge) => {
|
||||
Object.keys(edge.data).forEach((key) => {
|
||||
if (key.startsWith('_'))
|
||||
delete edge.data[key]
|
||||
})
|
||||
})
|
||||
})
|
||||
return {
|
||||
url: `/apps/${appId || appIdParams}/workflows/draft`,
|
||||
params: {
|
||||
graph: {
|
||||
nodes: producedNodes,
|
||||
edges: producedEdges,
|
||||
viewport: {
|
||||
x,
|
||||
y,
|
||||
zoom,
|
||||
},
|
||||
},
|
||||
features: {
|
||||
opening_statement: features.opening?.opening_statement || '',
|
||||
suggested_questions: features.opening?.suggested_questions || [],
|
||||
suggested_questions_after_answer: features.suggested,
|
||||
text_to_speech: features.text2speech,
|
||||
speech_to_text: features.speech2text,
|
||||
retriever_resource: features.citation,
|
||||
sensitive_word_avoidance: features.moderation,
|
||||
file_upload: features.file,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}, [store, featuresStore, workflowStore])
|
||||
|
||||
const syncWorkflowDraftWhenPageClose = useCallback(() => {
|
||||
const postParams = getPostParams()
|
||||
|
||||
if (postParams) {
|
||||
navigator.sendBeacon(
|
||||
`${API_PREFIX}/apps/${params.appId}/workflows/draft?_token=${localStorage.getItem('console_token')}`,
|
||||
JSON.stringify(postParams.params),
|
||||
)
|
||||
}
|
||||
}, [getPostParams, params.appId])
|
||||
|
||||
const doSyncWorkflowDraft = useCallback(async (appId?: string) => {
|
||||
const postParams = getPostParams(appId)
|
||||
|
||||
if (postParams) {
|
||||
const res = await syncWorkflowDraft(postParams)
|
||||
workflowStore.getState().setDraftUpdatedAt(res.updated_at)
|
||||
}
|
||||
}, [workflowStore, getPostParams])
|
||||
|
||||
const handleSyncWorkflowDraft = useCallback((sync?: boolean, appId?: string) => {
|
||||
if (getNodesReadOnly())
|
||||
return
|
||||
|
||||
if (sync)
|
||||
doSyncWorkflowDraft(appId)
|
||||
else
|
||||
debouncedSyncWorkflowDraft(doSyncWorkflowDraft)
|
||||
}, [debouncedSyncWorkflowDraft, doSyncWorkflowDraft, getNodesReadOnly])
|
||||
|
||||
return {
|
||||
doSyncWorkflowDraft,
|
||||
handleSyncWorkflowDraft,
|
||||
syncWorkflowDraftWhenPageClose,
|
||||
}
|
||||
}
|
||||
352
web/app/components/workflow/hooks/use-workflow-run.ts
Normal file
352
web/app/components/workflow/hooks/use-workflow-run.ts
Normal file
|
|
@ -0,0 +1,352 @@
|
|||
import { useCallback } from 'react'
|
||||
import {
|
||||
useReactFlow,
|
||||
useStoreApi,
|
||||
} from 'reactflow'
|
||||
import produce from 'immer'
|
||||
import { useWorkflowStore } from '../store'
|
||||
import {
|
||||
NodeRunningStatus,
|
||||
WorkflowRunningStatus,
|
||||
} from '../types'
|
||||
import { useWorkflow } from './use-workflow'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import type { IOtherOptions } from '@/service/base'
|
||||
import { ssePost } from '@/service/base'
|
||||
import {
|
||||
fetchPublishedWorkflow,
|
||||
stopWorkflowRun,
|
||||
} from '@/service/workflow'
|
||||
import { useFeaturesStore } from '@/app/components/base/features/hooks'
|
||||
|
||||
export const useWorkflowRun = () => {
|
||||
const store = useStoreApi()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const reactflow = useReactFlow()
|
||||
const featuresStore = useFeaturesStore()
|
||||
const { renderTreeFromRecord } = useWorkflow()
|
||||
|
||||
const handleBackupDraft = useCallback(() => {
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
} = store.getState()
|
||||
const { getViewport } = reactflow
|
||||
const {
|
||||
backupDraft,
|
||||
setBackupDraft,
|
||||
} = workflowStore.getState()
|
||||
const { features } = featuresStore!.getState()
|
||||
|
||||
if (!backupDraft) {
|
||||
setBackupDraft({
|
||||
nodes: getNodes(),
|
||||
edges,
|
||||
viewport: getViewport(),
|
||||
features,
|
||||
})
|
||||
}
|
||||
}, [reactflow, workflowStore, store, featuresStore])
|
||||
|
||||
const handleLoadBackupDraft = useCallback(() => {
|
||||
const {
|
||||
setNodes,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const { setViewport } = reactflow
|
||||
const {
|
||||
backupDraft,
|
||||
setBackupDraft,
|
||||
} = workflowStore.getState()
|
||||
|
||||
if (backupDraft) {
|
||||
const {
|
||||
nodes,
|
||||
edges,
|
||||
viewport,
|
||||
features,
|
||||
} = backupDraft
|
||||
setNodes(nodes)
|
||||
setEdges(edges)
|
||||
setViewport(viewport)
|
||||
featuresStore!.setState({ features })
|
||||
setBackupDraft(undefined)
|
||||
}
|
||||
}, [store, reactflow, workflowStore, featuresStore])
|
||||
|
||||
const handleRunSetting = useCallback((shouldClear?: boolean) => {
|
||||
if (shouldClear) {
|
||||
workflowStore.setState({
|
||||
workflowRunningData: undefined,
|
||||
historyWorkflowData: undefined,
|
||||
showInputsPanel: false,
|
||||
})
|
||||
}
|
||||
else {
|
||||
workflowStore.setState({
|
||||
workflowRunningData: {
|
||||
result: {
|
||||
status: shouldClear ? '' : WorkflowRunningStatus.Waiting,
|
||||
},
|
||||
tracing: [],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const {
|
||||
setNodes,
|
||||
getNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
|
||||
if (shouldClear) {
|
||||
handleLoadBackupDraft()
|
||||
}
|
||||
else {
|
||||
handleBackupDraft()
|
||||
const newNodes = produce(getNodes(), (draft) => {
|
||||
draft.forEach((node) => {
|
||||
node.data._runningStatus = NodeRunningStatus.Waiting
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
draft.forEach((edge) => {
|
||||
edge.data._runned = false
|
||||
})
|
||||
})
|
||||
setEdges(newEdges)
|
||||
}
|
||||
}, [store, handleLoadBackupDraft, handleBackupDraft, workflowStore])
|
||||
|
||||
const handleRun = useCallback((
|
||||
params: any,
|
||||
callback?: IOtherOptions,
|
||||
) => {
|
||||
const {
|
||||
onWorkflowStarted,
|
||||
onWorkflowFinished,
|
||||
onNodeStarted,
|
||||
onNodeFinished,
|
||||
onError,
|
||||
...restCallback
|
||||
} = callback || {}
|
||||
workflowStore.setState({ historyWorkflowData: undefined })
|
||||
const appDetail = useAppStore.getState().appDetail
|
||||
const workflowContainer = document.getElementById('workflow-container')
|
||||
|
||||
const {
|
||||
clientWidth,
|
||||
clientHeight,
|
||||
} = workflowContainer!
|
||||
|
||||
let url = ''
|
||||
if (appDetail?.mode === 'advanced-chat')
|
||||
url = `/apps/${appDetail.id}/advanced-chat/workflows/draft/run`
|
||||
|
||||
if (appDetail?.mode === 'workflow')
|
||||
url = `/apps/${appDetail.id}/workflows/draft/run`
|
||||
|
||||
let prevNodeId = ''
|
||||
|
||||
const {
|
||||
workflowRunningData,
|
||||
setWorkflowRunningData,
|
||||
} = workflowStore.getState()
|
||||
setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
|
||||
draft.result = {
|
||||
...draft?.result,
|
||||
status: WorkflowRunningStatus.Running,
|
||||
}
|
||||
}))
|
||||
|
||||
ssePost(
|
||||
url,
|
||||
{
|
||||
body: params,
|
||||
},
|
||||
{
|
||||
onWorkflowStarted: (params) => {
|
||||
const { task_id, data } = params
|
||||
const {
|
||||
workflowRunningData,
|
||||
setWorkflowRunningData,
|
||||
} = workflowStore.getState()
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
} = store.getState()
|
||||
setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
|
||||
draft.task_id = task_id
|
||||
draft.result = {
|
||||
...draft?.result,
|
||||
...data,
|
||||
status: WorkflowRunningStatus.Running,
|
||||
}
|
||||
}))
|
||||
|
||||
const newNodes = produce(getNodes(), (draft) => {
|
||||
draft.forEach((node) => {
|
||||
node.data._runningStatus = NodeRunningStatus.Waiting
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
|
||||
if (onWorkflowStarted)
|
||||
onWorkflowStarted(params)
|
||||
},
|
||||
onWorkflowFinished: (params) => {
|
||||
const { data } = params
|
||||
const {
|
||||
workflowRunningData,
|
||||
setWorkflowRunningData,
|
||||
} = workflowStore.getState()
|
||||
|
||||
setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
|
||||
draft.result = {
|
||||
...draft.result,
|
||||
...data,
|
||||
}
|
||||
}))
|
||||
|
||||
prevNodeId = ''
|
||||
|
||||
if (onWorkflowFinished)
|
||||
onWorkflowFinished(params)
|
||||
},
|
||||
onError: (params) => {
|
||||
const {
|
||||
workflowRunningData,
|
||||
setWorkflowRunningData,
|
||||
} = workflowStore.getState()
|
||||
|
||||
setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
|
||||
draft.result = {
|
||||
...draft.result,
|
||||
status: WorkflowRunningStatus.Failed,
|
||||
}
|
||||
}))
|
||||
|
||||
if (onError)
|
||||
onError(params)
|
||||
},
|
||||
onNodeStarted: (params) => {
|
||||
const { data } = params
|
||||
const {
|
||||
workflowRunningData,
|
||||
setWorkflowRunningData,
|
||||
} = workflowStore.getState()
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
edges,
|
||||
setEdges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
|
||||
draft.tracing!.push({
|
||||
...data,
|
||||
status: NodeRunningStatus.Running,
|
||||
} as any)
|
||||
}))
|
||||
|
||||
const {
|
||||
setViewport,
|
||||
} = reactflow
|
||||
const currentNodeIndex = nodes.findIndex(node => node.id === data.node_id)
|
||||
const currentNode = nodes[currentNodeIndex]
|
||||
const position = currentNode.position
|
||||
const zoom = 1
|
||||
|
||||
setViewport({
|
||||
x: (clientWidth - 400 - currentNode.width!) / 2 - position.x,
|
||||
y: (clientHeight - currentNode.height!) / 2 - position.y,
|
||||
zoom,
|
||||
})
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft[currentNodeIndex].data._runningStatus = NodeRunningStatus.Running
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const newEdges = produce(edges, (draft) => {
|
||||
const edge = draft.find(edge => edge.target === data.node_id && edge.source === prevNodeId)
|
||||
|
||||
if (edge)
|
||||
edge.data = { ...edge.data, _runned: true } as any
|
||||
})
|
||||
setEdges(newEdges)
|
||||
|
||||
if (onNodeStarted)
|
||||
onNodeStarted(params)
|
||||
},
|
||||
onNodeFinished: (params) => {
|
||||
const { data } = params
|
||||
const {
|
||||
workflowRunningData,
|
||||
setWorkflowRunningData,
|
||||
} = workflowStore.getState()
|
||||
const {
|
||||
getNodes,
|
||||
setNodes,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
|
||||
const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id)
|
||||
|
||||
if (currentIndex > -1 && draft.tracing) {
|
||||
draft.tracing[currentIndex] = {
|
||||
...(draft.tracing[currentIndex].extras
|
||||
? { extras: draft.tracing[currentIndex].extras }
|
||||
: {}),
|
||||
...data,
|
||||
} as any
|
||||
}
|
||||
}))
|
||||
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
const currentNode = draft.find(node => node.id === data.node_id)!
|
||||
|
||||
currentNode.data._runningStatus = data.status as any
|
||||
})
|
||||
setNodes(newNodes)
|
||||
|
||||
prevNodeId = data.node_id
|
||||
|
||||
if (onNodeFinished)
|
||||
onNodeFinished(params)
|
||||
},
|
||||
...restCallback,
|
||||
},
|
||||
)
|
||||
}, [store, reactflow, workflowStore])
|
||||
|
||||
const handleStopRun = useCallback((taskId: string) => {
|
||||
const appId = useAppStore.getState().appDetail?.id
|
||||
|
||||
stopWorkflowRun(`/apps/${appId}/workflow-runs/tasks/${taskId}/stop`)
|
||||
}, [])
|
||||
|
||||
const handleRestoreFromPublishedWorkflow = useCallback(async () => {
|
||||
const appDetail = useAppStore.getState().appDetail
|
||||
const publishedWorkflow = await fetchPublishedWorkflow(`/apps/${appDetail?.id}/workflows/publish`)
|
||||
|
||||
if (publishedWorkflow) {
|
||||
const nodes = publishedWorkflow.graph.nodes
|
||||
const edges = publishedWorkflow.graph.edges
|
||||
const viewport = publishedWorkflow.graph.viewport
|
||||
|
||||
renderTreeFromRecord(nodes, edges, viewport)
|
||||
featuresStore?.setState({ features: publishedWorkflow.features })
|
||||
workflowStore.getState().setPublishedAt(publishedWorkflow.created_at)
|
||||
}
|
||||
}, [featuresStore, workflowStore, renderTreeFromRecord])
|
||||
|
||||
return {
|
||||
handleBackupDraft,
|
||||
handleLoadBackupDraft,
|
||||
handleRunSetting,
|
||||
handleRun,
|
||||
handleStopRun,
|
||||
handleRestoreFromPublishedWorkflow,
|
||||
}
|
||||
}
|
||||
73
web/app/components/workflow/hooks/use-workflow-template.ts
Normal file
73
web/app/components/workflow/hooks/use-workflow-template.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { generateNewNode } from '../utils'
|
||||
import {
|
||||
NODE_WIDTH_X_OFFSET,
|
||||
START_INITIAL_POSITION,
|
||||
} from '../constants'
|
||||
import { useIsChatMode } from './use-workflow'
|
||||
import { useNodesInitialData } from './use-nodes-data'
|
||||
|
||||
export const useWorkflowTemplate = () => {
|
||||
const isChatMode = useIsChatMode()
|
||||
const nodesInitialData = useNodesInitialData()
|
||||
|
||||
const startNode = generateNewNode({
|
||||
data: nodesInitialData.start,
|
||||
position: START_INITIAL_POSITION,
|
||||
})
|
||||
|
||||
if (isChatMode) {
|
||||
const llmNode = generateNewNode({
|
||||
id: 'llm',
|
||||
data: {
|
||||
...nodesInitialData.llm,
|
||||
memory: {
|
||||
window: { enabled: false, size: 10 },
|
||||
},
|
||||
selected: true,
|
||||
},
|
||||
position: {
|
||||
x: START_INITIAL_POSITION.x + NODE_WIDTH_X_OFFSET,
|
||||
y: START_INITIAL_POSITION.y,
|
||||
},
|
||||
} as any)
|
||||
|
||||
const answerNode = generateNewNode({
|
||||
id: 'answer',
|
||||
data: {
|
||||
...nodesInitialData.answer,
|
||||
answer: `{{#${llmNode.id}.text#}}`,
|
||||
},
|
||||
position: {
|
||||
x: START_INITIAL_POSITION.x + NODE_WIDTH_X_OFFSET * 2,
|
||||
y: START_INITIAL_POSITION.y,
|
||||
},
|
||||
} as any)
|
||||
|
||||
const startToLlmEdge = {
|
||||
id: `${startNode.id}-${llmNode.id}`,
|
||||
source: startNode.id,
|
||||
sourceHandle: 'source',
|
||||
target: llmNode.id,
|
||||
targetHandle: 'target',
|
||||
}
|
||||
|
||||
const llmToAnswerEdge = {
|
||||
id: `${llmNode.id}-${answerNode.id}`,
|
||||
source: llmNode.id,
|
||||
sourceHandle: 'source',
|
||||
target: answerNode.id,
|
||||
targetHandle: 'target',
|
||||
}
|
||||
|
||||
return {
|
||||
nodes: [startNode, llmNode, answerNode],
|
||||
edges: [startToLlmEdge, llmToAnswerEdge],
|
||||
}
|
||||
}
|
||||
else {
|
||||
return {
|
||||
nodes: [startNode],
|
||||
edges: [],
|
||||
}
|
||||
}
|
||||
}
|
||||
472
web/app/components/workflow/hooks/use-workflow.ts
Normal file
472
web/app/components/workflow/hooks/use-workflow.ts
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
} from 'react'
|
||||
import dayjs from 'dayjs'
|
||||
import { uniqBy } from 'lodash-es'
|
||||
import { useContext } from 'use-context-selector'
|
||||
import useSWR from 'swr'
|
||||
import produce from 'immer'
|
||||
import {
|
||||
getIncomers,
|
||||
getOutgoers,
|
||||
useReactFlow,
|
||||
useStoreApi,
|
||||
} from 'reactflow'
|
||||
import type {
|
||||
Connection,
|
||||
Viewport,
|
||||
} from 'reactflow'
|
||||
import {
|
||||
getLayoutByDagre,
|
||||
initialEdges,
|
||||
initialNodes,
|
||||
} from '../utils'
|
||||
import type {
|
||||
Edge,
|
||||
Node,
|
||||
ValueSelector,
|
||||
} from '../types'
|
||||
import {
|
||||
BlockEnum,
|
||||
WorkflowRunningStatus,
|
||||
} from '../types'
|
||||
import {
|
||||
useStore,
|
||||
useWorkflowStore,
|
||||
} from '../store'
|
||||
import {
|
||||
AUTO_LAYOUT_OFFSET,
|
||||
SUPPORT_OUTPUT_VARS_NODE,
|
||||
} from '../constants'
|
||||
import { findUsedVarNodes, getNodeOutputVars, updateNodeVars } from '../nodes/_base/components/variable/utils'
|
||||
import { useNodesExtraData } from './use-nodes-data'
|
||||
import { useWorkflowTemplate } from './use-workflow-template'
|
||||
import { useNodesSyncDraft } from './use-nodes-sync-draft'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import {
|
||||
fetchNodesDefaultConfigs,
|
||||
fetchPublishedWorkflow,
|
||||
fetchWorkflowDraft,
|
||||
syncWorkflowDraft,
|
||||
} from '@/service/workflow'
|
||||
import {
|
||||
fetchAllBuiltInTools,
|
||||
fetchAllCustomTools,
|
||||
} from '@/service/tools'
|
||||
import I18n from '@/context/i18n'
|
||||
export const useIsChatMode = () => {
|
||||
const appDetail = useAppStore(s => s.appDetail)
|
||||
|
||||
return appDetail?.mode === 'advanced-chat'
|
||||
}
|
||||
|
||||
export const useWorkflow = () => {
|
||||
const { locale } = useContext(I18n)
|
||||
const store = useStoreApi()
|
||||
const reactflow = useReactFlow()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
|
||||
const handleLayout = useCallback(async () => {
|
||||
workflowStore.setState({ nodeAnimation: true })
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
setNodes,
|
||||
} = store.getState()
|
||||
const { setViewport } = reactflow
|
||||
const nodes = getNodes()
|
||||
const layout = getLayoutByDagre(nodes, edges)
|
||||
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((node) => {
|
||||
const nodeWithPosition = layout.node(node.id)
|
||||
node.position = {
|
||||
x: nodeWithPosition.x + AUTO_LAYOUT_OFFSET.x,
|
||||
y: nodeWithPosition.y + AUTO_LAYOUT_OFFSET.y,
|
||||
}
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
const zoom = 0.7
|
||||
setViewport({
|
||||
x: 0,
|
||||
y: 0,
|
||||
zoom,
|
||||
})
|
||||
setTimeout(() => {
|
||||
handleSyncWorkflowDraft()
|
||||
})
|
||||
}, [store, reactflow, handleSyncWorkflowDraft, workflowStore])
|
||||
|
||||
const getTreeLeafNodes = useCallback((nodeId: string) => {
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const startNode = nodes.find(node => node.data.type === BlockEnum.Start)
|
||||
|
||||
if (!startNode)
|
||||
return []
|
||||
|
||||
const list: Node[] = []
|
||||
const preOrder = (root: Node, callback: (node: Node) => void) => {
|
||||
if (root.id === nodeId)
|
||||
return
|
||||
const outgoers = getOutgoers(root, nodes, edges)
|
||||
|
||||
if (outgoers.length) {
|
||||
outgoers.forEach((outgoer) => {
|
||||
preOrder(outgoer, callback)
|
||||
})
|
||||
}
|
||||
else {
|
||||
if (root.id !== nodeId)
|
||||
callback(root)
|
||||
}
|
||||
}
|
||||
preOrder(startNode, (node) => {
|
||||
list.push(node)
|
||||
})
|
||||
|
||||
const incomers = getIncomers({ id: nodeId } as Node, nodes, edges)
|
||||
|
||||
list.push(...incomers)
|
||||
|
||||
return uniqBy(list, 'id').filter((item) => {
|
||||
return SUPPORT_OUTPUT_VARS_NODE.includes(item.data.type)
|
||||
})
|
||||
}, [store])
|
||||
|
||||
const getBeforeNodesInSameBranch = useCallback((nodeId: string) => {
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const currentNode = nodes.find(node => node.id === nodeId)
|
||||
const list: Node[] = []
|
||||
|
||||
if (!currentNode)
|
||||
return list
|
||||
|
||||
const traverse = (root: Node, callback: (node: Node) => void) => {
|
||||
if (root) {
|
||||
const incomers = getIncomers(root, nodes, edges)
|
||||
|
||||
if (incomers.length) {
|
||||
incomers.forEach((node) => {
|
||||
callback(node)
|
||||
traverse(node, callback)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
traverse(currentNode, (node) => {
|
||||
list.push(node)
|
||||
})
|
||||
|
||||
const length = list.length
|
||||
if (length) {
|
||||
return uniqBy(list, 'id').reverse().filter((item) => {
|
||||
return SUPPORT_OUTPUT_VARS_NODE.includes(item.data.type)
|
||||
})
|
||||
}
|
||||
|
||||
return []
|
||||
}, [store])
|
||||
|
||||
const getAfterNodesInSameBranch = useCallback((nodeId: string) => {
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const currentNode = nodes.find(node => node.id === nodeId)!
|
||||
|
||||
if (!currentNode)
|
||||
return []
|
||||
const list: Node[] = [currentNode]
|
||||
|
||||
const traverse = (root: Node, callback: (node: Node) => void) => {
|
||||
if (root) {
|
||||
const outgoers = getOutgoers(root, nodes, edges)
|
||||
|
||||
if (outgoers.length) {
|
||||
outgoers.forEach((node) => {
|
||||
callback(node)
|
||||
traverse(node, callback)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
traverse(currentNode, (node) => {
|
||||
list.push(node)
|
||||
})
|
||||
|
||||
return uniqBy(list, 'id')
|
||||
}, [store])
|
||||
|
||||
const getBeforeNodeById = useCallback((nodeId: string) => {
|
||||
const {
|
||||
getNodes,
|
||||
edges,
|
||||
} = store.getState()
|
||||
const nodes = getNodes()
|
||||
const node = nodes.find(node => node.id === nodeId)!
|
||||
|
||||
return getIncomers(node, nodes, edges)
|
||||
}, [store])
|
||||
|
||||
const handleOutVarRenameChange = useCallback((nodeId: string, oldValeSelector: ValueSelector, newVarSelector: ValueSelector) => {
|
||||
const { getNodes, setNodes } = store.getState()
|
||||
const afterNodes = getAfterNodesInSameBranch(nodeId)
|
||||
const effectNodes = findUsedVarNodes(oldValeSelector, afterNodes)
|
||||
// console.log(effectNodes)
|
||||
if (effectNodes.length > 0) {
|
||||
const newNodes = getNodes().map((node) => {
|
||||
if (effectNodes.find(n => n.id === node.id))
|
||||
return updateNodeVars(node, oldValeSelector, newVarSelector)
|
||||
|
||||
return node
|
||||
})
|
||||
setNodes(newNodes)
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [store])
|
||||
|
||||
const isVarUsedInNodes = useCallback((varSelector: ValueSelector) => {
|
||||
const nodeId = varSelector[0]
|
||||
const afterNodes = getAfterNodesInSameBranch(nodeId)
|
||||
const effectNodes = findUsedVarNodes(varSelector, afterNodes)
|
||||
return effectNodes.length > 0
|
||||
}, [getAfterNodesInSameBranch])
|
||||
|
||||
const removeUsedVarInNodes = useCallback((varSelector: ValueSelector) => {
|
||||
const nodeId = varSelector[0]
|
||||
const { getNodes, setNodes } = store.getState()
|
||||
const afterNodes = getAfterNodesInSameBranch(nodeId)
|
||||
const effectNodes = findUsedVarNodes(varSelector, afterNodes)
|
||||
if (effectNodes.length > 0) {
|
||||
const newNodes = getNodes().map((node) => {
|
||||
if (effectNodes.find(n => n.id === node.id))
|
||||
return updateNodeVars(node, varSelector, [])
|
||||
|
||||
return node
|
||||
})
|
||||
setNodes(newNodes)
|
||||
}
|
||||
}, [getAfterNodesInSameBranch, store])
|
||||
|
||||
const isNodeVarsUsedInNodes = useCallback((node: Node, isChatMode: boolean) => {
|
||||
const outputVars = getNodeOutputVars(node, isChatMode)
|
||||
const isUsed = outputVars.some((varSelector) => {
|
||||
return isVarUsedInNodes(varSelector)
|
||||
})
|
||||
return isUsed
|
||||
}, [isVarUsedInNodes])
|
||||
|
||||
const isValidConnection = useCallback(({ source, target }: Connection) => {
|
||||
const { getNodes } = store.getState()
|
||||
const nodes = getNodes()
|
||||
const sourceNode: Node = nodes.find(node => node.id === source)!
|
||||
const targetNode: Node = nodes.find(node => node.id === target)!
|
||||
|
||||
if (sourceNode && targetNode) {
|
||||
const sourceNodeAvailableNextNodes = nodesExtraData[sourceNode.data.type].availableNextNodes
|
||||
const targetNodeAvailablePrevNodes = [...nodesExtraData[targetNode.data.type].availablePrevNodes, BlockEnum.Start]
|
||||
if (!sourceNodeAvailableNextNodes.includes(targetNode.data.type))
|
||||
return false
|
||||
|
||||
if (!targetNodeAvailablePrevNodes.includes(sourceNode.data.type))
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}, [store, nodesExtraData])
|
||||
|
||||
const formatTimeFromNow = useCallback((time: number) => {
|
||||
return dayjs(time).locale(locale === 'zh-Hans' ? 'zh-cn' : locale).fromNow()
|
||||
}, [locale])
|
||||
|
||||
const renderTreeFromRecord = useCallback((nodes: Node[], edges: Edge[], viewport?: Viewport) => {
|
||||
const { setNodes } = store.getState()
|
||||
const { setViewport, setEdges } = reactflow
|
||||
|
||||
setNodes(initialNodes(nodes, edges))
|
||||
setEdges(initialEdges(edges, nodes))
|
||||
|
||||
if (viewport)
|
||||
setViewport(viewport)
|
||||
}, [store, reactflow])
|
||||
|
||||
const getNode = useCallback((nodeId?: string) => {
|
||||
const { getNodes } = store.getState()
|
||||
const nodes = getNodes()
|
||||
|
||||
return nodes.find(node => node.id === nodeId) || nodes.find(node => node.data.type === BlockEnum.Start)
|
||||
}, [store])
|
||||
|
||||
return {
|
||||
handleLayout,
|
||||
getTreeLeafNodes,
|
||||
getBeforeNodesInSameBranch,
|
||||
getAfterNodesInSameBranch,
|
||||
handleOutVarRenameChange,
|
||||
isVarUsedInNodes,
|
||||
removeUsedVarInNodes,
|
||||
isNodeVarsUsedInNodes,
|
||||
isValidConnection,
|
||||
formatTimeFromNow,
|
||||
renderTreeFromRecord,
|
||||
getNode,
|
||||
getBeforeNodeById,
|
||||
}
|
||||
}
|
||||
|
||||
export const useFetchToolsData = () => {
|
||||
const workflowStore = useWorkflowStore()
|
||||
|
||||
const handleFetchAllTools = useCallback(async (type: string) => {
|
||||
if (type === 'builtin') {
|
||||
const buildInTools = await fetchAllBuiltInTools()
|
||||
|
||||
workflowStore.setState({
|
||||
buildInTools: buildInTools || [],
|
||||
})
|
||||
}
|
||||
if (type === 'custom') {
|
||||
const customTools = await fetchAllCustomTools()
|
||||
|
||||
workflowStore.setState({
|
||||
customTools: customTools || [],
|
||||
})
|
||||
}
|
||||
}, [workflowStore])
|
||||
|
||||
return {
|
||||
handleFetchAllTools,
|
||||
}
|
||||
}
|
||||
|
||||
export const useWorkflowInit = () => {
|
||||
const workflowStore = useWorkflowStore()
|
||||
const {
|
||||
nodes: nodesTemplate,
|
||||
edges: edgesTemplate,
|
||||
} = useWorkflowTemplate()
|
||||
const { handleFetchAllTools } = useFetchToolsData()
|
||||
const appDetail = useAppStore(state => state.appDetail)!
|
||||
const { data, isLoading, error, mutate } = useSWR(`/apps/${appDetail.id}/workflows/draft`, fetchWorkflowDraft)
|
||||
workflowStore.setState({ appId: appDetail.id })
|
||||
|
||||
const handleFetchPreloadData = useCallback(async () => {
|
||||
try {
|
||||
const nodesDefaultConfigsData = await fetchNodesDefaultConfigs(`/apps/${appDetail?.id}/workflows/default-workflow-block-configs`)
|
||||
const publishedWorkflow = await fetchPublishedWorkflow(`/apps/${appDetail?.id}/workflows/publish`)
|
||||
workflowStore.setState({
|
||||
nodesDefaultConfigs: nodesDefaultConfigsData.reduce((acc, block) => {
|
||||
if (!acc[block.type])
|
||||
acc[block.type] = { ...block.config }
|
||||
return acc
|
||||
}, {} as Record<string, any>),
|
||||
})
|
||||
workflowStore.getState().setPublishedAt(publishedWorkflow?.created_at)
|
||||
}
|
||||
catch (e) {
|
||||
|
||||
}
|
||||
}, [workflowStore, appDetail])
|
||||
|
||||
useEffect(() => {
|
||||
handleFetchPreloadData()
|
||||
handleFetchAllTools('builtin')
|
||||
handleFetchAllTools('custom')
|
||||
}, [handleFetchPreloadData, handleFetchAllTools])
|
||||
|
||||
useEffect(() => {
|
||||
if (data)
|
||||
workflowStore.getState().setDraftUpdatedAt(data.updated_at)
|
||||
}, [data, workflowStore])
|
||||
|
||||
if (error && error.json && !error.bodyUsed && appDetail) {
|
||||
error.json().then((err: any) => {
|
||||
if (err.code === 'draft_workflow_not_exist') {
|
||||
workflowStore.setState({ notInitialWorkflow: true })
|
||||
syncWorkflowDraft({
|
||||
url: `/apps/${appDetail.id}/workflows/draft`,
|
||||
params: {
|
||||
graph: {
|
||||
nodes: nodesTemplate,
|
||||
edges: edgesTemplate,
|
||||
},
|
||||
features: {},
|
||||
},
|
||||
}).then((res) => {
|
||||
workflowStore.getState().setDraftUpdatedAt(res.updated_at)
|
||||
mutate()
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
isLoading,
|
||||
}
|
||||
}
|
||||
|
||||
export const useWorkflowReadOnly = () => {
|
||||
const workflowStore = useWorkflowStore()
|
||||
const workflowRunningData = useStore(s => s.workflowRunningData)
|
||||
|
||||
const getWorkflowReadOnly = useCallback(() => {
|
||||
return workflowStore.getState().workflowRunningData?.result.status === WorkflowRunningStatus.Running
|
||||
}, [workflowStore])
|
||||
|
||||
return {
|
||||
workflowReadOnly: workflowRunningData?.result.status === WorkflowRunningStatus.Running,
|
||||
getWorkflowReadOnly,
|
||||
}
|
||||
}
|
||||
export const useNodesReadOnly = () => {
|
||||
const workflowStore = useWorkflowStore()
|
||||
const workflowRunningData = useStore(s => s.workflowRunningData)
|
||||
const historyWorkflowData = useStore(s => s.historyWorkflowData)
|
||||
const isRestoring = useStore(s => s.isRestoring)
|
||||
|
||||
const getNodesReadOnly = useCallback(() => {
|
||||
const {
|
||||
workflowRunningData,
|
||||
historyWorkflowData,
|
||||
isRestoring,
|
||||
} = workflowStore.getState()
|
||||
|
||||
return workflowRunningData || historyWorkflowData || isRestoring
|
||||
}, [workflowStore])
|
||||
|
||||
return {
|
||||
nodesReadOnly: !!(workflowRunningData || historyWorkflowData || isRestoring),
|
||||
getNodesReadOnly,
|
||||
}
|
||||
}
|
||||
|
||||
export const useToolIcon = (data: Node['data']) => {
|
||||
const buildInTools = useStore(s => s.buildInTools)
|
||||
const customTools = useStore(s => s.customTools)
|
||||
const toolIcon = useMemo(() => {
|
||||
if (data.type === BlockEnum.Tool) {
|
||||
if (data.provider_type === 'builtin')
|
||||
return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
|
||||
|
||||
return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
|
||||
}
|
||||
}, [data, buildInTools, customTools])
|
||||
|
||||
return toolIcon
|
||||
}
|
||||
261
web/app/components/workflow/index.tsx
Normal file
261
web/app/components/workflow/index.tsx
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
'use client'
|
||||
|
||||
import type { FC } from 'react'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
} from 'react'
|
||||
import { setAutoFreeze } from 'immer'
|
||||
import {
|
||||
useKeyPress,
|
||||
} from 'ahooks'
|
||||
import ReactFlow, {
|
||||
Background,
|
||||
ReactFlowProvider,
|
||||
useOnViewportChange,
|
||||
} from 'reactflow'
|
||||
import type { Viewport } from 'reactflow'
|
||||
import 'reactflow/dist/style.css'
|
||||
import './style.css'
|
||||
import type {
|
||||
Edge,
|
||||
Node,
|
||||
} from './types'
|
||||
import { WorkflowContextProvider } from './context'
|
||||
import {
|
||||
useEdgesInteractions,
|
||||
useNodesInteractions,
|
||||
useNodesReadOnly,
|
||||
useNodesSyncDraft,
|
||||
useWorkflow,
|
||||
useWorkflowInit,
|
||||
useWorkflowReadOnly,
|
||||
} from './hooks'
|
||||
import Header from './header'
|
||||
import CustomNode from './nodes'
|
||||
import Operator from './operator'
|
||||
import CustomEdge from './custom-edge'
|
||||
import CustomConnectionLine from './custom-connection-line'
|
||||
import Panel from './panel'
|
||||
import Features from './features'
|
||||
import HelpLine from './help-line'
|
||||
import { useStore } from './store'
|
||||
import {
|
||||
initialEdges,
|
||||
initialNodes,
|
||||
} from './utils'
|
||||
import Loading from '@/app/components/base/loading'
|
||||
import { FeaturesProvider } from '@/app/components/base/features'
|
||||
import type { Features as FeaturesData } from '@/app/components/base/features/types'
|
||||
|
||||
const nodeTypes = {
|
||||
custom: CustomNode,
|
||||
}
|
||||
const edgeTypes = {
|
||||
custom: CustomEdge,
|
||||
}
|
||||
|
||||
type WorkflowProps = {
|
||||
nodes: Node[]
|
||||
edges: Edge[]
|
||||
viewport?: Viewport
|
||||
}
|
||||
const Workflow: FC<WorkflowProps> = memo(({
|
||||
nodes,
|
||||
edges,
|
||||
viewport,
|
||||
}) => {
|
||||
const showFeaturesPanel = useStore(state => state.showFeaturesPanel)
|
||||
const nodeAnimation = useStore(s => s.nodeAnimation)
|
||||
const {
|
||||
handleSyncWorkflowDraft,
|
||||
syncWorkflowDraftWhenPageClose,
|
||||
} = useNodesSyncDraft()
|
||||
const { workflowReadOnly } = useWorkflowReadOnly()
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
|
||||
useEffect(() => {
|
||||
setAutoFreeze(false)
|
||||
|
||||
return () => {
|
||||
setAutoFreeze(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
handleSyncWorkflowDraft(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleSyncWorkflowDraftWhenPageClose = useCallback(() => {
|
||||
if (document.visibilityState === 'hidden')
|
||||
syncWorkflowDraftWhenPageClose()
|
||||
}, [syncWorkflowDraftWhenPageClose])
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener('visibilitychange', handleSyncWorkflowDraftWhenPageClose)
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', handleSyncWorkflowDraftWhenPageClose)
|
||||
}
|
||||
}, [handleSyncWorkflowDraftWhenPageClose])
|
||||
|
||||
const {
|
||||
handleNodeDragStart,
|
||||
handleNodeDrag,
|
||||
handleNodeDragStop,
|
||||
handleNodeEnter,
|
||||
handleNodeLeave,
|
||||
handleNodeClick,
|
||||
handleNodeConnect,
|
||||
handleNodeConnectStart,
|
||||
handleNodeConnectEnd,
|
||||
} = useNodesInteractions()
|
||||
const {
|
||||
handleEdgeEnter,
|
||||
handleEdgeLeave,
|
||||
handleEdgeDelete,
|
||||
handleEdgesChange,
|
||||
} = useEdgesInteractions()
|
||||
const { isValidConnection } = useWorkflow()
|
||||
|
||||
useOnViewportChange({
|
||||
onEnd: () => {
|
||||
handleSyncWorkflowDraft()
|
||||
},
|
||||
})
|
||||
|
||||
useKeyPress('Backspace', handleEdgeDelete)
|
||||
|
||||
return (
|
||||
<div
|
||||
id='workflow-container'
|
||||
className={`
|
||||
relative w-full min-w-[960px] h-full bg-[#F0F2F7]
|
||||
${workflowReadOnly && 'workflow-panel-animation'}
|
||||
${nodeAnimation && 'workflow-node-animation'}
|
||||
`}
|
||||
>
|
||||
<Header />
|
||||
<Panel />
|
||||
<Operator />
|
||||
{
|
||||
showFeaturesPanel && <Features />
|
||||
}
|
||||
<HelpLine />
|
||||
<ReactFlow
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
onNodeDragStart={handleNodeDragStart}
|
||||
onNodeDrag={handleNodeDrag}
|
||||
onNodeDragStop={handleNodeDragStop}
|
||||
onNodeMouseEnter={handleNodeEnter}
|
||||
onNodeMouseLeave={handleNodeLeave}
|
||||
onNodeClick={handleNodeClick}
|
||||
onConnect={handleNodeConnect}
|
||||
onConnectStart={handleNodeConnectStart}
|
||||
onConnectEnd={handleNodeConnectEnd}
|
||||
onEdgeMouseEnter={handleEdgeEnter}
|
||||
onEdgeMouseLeave={handleEdgeLeave}
|
||||
onEdgesChange={handleEdgesChange}
|
||||
connectionLineComponent={CustomConnectionLine}
|
||||
defaultViewport={viewport}
|
||||
multiSelectionKeyCode={null}
|
||||
deleteKeyCode={null}
|
||||
nodesDraggable={!nodesReadOnly}
|
||||
nodesConnectable={!nodesReadOnly}
|
||||
nodesFocusable={!nodesReadOnly}
|
||||
edgesFocusable={!nodesReadOnly}
|
||||
panOnDrag={!workflowReadOnly}
|
||||
zoomOnPinch={!workflowReadOnly}
|
||||
zoomOnScroll={!workflowReadOnly}
|
||||
zoomOnDoubleClick={!workflowReadOnly}
|
||||
isValidConnection={isValidConnection}
|
||||
>
|
||||
<Background
|
||||
gap={[14, 14]}
|
||||
size={2}
|
||||
color='#E4E5E7'
|
||||
/>
|
||||
</ReactFlow>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
Workflow.displayName = 'Workflow'
|
||||
|
||||
const WorkflowWrap = memo(() => {
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
} = useWorkflowInit()
|
||||
|
||||
const nodesData = useMemo(() => {
|
||||
if (data)
|
||||
return initialNodes(data.graph.nodes, data.graph.edges)
|
||||
|
||||
return []
|
||||
}, [data])
|
||||
const edgesData = useMemo(() => {
|
||||
if (data)
|
||||
return initialEdges(data.graph.edges, data.graph.nodes)
|
||||
|
||||
return []
|
||||
}, [data])
|
||||
|
||||
if (!data || isLoading) {
|
||||
return (
|
||||
<div className='flex justify-center items-center relative w-full h-full bg-[#F0F2F7]'>
|
||||
<Loading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const features = data.features || {}
|
||||
const initialFeatures: FeaturesData = {
|
||||
file: {
|
||||
image: {
|
||||
enabled: !!features.file_upload?.image.enabled,
|
||||
number_limits: features.file_upload?.image.number_limits || 3,
|
||||
transfer_methods: features.file_upload?.image.transfer_methods || ['local_file', 'remote_url'],
|
||||
},
|
||||
},
|
||||
opening: {
|
||||
enabled: !!features.opening_statement,
|
||||
opening_statement: features.opening_statement,
|
||||
suggested_questions: features.suggested_questions,
|
||||
},
|
||||
suggested: features.suggested_questions_after_answer || { enabled: false },
|
||||
speech2text: features.speech_to_text || { enabled: false },
|
||||
text2speech: features.text_to_speech || { enabled: false },
|
||||
citation: features.retriever_resource || { enabled: false },
|
||||
moderation: features.sensitive_word_avoidance || { enabled: false },
|
||||
}
|
||||
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<FeaturesProvider features={initialFeatures}>
|
||||
<Workflow
|
||||
nodes={nodesData}
|
||||
edges={edgesData}
|
||||
viewport={data?.graph.viewport}
|
||||
/>
|
||||
</FeaturesProvider>
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
})
|
||||
WorkflowWrap.displayName = 'WorkflowWrap'
|
||||
|
||||
const WorkflowContainer = () => {
|
||||
return (
|
||||
<WorkflowContextProvider>
|
||||
<WorkflowWrap />
|
||||
</WorkflowContextProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(WorkflowContainer)
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import cn from 'classnames'
|
||||
import { Plus } from '@/app/components/base/icons/src/vender/line/general'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
text: string
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
const AddButton: FC<Props> = ({
|
||||
className,
|
||||
text,
|
||||
onClick,
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(className, 'flex items-center h-7 justify-center bg-gray-100 hover:bg-gray-200 rounded-lg cursor-pointer text-xs font-medium text-gray-700 space-x-1')}
|
||||
onClick={onClick}
|
||||
>
|
||||
<Plus className='w-3.5 h-3.5' />
|
||||
<div>{text}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(AddButton)
|
||||
|
|
@ -0,0 +1,184 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import produce from 'immer'
|
||||
import type { InputVar } from '../../../../types'
|
||||
import { BlockEnum, InputVarType } from '../../../../types'
|
||||
import CodeEditor from '../editor/code-editor'
|
||||
import { CodeLanguage } from '../../../code/types'
|
||||
import Select from '@/app/components/base/select'
|
||||
import TextGenerationImageUploader from '@/app/components/base/image-uploader/text-generation-image-uploader'
|
||||
import { Resolution } from '@/types/app'
|
||||
import { Trash03 } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { useFeatures } from '@/app/components/base/features/hooks'
|
||||
import { VarBlockIcon } from '@/app/components/workflow/block-icon'
|
||||
import { Line3 } from '@/app/components/base/icons/src/public/common'
|
||||
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
|
||||
|
||||
type Props = {
|
||||
payload: InputVar
|
||||
value: any
|
||||
onChange: (value: any) => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
const FormItem: FC<Props> = ({
|
||||
payload,
|
||||
value,
|
||||
onChange,
|
||||
className,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const { type } = payload
|
||||
const fileSettings = useFeatures(s => s.features.file)
|
||||
const handleContextItemChange = useCallback((index: number) => {
|
||||
return (newValue: any) => {
|
||||
const newValues = produce(value, (draft: any) => {
|
||||
draft[index] = newValue
|
||||
})
|
||||
onChange(newValues)
|
||||
}
|
||||
}, [value, onChange])
|
||||
|
||||
const handleContextItemRemove = useCallback((index: number) => {
|
||||
return () => {
|
||||
const newValues = produce(value, (draft: any) => {
|
||||
draft.splice(index, 1)
|
||||
})
|
||||
onChange(newValues)
|
||||
}
|
||||
}, [value, onChange])
|
||||
const nodeKey = (() => {
|
||||
if (typeof payload.label === 'object') {
|
||||
const { nodeType, nodeName, variable } = payload.label
|
||||
return (
|
||||
<div className='h-full flex items-center'>
|
||||
<div className='flex items-center'>
|
||||
<div className='p-[1px]'>
|
||||
<VarBlockIcon type={nodeType || BlockEnum.Start} />
|
||||
</div>
|
||||
<div className='mx-0.5 text-xs font-medium text-gray-700 max-w-[150px] truncate' title={nodeName}>
|
||||
{nodeName}
|
||||
</div>
|
||||
<Line3 className='mr-0.5'></Line3>
|
||||
</div>
|
||||
|
||||
<div className='flex items-center text-primary-600'>
|
||||
<Variable02 className='w-3.5 h-3.5' />
|
||||
<div className='ml-0.5 text-xs font-medium max-w-[150px] truncate' title={variable} >
|
||||
{variable}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return ''
|
||||
})()
|
||||
return (
|
||||
<div className={`${className}`}>
|
||||
{type !== InputVarType.contexts && <div className='h-8 leading-8 text-[13px] font-medium text-gray-700 truncate'>{typeof payload.label === 'object' ? nodeKey : payload.label}</div>}
|
||||
<div className='grow'>
|
||||
{
|
||||
type === InputVarType.textInput && (
|
||||
<input
|
||||
className="w-full px-3 text-sm leading-8 text-gray-900 border-0 rounded-lg grow h-8 bg-gray-50 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
|
||||
type="text"
|
||||
value={value || ''}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
placeholder={t('appDebug.variableConig.inputPlaceholder')!}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
type === InputVarType.number && (
|
||||
<input
|
||||
className="w-full px-3 text-sm leading-8 text-gray-900 border-0 rounded-lg grow h-8 bg-gray-50 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
|
||||
type="number"
|
||||
value={value || ''}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
placeholder={t('appDebug.variableConig.inputPlaceholder')!}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
type === InputVarType.paragraph && (
|
||||
<textarea
|
||||
className="w-full px-3 py-1 text-sm leading-[18px] text-gray-900 border-0 rounded-lg grow h-[120px] bg-gray-50 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
|
||||
value={value || ''}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
placeholder={t('appDebug.variableConig.inputPlaceholder')!}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
type === InputVarType.select && (
|
||||
<Select
|
||||
className="w-full"
|
||||
defaultValue={value || ''}
|
||||
items={payload.options?.map(option => ({ name: option, value: option })) || []}
|
||||
onSelect={i => onChange(i.value)}
|
||||
allowSearch={false}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
type === InputVarType.json && (
|
||||
<CodeEditor
|
||||
value={value}
|
||||
title={<span>JSON</span>}
|
||||
language={CodeLanguage.json}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
type === InputVarType.files && (
|
||||
<TextGenerationImageUploader
|
||||
settings={{
|
||||
...fileSettings.image,
|
||||
detail: Resolution.high,
|
||||
}}
|
||||
onFilesChange={files => onChange(files.filter(file => file.progress !== -1).map(fileItem => ({
|
||||
type: 'image',
|
||||
transfer_method: fileItem.type,
|
||||
url: fileItem.url,
|
||||
upload_file_id: fileItem.fileId,
|
||||
})))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
type === InputVarType.contexts && (
|
||||
<div className='space-y-2'>
|
||||
{(value || []).map((item: any, index: number) => (
|
||||
<CodeEditor
|
||||
key={index}
|
||||
value={item}
|
||||
title={<span>JSON</span>}
|
||||
headerRight={
|
||||
(value as any).length > 1
|
||||
? (<Trash03
|
||||
onClick={handleContextItemRemove(index)}
|
||||
className='mr-1 w-3.5 h-3.5 text-gray-500 cursor-pointer'
|
||||
/>)
|
||||
: undefined
|
||||
}
|
||||
language={CodeLanguage.json}
|
||||
onChange={handleContextItemChange(index)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(FormItem)
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import cn from 'classnames'
|
||||
import type { InputVar } from '../../../../types'
|
||||
import FormItem from './form-item'
|
||||
import { InputVarType } from '@/app/components/workflow/types'
|
||||
import AddButton from '@/app/components/base/button/add-button'
|
||||
import { RETRIEVAL_OUTPUT_STRUCT } from '@/app/components/workflow/constants'
|
||||
|
||||
export type Props = {
|
||||
className?: string
|
||||
label?: string
|
||||
inputs: InputVar[]
|
||||
values: Record<string, string>
|
||||
onChange: (newValues: Record<string, any>) => void
|
||||
}
|
||||
|
||||
const Form: FC<Props> = ({
|
||||
className,
|
||||
label,
|
||||
inputs,
|
||||
values,
|
||||
onChange,
|
||||
}) => {
|
||||
const handleChange = useCallback((key: string) => {
|
||||
return (value: any) => {
|
||||
const newValues = produce(values, (draft) => {
|
||||
draft[key] = value
|
||||
})
|
||||
onChange(newValues)
|
||||
}
|
||||
}, [values, onChange])
|
||||
|
||||
const handleAddContext = useCallback(() => {
|
||||
const newValues = produce(values, (draft: any) => {
|
||||
const key = inputs[0].variable
|
||||
draft[key].push(RETRIEVAL_OUTPUT_STRUCT)
|
||||
})
|
||||
onChange(newValues)
|
||||
}, [values, onChange, inputs])
|
||||
return (
|
||||
<div className={cn(className, 'space-y-2')}>
|
||||
{label && (
|
||||
<div className='mb-1 flex items-center justify-between'>
|
||||
<div className='flex items-center h-6 text-xs font-medium text-gray-500 uppercase'>{label}</div>
|
||||
{inputs[0]?.type === InputVarType.contexts && (
|
||||
<AddButton onClick={handleAddContext} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{inputs.map((input, index) => {
|
||||
return (
|
||||
<FormItem
|
||||
key={index}
|
||||
payload={input}
|
||||
value={values[input.variable]}
|
||||
onChange={handleChange(input.variable)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(Form)
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import cn from 'classnames'
|
||||
import type { Props as FormProps } from './form'
|
||||
import Form from './form'
|
||||
import Button from '@/app/components/base/button'
|
||||
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
|
||||
import { Loading02, XClose } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import Split from '@/app/components/workflow/nodes/_base/components/split'
|
||||
import { InputVarType, NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import ResultPanel from '@/app/components/workflow/run/result-panel'
|
||||
import Toast from '@/app/components/base/toast'
|
||||
|
||||
const i18nPrefix = 'workflow.singleRun'
|
||||
|
||||
type BeforeRunFormProps = {
|
||||
nodeName: string
|
||||
onHide: () => void
|
||||
onRun: (submitData: Record<string, any>) => void
|
||||
onStop: () => void
|
||||
runningStatus: NodeRunningStatus
|
||||
result?: JSX.Element
|
||||
forms: FormProps[]
|
||||
}
|
||||
|
||||
function formatValue(value: string | any, type: InputVarType) {
|
||||
if (type === InputVarType.number)
|
||||
return parseFloat(value)
|
||||
if (type === InputVarType.json)
|
||||
return JSON.parse(value)
|
||||
if (type === InputVarType.contexts) {
|
||||
return value.map((item: any) => {
|
||||
return JSON.parse(item)
|
||||
})
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
const BeforeRunForm: FC<BeforeRunFormProps> = ({
|
||||
nodeName,
|
||||
onHide,
|
||||
onRun,
|
||||
onStop,
|
||||
runningStatus,
|
||||
result,
|
||||
forms,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const isFinished = runningStatus === NodeRunningStatus.Succeeded || runningStatus === NodeRunningStatus.Failed
|
||||
const isRunning = runningStatus === NodeRunningStatus.Running
|
||||
|
||||
const handleRun = useCallback(() => {
|
||||
let errMsg = ''
|
||||
forms.forEach((form) => {
|
||||
form.inputs.forEach((input) => {
|
||||
const value = form.values[input.variable]
|
||||
if (!errMsg && input.required && (value === '' || value === undefined || value === null || (input.type === InputVarType.files && value.length === 0)))
|
||||
errMsg = t('workflow.errorMsg.fieldRequired', { field: typeof input.label === 'object' ? input.label.variable : input.label })
|
||||
})
|
||||
})
|
||||
if (errMsg) {
|
||||
Toast.notify({
|
||||
message: errMsg,
|
||||
type: 'error',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const submitData: Record<string, any> = {}
|
||||
let parseErrorJsonField = ''
|
||||
forms.forEach((form) => {
|
||||
form.inputs.forEach((input) => {
|
||||
try {
|
||||
const value = formatValue(form.values[input.variable], input.type)
|
||||
submitData[input.variable] = value
|
||||
}
|
||||
catch (e) {
|
||||
parseErrorJsonField = input.variable
|
||||
}
|
||||
})
|
||||
})
|
||||
if (parseErrorJsonField) {
|
||||
Toast.notify({
|
||||
message: t('workflow.errorMsg.invalidJson', { field: parseErrorJsonField }),
|
||||
type: 'error',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
onRun(submitData)
|
||||
}, [forms, onRun, t])
|
||||
return (
|
||||
<div className='absolute inset-0 z-10 rounded-2xl pt-10' style={{
|
||||
backgroundColor: 'rgba(16, 24, 40, 0.20)',
|
||||
}}>
|
||||
<div className='h-full rounded-2xl bg-white flex flex-col'>
|
||||
<div className='shrink-0 flex justify-between items-center h-8 pl-4 pr-3 pt-3'>
|
||||
<div className='text-base font-semibold text-gray-900 truncate'>
|
||||
{t(`${i18nPrefix}.testRun`)} {nodeName}
|
||||
</div>
|
||||
<div className='ml-2 shrink-0 p-1 cursor-pointer' onClick={onHide}>
|
||||
<XClose className='w-4 h-4 text-gray-500 ' />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='h-0 grow overflow-y-auto pb-4'>
|
||||
<div className='mt-3 px-4 space-y-4'>
|
||||
{forms.map((form, index) => (
|
||||
<div key={index}>
|
||||
<Form
|
||||
key={index}
|
||||
className={cn(index < forms.length - 1 && 'mb-4')}
|
||||
{...form}
|
||||
/>
|
||||
{index < forms.length - 1 && <Split />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className='mt-4 flex justify-between space-x-2 px-4' >
|
||||
{isRunning && (
|
||||
<div
|
||||
className='p-2 rounded-lg border border-gray-200 bg-white shadow-xs cursor-pointer'
|
||||
onClick={onStop}
|
||||
>
|
||||
<StopCircle className='w-4 h-4 text-gray-500' />
|
||||
</div>
|
||||
)}
|
||||
<Button disabled={isRunning} type='primary' className='w-0 grow !h-8 flex items-center space-x-2 text-[13px]' onClick={handleRun}>
|
||||
{isRunning && <Loading02 className='animate-spin w-4 h-4 text-white' />}
|
||||
<div>{t(`${i18nPrefix}.${isRunning ? 'running' : 'startRun'}`)}</div>
|
||||
</Button>
|
||||
</div>
|
||||
{isRunning && (
|
||||
<ResultPanel status='running' showSteps={false} />
|
||||
)}
|
||||
{isFinished && (
|
||||
<>
|
||||
{result}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(BeforeRunForm)
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback, useRef, useState } from 'react'
|
||||
import copy from 'copy-to-clipboard'
|
||||
import cn from 'classnames'
|
||||
import PromptEditorHeightResizeWrap from '@/app/components/app/configuration/config-prompt/prompt-editor-height-resize-wrap'
|
||||
import { Clipboard, ClipboardCheck } from '@/app/components/base/icons/src/vender/line/files'
|
||||
import ToggleExpandBtn from '@/app/components/workflow/nodes/_base/components/toggle-expand-btn'
|
||||
import useToggleExpend from '@/app/components/workflow/nodes/_base/hooks/use-toggle-expend'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
title: JSX.Element | string
|
||||
headerRight?: JSX.Element
|
||||
children: JSX.Element
|
||||
minHeight?: number
|
||||
value: string
|
||||
isFocus: boolean
|
||||
}
|
||||
|
||||
const Base: FC<Props> = ({
|
||||
className,
|
||||
title,
|
||||
headerRight,
|
||||
children,
|
||||
minHeight = 120,
|
||||
value,
|
||||
isFocus,
|
||||
}) => {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const {
|
||||
wrapClassName,
|
||||
isExpand,
|
||||
setIsExpand,
|
||||
editorExpandHeight,
|
||||
} = useToggleExpend({ ref, hasFooter: false })
|
||||
|
||||
const editorContentMinHeight = minHeight - 28
|
||||
const [editorContentHeight, setEditorContentHeight] = useState(editorContentMinHeight)
|
||||
|
||||
const [isCopied, setIsCopied] = React.useState(false)
|
||||
const handleCopy = useCallback(() => {
|
||||
copy(value)
|
||||
setIsCopied(true)
|
||||
}, [value])
|
||||
|
||||
return (
|
||||
<div className={cn(wrapClassName)}>
|
||||
<div ref={ref} className={cn(className, isExpand && 'h-full', 'rounded-lg border', isFocus ? 'bg-white border-gray-200' : 'bg-gray-100 border-gray-100 overflow-hidden')}>
|
||||
<div className='flex justify-between items-center h-7 pt-1 pl-3 pr-2'>
|
||||
<div className='text-xs font-semibold text-gray-700'>{title}</div>
|
||||
<div className='flex items-center'>
|
||||
{headerRight}
|
||||
{!isCopied
|
||||
? (
|
||||
<Clipboard className='mx-1 w-3.5 h-3.5 text-gray-500 cursor-pointer' onClick={handleCopy} />
|
||||
)
|
||||
: (
|
||||
<ClipboardCheck className='mx-1 w-3.5 h-3.5 text-gray-500' />
|
||||
)
|
||||
}
|
||||
<div className='ml-1'>
|
||||
<ToggleExpandBtn isExpand={isExpand} onExpandChange={setIsExpand} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<PromptEditorHeightResizeWrap
|
||||
height={isExpand ? editorExpandHeight : editorContentHeight}
|
||||
minHeight={editorContentMinHeight}
|
||||
onHeightChange={setEditorContentHeight}
|
||||
hideResize={isExpand}
|
||||
>
|
||||
<div className='h-full pb-2'>
|
||||
{children}
|
||||
</div>
|
||||
</PromptEditorHeightResizeWrap>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(Base)
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import Editor, { loader } from '@monaco-editor/react'
|
||||
import React, { useRef } from 'react'
|
||||
import Base from '../base'
|
||||
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
|
||||
import './style.css'
|
||||
|
||||
// load file from local instead of cdn https://github.com/suren-atoyan/monaco-react/issues/482
|
||||
loader.config({ paths: { vs: '/vs' } })
|
||||
|
||||
type Props = {
|
||||
value?: string | object
|
||||
onChange?: (value: string) => void
|
||||
title: JSX.Element
|
||||
language: CodeLanguage
|
||||
headerRight?: JSX.Element
|
||||
readOnly?: boolean
|
||||
isJSONStringifyBeauty?: boolean
|
||||
height?: number
|
||||
}
|
||||
|
||||
const languageMap = {
|
||||
[CodeLanguage.javascript]: 'javascript',
|
||||
[CodeLanguage.python3]: 'python',
|
||||
[CodeLanguage.json]: 'json',
|
||||
}
|
||||
|
||||
const CodeEditor: FC<Props> = ({
|
||||
value = '',
|
||||
onChange = () => { },
|
||||
title,
|
||||
headerRight,
|
||||
language,
|
||||
readOnly,
|
||||
isJSONStringifyBeauty,
|
||||
height,
|
||||
}) => {
|
||||
const [isFocus, setIsFocus] = React.useState(false)
|
||||
|
||||
const handleEditorChange = (value: string | undefined) => {
|
||||
onChange(value || '')
|
||||
}
|
||||
|
||||
const editorRef = useRef(null)
|
||||
const handleEditorDidMount = (editor: any, monaco: any) => {
|
||||
editorRef.current = editor
|
||||
editor.onDidFocusEditorText(() => {
|
||||
setIsFocus(true)
|
||||
})
|
||||
editor.onDidBlurEditorText(() => {
|
||||
setIsFocus(false)
|
||||
})
|
||||
|
||||
monaco.editor.defineTheme('blur-theme', {
|
||||
base: 'vs',
|
||||
inherit: true,
|
||||
rules: [],
|
||||
colors: {
|
||||
'editor.background': '#F2F4F7',
|
||||
},
|
||||
})
|
||||
|
||||
monaco.editor.defineTheme('focus-theme', {
|
||||
base: 'vs',
|
||||
inherit: true,
|
||||
rules: [],
|
||||
colors: {
|
||||
'editor.background': '#ffffff',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const outPutValue = (() => {
|
||||
if (!isJSONStringifyBeauty)
|
||||
return value as string
|
||||
try {
|
||||
return JSON.stringify(value as object, null, 2)
|
||||
}
|
||||
catch (e) {
|
||||
return value as string
|
||||
}
|
||||
})()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Base
|
||||
title={title}
|
||||
value={outPutValue}
|
||||
headerRight={headerRight}
|
||||
isFocus={isFocus && !readOnly}
|
||||
minHeight={height || 200}
|
||||
>
|
||||
<>
|
||||
{/* https://www.npmjs.com/package/@monaco-editor/react */}
|
||||
<Editor
|
||||
className='h-full'
|
||||
// language={language === CodeLanguage.javascript ? 'javascript' : 'python'}
|
||||
language={languageMap[language] || 'javascript'}
|
||||
theme={isFocus ? 'focus-theme' : 'blur-theme'}
|
||||
value={outPutValue}
|
||||
onChange={handleEditorChange}
|
||||
// https://microsoft.github.io/monaco-editor/typedoc/interfaces/editor.IEditorOptions.html
|
||||
options={{
|
||||
readOnly,
|
||||
domReadOnly: true,
|
||||
quickSuggestions: false,
|
||||
minimap: { enabled: false },
|
||||
lineNumbersMinChars: 1, // would change line num width
|
||||
wordWrap: 'on', // auto line wrap
|
||||
// lineNumbers: (num) => {
|
||||
// return <div>{num}</div>
|
||||
// }
|
||||
}}
|
||||
onMount={handleEditorDidMount}
|
||||
/>
|
||||
</>
|
||||
</Base>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(CodeEditor)
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
.margin-view-overlays {
|
||||
padding-left: 10px;
|
||||
}
|
||||
|
||||
/* hide readonly tooltip */
|
||||
.monaco-editor-overlaymessage {
|
||||
display: none !important;
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import Base from './base'
|
||||
|
||||
type Props = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
title: JSX.Element | string
|
||||
headerRight?: JSX.Element
|
||||
minHeight?: number
|
||||
onBlur?: () => void
|
||||
placeholder?: string
|
||||
readonly?: boolean
|
||||
}
|
||||
|
||||
const TextEditor: FC<Props> = ({
|
||||
value,
|
||||
onChange,
|
||||
title,
|
||||
headerRight,
|
||||
minHeight,
|
||||
onBlur,
|
||||
placeholder,
|
||||
readonly,
|
||||
}) => {
|
||||
const [isFocus, {
|
||||
setTrue: setIsFocus,
|
||||
setFalse: setIsNotFocus,
|
||||
}] = useBoolean(false)
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsNotFocus()
|
||||
onBlur?.()
|
||||
}, [setIsNotFocus, onBlur])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Base
|
||||
title={title}
|
||||
value={value}
|
||||
headerRight={headerRight}
|
||||
isFocus={isFocus}
|
||||
minHeight={minHeight}
|
||||
>
|
||||
<textarea
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
onFocus={setIsFocus}
|
||||
onBlur={handleBlur}
|
||||
className='w-full h-full px-3 resize-none bg-transparent border-none focus:outline-none leading-[18px] text-[13px] font-normal text-gray-900 placeholder:text-gray-300'
|
||||
placeholder={placeholder}
|
||||
readOnly={readonly}
|
||||
/>
|
||||
</Base>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(TextEditor)
|
||||
57
web/app/components/workflow/nodes/_base/components/field.tsx
Normal file
57
web/app/components/workflow/nodes/_base/components/field.tsx
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import cn from 'classnames'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import { HelpCircle } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import TooltipPlus from '@/app/components/base/tooltip-plus'
|
||||
import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
type Props = {
|
||||
title: string
|
||||
tooltip?: string
|
||||
supportFold?: boolean
|
||||
children?: JSX.Element | string | null
|
||||
operations?: JSX.Element
|
||||
inline?: boolean
|
||||
}
|
||||
|
||||
const Filed: FC<Props> = ({
|
||||
title,
|
||||
tooltip,
|
||||
children,
|
||||
operations,
|
||||
inline,
|
||||
supportFold,
|
||||
}) => {
|
||||
const [fold, {
|
||||
toggle: toggleFold,
|
||||
}] = useBoolean(true)
|
||||
return (
|
||||
<div className={cn(inline && 'flex justify-between items-center', supportFold && 'cursor-pointer')}>
|
||||
<div
|
||||
onClick={() => supportFold && toggleFold()}
|
||||
className='flex justify-between items-center'>
|
||||
<div className='flex items-center h-6'>
|
||||
<div className='text-[13px] font-medium text-gray-700 uppercase'>{title}</div>
|
||||
{tooltip && (
|
||||
<TooltipPlus popupContent={
|
||||
<div className='w-[120px]'>
|
||||
{tooltip}
|
||||
</div>}>
|
||||
<HelpCircle className='w-3.5 h-3.5 ml-0.5 text-gray-400' />
|
||||
</TooltipPlus>
|
||||
)}
|
||||
|
||||
</div>
|
||||
<div className='flex'>
|
||||
{operations && <div>{operations}</div>}
|
||||
{supportFold && (
|
||||
<ChevronRight className='w-3.5 h-3.5 text-gray-500 cursor-pointer transform transition-transform' style={{ transform: fold ? 'rotate(0deg)' : 'rotate(90deg)' }} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{children && (!supportFold || (supportFold && !fold)) && <div className={cn(!inline && 'mt-1')}>{children}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(Filed)
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
|
||||
type Props = {
|
||||
title: string
|
||||
content: string | JSX.Element
|
||||
}
|
||||
|
||||
const InfoPanel: FC<Props> = ({
|
||||
title,
|
||||
content,
|
||||
}) => {
|
||||
return (
|
||||
<div>
|
||||
<div className='px-[5px] py-[3px] bg-gray-100 rounded-md'>
|
||||
<div className='leading-4 text-[10px] font-medium text-gray-500 uppercase'>
|
||||
{title}
|
||||
</div>
|
||||
<div className='leading-4 text-xs font-normal text-gray-700'>
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(InfoPanel)
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useEffect } from 'react'
|
||||
import cn from 'classnames'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type {
|
||||
Node,
|
||||
NodeOutPutVar,
|
||||
} from '@/app/components/workflow/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import PromptEditor from '@/app/components/base/prompt-editor'
|
||||
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
|
||||
import TooltipPlus from '@/app/components/base/tooltip-plus'
|
||||
|
||||
type Props = {
|
||||
instanceId?: string
|
||||
className?: string
|
||||
placeholder?: string
|
||||
placeholderClassName?: string
|
||||
promptMinHeightClassName?: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onFocusChange?: (value: boolean) => void
|
||||
readOnly?: boolean
|
||||
justVar?: boolean
|
||||
nodesOutputVars?: NodeOutPutVar[]
|
||||
availableNodes?: Node[]
|
||||
}
|
||||
|
||||
const Editor: FC<Props> = ({
|
||||
instanceId,
|
||||
className,
|
||||
placeholder,
|
||||
placeholderClassName,
|
||||
promptMinHeightClassName = 'min-h-[20px]',
|
||||
value,
|
||||
onChange,
|
||||
onFocusChange,
|
||||
readOnly,
|
||||
nodesOutputVars,
|
||||
availableNodes = [],
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const [isFocus, {
|
||||
setTrue: setFocus,
|
||||
setFalse: setBlur,
|
||||
}] = useBoolean(false)
|
||||
|
||||
useEffect(() => {
|
||||
onFocusChange?.(isFocus)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isFocus])
|
||||
|
||||
return (
|
||||
<div className={cn(className, 'relative')}>
|
||||
<>
|
||||
<PromptEditor
|
||||
instanceId={instanceId}
|
||||
className={cn(promptMinHeightClassName, '!leading-[18px]')}
|
||||
placeholder={placeholder}
|
||||
placeholderClassName={placeholderClassName}
|
||||
value={value}
|
||||
contextBlock={{
|
||||
show: false,
|
||||
selectable: false,
|
||||
datasets: [],
|
||||
onAddContext: () => { },
|
||||
}}
|
||||
historyBlock={{
|
||||
show: false,
|
||||
selectable: false,
|
||||
history: {
|
||||
user: 'Human',
|
||||
assistant: 'Assistant',
|
||||
},
|
||||
onEditRole: () => { },
|
||||
}}
|
||||
queryBlock={{
|
||||
show: false,
|
||||
selectable: false,
|
||||
}}
|
||||
workflowVariableBlock={{
|
||||
show: true,
|
||||
variables: nodesOutputVars || [],
|
||||
workflowNodesMap: availableNodes.reduce((acc, node) => {
|
||||
acc[node.id] = {
|
||||
title: node.data.title,
|
||||
type: node.data.type,
|
||||
}
|
||||
if (node.data.type === BlockEnum.Start) {
|
||||
acc.sys = {
|
||||
title: t('workflow.blocks.start'),
|
||||
type: BlockEnum.Start,
|
||||
}
|
||||
}
|
||||
return acc
|
||||
}, {} as any),
|
||||
}}
|
||||
onChange={onChange}
|
||||
editable={!readOnly}
|
||||
onBlur={setBlur}
|
||||
onFocus={setFocus}
|
||||
/>
|
||||
{/* to patch Editor not support dynamic change editable status */}
|
||||
{readOnly && <div className='absolute inset-0 z-10'></div>}
|
||||
{isFocus && (
|
||||
<div className='absolute z-10 top-[-9px] right-1'>
|
||||
<TooltipPlus
|
||||
popupContent={`${t('workflow.common.insertVarTip')}`}
|
||||
>
|
||||
<div className='p-0.5 rounded-[5px] shadow-lg cursor-pointer bg-white hover:bg-gray-100 border-[0.5px] border-black/5'>
|
||||
<Variable02 className='w-3.5 h-3.5 text-gray-500' />
|
||||
</div>
|
||||
</TooltipPlus>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div >
|
||||
)
|
||||
}
|
||||
export default React.memo(Editor)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { InputVarType } from '../../../types'
|
||||
import { AlignLeft, LetterSpacing01 } from '@/app/components/base/icons/src/vender/line/editor'
|
||||
import { CheckDone01, Hash02 } from '@/app/components/base/icons/src/vender/line/general'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
type: InputVarType
|
||||
}
|
||||
|
||||
const getIcon = (type: InputVarType) => {
|
||||
return ({
|
||||
[InputVarType.textInput]: LetterSpacing01,
|
||||
[InputVarType.paragraph]: AlignLeft,
|
||||
[InputVarType.select]: CheckDone01,
|
||||
[InputVarType.number]: Hash02,
|
||||
} as any)[type] || LetterSpacing01
|
||||
}
|
||||
|
||||
const InputVarTypeIcon: FC<Props> = ({
|
||||
className,
|
||||
type,
|
||||
}) => {
|
||||
const Icon = getIcon(type)
|
||||
return (
|
||||
<Icon className={className} />
|
||||
)
|
||||
}
|
||||
export default React.memo(InputVarTypeIcon)
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import produce from 'immer'
|
||||
import cn from 'classnames'
|
||||
import type { Memory } from '../../../types'
|
||||
import { MemoryRole } from '../../../types'
|
||||
import Field from '@/app/components/workflow/nodes/_base/components/field'
|
||||
import Switch from '@/app/components/base/switch'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
|
||||
const i18nPrefix = 'workflow.nodes.common.memory'
|
||||
const WINDOW_SIZE_MIN = 1
|
||||
const WINDOW_SIZE_MAX = 100
|
||||
const WINDOW_SIZE_DEFAULT = 50
|
||||
type RoleItemProps = {
|
||||
readonly: boolean
|
||||
title: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
const RoleItem: FC<RoleItemProps> = ({
|
||||
readonly,
|
||||
title,
|
||||
value,
|
||||
onChange,
|
||||
}) => {
|
||||
const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
onChange(e.target.value)
|
||||
}, [onChange])
|
||||
return (
|
||||
<div className='flex items-center justify-between'>
|
||||
<div className='text-[13px] font-normal text-gray-700'>{title}</div>
|
||||
<input
|
||||
readOnly={readonly}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
className='w-[200px] h-8 leading-8 px-2.5 rounded-lg border-0 bg-gray-100 text-gray-900 text-[13px] placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200'
|
||||
type='text' />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
readonly: boolean
|
||||
config: { data?: Memory }
|
||||
onChange: (memory?: Memory) => void
|
||||
canSetRoleName?: boolean
|
||||
}
|
||||
|
||||
const MEMORY_DEFAULT: Memory = { window: { enabled: false, size: WINDOW_SIZE_DEFAULT } }
|
||||
|
||||
const MemoryConfig: FC<Props> = ({
|
||||
className,
|
||||
readonly,
|
||||
config = { data: MEMORY_DEFAULT },
|
||||
onChange,
|
||||
canSetRoleName = false,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const payload = config.data
|
||||
const handleMemoryEnabledChange = useCallback((enabled: boolean) => {
|
||||
onChange(enabled ? MEMORY_DEFAULT : undefined)
|
||||
}, [onChange])
|
||||
const handleWindowEnabledChange = useCallback((enabled: boolean) => {
|
||||
const newPayload = produce(config.data || MEMORY_DEFAULT, (draft) => {
|
||||
if (!draft.window)
|
||||
draft.window = { enabled: false, size: WINDOW_SIZE_DEFAULT }
|
||||
|
||||
draft.window.enabled = enabled
|
||||
})
|
||||
|
||||
onChange(newPayload)
|
||||
}, [config, onChange])
|
||||
|
||||
const handleWindowSizeChange = useCallback((size: number | string) => {
|
||||
const newPayload = produce(payload || MEMORY_DEFAULT, (draft) => {
|
||||
if (!draft.window)
|
||||
draft.window = { enabled: true, size: WINDOW_SIZE_DEFAULT }
|
||||
let limitedSize: null | string | number = size
|
||||
if (limitedSize === '') {
|
||||
limitedSize = null
|
||||
}
|
||||
else {
|
||||
limitedSize = parseInt(limitedSize as string, 10)
|
||||
if (isNaN(limitedSize))
|
||||
limitedSize = WINDOW_SIZE_DEFAULT
|
||||
|
||||
if (limitedSize < WINDOW_SIZE_MIN)
|
||||
limitedSize = WINDOW_SIZE_MIN
|
||||
|
||||
if (limitedSize > WINDOW_SIZE_MAX)
|
||||
limitedSize = WINDOW_SIZE_MAX
|
||||
}
|
||||
|
||||
draft.window.size = limitedSize as number
|
||||
})
|
||||
onChange(newPayload)
|
||||
}, [payload, onChange])
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
const payload = config.data
|
||||
if (!payload)
|
||||
return
|
||||
|
||||
if (payload.window.size === '' || payload.window.size === null)
|
||||
handleWindowSizeChange(WINDOW_SIZE_DEFAULT)
|
||||
}, [handleWindowSizeChange, config])
|
||||
|
||||
const handleRolePrefixChange = useCallback((role: MemoryRole) => {
|
||||
return (value: string) => {
|
||||
const newPayload = produce(config.data || MEMORY_DEFAULT, (draft) => {
|
||||
if (!draft.role_prefix) {
|
||||
draft.role_prefix = {
|
||||
user: '',
|
||||
assistant: '',
|
||||
}
|
||||
}
|
||||
draft.role_prefix[role] = value
|
||||
})
|
||||
onChange(newPayload)
|
||||
}
|
||||
}, [config, onChange])
|
||||
return (
|
||||
<div className={cn(className)}>
|
||||
<Field
|
||||
title={t(`${i18nPrefix}.memory`)}
|
||||
tooltip={t(`${i18nPrefix}.memoryTip`)!}
|
||||
operations={
|
||||
<Switch
|
||||
defaultValue={!!payload}
|
||||
onChange={handleMemoryEnabledChange}
|
||||
size='md'
|
||||
disabled={readonly}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{payload && (
|
||||
<>
|
||||
{/* window size */}
|
||||
<div className='flex justify-between'>
|
||||
<div className='flex items-center h-8 space-x-1'>
|
||||
<Switch
|
||||
defaultValue={payload?.window?.enabled}
|
||||
onChange={handleWindowEnabledChange}
|
||||
size='md'
|
||||
disabled={readonly}
|
||||
/>
|
||||
<div className='leading-[18px] text-xs font-medium text-gray-500 uppercase'>{t(`${i18nPrefix}.windowSize`)}</div>
|
||||
</div>
|
||||
<div className='flex items-center h-8 space-x-2'>
|
||||
<Slider
|
||||
className='w-[144px]'
|
||||
value={(payload.window?.size || WINDOW_SIZE_DEFAULT) as number}
|
||||
min={WINDOW_SIZE_MIN}
|
||||
max={WINDOW_SIZE_MAX}
|
||||
step={1}
|
||||
onChange={handleWindowSizeChange}
|
||||
disabled={readonly || !payload.window?.enabled}
|
||||
/>
|
||||
<input
|
||||
value={(payload.window?.size || WINDOW_SIZE_DEFAULT) as number}
|
||||
className='shrink-0 block ml-4 pl-3 w-12 h-8 appearance-none outline-none rounded-lg bg-gray-100 text-[13px] text-gra-900'
|
||||
type='number'
|
||||
min={WINDOW_SIZE_MIN}
|
||||
max={WINDOW_SIZE_MAX}
|
||||
step={1}
|
||||
onChange={e => handleWindowSizeChange(e.target.value)}
|
||||
onBlur={handleBlur}
|
||||
disabled={readonly}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{canSetRoleName && (
|
||||
<div className='mt-4'>
|
||||
<div className='leading-6 text-xs font-medium text-gray-500 uppercase'>{t(`${i18nPrefix}.conversationRoleName`)}</div>
|
||||
<div className='mt-1 space-y-2'>
|
||||
<RoleItem
|
||||
readonly={readonly}
|
||||
title={t(`${i18nPrefix}.user`)}
|
||||
value={payload.role_prefix?.user || ''}
|
||||
onChange={handleRolePrefixChange(MemoryRole.user)}
|
||||
/>
|
||||
<RoleItem
|
||||
readonly={readonly}
|
||||
title={t(`${i18nPrefix}.assistant`)}
|
||||
value={payload.role_prefix?.assistant || ''}
|
||||
onChange={handleRolePrefixChange(MemoryRole.assistant)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
</Field>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(MemoryConfig)
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
useNodesExtraData,
|
||||
useNodesInteractions,
|
||||
useNodesReadOnly,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import BlockSelector from '@/app/components/workflow/block-selector'
|
||||
import { Plus } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import type {
|
||||
BlockEnum,
|
||||
OnSelectBlock,
|
||||
} from '@/app/components/workflow/types'
|
||||
|
||||
type AddProps = {
|
||||
nodeId: string
|
||||
nodeType: BlockEnum
|
||||
sourceHandle: string
|
||||
branchName?: string
|
||||
}
|
||||
const Add = ({
|
||||
nodeId,
|
||||
nodeType,
|
||||
sourceHandle,
|
||||
branchName,
|
||||
}: AddProps) => {
|
||||
const { t } = useTranslation()
|
||||
const { handleNodeAdd } = useNodesInteractions()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const availableNextNodes = nodesExtraData[nodeType].availableNextNodes
|
||||
|
||||
const handleSelect = useCallback<OnSelectBlock>((type, toolDefaultValue) => {
|
||||
handleNodeAdd(
|
||||
{
|
||||
nodeType: type,
|
||||
toolDefaultValue,
|
||||
},
|
||||
{
|
||||
prevNodeId: nodeId,
|
||||
prevNodeSourceHandle: sourceHandle,
|
||||
},
|
||||
)
|
||||
}, [nodeId, sourceHandle, handleNodeAdd])
|
||||
|
||||
const renderTrigger = useCallback((open: boolean) => {
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
relative flex items-center px-2 h-9 rounded-lg border border-dashed border-gray-200 bg-gray-50
|
||||
hover:bg-gray-100 text-xs text-gray-500 cursor-pointer
|
||||
${open && '!bg-gray-100'}
|
||||
${nodesReadOnly && '!cursor-not-allowed'}
|
||||
`}
|
||||
>
|
||||
{
|
||||
branchName && (
|
||||
<div
|
||||
className='absolute left-1 right-1 -top-[7.5px] flex items-center h-3 text-[10px] text-gray-500 font-semibold'
|
||||
title={branchName.toLocaleUpperCase()}
|
||||
>
|
||||
<div className='inline-block px-0.5 rounded-[5px] bg-white truncate'>{branchName.toLocaleUpperCase()}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<div className='flex items-center justify-center mr-1.5 w-5 h-5 rounded-[5px] bg-gray-200'>
|
||||
<Plus className='w-3 h-3' />
|
||||
</div>
|
||||
{t('workflow.panel.selectNextStep')}
|
||||
</div>
|
||||
)
|
||||
}, [branchName, t, nodesReadOnly])
|
||||
|
||||
return (
|
||||
<BlockSelector
|
||||
disabled={nodesReadOnly}
|
||||
onSelect={handleSelect}
|
||||
placement='top'
|
||||
offset={0}
|
||||
trigger={renderTrigger}
|
||||
popupClassName='!w-[328px]'
|
||||
availableBlocksTypes={availableNextNodes}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Add)
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
import { memo } from 'react'
|
||||
import {
|
||||
getConnectedEdges,
|
||||
getOutgoers,
|
||||
useEdges,
|
||||
useStoreApi,
|
||||
} from 'reactflow'
|
||||
import { useToolIcon } from '../../../../hooks'
|
||||
import BlockIcon from '../../../../block-icon'
|
||||
import type {
|
||||
Branch,
|
||||
Node,
|
||||
} from '../../../../types'
|
||||
import { BlockEnum } from '../../../../types'
|
||||
import Add from './add'
|
||||
import Item from './item'
|
||||
import Line from './line'
|
||||
|
||||
type NextStepProps = {
|
||||
selectedNode: Node
|
||||
}
|
||||
const NextStep = ({
|
||||
selectedNode,
|
||||
}: NextStepProps) => {
|
||||
const data = selectedNode.data
|
||||
const toolIcon = useToolIcon(data)
|
||||
const store = useStoreApi()
|
||||
const branches = data._targetBranches || []
|
||||
const nodeWithBranches = data.type === BlockEnum.IfElse || data.type === BlockEnum.QuestionClassifier
|
||||
const edges = useEdges()
|
||||
const outgoers = getOutgoers(selectedNode as Node, store.getState().getNodes(), edges)
|
||||
const connectedEdges = getConnectedEdges([selectedNode] as Node[], edges).filter(edge => edge.source === selectedNode!.id)
|
||||
|
||||
return (
|
||||
<div className='flex py-1'>
|
||||
<div className='shrink-0 relative flex items-center justify-center w-9 h-9 bg-white rounded-lg border-[0.5px] border-gray-200 shadow-xs'>
|
||||
<BlockIcon
|
||||
type={selectedNode!.data.type}
|
||||
toolIcon={toolIcon}
|
||||
/>
|
||||
</div>
|
||||
<Line linesNumber={nodeWithBranches ? branches.length : 1} />
|
||||
<div className='grow'>
|
||||
{
|
||||
!nodeWithBranches && !!outgoers.length && (
|
||||
<Item
|
||||
nodeId={outgoers[0].id}
|
||||
data={outgoers[0].data}
|
||||
sourceHandle='source'
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
!nodeWithBranches && !outgoers.length && (
|
||||
<Add
|
||||
nodeId={selectedNode!.id}
|
||||
nodeType={selectedNode!.data.type}
|
||||
sourceHandle='source'
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
!!branches?.length && nodeWithBranches && (
|
||||
branches.map((branch: Branch) => {
|
||||
const connected = connectedEdges.find(edge => edge.sourceHandle === branch.id)
|
||||
const target = outgoers.find(outgoer => outgoer.id === connected?.target)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={branch.id}
|
||||
className='mb-3 last-of-type:mb-0'
|
||||
>
|
||||
{
|
||||
connected && (
|
||||
<Item
|
||||
data={target!.data!}
|
||||
nodeId={target!.id}
|
||||
sourceHandle={branch.id}
|
||||
branchName={branch.name}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
!connected && (
|
||||
<Add
|
||||
key={branch.id}
|
||||
nodeId={selectedNode!.id}
|
||||
nodeType={selectedNode!.data.type}
|
||||
sourceHandle={branch.id}
|
||||
branchName={branch.name}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(NextStep)
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { intersection } from 'lodash-es'
|
||||
import type {
|
||||
CommonNodeType,
|
||||
OnSelectBlock,
|
||||
} from '@/app/components/workflow/types'
|
||||
import BlockIcon from '@/app/components/workflow/block-icon'
|
||||
import BlockSelector from '@/app/components/workflow/block-selector'
|
||||
import {
|
||||
useNodesExtraData,
|
||||
useNodesInteractions,
|
||||
useNodesReadOnly,
|
||||
useToolIcon,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import Button from '@/app/components/base/button'
|
||||
|
||||
type ItemProps = {
|
||||
nodeId: string
|
||||
sourceHandle: string
|
||||
branchName?: string
|
||||
data: CommonNodeType
|
||||
}
|
||||
const Item = ({
|
||||
nodeId,
|
||||
sourceHandle,
|
||||
branchName,
|
||||
data,
|
||||
}: ItemProps) => {
|
||||
const { t } = useTranslation()
|
||||
const { handleNodeChange } = useNodesInteractions()
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const toolIcon = useToolIcon(data)
|
||||
const availablePrevNodes = nodesExtraData[data.type].availablePrevNodes
|
||||
const availableNextNodes = nodesExtraData[data.type].availableNextNodes
|
||||
const handleSelect = useCallback<OnSelectBlock>((type, toolDefaultValue) => {
|
||||
handleNodeChange(nodeId, type, sourceHandle, toolDefaultValue)
|
||||
}, [nodeId, sourceHandle, handleNodeChange])
|
||||
const renderTrigger = useCallback((open: boolean) => {
|
||||
return (
|
||||
<Button
|
||||
className={`
|
||||
hidden group-hover:flex px-2 py-0 h-6 bg-white text-xs text-gray-700 font-medium rounded-md
|
||||
${open && '!bg-gray-100 !flex'}
|
||||
`}
|
||||
>
|
||||
{t('workflow.panel.change')}
|
||||
</Button>
|
||||
)
|
||||
}, [t])
|
||||
|
||||
return (
|
||||
<div
|
||||
className='relative group flex items-center mb-3 last-of-type:mb-0 px-2 h-9 rounded-lg border-[0.5px] border-gray-200 bg-white hover:bg-gray-50 shadow-xs text-xs text-gray-700 cursor-pointer'
|
||||
>
|
||||
{
|
||||
branchName && (
|
||||
<div
|
||||
className='absolute left-1 right-1 -top-[7.5px] flex items-center h-3 text-[10px] text-gray-500 font-semibold'
|
||||
title={branchName.toLocaleUpperCase()}
|
||||
>
|
||||
<div className='inline-block px-0.5 rounded-[5px] bg-white truncate'>{branchName.toLocaleUpperCase()}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<BlockIcon
|
||||
type={data.type}
|
||||
toolIcon={toolIcon}
|
||||
className='shrink-0 mr-1.5'
|
||||
/>
|
||||
<div className='grow'>{data.title}</div>
|
||||
{
|
||||
!nodesReadOnly && (
|
||||
<BlockSelector
|
||||
onSelect={handleSelect}
|
||||
placement='top-end'
|
||||
offset={{
|
||||
mainAxis: 6,
|
||||
crossAxis: 8,
|
||||
}}
|
||||
trigger={renderTrigger}
|
||||
popupClassName='!w-[328px]'
|
||||
availableBlocksTypes={intersection(availablePrevNodes, availableNextNodes)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Item)
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
import { memo } from 'react'
|
||||
|
||||
type LineProps = {
|
||||
linesNumber: number
|
||||
}
|
||||
const Line = ({
|
||||
linesNumber,
|
||||
}: LineProps) => {
|
||||
const svgHeight = linesNumber * 36 + (linesNumber - 1) * 12
|
||||
|
||||
return (
|
||||
<svg className='shrink-0 w-6' style={{ height: svgHeight }}>
|
||||
{
|
||||
Array(linesNumber).fill(0).map((_, index) => (
|
||||
<g key={index}>
|
||||
{
|
||||
index === 0 && (
|
||||
<>
|
||||
<rect
|
||||
x={0}
|
||||
y={16}
|
||||
width={1}
|
||||
height={4}
|
||||
fill='#98A2B3'
|
||||
/>
|
||||
<path
|
||||
d='M0,18 L24,18'
|
||||
strokeWidth={1}
|
||||
stroke='#D0D5DD'
|
||||
fill='none'
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
{
|
||||
index > 0 && (
|
||||
<path
|
||||
d={`M0,18 Q12,18 12,28 L12,${index * 48 + 18 - 10} Q12,${index * 48 + 18} 24,${index * 48 + 18}`}
|
||||
strokeWidth={1}
|
||||
stroke='#D0D5DD'
|
||||
fill='none'
|
||||
/>
|
||||
)
|
||||
}
|
||||
<rect
|
||||
x={23}
|
||||
y={index * 48 + 18 - 2}
|
||||
width={1}
|
||||
height={4}
|
||||
fill='#98A2B3'
|
||||
/>
|
||||
</g>
|
||||
))
|
||||
}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Line)
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import type { FC } from 'react'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
useNodeDataUpdate,
|
||||
useNodesInteractions,
|
||||
useNodesSyncDraft,
|
||||
} from '../../../hooks'
|
||||
import type { Node } from '../../../types'
|
||||
import { canRunBySingle } from '../../../utils'
|
||||
import PanelOperator from './panel-operator'
|
||||
import {
|
||||
Play,
|
||||
Stop,
|
||||
} from '@/app/components/base/icons/src/vender/line/mediaAndDevices'
|
||||
import TooltipPlus from '@/app/components/base/tooltip-plus'
|
||||
|
||||
type NodeControlProps = Pick<Node, 'id' | 'data'>
|
||||
const NodeControl: FC<NodeControlProps> = ({
|
||||
id,
|
||||
data,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const { handleNodeDataUpdate } = useNodeDataUpdate()
|
||||
const { handleNodeSelect } = useNodesInteractions()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
|
||||
const handleOpenChange = useCallback((newOpen: boolean) => {
|
||||
setOpen(newOpen)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
hidden group-hover:flex pb-1 absolute right-0 -top-7 h-7
|
||||
${data.selected && '!flex'}
|
||||
${open && '!flex'}
|
||||
`}
|
||||
>
|
||||
<div
|
||||
className='flex items-center px-0.5 h-6 bg-white rounded-lg border-[0.5px] border-gray-100 shadow-xs text-gray-500'
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
{
|
||||
canRunBySingle(data.type) && (
|
||||
<div
|
||||
className='flex items-center justify-center w-5 h-5 rounded-md cursor-pointer hover:bg-black/5'
|
||||
onClick={() => {
|
||||
handleNodeDataUpdate({
|
||||
id,
|
||||
data: {
|
||||
_isSingleRun: !data._isSingleRun,
|
||||
},
|
||||
})
|
||||
handleNodeSelect(id)
|
||||
if (!data._isSingleRun)
|
||||
handleSyncWorkflowDraft(true)
|
||||
}}
|
||||
>
|
||||
{
|
||||
data._isSingleRun
|
||||
? <Stop className='w-3 h-3' />
|
||||
: (
|
||||
<TooltipPlus
|
||||
popupContent={t('workflow.panel.runThisStep')}
|
||||
>
|
||||
<Play className='w-3 h-3' />
|
||||
</TooltipPlus>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<PanelOperator
|
||||
id={id}
|
||||
data={data}
|
||||
offset={0}
|
||||
onOpenChange={handleOpenChange}
|
||||
triggerClassName='!w-5 !h-5'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(NodeControl)
|
||||
|
|
@ -0,0 +1,183 @@
|
|||
import type { MouseEvent } from 'react'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useState,
|
||||
} from 'react'
|
||||
import {
|
||||
Handle,
|
||||
Position,
|
||||
} from 'reactflow'
|
||||
import { BlockEnum } from '../../../types'
|
||||
import type { Node } from '../../../types'
|
||||
import BlockSelector from '../../../block-selector'
|
||||
import type { ToolDefaultValue } from '../../../block-selector/types'
|
||||
import {
|
||||
useNodesExtraData,
|
||||
useNodesInteractions,
|
||||
} from '../../../hooks'
|
||||
import { useStore } from '../../../store'
|
||||
|
||||
type NodeHandleProps = {
|
||||
handleId: string
|
||||
handleClassName?: string
|
||||
nodeSelectorClassName?: string
|
||||
} & Pick<Node, 'id' | 'data'>
|
||||
|
||||
export const NodeTargetHandle = memo(({
|
||||
id,
|
||||
data,
|
||||
handleId,
|
||||
handleClassName,
|
||||
nodeSelectorClassName,
|
||||
}: NodeHandleProps) => {
|
||||
const [open, setOpen] = useState(false)
|
||||
const { handleNodeAdd } = useNodesInteractions()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const connected = data._connectedTargetHandleIds?.includes(handleId)
|
||||
const availablePrevNodes = nodesExtraData[data.type].availablePrevNodes
|
||||
const isConnectable = !!availablePrevNodes.length
|
||||
|
||||
const handleOpenChange = useCallback((v: boolean) => {
|
||||
setOpen(v)
|
||||
}, [])
|
||||
const handleHandleClick = useCallback((e: MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!connected)
|
||||
setOpen(v => !v)
|
||||
}, [connected])
|
||||
const handleSelect = useCallback((type: BlockEnum, toolDefaultValue?: ToolDefaultValue) => {
|
||||
handleNodeAdd(
|
||||
{
|
||||
nodeType: type,
|
||||
toolDefaultValue,
|
||||
},
|
||||
{
|
||||
nextNodeId: id,
|
||||
nextNodeTargetHandle: handleId,
|
||||
},
|
||||
)
|
||||
}, [handleNodeAdd, id, handleId])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Handle
|
||||
id={handleId}
|
||||
type='target'
|
||||
position={Position.Left}
|
||||
className={`
|
||||
!w-4 !h-4 !bg-transparent !rounded-none !outline-none !border-none z-[1]
|
||||
after:absolute after:w-0.5 after:h-2 after:left-1.5 after:top-1 after:bg-primary-500
|
||||
hover:scale-125 transition-all
|
||||
${!connected && 'after:opacity-0'}
|
||||
${data.type === BlockEnum.Start && 'opacity-0'}
|
||||
${handleClassName}
|
||||
`}
|
||||
isConnectable={isConnectable}
|
||||
onClick={handleHandleClick}
|
||||
>
|
||||
{
|
||||
!connected && isConnectable && !data._isInvalidConnection && (
|
||||
<BlockSelector
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSelect={handleSelect}
|
||||
asChild
|
||||
placement='left'
|
||||
triggerClassName={open => `
|
||||
hidden absolute left-0 top-0 pointer-events-none
|
||||
${nodeSelectorClassName}
|
||||
group-hover:!flex
|
||||
${data.selected && '!flex'}
|
||||
${open && '!flex'}
|
||||
`}
|
||||
availableBlocksTypes={availablePrevNodes}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</Handle>
|
||||
</>
|
||||
)
|
||||
})
|
||||
NodeTargetHandle.displayName = 'NodeTargetHandle'
|
||||
|
||||
export const NodeSourceHandle = memo(({
|
||||
id,
|
||||
data,
|
||||
handleId,
|
||||
handleClassName,
|
||||
nodeSelectorClassName,
|
||||
}: NodeHandleProps) => {
|
||||
const notInitialWorkflow = useStore(s => s.notInitialWorkflow)
|
||||
const [open, setOpen] = useState(false)
|
||||
const { handleNodeAdd } = useNodesInteractions()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const availableNextNodes = nodesExtraData[data.type].availableNextNodes
|
||||
const isConnectable = !!availableNextNodes.length
|
||||
const connected = data._connectedSourceHandleIds?.includes(handleId)
|
||||
const handleOpenChange = useCallback((v: boolean) => {
|
||||
setOpen(v)
|
||||
}, [])
|
||||
const handleHandleClick = useCallback((e: MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!connected)
|
||||
setOpen(v => !v)
|
||||
}, [connected])
|
||||
const handleSelect = useCallback((type: BlockEnum, toolDefaultValue?: ToolDefaultValue) => {
|
||||
handleNodeAdd(
|
||||
{
|
||||
nodeType: type,
|
||||
toolDefaultValue,
|
||||
},
|
||||
{
|
||||
prevNodeId: id,
|
||||
prevNodeSourceHandle: handleId,
|
||||
},
|
||||
)
|
||||
}, [handleNodeAdd, id, handleId])
|
||||
|
||||
useEffect(() => {
|
||||
if (notInitialWorkflow && data.type === BlockEnum.Start)
|
||||
setOpen(true)
|
||||
}, [notInitialWorkflow, data.type])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Handle
|
||||
id={handleId}
|
||||
type='source'
|
||||
position={Position.Right}
|
||||
className={`
|
||||
!w-4 !h-4 !bg-transparent !rounded-none !outline-none !border-none z-[1]
|
||||
after:absolute after:w-0.5 after:h-2 after:right-1.5 after:top-1 after:bg-primary-500
|
||||
hover:scale-125 transition-all
|
||||
${!connected && 'after:opacity-0'}
|
||||
${handleClassName}
|
||||
`}
|
||||
isConnectable={isConnectable}
|
||||
onClick={handleHandleClick}
|
||||
>
|
||||
{
|
||||
!connected && isConnectable && !data._isInvalidConnection && (
|
||||
<BlockSelector
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSelect={handleSelect}
|
||||
asChild
|
||||
triggerClassName={open => `
|
||||
hidden absolute top-0 left-0 pointer-events-none
|
||||
${nodeSelectorClassName}
|
||||
group-hover:!flex
|
||||
${data.selected && '!flex'}
|
||||
${open && '!flex'}
|
||||
`}
|
||||
availableBlocksTypes={availableNextNodes}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</Handle>
|
||||
</>
|
||||
)
|
||||
})
|
||||
NodeSourceHandle.displayName = 'NodeSourceHandle'
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import cn from 'classnames'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
title?: string
|
||||
children: JSX.Element
|
||||
}
|
||||
|
||||
const OutputVars: FC<Props> = ({
|
||||
className,
|
||||
title,
|
||||
children,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const [isFold, {
|
||||
toggle: toggleFold,
|
||||
}] = useBoolean(true)
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
onClick={toggleFold}
|
||||
className={cn(className, 'flex justify-between leading-[18px] text-[13px] font-semibold text-gray-700 uppercase cursor-pointer')}>
|
||||
<div>{title || t('workflow.nodes.common.outputVars')}</div>
|
||||
<ChevronRight className='w-4 h-4 text-gray-500 transform transition-transform' style={{ transform: isFold ? 'rotate(0deg)' : 'rotate(90deg)' }} />
|
||||
</div>
|
||||
{!isFold && (
|
||||
<div className='mt-2 space-y-1'>
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
type VarItemProps = {
|
||||
name: string
|
||||
type: string
|
||||
description: string
|
||||
subItems?: {
|
||||
name: string
|
||||
type: string
|
||||
description: string
|
||||
}[]
|
||||
}
|
||||
|
||||
export const VarItem: FC<VarItemProps> = ({
|
||||
name,
|
||||
type,
|
||||
description,
|
||||
subItems,
|
||||
}) => {
|
||||
return (
|
||||
<div className='py-1'>
|
||||
<div className='flex leading-[18px] items-center'>
|
||||
<div className='text-[13px] font-medium text-gray-900 font-mono'>{name}</div>
|
||||
<div className='ml-2 text-xs font-normal text-gray-500 capitalize'>{type}</div>
|
||||
</div>
|
||||
<div className='mt-0.5 leading-[18px] text-xs font-normal text-gray-600'>
|
||||
{description}
|
||||
{subItems && (
|
||||
<div className='ml-2 border-l border-gray-200 pl-2'>
|
||||
{subItems.map((item, index) => (
|
||||
<VarItem
|
||||
key={index}
|
||||
name={item.name}
|
||||
type={item.type}
|
||||
description={item.description}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(OutputVars)
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useMemo,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { intersection } from 'lodash-es'
|
||||
import BlockSelector from '@/app/components/workflow/block-selector'
|
||||
import {
|
||||
useNodesExtraData,
|
||||
useNodesInteractions,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import type {
|
||||
BlockEnum,
|
||||
OnSelectBlock,
|
||||
} from '@/app/components/workflow/types'
|
||||
|
||||
type ChangeBlockProps = {
|
||||
nodeId: string
|
||||
nodeType: BlockEnum
|
||||
sourceHandle: string
|
||||
}
|
||||
const ChangeBlock = ({
|
||||
nodeId,
|
||||
nodeType,
|
||||
sourceHandle,
|
||||
}: ChangeBlockProps) => {
|
||||
const { t } = useTranslation()
|
||||
const { handleNodeChange } = useNodesInteractions()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const availablePrevNodes = nodesExtraData[nodeType].availablePrevNodes
|
||||
const availableNextNodes = nodesExtraData[nodeType].availableNextNodes
|
||||
|
||||
const availableNodes = useMemo(() => {
|
||||
if (availableNextNodes.length && availableNextNodes.length)
|
||||
return intersection(availablePrevNodes, availableNextNodes)
|
||||
else if (availablePrevNodes.length)
|
||||
return availablePrevNodes
|
||||
else
|
||||
return availableNextNodes
|
||||
}, [availablePrevNodes, availableNextNodes])
|
||||
|
||||
const handleSelect = useCallback<OnSelectBlock>((type, toolDefaultValue) => {
|
||||
handleNodeChange(nodeId, type, sourceHandle, toolDefaultValue)
|
||||
}, [handleNodeChange, nodeId, sourceHandle])
|
||||
|
||||
const renderTrigger = useCallback(() => {
|
||||
return (
|
||||
<div className='flex items-center px-3 w-[232px] h-8 text-sm text-gray-700 rounded-lg cursor-pointer hover:bg-gray-50'>
|
||||
{t('workflow.panel.changeBlock')}
|
||||
</div>
|
||||
)
|
||||
}, [t])
|
||||
|
||||
return (
|
||||
<BlockSelector
|
||||
placement='bottom-end'
|
||||
offset={{
|
||||
mainAxis: -36,
|
||||
crossAxis: 4,
|
||||
}}
|
||||
onSelect={handleSelect}
|
||||
trigger={renderTrigger}
|
||||
popupClassName='min-w-[240px]'
|
||||
availableBlocksTypes={availableNodes}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ChangeBlock)
|
||||
|
|
@ -0,0 +1,162 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useEdges } from 'reactflow'
|
||||
import type { OffsetOptions } from '@floating-ui/react'
|
||||
import ChangeBlock from './change-block'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
import {
|
||||
useNodesExtraData,
|
||||
useNodesInteractions,
|
||||
useNodesReadOnly,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import { DotsHorizontal } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import type { Node } from '@/app/components/workflow/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { useGetLanguage } from '@/context/i18n'
|
||||
|
||||
type PanelOperatorProps = {
|
||||
id: string
|
||||
data: Node['data']
|
||||
triggerClassName?: string
|
||||
offset?: OffsetOptions
|
||||
onOpenChange?: (open: boolean) => void
|
||||
inNode?: boolean
|
||||
}
|
||||
const PanelOperator = ({
|
||||
id,
|
||||
data,
|
||||
triggerClassName,
|
||||
offset = {
|
||||
mainAxis: 4,
|
||||
crossAxis: 53,
|
||||
},
|
||||
onOpenChange,
|
||||
inNode,
|
||||
}: PanelOperatorProps) => {
|
||||
const { t } = useTranslation()
|
||||
const language = useGetLanguage()
|
||||
const edges = useEdges()
|
||||
const { handleNodeDelete } = useNodesInteractions()
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const buildInTools = useStore(s => s.buildInTools)
|
||||
const customTools = useStore(s => s.customTools)
|
||||
const [open, setOpen] = useState(false)
|
||||
const edge = edges.find(edge => edge.target === id)
|
||||
const author = useMemo(() => {
|
||||
if (data.type !== BlockEnum.Tool)
|
||||
return nodesExtraData[data.type].author
|
||||
|
||||
if (data.provider_type === 'builtin')
|
||||
return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.author
|
||||
|
||||
return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.author
|
||||
}, [data, nodesExtraData, buildInTools, customTools])
|
||||
|
||||
const about = useMemo(() => {
|
||||
if (data.type !== BlockEnum.Tool)
|
||||
return nodesExtraData[data.type].about
|
||||
|
||||
if (data.provider_type === 'builtin')
|
||||
return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.description[language]
|
||||
|
||||
return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.description[language]
|
||||
}, [data, nodesExtraData, language, buildInTools, customTools])
|
||||
|
||||
const handleOpenChange = useCallback((newOpen: boolean) => {
|
||||
setOpen(newOpen)
|
||||
|
||||
if (onOpenChange)
|
||||
onOpenChange(newOpen)
|
||||
}, [onOpenChange])
|
||||
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
placement='bottom-end'
|
||||
offset={offset}
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
>
|
||||
<PortalToFollowElemTrigger onClick={() => handleOpenChange(!open)}>
|
||||
<div
|
||||
className={`
|
||||
flex items-center justify-center w-6 h-6 rounded-md cursor-pointer
|
||||
hover:bg-black/5
|
||||
${open && 'bg-black/5'}
|
||||
${triggerClassName}
|
||||
`}
|
||||
>
|
||||
<DotsHorizontal className={`w-4 h-4 ${inNode ? 'text-gray-500' : 'text-gray-700'}`} />
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-[11]'>
|
||||
<div className='w-[240px] border-[0.5px] border-gray-200 rounded-lg shadow-xl bg-white'>
|
||||
<div className='p-1'>
|
||||
{
|
||||
data.type !== BlockEnum.Start && !nodesReadOnly && (
|
||||
<ChangeBlock
|
||||
nodeId={id}
|
||||
nodeType={data.type}
|
||||
sourceHandle={edge?.sourceHandle || 'source'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
<a
|
||||
href={
|
||||
language === 'zh_Hans'
|
||||
? 'https://docs.dify.ai/v/zh-hans/guides/workflow'
|
||||
: 'https://docs.dify.ai/features/workflow'
|
||||
}
|
||||
target='_blank'
|
||||
className='flex items-center px-3 h-8 text-sm text-gray-700 rounded-lg cursor-pointer hover:bg-gray-50'
|
||||
>
|
||||
{t('workflow.panel.helpLink')}
|
||||
</a>
|
||||
</div>
|
||||
{
|
||||
data.type !== BlockEnum.Start && !nodesReadOnly && (
|
||||
<>
|
||||
<div className='h-[1px] bg-gray-100'></div>
|
||||
<div className='p-1'>
|
||||
<div
|
||||
className={`
|
||||
flex items-center px-3 h-8 text-sm text-gray-700 rounded-lg cursor-pointer
|
||||
hover:bg-rose-50 hover:text-red-500
|
||||
`}
|
||||
onClick={() => handleNodeDelete(id)}
|
||||
>
|
||||
{t('common.operation.delete')}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
<div className='h-[1px] bg-gray-100'></div>
|
||||
<div className='p-1'>
|
||||
<div className='px-3 py-2 text-xs text-gray-500'>
|
||||
<div className='flex items-center mb-1 h-[22px] font-medium'>
|
||||
{t('workflow.panel.about').toLocaleUpperCase()}
|
||||
</div>
|
||||
<div className='mb-1 text-gray-700 leading-[18px]'>{about}</div>
|
||||
<div className='leading-[18px]'>
|
||||
{t('workflow.panel.createdBy')} {author}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(PanelOperator)
|
||||
|
|
@ -0,0 +1,210 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import cn from 'classnames'
|
||||
import copy from 'copy-to-clipboard'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import {
|
||||
BlockEnum,
|
||||
type Node,
|
||||
type NodeOutPutVar,
|
||||
} from '../../../../types'
|
||||
import ToggleExpandBtn from '@/app/components/workflow/nodes/_base/components/toggle-expand-btn'
|
||||
import useToggleExpend from '@/app/components/workflow/nodes/_base/hooks/use-toggle-expend'
|
||||
import PromptEditorHeightResizeWrap from '@/app/components/app/configuration/config-prompt/prompt-editor-height-resize-wrap'
|
||||
import PromptEditor from '@/app/components/base/prompt-editor'
|
||||
import { Clipboard, ClipboardCheck } from '@/app/components/base/icons/src/vender/line/files'
|
||||
import s from '@/app/components/app/configuration/config-prompt/style.module.css'
|
||||
import { Trash03 } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import TooltipPlus from '@/app/components/base/tooltip-plus'
|
||||
import { useEventEmitterContextContext } from '@/context/event-emitter'
|
||||
import { PROMPT_EDITOR_INSERT_QUICKLY } from '@/app/components/base/prompt-editor/plugins/update-block'
|
||||
|
||||
type Props = {
|
||||
instanceId?: string
|
||||
title: string | JSX.Element
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
readOnly?: boolean
|
||||
showRemove?: boolean
|
||||
onRemove?: () => void
|
||||
justVar?: boolean
|
||||
isChatModel?: boolean
|
||||
isChatApp?: boolean
|
||||
isShowContext?: boolean
|
||||
hasSetBlockStatus?: {
|
||||
context: boolean
|
||||
history: boolean
|
||||
query: boolean
|
||||
}
|
||||
nodesOutputVars?: NodeOutPutVar[]
|
||||
availableNodes?: Node[]
|
||||
}
|
||||
|
||||
const Editor: FC<Props> = ({
|
||||
instanceId,
|
||||
title,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
showRemove,
|
||||
onRemove,
|
||||
justVar,
|
||||
isChatModel,
|
||||
isChatApp,
|
||||
isShowContext,
|
||||
hasSetBlockStatus,
|
||||
nodesOutputVars,
|
||||
availableNodes = [],
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const { eventEmitter } = useEventEmitterContextContext()
|
||||
|
||||
const isShowHistory = !isChatModel && isChatApp
|
||||
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const {
|
||||
wrapClassName,
|
||||
isExpand,
|
||||
setIsExpand,
|
||||
editorExpandHeight,
|
||||
} = useToggleExpend({ ref })
|
||||
const minHeight = 98
|
||||
const [editorHeight, setEditorHeight] = React.useState(minHeight)
|
||||
const [isCopied, setIsCopied] = React.useState(false)
|
||||
const handleCopy = useCallback(() => {
|
||||
copy(value)
|
||||
setIsCopied(true)
|
||||
}, [value])
|
||||
|
||||
const [isFocus, {
|
||||
setTrue: setFocus,
|
||||
setFalse: setBlur,
|
||||
}] = useBoolean(false)
|
||||
const hideTooltipRunId = useRef(0)
|
||||
|
||||
const [isShowInsertToolTip, setIsShowInsertTooltip] = useState(false)
|
||||
useEffect(() => {
|
||||
if (isFocus) {
|
||||
clearTimeout(hideTooltipRunId.current)
|
||||
setIsShowInsertTooltip(true)
|
||||
}
|
||||
else {
|
||||
hideTooltipRunId.current = setTimeout(() => {
|
||||
setIsShowInsertTooltip(false)
|
||||
}, 100) as any
|
||||
}
|
||||
}, [isFocus])
|
||||
|
||||
const handleInsertVariable = () => {
|
||||
setFocus()
|
||||
eventEmitter?.emit({ type: PROMPT_EDITOR_INSERT_QUICKLY, instanceId } as any)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn(wrapClassName)}>
|
||||
<div ref={ref} className={cn(isFocus ? s.gradientBorder : 'bg-gray-100', isExpand && 'h-full', '!rounded-[9px] p-0.5')}>
|
||||
<div className={cn(isFocus ? 'bg-gray-50' : 'bg-gray-100', isExpand && 'h-full flex flex-col', 'rounded-lg')}>
|
||||
<div className='pt-1 pl-3 pr-2 flex justify-between h-6 items-center'>
|
||||
<div className='leading-4 text-xs font-semibold text-gray-700 uppercase'>{title}</div>
|
||||
<div className='flex items-center'>
|
||||
<div className='leading-[18px] text-xs font-medium text-gray-500'>{value?.length || 0}</div>
|
||||
<div className='w-px h-3 ml-2 mr-2 bg-gray-200'></div>
|
||||
{/* Operations */}
|
||||
<div className='flex items-center space-x-2'>
|
||||
{showRemove && (
|
||||
<Trash03 className='w-3.5 h-3.5 text-gray-500 cursor-pointer' onClick={onRemove} />
|
||||
)}
|
||||
{!isCopied
|
||||
? (
|
||||
<Clipboard className='w-3.5 h-3.5 text-gray-500 cursor-pointer' onClick={handleCopy} />
|
||||
)
|
||||
: (
|
||||
<ClipboardCheck className='mx-1 w-3.5 h-3.5 text-gray-500' />
|
||||
)
|
||||
}
|
||||
<ToggleExpandBtn isExpand={isExpand} onExpandChange={setIsExpand} />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<PromptEditorHeightResizeWrap
|
||||
className={cn(isExpand && 'h-0 grow', 'px-3 min-h-[102px] overflow-y-auto text-sm text-gray-700')}
|
||||
height={isExpand ? editorExpandHeight : editorHeight}
|
||||
minHeight={minHeight}
|
||||
onHeightChange={setEditorHeight}
|
||||
footer={(
|
||||
<div className='pl-3 pb-2 flex'>
|
||||
{(isFocus || isShowInsertToolTip)
|
||||
? (
|
||||
<TooltipPlus
|
||||
popupContent={`${t('workflow.common.insertVarTip')}`}
|
||||
>
|
||||
<div
|
||||
className="h-[18px] leading-[18px] px-1 rounded-md bg-gray-100 text-xs text-gray-500"
|
||||
onClick={handleInsertVariable}
|
||||
>{'{x} '}{t('workflow.nodes.common.insertVarTip')}</div>
|
||||
</TooltipPlus>)
|
||||
: <div className='h-[18px]'></div>}
|
||||
</div>
|
||||
)}
|
||||
hideResize={isExpand}
|
||||
>
|
||||
<>
|
||||
<PromptEditor
|
||||
instanceId={instanceId}
|
||||
className={cn('min-h-[84px]')}
|
||||
compact
|
||||
style={isExpand ? { height: editorExpandHeight - 5 } : {}}
|
||||
value={value}
|
||||
contextBlock={{
|
||||
show: justVar ? false : isShowContext,
|
||||
selectable: !hasSetBlockStatus?.context,
|
||||
canNotAddContext: true,
|
||||
}}
|
||||
historyBlock={{
|
||||
show: justVar ? false : isShowHistory,
|
||||
selectable: !hasSetBlockStatus?.history,
|
||||
history: {
|
||||
user: 'Human',
|
||||
assistant: 'Assistant',
|
||||
},
|
||||
}}
|
||||
queryBlock={{
|
||||
show: false, // use [sys.query] instead of query block
|
||||
selectable: false,
|
||||
}}
|
||||
workflowVariableBlock={{
|
||||
show: true,
|
||||
variables: nodesOutputVars || [],
|
||||
workflowNodesMap: availableNodes.reduce((acc, node) => {
|
||||
acc[node.id] = {
|
||||
title: node.data.title,
|
||||
type: node.data.type,
|
||||
}
|
||||
if (node.data.type === BlockEnum.Start) {
|
||||
acc.sys = {
|
||||
title: t('workflow.blocks.start'),
|
||||
type: BlockEnum.Start,
|
||||
}
|
||||
}
|
||||
return acc
|
||||
}, {} as any),
|
||||
}}
|
||||
onChange={onChange}
|
||||
onBlur={setBlur}
|
||||
onFocus={setFocus}
|
||||
editable={!readOnly}
|
||||
/>
|
||||
{/* to patch Editor not support dynamic change editable status */}
|
||||
{readOnly && <div className='absolute inset-0 z-10'></div>}
|
||||
</>
|
||||
</PromptEditorHeightResizeWrap>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
)
|
||||
}
|
||||
export default React.memo(Editor)
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useWorkflow } from '../../../hooks'
|
||||
import { BlockEnum } from '../../../types'
|
||||
import { VarBlockIcon } from '../../../block-icon'
|
||||
import { getNodeInfoById, isSystemVar } from './variable/utils'
|
||||
import { Line3 } from '@/app/components/base/icons/src/public/common'
|
||||
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
|
||||
type Props = {
|
||||
nodeId: string
|
||||
value: string
|
||||
}
|
||||
|
||||
const VAR_PLACEHOLDER = '@#!@#!'
|
||||
|
||||
const ReadonlyInputWithSelectVar: FC<Props> = ({
|
||||
nodeId,
|
||||
value,
|
||||
}) => {
|
||||
const { getBeforeNodesInSameBranch } = useWorkflow()
|
||||
const availableNodes = getBeforeNodesInSameBranch(nodeId)
|
||||
const startNode = availableNodes.find((node: any) => {
|
||||
return node.data.type === BlockEnum.Start
|
||||
})
|
||||
|
||||
const res = (() => {
|
||||
const vars: string[] = []
|
||||
const strWithVarPlaceholder = value.replaceAll(/{{#([^#]*)#}}/g, (_match, p1) => {
|
||||
vars.push(p1)
|
||||
return VAR_PLACEHOLDER
|
||||
})
|
||||
|
||||
const html: JSX.Element[] = strWithVarPlaceholder.split(VAR_PLACEHOLDER).map((str, index) => {
|
||||
if (!vars[index])
|
||||
return <span className='relative top-[-3px] leading-[16px]' key={index}>{str}</span>
|
||||
|
||||
const value = vars[index].split('.')
|
||||
const isSystem = isSystemVar(value)
|
||||
const node = (isSystem ? startNode : getNodeInfoById(availableNodes, value[0]))?.data
|
||||
const varName = `${isSystem ? 'sys.' : ''}${value[value.length - 1]}`
|
||||
|
||||
return (<span key={index}>
|
||||
<span className='relative top-[-3px] leading-[16px]'>{str}</span>
|
||||
<div className=' inline-flex h-[16px] items-center px-1.5 rounded-[5px] bg-white'>
|
||||
<div className='flex items-center'>
|
||||
<div className='p-[1px]'>
|
||||
<VarBlockIcon
|
||||
className='!text-gray-900'
|
||||
type={node?.type || BlockEnum.Start}
|
||||
/>
|
||||
</div>
|
||||
<div className='max-w-[60px] mx-0.5 text-xs font-medium text-gray-700 truncate' title={node?.title}>{node?.title}</div>
|
||||
<Line3 className='mr-0.5'></Line3>
|
||||
</div>
|
||||
<div className='flex items-center text-primary-600'>
|
||||
<Variable02 className='w-3.5 h-3.5' />
|
||||
<div className='max-w-[50px] ml-0.5 text-xs font-medium truncate' title={varName}>{varName}</div>
|
||||
</div>
|
||||
</div>
|
||||
</span>)
|
||||
})
|
||||
return html
|
||||
})()
|
||||
|
||||
return (
|
||||
<div className='break-all text-xs'>
|
||||
{res}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(ReadonlyInputWithSelectVar)
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import cn from 'classnames'
|
||||
import { Trash03 } from '@/app/components/base/icons/src/vender/line/general'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
onClick: (e: React.MouseEvent) => void
|
||||
}
|
||||
|
||||
const Remove: FC<Props> = ({
|
||||
className,
|
||||
onClick,
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(className, 'p-1 cursor-pointer rounded-md hover:bg-black/5 text-gray-500 hover:text-gray-800')}
|
||||
onClick={onClick}
|
||||
>
|
||||
<Trash03 className='w-4 h-4' />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(Remove)
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Confirm from '@/app/components/base/confirm'
|
||||
|
||||
type Props = {
|
||||
isShow: boolean
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}
|
||||
const i18nPrefix = 'workflow.common.effectVarConfirm'
|
||||
|
||||
const RemoveVarConfirm: FC<Props> = ({
|
||||
isShow,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<Confirm
|
||||
isShow={isShow}
|
||||
title={t(`${i18nPrefix}.title`)}
|
||||
content={t(`${i18nPrefix}.content`)}
|
||||
onConfirm={onConfirm}
|
||||
onCancel={onCancel}
|
||||
onClose={onCancel}
|
||||
/>
|
||||
)
|
||||
}
|
||||
export default React.memo(RemoveVarConfirm)
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useBoolean, useClickAway } from 'ahooks'
|
||||
import cn from 'classnames'
|
||||
import { ChevronSelectorVertical } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
import { Check } from '@/app/components/base/icons/src/vender/line/general'
|
||||
type Item = {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
type Props = {
|
||||
trigger?: JSX.Element
|
||||
DropDownIcon?: any
|
||||
noLeft?: boolean
|
||||
options: Item[]
|
||||
value: string
|
||||
placeholder?: string
|
||||
onChange: (value: any) => void
|
||||
uppercase?: boolean
|
||||
popupClassName?: string
|
||||
triggerClassName?: string
|
||||
itemClassName?: string
|
||||
readonly?: boolean
|
||||
showChecked?: boolean
|
||||
}
|
||||
|
||||
const TypeSelector: FC<Props> = ({
|
||||
trigger,
|
||||
DropDownIcon = ChevronSelectorVertical,
|
||||
noLeft,
|
||||
options: list,
|
||||
value,
|
||||
placeholder = '',
|
||||
onChange,
|
||||
uppercase,
|
||||
triggerClassName,
|
||||
popupClassName,
|
||||
itemClassName,
|
||||
readonly,
|
||||
showChecked,
|
||||
}) => {
|
||||
const noValue = value === '' || value === undefined || value === null
|
||||
const item = list.find(item => item.value === value)
|
||||
const [showOption, { setFalse: setHide, toggle: toggleShow }] = useBoolean(false)
|
||||
const ref = React.useRef(null)
|
||||
useClickAway(() => {
|
||||
setHide()
|
||||
}, ref)
|
||||
return (
|
||||
<div className={cn(!trigger && !noLeft && 'left-[-8px]', 'relative')} ref={ref}>
|
||||
{trigger
|
||||
? (
|
||||
<div
|
||||
onClick={toggleShow}
|
||||
>
|
||||
{trigger}
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<div
|
||||
onClick={toggleShow}
|
||||
className={cn(showOption && 'bg-black/5', 'flex items-center h-5 pl-1 pr-0.5 rounded-md text-xs font-semibold text-gray-700 cursor-pointer hover:bg-black/5')}>
|
||||
<div className={cn(triggerClassName, 'text-sm font-semibold', uppercase && 'uppercase', noValue && 'text-gray-400')}>{!noValue ? item?.label : placeholder}</div>
|
||||
{!readonly && <DropDownIcon className='w-3 h-3 ' />}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(showOption && !readonly) && (
|
||||
<div className={cn(popupClassName, 'absolute z-10 top-[24px] w-[120px] p-1 border border-gray-200 shadow-lg rounded-lg bg-white')}>
|
||||
{list.map(item => (
|
||||
<div
|
||||
key={item.value}
|
||||
onClick={() => {
|
||||
setHide()
|
||||
onChange(item.value)
|
||||
}}
|
||||
className={cn(itemClassName, uppercase && 'uppercase', 'flex items-center h-[30px] justify-between min-w-[44px] px-3 rounded-lg cursor-pointer text-[13px] font-medium text-gray-700 hover:bg-gray-50')}
|
||||
>
|
||||
<div>{item.label}</div>
|
||||
{showChecked && item.value === value && <Check className='text-primary-600 w-4 h-4' />}
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(TypeSelector)
|
||||
18
web/app/components/workflow/nodes/_base/components/split.tsx
Normal file
18
web/app/components/workflow/nodes/_base/components/split.tsx
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import cn from 'classnames'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
}
|
||||
|
||||
const Split: FC<Props> = ({
|
||||
className,
|
||||
}) => {
|
||||
return (
|
||||
<div className={cn(className, 'h-[0.5px] bg-black/5')}>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(Split)
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import cn from 'classnames'
|
||||
import { varHighlightHTML } from '@/app/components/app/configuration/base/var-highlight'
|
||||
type Props = {
|
||||
isFocus?: boolean
|
||||
onFocus?: () => void
|
||||
value: string
|
||||
children?: React.ReactNode
|
||||
wrapClassName?: string
|
||||
textClassName?: string
|
||||
readonly?: boolean
|
||||
}
|
||||
|
||||
const SupportVarInput: FC<Props> = ({
|
||||
isFocus,
|
||||
onFocus,
|
||||
children,
|
||||
value,
|
||||
wrapClassName,
|
||||
textClassName,
|
||||
readonly,
|
||||
}) => {
|
||||
const withHightContent = (value || '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/\{\{([^}]+)\}\}/g, varHighlightHTML({ name: '$1', className: '!mb-0' })) // `<span class="${highLightClassName}">{{$1}}</span>`
|
||||
.replace(/\n/g, '<br />')
|
||||
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
cn(wrapClassName, 'flex w-full h-full')
|
||||
} onClick={onFocus}
|
||||
>
|
||||
{(isFocus && !readonly && children)
|
||||
? (
|
||||
children
|
||||
)
|
||||
: (
|
||||
<div
|
||||
className={cn(textClassName, 'w-0 grow h-full whitespace-nowrap truncate')}
|
||||
title={value}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: withHightContent,
|
||||
}}></div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(SupportVarInput)
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useState,
|
||||
} from 'react'
|
||||
import Textarea from 'rc-textarea'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type TitleInputProps = {
|
||||
value: string
|
||||
onBlur: (value: string) => void
|
||||
}
|
||||
|
||||
export const TitleInput = memo(({
|
||||
value,
|
||||
onBlur,
|
||||
}: TitleInputProps) => {
|
||||
const { t } = useTranslation()
|
||||
const [localValue, setLocalValue] = useState(value)
|
||||
|
||||
const handleBlur = () => {
|
||||
if (!localValue) {
|
||||
setLocalValue(value)
|
||||
onBlur(value)
|
||||
return
|
||||
}
|
||||
|
||||
onBlur(localValue)
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
value={localValue}
|
||||
onChange={e => setLocalValue(e.target.value)}
|
||||
className={`
|
||||
grow mr-2 px-1 h-6 text-base text-gray-900 font-semibold rounded-lg border border-transparent appearance-none outline-none
|
||||
hover:bg-gray-50
|
||||
focus:border-gray-300 focus:shadow-xs focus:bg-white caret-[#295EFF]
|
||||
`}
|
||||
placeholder={t('workflow.common.addTitle') || ''}
|
||||
onBlur={handleBlur}
|
||||
/>
|
||||
)
|
||||
})
|
||||
TitleInput.displayName = 'TitleInput'
|
||||
|
||||
type DescriptionInputProps = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
export const DescriptionInput = memo(({
|
||||
value,
|
||||
onChange,
|
||||
}: DescriptionInputProps) => {
|
||||
const { t } = useTranslation()
|
||||
const [focus, setFocus] = useState(false)
|
||||
const handleFocus = useCallback(() => {
|
||||
setFocus(true)
|
||||
}, [])
|
||||
const handleBlur = useCallback(() => {
|
||||
setFocus(false)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
group flex px-2 py-[5px] max-h-[60px] rounded-lg overflow-y-auto
|
||||
border border-transparent hover:bg-gray-50 leading-0
|
||||
${focus && '!border-gray-300 shadow-xs !bg-gray-50'}
|
||||
`}
|
||||
>
|
||||
<Textarea
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
rows={1}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
className={`
|
||||
w-full text-xs text-gray-900 leading-[18px] bg-transparent
|
||||
appearance-none outline-none resize-none
|
||||
placeholder:text-gray-400 caret-[#295EFF]
|
||||
`}
|
||||
placeholder={t('workflow.common.addDescription') || ''}
|
||||
autoSize
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
DescriptionInput.displayName = 'DescriptionInput'
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { Expand04 } from '@/app/components/base/icons/src/vender/solid/arrows'
|
||||
import { Collapse04 } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
|
||||
type Props = {
|
||||
isExpand: boolean
|
||||
onExpandChange: (isExpand: boolean) => void
|
||||
}
|
||||
|
||||
const ExpandBtn: FC<Props> = ({
|
||||
isExpand,
|
||||
onExpandChange,
|
||||
}) => {
|
||||
const handleToggle = useCallback(() => {
|
||||
onExpandChange(!isExpand)
|
||||
}, [isExpand])
|
||||
|
||||
const Icon = isExpand ? Collapse04 : Expand04
|
||||
return (
|
||||
<Icon className='w-3.5 h-3.5 text-gray-500 cursor-pointer' onClick={handleToggle} />
|
||||
)
|
||||
}
|
||||
export default React.memo(ExpandBtn)
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { OutputVar } from '../../../code/types'
|
||||
import RemoveButton from '../remove-button'
|
||||
import VarTypePicker from './var-type-picker'
|
||||
import type { VarType } from '@/app/components/workflow/types'
|
||||
import { checkKeys } from '@/utils/var'
|
||||
import Toast from '@/app/components/base/toast'
|
||||
|
||||
type Props = {
|
||||
readonly: boolean
|
||||
outputs: OutputVar
|
||||
outputKeyOrders: string[]
|
||||
onChange: (payload: OutputVar, changedIndex?: number, newKey?: string) => void
|
||||
onRemove: (index: number) => void
|
||||
}
|
||||
|
||||
const OutputVarList: FC<Props> = ({
|
||||
readonly,
|
||||
outputs,
|
||||
outputKeyOrders,
|
||||
onChange,
|
||||
onRemove,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const list = outputKeyOrders.map((key) => {
|
||||
return {
|
||||
variable: key,
|
||||
variable_type: outputs[key]?.type,
|
||||
}
|
||||
})
|
||||
const handleVarNameChange = useCallback((index: number) => {
|
||||
return (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const oldKey = list[index].variable
|
||||
const newKey = e.target.value
|
||||
|
||||
const { isValid, errorKey, errorMessageKey } = checkKeys([newKey], true)
|
||||
if (!isValid) {
|
||||
Toast.notify({
|
||||
type: 'error',
|
||||
message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (list.map(item => item.variable?.trim()).includes(newKey.trim())) {
|
||||
Toast.notify({
|
||||
type: 'error',
|
||||
message: t('appDebug.varKeyError.keyAlreadyExists', { key: newKey }),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const newOutputs = produce(outputs, (draft) => {
|
||||
draft[newKey] = draft[oldKey]
|
||||
delete draft[oldKey]
|
||||
})
|
||||
onChange(newOutputs, index, newKey)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [list, onChange, outputs, outputKeyOrders])
|
||||
|
||||
const handleVarTypeChange = useCallback((index: number) => {
|
||||
return (value: string) => {
|
||||
const key = list[index].variable
|
||||
const newOutputs = produce(outputs, (draft) => {
|
||||
draft[key].type = value as VarType
|
||||
})
|
||||
onChange(newOutputs)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [list, onChange, outputs, outputKeyOrders])
|
||||
|
||||
const handleVarRemove = useCallback((index: number) => {
|
||||
return () => {
|
||||
onRemove(index)
|
||||
}
|
||||
}, [onRemove])
|
||||
|
||||
return (
|
||||
<div className='space-y-2'>
|
||||
{list.map((item, index) => (
|
||||
<div className='flex items-center space-x-1' key={index}>
|
||||
<input
|
||||
readOnly={readonly}
|
||||
value={item.variable}
|
||||
onChange={handleVarNameChange(index)}
|
||||
className='w-0 grow h-8 leading-8 px-2.5 rounded-lg border-0 bg-gray-100 text-gray-900 text-[13px] placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200'
|
||||
type='text' />
|
||||
<VarTypePicker
|
||||
readonly={readonly}
|
||||
value={item.variable_type}
|
||||
onChange={handleVarTypeChange(index)}
|
||||
/>
|
||||
<RemoveButton
|
||||
className='!p-2 !bg-gray-100 hover:!bg-gray-200'
|
||||
onClick={handleVarRemove(index)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(OutputVarList)
|
||||
|
|
@ -0,0 +1,542 @@
|
|||
import produce from 'immer'
|
||||
import { isArray, uniq } from 'lodash-es'
|
||||
import type { CodeNodeType } from '../../../code/types'
|
||||
import type { EndNodeType } from '../../../end/types'
|
||||
import type { AnswerNodeType } from '../../../answer/types'
|
||||
import type { LLMNodeType } from '../../../llm/types'
|
||||
import type { KnowledgeRetrievalNodeType } from '../../../knowledge-retrieval/types'
|
||||
import type { IfElseNodeType } from '../../../if-else/types'
|
||||
import type { TemplateTransformNodeType } from '../../../template-transform/types'
|
||||
import type { QuestionClassifierNodeType } from '../../../question-classifier/types'
|
||||
import type { HttpNodeType } from '../../../http/types'
|
||||
import { VarType as ToolVarType } from '../../../tool/types'
|
||||
import type { ToolNodeType } from '../../../tool/types'
|
||||
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
|
||||
import type { StartNodeType } from '@/app/components/workflow/nodes/start/types'
|
||||
import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import type { VariableAssignerNodeType } from '@/app/components/workflow/nodes/variable-assigner/types'
|
||||
import {
|
||||
CHAT_QUESTION_CLASSIFIER_OUTPUT_STRUCT,
|
||||
COMPLETION_QUESTION_CLASSIFIER_OUTPUT_STRUCT,
|
||||
HTTP_REQUEST_OUTPUT_STRUCT,
|
||||
KNOWLEDGE_RETRIEVAL_OUTPUT_STRUCT,
|
||||
LLM_OUTPUT_STRUCT,
|
||||
SUPPORT_OUTPUT_VARS_NODE,
|
||||
TEMPLATE_TRANSFORM_OUTPUT_STRUCT,
|
||||
TOOL_OUTPUT_STRUCT,
|
||||
} from '@/app/components/workflow/constants'
|
||||
import type { PromptItem } from '@/models/debug'
|
||||
import { VAR_REGEX } from '@/config'
|
||||
|
||||
const inputVarTypeToVarType = (type: InputVarType): VarType => {
|
||||
if (type === InputVarType.number)
|
||||
return VarType.number
|
||||
|
||||
return VarType.string
|
||||
}
|
||||
|
||||
const findExceptVarInObject = (obj: any, filterVar: (payload: Var, selector: ValueSelector) => boolean, value_selector: ValueSelector): Var => {
|
||||
const { children } = obj
|
||||
const res: Var = {
|
||||
variable: obj.variable,
|
||||
type: VarType.object,
|
||||
children: children.filter((item: Var) => {
|
||||
const { children } = item
|
||||
const currSelector = [...value_selector, item.variable]
|
||||
if (!children)
|
||||
return filterVar(item, currSelector)
|
||||
|
||||
const obj = findExceptVarInObject(item, filterVar, currSelector)
|
||||
return obj.children && obj.children?.length > 0
|
||||
}),
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
const formatItem = (item: any, isChatMode: boolean, filterVar: (payload: Var, selector: ValueSelector) => boolean): NodeOutPutVar => {
|
||||
const { id, data } = item
|
||||
const res: NodeOutPutVar = {
|
||||
nodeId: id,
|
||||
title: data.title,
|
||||
vars: [],
|
||||
}
|
||||
switch (data.type) {
|
||||
case BlockEnum.Start: {
|
||||
const {
|
||||
variables,
|
||||
} = data as StartNodeType
|
||||
res.vars = variables.map((v) => {
|
||||
return {
|
||||
variable: v.variable,
|
||||
type: inputVarTypeToVarType(v.type),
|
||||
isParagraph: v.type === InputVarType.paragraph,
|
||||
isSelect: v.type === InputVarType.select,
|
||||
options: v.options,
|
||||
required: v.required,
|
||||
}
|
||||
})
|
||||
if (isChatMode) {
|
||||
res.vars.push({
|
||||
variable: 'sys.query',
|
||||
type: VarType.string,
|
||||
})
|
||||
}
|
||||
res.vars.push({
|
||||
variable: 'sys.files',
|
||||
type: VarType.arrayFile,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.LLM: {
|
||||
res.vars = LLM_OUTPUT_STRUCT
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.KnowledgeRetrieval: {
|
||||
res.vars = KNOWLEDGE_RETRIEVAL_OUTPUT_STRUCT
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.Code: {
|
||||
const {
|
||||
outputs,
|
||||
} = data as CodeNodeType
|
||||
res.vars = Object.keys(outputs).map((key) => {
|
||||
return {
|
||||
variable: key,
|
||||
type: outputs[key].type,
|
||||
}
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.TemplateTransform: {
|
||||
res.vars = TEMPLATE_TRANSFORM_OUTPUT_STRUCT
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.QuestionClassifier: {
|
||||
res.vars = isChatMode ? CHAT_QUESTION_CLASSIFIER_OUTPUT_STRUCT : COMPLETION_QUESTION_CLASSIFIER_OUTPUT_STRUCT
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.HttpRequest: {
|
||||
res.vars = HTTP_REQUEST_OUTPUT_STRUCT
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.VariableAssigner: {
|
||||
const {
|
||||
output_type,
|
||||
} = data as VariableAssignerNodeType
|
||||
res.vars = [
|
||||
{
|
||||
variable: 'output',
|
||||
type: output_type,
|
||||
},
|
||||
]
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.Tool: {
|
||||
res.vars = TOOL_OUTPUT_STRUCT
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const selector = [id]
|
||||
res.vars = res.vars.filter((v) => {
|
||||
const { children } = v
|
||||
if (!children)
|
||||
return filterVar(v, selector)
|
||||
|
||||
const obj = findExceptVarInObject(v, filterVar, selector)
|
||||
return obj?.children && obj?.children.length > 0
|
||||
}).map((v) => {
|
||||
const { children } = v
|
||||
if (!children)
|
||||
return v
|
||||
|
||||
return findExceptVarInObject(v, filterVar, selector)
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
export const toNodeOutputVars = (nodes: any[], isChatMode: boolean, filterVar = (_payload: Var, _selector: ValueSelector) => true): NodeOutPutVar[] => {
|
||||
const res = nodes
|
||||
.filter(node => SUPPORT_OUTPUT_VARS_NODE.includes(node.data.type))
|
||||
.map((node) => {
|
||||
return {
|
||||
...formatItem(node, isChatMode, filterVar),
|
||||
isStartNode: node.data.type === BlockEnum.Start,
|
||||
}
|
||||
})
|
||||
.filter(item => item.vars.length > 0)
|
||||
return res
|
||||
}
|
||||
|
||||
export const isSystemVar = (valueSelector: ValueSelector) => {
|
||||
return valueSelector[0] === 'sys' || valueSelector[1] === 'sys'
|
||||
}
|
||||
|
||||
export const getNodeInfoById = (nodes: any, id: string) => {
|
||||
if (!isArray(nodes))
|
||||
return
|
||||
return nodes.find((node: any) => node.id === id)
|
||||
}
|
||||
|
||||
export const getVarType = (value: ValueSelector, availableNodes: any[], isChatMode: boolean): VarType | undefined => {
|
||||
const isSystem = isSystemVar(value)
|
||||
const startNode = availableNodes.find((node: any) => {
|
||||
return node.data.type === BlockEnum.Start
|
||||
})
|
||||
const allOutputVars = toNodeOutputVars(availableNodes, isChatMode)
|
||||
|
||||
const targetVarNodeId = isSystem ? startNode?.id : value[0]
|
||||
const targetVar = allOutputVars.find(v => v.nodeId === targetVarNodeId)
|
||||
|
||||
if (!targetVar)
|
||||
return undefined
|
||||
|
||||
let type: VarType = VarType.string
|
||||
let curr: any = targetVar.vars
|
||||
if (isSystem) {
|
||||
return curr.find((v: any) => v.variable === (value as ValueSelector).join('.'))?.type
|
||||
}
|
||||
else {
|
||||
(value as ValueSelector).slice(1).forEach((key, i) => {
|
||||
const isLast = i === value.length - 2
|
||||
curr = curr.find((v: any) => v.variable === key)
|
||||
if (isLast) {
|
||||
type = curr?.type
|
||||
}
|
||||
else {
|
||||
if (curr.type === VarType.object)
|
||||
curr = curr.children
|
||||
}
|
||||
})
|
||||
return type
|
||||
}
|
||||
}
|
||||
|
||||
const matchNotSystemVars = (prompts: string[]) => {
|
||||
if (!prompts)
|
||||
return []
|
||||
|
||||
const allVars: string[] = []
|
||||
prompts.forEach((prompt) => {
|
||||
VAR_REGEX.lastIndex = 0
|
||||
allVars.push(...(prompt.match(VAR_REGEX) || []))
|
||||
})
|
||||
const uniqVars = uniq(allVars).map(v => v.replaceAll('{{#', '').replace('#}}', '').split('.'))
|
||||
return uniqVars
|
||||
}
|
||||
|
||||
export const getNodeUsedVars = (node: Node): ValueSelector[] => {
|
||||
const { data } = node
|
||||
const { type } = data
|
||||
let res: ValueSelector[] = []
|
||||
switch (type) {
|
||||
case BlockEnum.End: {
|
||||
res = (data as EndNodeType).outputs?.map((output) => {
|
||||
return output.value_selector
|
||||
})
|
||||
break
|
||||
}
|
||||
case BlockEnum.Answer: {
|
||||
res = (data as AnswerNodeType).variables?.map((v) => {
|
||||
return v.value_selector
|
||||
})
|
||||
break
|
||||
}
|
||||
case BlockEnum.LLM: {
|
||||
const payload = (data as LLMNodeType)
|
||||
const isChatModel = payload.model?.mode === 'chat'
|
||||
let prompts: string[] = []
|
||||
if (isChatModel)
|
||||
prompts = (payload.prompt_template as PromptItem[])?.map(p => p.text) || []
|
||||
else
|
||||
prompts = [(payload.prompt_template as PromptItem).text]
|
||||
|
||||
const inputVars: ValueSelector[] = matchNotSystemVars(prompts)
|
||||
const contextVar = (data as LLMNodeType).context?.variable_selector ? [(data as LLMNodeType).context?.variable_selector] : []
|
||||
res = [...inputVars, ...contextVar]
|
||||
break
|
||||
}
|
||||
case BlockEnum.KnowledgeRetrieval: {
|
||||
res = [(data as KnowledgeRetrievalNodeType).query_variable_selector]
|
||||
break
|
||||
}
|
||||
case BlockEnum.IfElse: {
|
||||
res = (data as IfElseNodeType).conditions?.map((c) => {
|
||||
return c.variable_selector
|
||||
})
|
||||
break
|
||||
}
|
||||
case BlockEnum.Code: {
|
||||
res = (data as CodeNodeType).variables?.map((v) => {
|
||||
return v.value_selector
|
||||
})
|
||||
break
|
||||
}
|
||||
case BlockEnum.TemplateTransform: {
|
||||
res = (data as TemplateTransformNodeType).variables?.map((v: any) => {
|
||||
return v.value_selector
|
||||
})
|
||||
break
|
||||
}
|
||||
case BlockEnum.QuestionClassifier: {
|
||||
res = [(data as QuestionClassifierNodeType).query_variable_selector]
|
||||
break
|
||||
}
|
||||
case BlockEnum.HttpRequest: {
|
||||
const payload = (data as HttpNodeType)
|
||||
res = matchNotSystemVars([payload.url, payload.headers, payload.params, payload.body.data])
|
||||
break
|
||||
}
|
||||
case BlockEnum.Tool: {
|
||||
const payload = (data as ToolNodeType)
|
||||
const mixVars = matchNotSystemVars(Object.keys(payload.tool_parameters)?.filter(key => payload.tool_parameters[key].type === ToolVarType.mixed).map(key => payload.tool_parameters[key].value) as string[])
|
||||
const vars = Object.keys(payload.tool_parameters).filter(key => payload.tool_parameters[key].type === ToolVarType.variable).map(key => payload.tool_parameters[key].value as string) || []
|
||||
res = [...(mixVars as ValueSelector[]), ...(vars as any)]
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.VariableAssigner: {
|
||||
res = (data as VariableAssignerNodeType)?.variables
|
||||
}
|
||||
}
|
||||
return res || []
|
||||
}
|
||||
|
||||
export const findUsedVarNodes = (varSelector: ValueSelector, availableNodes: Node[]): Node[] => {
|
||||
const res: Node[] = []
|
||||
availableNodes.forEach((node) => {
|
||||
const vars = getNodeUsedVars(node)
|
||||
if (vars.find(v => v.join('.') === varSelector.join('.')))
|
||||
res.push(node)
|
||||
})
|
||||
return res
|
||||
}
|
||||
|
||||
export const updateNodeVars = (oldNode: Node, oldVarSelector: ValueSelector, newVarSelector: ValueSelector): Node => {
|
||||
const newNode = produce(oldNode, (draft: any) => {
|
||||
const { data } = draft
|
||||
const { type } = data
|
||||
switch (type) {
|
||||
case BlockEnum.End: {
|
||||
const payload = data as EndNodeType
|
||||
if (payload.outputs) {
|
||||
payload.outputs = payload.outputs.map((output) => {
|
||||
if (output.value_selector.join('.') === oldVarSelector.join('.'))
|
||||
output.value_selector = newVarSelector
|
||||
return output
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case BlockEnum.Answer: {
|
||||
const payload = data as AnswerNodeType
|
||||
if (payload.variables) {
|
||||
payload.variables = payload.variables.map((v) => {
|
||||
if (v.value_selector.join('.') === oldVarSelector.join('.'))
|
||||
v.value_selector = newVarSelector
|
||||
return v
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case BlockEnum.LLM: {
|
||||
const payload = data as LLMNodeType
|
||||
// TODO: update in inputs
|
||||
// if (payload.variables) {
|
||||
// payload.variables = payload.variables.map((v) => {
|
||||
// if (v.value_selector.join('.') === oldVarSelector.join('.'))
|
||||
// v.value_selector = newVarSelector
|
||||
// return v
|
||||
// })
|
||||
// }
|
||||
if (payload.context?.variable_selector?.join('.') === oldVarSelector.join('.'))
|
||||
payload.context.variable_selector = newVarSelector
|
||||
|
||||
break
|
||||
}
|
||||
case BlockEnum.KnowledgeRetrieval: {
|
||||
const payload = data as KnowledgeRetrievalNodeType
|
||||
if (payload.query_variable_selector.join('.') === oldVarSelector.join('.'))
|
||||
payload.query_variable_selector = newVarSelector
|
||||
break
|
||||
}
|
||||
case BlockEnum.IfElse: {
|
||||
const payload = data as IfElseNodeType
|
||||
if (payload.conditions) {
|
||||
payload.conditions = payload.conditions.map((c) => {
|
||||
if (c.variable_selector.join('.') === oldVarSelector.join('.'))
|
||||
c.variable_selector = newVarSelector
|
||||
return c
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case BlockEnum.Code: {
|
||||
const payload = data as CodeNodeType
|
||||
if (payload.variables) {
|
||||
payload.variables = payload.variables.map((v) => {
|
||||
if (v.value_selector.join('.') === oldVarSelector.join('.'))
|
||||
v.value_selector = newVarSelector
|
||||
return v
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case BlockEnum.TemplateTransform: {
|
||||
const payload = data as TemplateTransformNodeType
|
||||
if (payload.variables) {
|
||||
payload.variables = payload.variables.map((v: any) => {
|
||||
if (v.value_selector.join('.') === oldVarSelector.join('.'))
|
||||
v.value_selector = newVarSelector
|
||||
return v
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case BlockEnum.QuestionClassifier: {
|
||||
const payload = data as QuestionClassifierNodeType
|
||||
if (payload.query_variable_selector.join('.') === oldVarSelector.join('.'))
|
||||
payload.query_variable_selector = newVarSelector
|
||||
break
|
||||
}
|
||||
case BlockEnum.HttpRequest: {
|
||||
// TODO: update in inputs
|
||||
// const payload = data as HttpNodeType
|
||||
// if (payload.variables) {
|
||||
// payload.variables = payload.variables.map((v) => {
|
||||
// if (v.value_selector.join('.') === oldVarSelector.join('.'))
|
||||
// v.value_selector = newVarSelector
|
||||
// return v
|
||||
// })
|
||||
// }
|
||||
break
|
||||
}
|
||||
case BlockEnum.Tool: {
|
||||
// TODO: update in inputs
|
||||
// const payload = data as ToolNodeType
|
||||
// if (payload.tool_parameters) {
|
||||
// payload.tool_parameters = payload.tool_parameters.map((v) => {
|
||||
// if (v.type === VarKindType.static)
|
||||
// return v
|
||||
|
||||
// if (v.value_selector?.join('.') === oldVarSelector.join('.'))
|
||||
// v.value_selector = newVarSelector
|
||||
// return v
|
||||
// })
|
||||
// }
|
||||
break
|
||||
}
|
||||
case BlockEnum.VariableAssigner: {
|
||||
const payload = data as VariableAssignerNodeType
|
||||
if (payload.variables) {
|
||||
payload.variables = payload.variables.map((v) => {
|
||||
if (v.join('.') === oldVarSelector.join('.'))
|
||||
v = newVarSelector
|
||||
return v
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
return newNode
|
||||
}
|
||||
const varToValueSelectorList = (v: Var, parentValueSelector: ValueSelector, res: ValueSelector[]) => {
|
||||
if (!v.variable)
|
||||
return
|
||||
|
||||
res.push([...parentValueSelector, v.variable])
|
||||
|
||||
if (v.children && v.children.length > 0) {
|
||||
v.children.forEach((child) => {
|
||||
varToValueSelectorList(child, [...parentValueSelector, v.variable], res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const varsToValueSelectorList = (vars: Var | Var[], parentValueSelector: ValueSelector, res: ValueSelector[]) => {
|
||||
if (Array.isArray(vars)) {
|
||||
vars.forEach((v) => {
|
||||
varToValueSelectorList(v, parentValueSelector, res)
|
||||
})
|
||||
}
|
||||
varToValueSelectorList(vars as Var, parentValueSelector, res)
|
||||
}
|
||||
|
||||
export const getNodeOutputVars = (node: Node, isChatMode: boolean): ValueSelector[] => {
|
||||
const { data, id } = node
|
||||
const { type } = data
|
||||
let res: ValueSelector[] = []
|
||||
|
||||
switch (type) {
|
||||
case BlockEnum.Start: {
|
||||
const {
|
||||
variables,
|
||||
} = data as StartNodeType
|
||||
res = variables.map((v) => {
|
||||
return [id, v.variable]
|
||||
})
|
||||
|
||||
if (isChatMode) {
|
||||
res.push([id, 'sys', 'query'])
|
||||
res.push([id, 'sys', 'files'])
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.LLM: {
|
||||
varsToValueSelectorList(LLM_OUTPUT_STRUCT, [id], res)
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.KnowledgeRetrieval: {
|
||||
varsToValueSelectorList(KNOWLEDGE_RETRIEVAL_OUTPUT_STRUCT, [id], res)
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.Code: {
|
||||
const {
|
||||
outputs,
|
||||
} = data as CodeNodeType
|
||||
Object.keys(outputs).forEach((key) => {
|
||||
res.push([id, key])
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.TemplateTransform: {
|
||||
varsToValueSelectorList(TEMPLATE_TRANSFORM_OUTPUT_STRUCT, [id], res)
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.QuestionClassifier: {
|
||||
varsToValueSelectorList(isChatMode ? CHAT_QUESTION_CLASSIFIER_OUTPUT_STRUCT : COMPLETION_QUESTION_CLASSIFIER_OUTPUT_STRUCT, [id], res)
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.HttpRequest: {
|
||||
varsToValueSelectorList(HTTP_REQUEST_OUTPUT_STRUCT, [id], res)
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.VariableAssigner: {
|
||||
res.push([id, 'output'])
|
||||
break
|
||||
}
|
||||
|
||||
case BlockEnum.Tool: {
|
||||
varsToValueSelectorList(TOOL_OUTPUT_STRUCT, [id], res)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import produce from 'immer'
|
||||
import RemoveButton from '../remove-button'
|
||||
import VarReferencePicker from './var-reference-picker'
|
||||
import type { ValueSelector, Var, Variable } from '@/app/components/workflow/types'
|
||||
import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
|
||||
|
||||
type Props = {
|
||||
nodeId: string
|
||||
readonly: boolean
|
||||
list: Variable[]
|
||||
onChange: (list: Variable[]) => void
|
||||
isSupportConstantValue?: boolean
|
||||
onlyLeafNodeVar?: boolean
|
||||
filterVar?: (payload: Var, valueSelector: ValueSelector) => boolean
|
||||
}
|
||||
|
||||
const VarList: FC<Props> = ({
|
||||
nodeId,
|
||||
readonly,
|
||||
list,
|
||||
onChange,
|
||||
isSupportConstantValue,
|
||||
onlyLeafNodeVar,
|
||||
filterVar,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const handleVarNameChange = useCallback((index: number) => {
|
||||
return (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index].variable = e.target.value
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
}, [list, onChange])
|
||||
|
||||
const handleVarReferenceChange = useCallback((index: number) => {
|
||||
return (value: ValueSelector | string, varKindType: VarKindType) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
if (!isSupportConstantValue || varKindType === VarKindType.variable) {
|
||||
draft[index].value_selector = value as ValueSelector
|
||||
if (isSupportConstantValue)
|
||||
draft[index].variable_type = VarKindType.variable
|
||||
|
||||
if (!draft[index].variable)
|
||||
draft[index].variable = value[value.length - 1]
|
||||
}
|
||||
else {
|
||||
draft[index].variable_type = VarKindType.constant
|
||||
draft[index].value_selector = value as ValueSelector
|
||||
draft[index].value = value as string
|
||||
}
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
}, [isSupportConstantValue, list, onChange])
|
||||
|
||||
const handleVarRemove = useCallback((index: number) => {
|
||||
return () => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.splice(index, 1)
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
}, [list, onChange])
|
||||
|
||||
return (
|
||||
<div className='space-y-2'>
|
||||
{list.map((item, index) => (
|
||||
<div className='flex items-center space-x-1' key={index}>
|
||||
<input
|
||||
readOnly={readonly}
|
||||
value={list[index].variable}
|
||||
onChange={handleVarNameChange(index)}
|
||||
placeholder={t('workflow.common.variableNamePlaceholder')!}
|
||||
className='w-[120px] h-8 leading-8 px-2.5 rounded-lg border-0 bg-gray-100 text-gray-900 text-[13px] placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200'
|
||||
type='text'
|
||||
/>
|
||||
<VarReferencePicker
|
||||
nodeId={nodeId}
|
||||
readonly={readonly}
|
||||
isShowNodeName
|
||||
className='grow'
|
||||
value={item.variable_type === VarKindType.constant ? (item.value || '') : (item.value_selector || [])}
|
||||
isSupportConstantValue={isSupportConstantValue}
|
||||
onChange={handleVarReferenceChange(index)}
|
||||
defaultVarKindType={item.variable_type}
|
||||
onlyLeafNodeVar={onlyLeafNodeVar}
|
||||
filterVar={filterVar}
|
||||
/>
|
||||
{!readonly && (
|
||||
<RemoveButton
|
||||
className='!p-2 !bg-gray-100 hover:!bg-gray-200'
|
||||
onClick={handleVarRemove(index)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(VarList)
|
||||
|
|
@ -0,0 +1,292 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import cn from 'classnames'
|
||||
import produce from 'immer'
|
||||
import VarReferencePopup from './var-reference-popup'
|
||||
import { getNodeInfoById, isSystemVar, toNodeOutputVars } from './utils'
|
||||
import type { ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import { VarBlockIcon } from '@/app/components/workflow/block-icon'
|
||||
import { Line3 } from '@/app/components/base/icons/src/public/common'
|
||||
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useWorkflow,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
|
||||
import TypeSelector from '@/app/components/workflow/nodes/_base/components/selector'
|
||||
import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
import { XClose } from '@/app/components/base/icons/src/vender/line/general'
|
||||
|
||||
const TRIGGER_DEFAULT_WIDTH = 227
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
nodeId: string
|
||||
isShowNodeName: boolean
|
||||
readonly: boolean
|
||||
value: ValueSelector | string
|
||||
onChange: (value: ValueSelector | string, varKindType: VarKindType) => void
|
||||
onOpen?: () => void
|
||||
isSupportConstantValue?: boolean
|
||||
defaultVarKindType?: VarKindType
|
||||
onlyLeafNodeVar?: boolean
|
||||
filterVar?: (payload: Var, valueSelector: ValueSelector) => boolean
|
||||
}
|
||||
|
||||
const VarReferencePicker: FC<Props> = ({
|
||||
nodeId,
|
||||
readonly,
|
||||
className,
|
||||
isShowNodeName,
|
||||
value,
|
||||
onOpen = () => { },
|
||||
onChange,
|
||||
isSupportConstantValue,
|
||||
defaultVarKindType = VarKindType.constant,
|
||||
onlyLeafNodeVar,
|
||||
filterVar = () => true,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const triggerRef = useRef<HTMLDivElement>(null)
|
||||
const [triggerWidth, setTriggerWidth] = useState(TRIGGER_DEFAULT_WIDTH)
|
||||
useEffect(() => {
|
||||
if (triggerRef.current)
|
||||
setTriggerWidth(triggerRef.current.clientWidth)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [triggerRef.current])
|
||||
|
||||
const isChatMode = useIsChatMode()
|
||||
const [varKindType, setVarKindType] = useState<VarKindType>(defaultVarKindType)
|
||||
const isConstant = isSupportConstantValue && varKindType === VarKindType.constant
|
||||
const { getTreeLeafNodes, getBeforeNodesInSameBranch } = useWorkflow()
|
||||
const availableNodes = onlyLeafNodeVar ? getTreeLeafNodes(nodeId) : getBeforeNodesInSameBranch(nodeId)
|
||||
const allOutputVars = toNodeOutputVars(availableNodes, isChatMode)
|
||||
const outputVars = toNodeOutputVars(availableNodes, isChatMode, filterVar)
|
||||
const [open, setOpen] = useState(false)
|
||||
useEffect(() => {
|
||||
onOpen()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open])
|
||||
const hasValue = !isConstant && value.length > 0
|
||||
const startNode = availableNodes.find((node: any) => {
|
||||
return node.data.type === BlockEnum.Start
|
||||
})
|
||||
const outputVarNodeId = hasValue ? value[0] : ''
|
||||
const outputVarNode = (() => {
|
||||
if (!hasValue || isConstant)
|
||||
return null
|
||||
if (isSystemVar(value as ValueSelector))
|
||||
return startNode?.data
|
||||
|
||||
return getNodeInfoById(availableNodes, outputVarNodeId)?.data
|
||||
})()
|
||||
const varName = hasValue ? `${isSystemVar(value as ValueSelector) ? 'sys.' : ''}${value[value.length - 1]}` : ''
|
||||
|
||||
const getVarType = () => {
|
||||
if (isConstant)
|
||||
return 'undefined'
|
||||
const isSystem = isSystemVar(value as ValueSelector)
|
||||
const targetVarNodeId = isSystem ? startNode?.id : outputVarNodeId
|
||||
const targetVar = allOutputVars.find(v => v.nodeId === targetVarNodeId)
|
||||
|
||||
if (!targetVar)
|
||||
return 'undefined'
|
||||
|
||||
let type: VarType = VarType.string
|
||||
let curr: any = targetVar.vars
|
||||
if (isSystem) {
|
||||
return curr.find((v: any) => v.variable === (value as ValueSelector).join('.'))?.type
|
||||
}
|
||||
else {
|
||||
(value as ValueSelector).slice(1).forEach((key, i) => {
|
||||
const isLast = i === value.length - 2
|
||||
curr = curr.find((v: any) => v.variable === key)
|
||||
if (isLast) {
|
||||
type = curr?.type
|
||||
}
|
||||
else {
|
||||
if (curr.type === VarType.object)
|
||||
curr = curr.children
|
||||
}
|
||||
})
|
||||
return type
|
||||
}
|
||||
}
|
||||
|
||||
const varKindTypes = [
|
||||
{
|
||||
label: 'Variable',
|
||||
value: VarKindType.variable,
|
||||
},
|
||||
{
|
||||
label: 'Constant',
|
||||
value: VarKindType.constant,
|
||||
},
|
||||
]
|
||||
|
||||
const handleVarKindTypeChange = useCallback((value: VarKindType) => {
|
||||
setVarKindType(value)
|
||||
if (value === VarKindType.constant)
|
||||
onChange('', value)
|
||||
else
|
||||
onChange([], value)
|
||||
}, [onChange])
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [isFocus, setIsFocus] = useState(false)
|
||||
const [controlFocus, setControlFocus] = useState(0)
|
||||
useEffect(() => {
|
||||
if (controlFocus && inputRef.current) {
|
||||
inputRef.current.focus()
|
||||
setIsFocus(true)
|
||||
}
|
||||
}, [controlFocus])
|
||||
|
||||
const handleVarReferenceChange = useCallback((value: ValueSelector) => {
|
||||
// sys var not passed to backend
|
||||
const newValue = produce(value, (draft) => {
|
||||
if (draft[1] && draft[1].startsWith('sys')) {
|
||||
draft.shift()
|
||||
const paths = draft[0].split('.')
|
||||
paths.forEach((p, i) => {
|
||||
draft[i] = p
|
||||
})
|
||||
}
|
||||
})
|
||||
onChange(newValue, varKindType)
|
||||
setOpen(false)
|
||||
}, [onChange, varKindType])
|
||||
|
||||
const handleStaticChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
onChange(e.target.value as string, varKindType)
|
||||
}, [onChange, varKindType])
|
||||
|
||||
const handleClearVar = useCallback(() => {
|
||||
if (varKindType === VarKindType.constant)
|
||||
onChange('', varKindType)
|
||||
else
|
||||
onChange([], varKindType)
|
||||
}, [onChange, varKindType])
|
||||
|
||||
const type = getVarType()
|
||||
// 8(left/right-padding) + 14(icon) + 4 + 14 + 2 = 42 + 17 buff
|
||||
const availableWidth = triggerWidth - 56
|
||||
const [maxNodeNameWidth, maxVarNameWidth, maxTypeWidth] = (() => {
|
||||
const totalTextLength = ((outputVarNode?.title || '') + (varName || '') + (type || '')).length
|
||||
const PRIORITY_WIDTH = 15
|
||||
const maxNodeNameWidth = PRIORITY_WIDTH + Math.floor((outputVarNode?.title?.length || 0) / totalTextLength * availableWidth)
|
||||
const maxVarNameWidth = -PRIORITY_WIDTH + Math.floor((varName?.length || 0) / totalTextLength * availableWidth)
|
||||
const maxTypeWidth = Math.floor((type?.length || 0) / totalTextLength * availableWidth)
|
||||
return [maxNodeNameWidth, maxVarNameWidth, maxTypeWidth]
|
||||
})()
|
||||
|
||||
return (
|
||||
<div className={cn(className, !readonly && 'cursor-pointer')}>
|
||||
<PortalToFollowElem
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
placement='bottom-start'
|
||||
>
|
||||
<PortalToFollowElemTrigger onClick={() => {
|
||||
if (readonly)
|
||||
return
|
||||
!isConstant ? setOpen(!open) : setControlFocus(Date.now())
|
||||
}} className='!flex'>
|
||||
<div ref={triggerRef} className={cn((open || isFocus) ? 'border-gray-300' : 'border-gray-100', 'relative group/wrap flex items-center w-full h-8 p-1 rounded-lg bg-gray-100 border')}>
|
||||
{isSupportConstantValue
|
||||
? <div onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setOpen(false)
|
||||
setControlFocus(Date.now())
|
||||
}} className='mr-1 flex items-center space-x-1'>
|
||||
<TypeSelector
|
||||
noLeft
|
||||
triggerClassName='!text-xs'
|
||||
readonly={readonly}
|
||||
DropDownIcon={ChevronDown}
|
||||
value={varKindType}
|
||||
options={varKindTypes}
|
||||
onChange={handleVarKindTypeChange}
|
||||
/>
|
||||
<div className='h-4 w-px bg-black/5'></div>
|
||||
</div>
|
||||
: (!hasValue && <div className='ml-1.5 mr-1'>
|
||||
<Variable02 className='w-3.5 h-3.5 text-gray-400' />
|
||||
</div>)}
|
||||
{isConstant
|
||||
? (
|
||||
<input
|
||||
type='text'
|
||||
className='w-full h-8 leading-8 pl-0.5 bg-transparent text-[13px] font-normal text-gray-900 placeholder:text-gray-400 focus:outline-none overflow-hidden'
|
||||
value={isConstant ? value : ''}
|
||||
onChange={handleStaticChange}
|
||||
onFocus={() => setIsFocus(true)}
|
||||
onBlur={() => setIsFocus(false)}
|
||||
readOnly={readonly}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<div className={cn('inline-flex h-full items-center px-1.5 rounded-[5px]', hasValue && 'bg-white')}>
|
||||
{hasValue
|
||||
? (
|
||||
<>
|
||||
{isShowNodeName && (
|
||||
<div className='flex items-center'>
|
||||
<div className='p-[1px]'>
|
||||
<VarBlockIcon
|
||||
className='!text-gray-900'
|
||||
type={outputVarNode?.type || BlockEnum.Start}
|
||||
/>
|
||||
</div>
|
||||
<div className='mx-0.5 text-xs font-medium text-gray-700 truncate' title={outputVarNode?.title} style={{
|
||||
maxWidth: maxNodeNameWidth,
|
||||
}}>{outputVarNode?.title}</div>
|
||||
<Line3 className='mr-0.5'></Line3>
|
||||
</div>
|
||||
)}
|
||||
<div className='flex items-center text-primary-600'>
|
||||
{!hasValue && <Variable02 className='w-3.5 h-3.5' />}
|
||||
<div className='ml-0.5 text-xs font-medium truncate' title={varName} style={{
|
||||
maxWidth: maxVarNameWidth,
|
||||
}}>{varName}</div>
|
||||
</div>
|
||||
<div className='ml-0.5 text-xs font-normal text-gray-500 capitalize truncate' title={type} style={{
|
||||
maxWidth: maxTypeWidth,
|
||||
}}>{type}</div>
|
||||
</>
|
||||
)
|
||||
: <div className='text-[13px] font-normal text-gray-400'>{t('workflow.common.setVarValuePlaceholder')}</div>}
|
||||
</div>
|
||||
)}
|
||||
{(hasValue && !readonly) && (<div
|
||||
className='invisible group-hover/wrap:visible absolute h-5 right-1 top-[50%] translate-y-[-50%] group p-1 rounded-md hover:bg-black/5 cursor-pointer'
|
||||
onClick={handleClearVar}
|
||||
>
|
||||
<XClose className='w-3.5 h-3.5 text-gray-500 group-hover:text-gray-800' />
|
||||
</div>)}
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent style={{
|
||||
zIndex: 100,
|
||||
}}>
|
||||
{!isConstant && (
|
||||
<VarReferencePopup
|
||||
vars={outputVars}
|
||||
onChange={handleVarReferenceChange}
|
||||
itemWidth={triggerWidth}
|
||||
/>
|
||||
)}
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
</div >
|
||||
)
|
||||
}
|
||||
export default React.memo(VarReferencePicker)
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import VarReferenceVars from './var-reference-vars'
|
||||
import { type NodeOutPutVar, type ValueSelector } from '@/app/components/workflow/types'
|
||||
|
||||
type Props = {
|
||||
vars: NodeOutPutVar[]
|
||||
onChange: (value: ValueSelector) => void
|
||||
itemWidth?: number
|
||||
}
|
||||
const VarReferencePopup: FC<Props> = ({
|
||||
vars,
|
||||
onChange,
|
||||
itemWidth,
|
||||
}) => {
|
||||
// max-h-[300px] overflow-y-auto todo: use portal to handle long list
|
||||
return (
|
||||
<div className='p-1 bg-white rounded-lg border border-gray-200 shadow-lg space-y-1' style={{
|
||||
width: itemWidth || 228,
|
||||
}}>
|
||||
<VarReferenceVars
|
||||
searchBoxClassName='mt-1'
|
||||
vars={vars}
|
||||
onChange={onChange}
|
||||
itemWidth={itemWidth} />
|
||||
</div >
|
||||
)
|
||||
}
|
||||
export default React.memo(VarReferencePopup)
|
||||
|
|
@ -0,0 +1,296 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { useBoolean, useHover } from 'ahooks'
|
||||
import cn from 'classnames'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { type NodeOutPutVar, type ValueSelector, type Var, VarType } from '@/app/components/workflow/types'
|
||||
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
|
||||
import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import {
|
||||
SearchLg,
|
||||
} from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'
|
||||
import { checkKeys } from '@/utils/var'
|
||||
|
||||
type ObjectChildrenProps = {
|
||||
nodeId: string
|
||||
title: string
|
||||
data: Var[]
|
||||
objPath: string[]
|
||||
onChange: (value: ValueSelector, item: Var) => void
|
||||
onHovering?: (value: boolean) => void
|
||||
itemWidth?: number
|
||||
}
|
||||
|
||||
type ItemProps = {
|
||||
nodeId: string
|
||||
title: string
|
||||
objPath: string[]
|
||||
itemData: Var
|
||||
onChange: (value: ValueSelector, item: Var) => void
|
||||
onHovering?: (value: boolean) => void
|
||||
itemWidth?: number
|
||||
}
|
||||
|
||||
const Item: FC<ItemProps> = ({
|
||||
nodeId,
|
||||
title,
|
||||
objPath,
|
||||
itemData,
|
||||
onChange,
|
||||
onHovering,
|
||||
itemWidth,
|
||||
}) => {
|
||||
const isObj = itemData.type === VarType.object && itemData.children && itemData.children.length > 0
|
||||
const itemRef = useRef(null)
|
||||
const [isItemHovering, setIsItemHovering] = useState(false)
|
||||
const _ = useHover(itemRef, {
|
||||
onChange: (hovering) => {
|
||||
if (hovering) {
|
||||
setIsItemHovering(true)
|
||||
}
|
||||
else {
|
||||
if (isObj) {
|
||||
setTimeout(() => {
|
||||
setIsItemHovering(false)
|
||||
}, 100)
|
||||
}
|
||||
else {
|
||||
setIsItemHovering(false)
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
const [isChildrenHovering, setIsChildrenHovering] = useState(false)
|
||||
const isHovering = isItemHovering || isChildrenHovering
|
||||
const open = isObj && isHovering
|
||||
useEffect(() => {
|
||||
onHovering && onHovering(isHovering)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isHovering])
|
||||
const handleChosen = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (itemData.variable.startsWith('sys.')) { // system variable
|
||||
onChange([...objPath, ...itemData.variable.split('.')], itemData)
|
||||
}
|
||||
else {
|
||||
onChange([nodeId, ...objPath, itemData.variable], itemData)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
open={open}
|
||||
onOpenChange={() => { }}
|
||||
placement='left-start'
|
||||
>
|
||||
<PortalToFollowElemTrigger className='w-full'>
|
||||
<div
|
||||
ref={itemRef}
|
||||
className={cn(
|
||||
isObj ? ' pr-1' : 'pr-[18px]',
|
||||
isHovering && (isObj ? 'bg-primary-50' : 'bg-gray-50'),
|
||||
'relative w-full flex items-center h-6 pl-3 rounded-md cursor-pointer')
|
||||
}
|
||||
// style={{ width: itemWidth || 252 }}
|
||||
onClick={handleChosen}
|
||||
>
|
||||
<div className='flex items-center w-0 grow'>
|
||||
<Variable02 className='shrink-0 w-3.5 h-3.5 text-primary-500' />
|
||||
<div title={itemData.variable} className='ml-1 w-0 grow truncate text-[13px] font-normal text-gray-900'>{itemData.variable}</div>
|
||||
</div>
|
||||
<div className='ml-1 shrink-0 text-xs font-normal text-gray-500 capitalize'>{itemData.type}</div>
|
||||
{isObj && (
|
||||
<ChevronRight className='ml-0.5 w-3 h-3 text-gray-500' />
|
||||
)}
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent style={{
|
||||
zIndex: 100,
|
||||
}}>
|
||||
{isObj && (
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
<ObjectChildren
|
||||
nodeId={nodeId}
|
||||
title={title}
|
||||
objPath={[...objPath, itemData.variable]}
|
||||
data={itemData.children as Var[]}
|
||||
onChange={onChange}
|
||||
onHovering={setIsChildrenHovering}
|
||||
itemWidth={itemWidth}
|
||||
/>
|
||||
)}
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
const ObjectChildren: FC<ObjectChildrenProps> = ({
|
||||
title,
|
||||
nodeId,
|
||||
objPath,
|
||||
data,
|
||||
onChange,
|
||||
onHovering,
|
||||
itemWidth,
|
||||
}) => {
|
||||
const currObjPath = objPath
|
||||
const itemRef = useRef(null)
|
||||
const [isItemHovering, setIsItemHovering] = useState(false)
|
||||
const _ = useHover(itemRef, {
|
||||
onChange: (hovering) => {
|
||||
if (hovering) {
|
||||
setIsItemHovering(true)
|
||||
}
|
||||
else {
|
||||
setTimeout(() => {
|
||||
setIsItemHovering(false)
|
||||
}, 100)
|
||||
}
|
||||
},
|
||||
})
|
||||
const [isChildrenHovering, setIsChildrenHovering] = useState(false)
|
||||
const isHovering = isItemHovering || isChildrenHovering
|
||||
useEffect(() => {
|
||||
onHovering && onHovering(isHovering)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isHovering])
|
||||
useEffect(() => {
|
||||
onHovering && onHovering(isItemHovering)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isItemHovering])
|
||||
// absolute top-[-2px]
|
||||
return (
|
||||
<div ref={itemRef} className=' bg-white rounded-lg border border-gray-200 shadow-lg space-y-1' style={{
|
||||
right: itemWidth ? itemWidth - 10 : 215,
|
||||
minWidth: 252,
|
||||
}}>
|
||||
<div className='flex items-center h-[22px] px-3 text-xs font-normal text-gray-700'><span className='text-gray-500'>{title}.</span>{currObjPath.join('.')}</div>
|
||||
{
|
||||
(data && data.length > 0)
|
||||
&& data.map((v, i) => (
|
||||
<Item
|
||||
key={i}
|
||||
nodeId={nodeId}
|
||||
title={title}
|
||||
objPath={objPath}
|
||||
itemData={v}
|
||||
onChange={onChange}
|
||||
onHovering={setIsChildrenHovering}
|
||||
/>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type Props = {
|
||||
hideSearch?: boolean
|
||||
searchBoxClassName?: string
|
||||
vars: NodeOutPutVar[]
|
||||
onChange: (value: ValueSelector, item: Var) => void
|
||||
itemWidth?: number
|
||||
}
|
||||
const VarReferenceVars: FC<Props> = ({
|
||||
hideSearch,
|
||||
searchBoxClassName,
|
||||
vars,
|
||||
onChange,
|
||||
itemWidth,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const filteredVars = vars.filter((v) => {
|
||||
const children = v.vars.filter(v => checkKeys([v.variable], false).isValid || v.variable.startsWith('sys.'))
|
||||
return children.length > 0
|
||||
}).filter((v) => {
|
||||
if (!searchText)
|
||||
return v
|
||||
const children = v.vars.filter(v => v.variable.toLowerCase().includes(searchText.toLowerCase()))
|
||||
return children.length > 0
|
||||
}).map((v) => {
|
||||
let vars = v.vars.filter(v => checkKeys([v.variable], false).isValid || v.variable.startsWith('sys.'))
|
||||
if (searchText)
|
||||
vars = vars.filter(v => v.variable.toLowerCase().includes(searchText.toLowerCase()))
|
||||
|
||||
return {
|
||||
...v,
|
||||
vars,
|
||||
}
|
||||
})
|
||||
const [isFocus, {
|
||||
setFalse: setBlur,
|
||||
setTrue: setFocus,
|
||||
}] = useBoolean(false)
|
||||
return (
|
||||
<>
|
||||
{
|
||||
!hideSearch && (
|
||||
<>
|
||||
<div
|
||||
className={cn(searchBoxClassName, isFocus && 'shadow-sm bg-white', 'mb-2 mx-1 flex items-center px-2 rounded-lg bg-gray-100 ')}
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
|
||||
<SearchLg className='shrink-0 ml-[1px] mr-[5px] w-3.5 h-3.5 text-gray-400' />
|
||||
<input
|
||||
value={searchText}
|
||||
className='grow px-0.5 py-[7px] text-[13px] text-gray-700 bg-transparent appearance-none outline-none caret-primary-600 placeholder:text-gray-400'
|
||||
placeholder={t('workflow.common.searchVar') || ''}
|
||||
onChange={e => setSearchText(e.target.value)}
|
||||
onFocus={setFocus}
|
||||
onBlur={setBlur}
|
||||
autoFocus
|
||||
/>
|
||||
{
|
||||
searchText && (
|
||||
<div
|
||||
className='flex items-center justify-center ml-[5px] w-[18px] h-[18px] cursor-pointer'
|
||||
onClick={() => setSearchText('')}
|
||||
>
|
||||
<XCircle className='w-[14px] h-[14px] text-gray-400' />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
<div className='h-[0.5px] bg-black/5 relative left-[-4px]' style={{
|
||||
width: 'calc(100% + 8px)',
|
||||
}}></div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
{filteredVars.length > 0
|
||||
? <div>
|
||||
|
||||
{
|
||||
filteredVars.map((item, i) => (
|
||||
<div key={i}>
|
||||
<div
|
||||
className='leading-[22px] px-3 text-xs font-medium text-gray-500 uppercase truncate'
|
||||
title={item.title}
|
||||
>{item.title}</div>
|
||||
{item.vars.map((v, j) => (
|
||||
<Item
|
||||
key={j}
|
||||
title={item.title}
|
||||
nodeId={item.nodeId}
|
||||
objPath={[]}
|
||||
itemData={v}
|
||||
onChange={onChange}
|
||||
itemWidth={itemWidth}
|
||||
/>
|
||||
))}
|
||||
</div>))
|
||||
}
|
||||
</div>
|
||||
: <div className='pl-3 leading-[18px] text-xs font-medium text-gray-500 uppercase'>{t('workflow.common.noVar')}</div>}
|
||||
</ >
|
||||
)
|
||||
}
|
||||
export default React.memo(VarReferenceVars)
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import cn from 'classnames'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import { Check } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
readonly: boolean
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
const TYPES = [VarType.string, VarType.number, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject, VarType.object]
|
||||
const VarReferencePicker: FC<Props> = ({
|
||||
readonly,
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
}) => {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const handleChange = useCallback((type: string) => {
|
||||
return () => {
|
||||
setOpen(false)
|
||||
onChange(type)
|
||||
}
|
||||
}, [onChange])
|
||||
|
||||
return (
|
||||
<div className={cn(className, !readonly && 'cursor-pointer select-none')}>
|
||||
<PortalToFollowElem
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
placement='bottom-start'
|
||||
offset={4}
|
||||
>
|
||||
<PortalToFollowElemTrigger onClick={() => setOpen(!open)} className='w-[120px] cursor-pointer'>
|
||||
<div className='flex items-center h-8 justify-between px-2.5 rounded-lg border-0 bg-gray-100 text-gray-900 text-[13px]'>
|
||||
<div className='capitalize grow w-0 truncate' title={value}>{value}</div>
|
||||
<ChevronDown className='shrink-0 w-3.5 h-3.5 text-gray-700' />
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent style={{
|
||||
zIndex: 100,
|
||||
}}>
|
||||
<div className='w-[120px] p-1 bg-white rounded-lg shadow-sm'>
|
||||
{TYPES.map(type => (
|
||||
<div
|
||||
key={type}
|
||||
className='flex items-center h-[30px] justify-between pl-3 pr-2 rounded-lg hover:bg-gray-100 text-gray-900 text-[13px] cursor-pointer'
|
||||
onClick={handleChange(type)}
|
||||
>
|
||||
<div className='w-0 grow capitalize truncate'>{type}</div>
|
||||
{type === value && <Check className='shrink-0 w-4 h-4 text-primary-600' />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(VarReferencePicker)
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import {
|
||||
useIsChatMode,
|
||||
useWorkflow,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import { toNodeOutputVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'
|
||||
import type { ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
|
||||
type Params = {
|
||||
onlyLeafNodeVar?: boolean
|
||||
filterVar: (payload: Var, selector: ValueSelector) => boolean
|
||||
}
|
||||
const useAvailableVarList = (nodeId: string, {
|
||||
onlyLeafNodeVar,
|
||||
filterVar,
|
||||
}: Params = {
|
||||
onlyLeafNodeVar: false,
|
||||
filterVar: () => true,
|
||||
}) => {
|
||||
const { getTreeLeafNodes, getBeforeNodesInSameBranch } = useWorkflow()
|
||||
const isChatMode = useIsChatMode()
|
||||
|
||||
const availableNodes = onlyLeafNodeVar ? getTreeLeafNodes(nodeId) : getBeforeNodesInSameBranch(nodeId)
|
||||
const availableVars = toNodeOutputVars(availableNodes, isChatMode, filterVar)
|
||||
return {
|
||||
availableVars,
|
||||
availableNodes,
|
||||
}
|
||||
}
|
||||
|
||||
export default useAvailableVarList
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import { useNodeDataUpdate } from '@/app/components/workflow/hooks'
|
||||
import type { CommonNodeType } from '@/app/components/workflow/types'
|
||||
const useNodeCrud = <T>(id: string, data: CommonNodeType<T>) => {
|
||||
const { handleNodeDataUpdateWithSyncDraft } = useNodeDataUpdate()
|
||||
|
||||
const setInputs = (newInputs: CommonNodeType<T>) => {
|
||||
handleNodeDataUpdateWithSyncDraft({
|
||||
id,
|
||||
data: newInputs,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
inputs: data,
|
||||
setInputs,
|
||||
}
|
||||
}
|
||||
|
||||
export default useNodeCrud
|
||||
|
|
@ -0,0 +1,275 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { unionBy } from 'lodash-es'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useNodeDataUpdate,
|
||||
useWorkflow,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import { getNodeInfoById, isSystemVar, toNodeOutputVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'
|
||||
|
||||
import type { CommonNodeType, InputVar, ValueSelector, Var, Variable } from '@/app/components/workflow/types'
|
||||
import { BlockEnum, InputVarType, NodeRunningStatus, VarType } from '@/app/components/workflow/types'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import { singleNodeRun } from '@/service/workflow'
|
||||
import Toast from '@/app/components/base/toast'
|
||||
import LLMDefault from '@/app/components/workflow/nodes/llm/default'
|
||||
import KnowledgeRetrievalDefault from '@/app/components/workflow/nodes/knowledge-retrieval/default'
|
||||
import IfElseDefault from '@/app/components/workflow/nodes/if-else/default'
|
||||
import CodeDefault from '@/app/components/workflow/nodes/code/default'
|
||||
import TemplateTransformDefault from '@/app/components/workflow/nodes/template-transform/default'
|
||||
import QuestionClassifyDefault from '@/app/components/workflow/nodes/question-classifier/default'
|
||||
import HTTPDefault from '@/app/components/workflow/nodes/http/default'
|
||||
import ToolDefault from '@/app/components/workflow/nodes/tool/default'
|
||||
import VariableAssigner from '@/app/components/workflow/nodes/variable-assigner/default'
|
||||
import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'
|
||||
const { checkValid: checkLLMValid } = LLMDefault
|
||||
const { checkValid: checkKnowledgeRetrievalValid } = KnowledgeRetrievalDefault
|
||||
const { checkValid: checkIfElseValid } = IfElseDefault
|
||||
const { checkValid: checkCodeValid } = CodeDefault
|
||||
const { checkValid: checkTemplateTransformValid } = TemplateTransformDefault
|
||||
const { checkValid: checkQuestionClassifyValid } = QuestionClassifyDefault
|
||||
const { checkValid: checkHttpValid } = HTTPDefault
|
||||
const { checkValid: checkToolValid } = ToolDefault
|
||||
const { checkValid: checkVariableAssignerValid } = VariableAssigner
|
||||
|
||||
const checkValidFns: Record<BlockEnum, Function> = {
|
||||
[BlockEnum.LLM]: checkLLMValid,
|
||||
[BlockEnum.KnowledgeRetrieval]: checkKnowledgeRetrievalValid,
|
||||
[BlockEnum.IfElse]: checkIfElseValid,
|
||||
[BlockEnum.Code]: checkCodeValid,
|
||||
[BlockEnum.TemplateTransform]: checkTemplateTransformValid,
|
||||
[BlockEnum.QuestionClassifier]: checkQuestionClassifyValid,
|
||||
[BlockEnum.HttpRequest]: checkHttpValid,
|
||||
[BlockEnum.Tool]: checkToolValid,
|
||||
[BlockEnum.VariableAssigner]: checkVariableAssignerValid,
|
||||
} as any
|
||||
|
||||
type Params<T> = {
|
||||
id: string
|
||||
data: CommonNodeType<T>
|
||||
defaultRunInputData: Record<string, any>
|
||||
moreDataForCheckValid?: any
|
||||
}
|
||||
|
||||
const varTypeToInputVarType = (type: VarType, {
|
||||
isSelect,
|
||||
isParagraph,
|
||||
}: {
|
||||
isSelect: boolean
|
||||
isParagraph: boolean
|
||||
}) => {
|
||||
if (isSelect)
|
||||
return InputVarType.select
|
||||
if (isParagraph)
|
||||
return InputVarType.paragraph
|
||||
if (type === VarType.number)
|
||||
return InputVarType.number
|
||||
if ([VarType.object, VarType.array, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject].includes(type))
|
||||
return InputVarType.json
|
||||
if (type === VarType.arrayFile)
|
||||
return InputVarType.files
|
||||
|
||||
return InputVarType.textInput
|
||||
}
|
||||
|
||||
const useOneStepRun = <T>({
|
||||
id,
|
||||
data,
|
||||
defaultRunInputData,
|
||||
moreDataForCheckValid,
|
||||
}: Params<T>) => {
|
||||
const { t } = useTranslation()
|
||||
const { getBeforeNodesInSameBranch } = useWorkflow() as any
|
||||
const isChatMode = useIsChatMode()
|
||||
|
||||
const availableNodes = getBeforeNodesInSameBranch(id)
|
||||
const allOutputVars = toNodeOutputVars(getBeforeNodesInSameBranch(id), isChatMode)
|
||||
const getVar = (valueSelector: ValueSelector): Var | undefined => {
|
||||
let res: Var | undefined
|
||||
const isSystem = valueSelector[0] === 'sys'
|
||||
const targetVar = isSystem ? allOutputVars.find(item => !!item.isStartNode) : allOutputVars.find(v => v.nodeId === valueSelector[0])
|
||||
if (!targetVar)
|
||||
return undefined
|
||||
if (isSystem)
|
||||
return targetVar.vars.find(item => item.variable.split('.')[1] === valueSelector[1])
|
||||
|
||||
let curr: any = targetVar.vars
|
||||
valueSelector.slice(1).forEach((key, i) => {
|
||||
const isLast = i === valueSelector.length - 2
|
||||
curr = curr.find((v: any) => v.variable === key)
|
||||
if (isLast) {
|
||||
res = curr
|
||||
}
|
||||
else {
|
||||
if (curr.type === VarType.object)
|
||||
curr = curr.children
|
||||
}
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
const checkValid = checkValidFns[data.type]
|
||||
const appId = useAppStore.getState().appDetail?.id
|
||||
const [runInputData, setRunInputData] = useState<Record<string, any>>(defaultRunInputData || {})
|
||||
const [runResult, setRunResult] = useState<any>(null)
|
||||
|
||||
const { handleNodeDataUpdate }: { handleNodeDataUpdate: (data: any) => void } = useNodeDataUpdate()
|
||||
const [canShowSingleRun, setCanShowSingleRun] = useState(false)
|
||||
const isShowSingleRun = data._isSingleRun && canShowSingleRun
|
||||
useEffect(() => {
|
||||
if (!checkValid) {
|
||||
setCanShowSingleRun(true)
|
||||
return
|
||||
}
|
||||
|
||||
if (data._isSingleRun) {
|
||||
const { isValid, errorMessage } = checkValid(data, t, moreDataForCheckValid)
|
||||
setCanShowSingleRun(isValid)
|
||||
if (!isValid) {
|
||||
handleNodeDataUpdate({
|
||||
id,
|
||||
data: {
|
||||
...data,
|
||||
_isSingleRun: false,
|
||||
},
|
||||
})
|
||||
Toast.notify({
|
||||
type: 'error',
|
||||
message: errorMessage,
|
||||
})
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data._isSingleRun])
|
||||
const hideSingleRun = () => {
|
||||
handleNodeDataUpdate({
|
||||
id,
|
||||
data: {
|
||||
...data,
|
||||
_isSingleRun: false,
|
||||
},
|
||||
})
|
||||
}
|
||||
const runningStatus = data._singleRunningStatus || NodeRunningStatus.NotStart
|
||||
const isCompleted = runningStatus === NodeRunningStatus.Succeeded || runningStatus === NodeRunningStatus.Failed
|
||||
|
||||
const handleRun = async (submitData: Record<string, any>) => {
|
||||
handleNodeDataUpdate({
|
||||
id,
|
||||
data: {
|
||||
...data,
|
||||
_singleRunningStatus: NodeRunningStatus.Running,
|
||||
},
|
||||
})
|
||||
let res: any
|
||||
try {
|
||||
res = await singleNodeRun(appId!, id, { inputs: submitData }) as any
|
||||
if (res.error)
|
||||
throw new Error(res.error)
|
||||
}
|
||||
catch (e: any) {
|
||||
handleNodeDataUpdate({
|
||||
id,
|
||||
data: {
|
||||
...data,
|
||||
_singleRunningStatus: NodeRunningStatus.Failed,
|
||||
},
|
||||
})
|
||||
return false
|
||||
}
|
||||
finally {
|
||||
setRunResult({
|
||||
...res,
|
||||
created_by: res.created_by_account?.name || '',
|
||||
})
|
||||
}
|
||||
handleNodeDataUpdate({
|
||||
id,
|
||||
data: {
|
||||
...data,
|
||||
_singleRunningStatus: NodeRunningStatus.Succeeded,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const handleStop = () => {
|
||||
handleNodeDataUpdate({
|
||||
id,
|
||||
data: {
|
||||
...data,
|
||||
_singleRunningStatus: NodeRunningStatus.NotStart,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const toVarInputs = (variables: Variable[]): InputVar[] => {
|
||||
if (!variables)
|
||||
return []
|
||||
|
||||
const varInputs = variables.map((item) => {
|
||||
const originalVar = getVar(item.value_selector)
|
||||
if (!originalVar) {
|
||||
return {
|
||||
label: item.label || item.variable,
|
||||
variable: item.variable,
|
||||
type: InputVarType.textInput,
|
||||
required: true,
|
||||
}
|
||||
}
|
||||
return {
|
||||
label: item.label || item.variable,
|
||||
variable: item.variable,
|
||||
type: varTypeToInputVarType(originalVar.type, {
|
||||
isSelect: !!originalVar.isSelect,
|
||||
isParagraph: !!originalVar.isParagraph,
|
||||
}),
|
||||
required: item.required !== false,
|
||||
options: originalVar.options,
|
||||
}
|
||||
})
|
||||
|
||||
return varInputs
|
||||
}
|
||||
|
||||
const getInputVars = (textList: string[]) => {
|
||||
const valueSelectors: ValueSelector[] = []
|
||||
textList.forEach((text) => {
|
||||
valueSelectors.push(...doGetInputVars(text))
|
||||
})
|
||||
|
||||
const variables = unionBy(valueSelectors, item => item.join('.')).map((item) => {
|
||||
const varInfo = getNodeInfoById(availableNodes, item[0])?.data
|
||||
|
||||
return {
|
||||
label: {
|
||||
nodeType: varInfo?.type,
|
||||
nodeName: varInfo?.title || availableNodes[0]?.data.title, // default start node title
|
||||
variable: isSystemVar(item) ? item.join('.') : item[item.length - 1],
|
||||
},
|
||||
variable: `#${item.join('.')}#`,
|
||||
value_selector: item,
|
||||
}
|
||||
})
|
||||
|
||||
const varInputs = toVarInputs(variables)
|
||||
return varInputs
|
||||
}
|
||||
|
||||
return {
|
||||
isShowSingleRun,
|
||||
hideSingleRun,
|
||||
toVarInputs,
|
||||
getInputVars,
|
||||
runningStatus,
|
||||
isCompleted,
|
||||
handleRun,
|
||||
handleStop,
|
||||
runInputData,
|
||||
setRunInputData,
|
||||
runResult,
|
||||
}
|
||||
}
|
||||
|
||||
export default useOneStepRun
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
import { useCallback, useState } from 'react'
|
||||
import produce from 'immer'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import { type OutputVar } from '../../code/types'
|
||||
import type { ValueSelector } from '@/app/components/workflow/types'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import {
|
||||
useWorkflow,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
|
||||
type Params<T> = {
|
||||
id: string
|
||||
inputs: T
|
||||
setInputs: (newInputs: T) => void
|
||||
varKey?: string
|
||||
outputKeyOrders: string[]
|
||||
onOutputKeyOrdersChange: (newOutputKeyOrders: string[]) => void
|
||||
}
|
||||
function useOutputVarList<T>({
|
||||
id,
|
||||
inputs,
|
||||
setInputs,
|
||||
varKey = 'outputs',
|
||||
outputKeyOrders = [],
|
||||
onOutputKeyOrdersChange,
|
||||
}: Params<T>) {
|
||||
const { handleOutVarRenameChange, isVarUsedInNodes, removeUsedVarInNodes } = useWorkflow()
|
||||
|
||||
const handleVarsChange = useCallback((newVars: OutputVar, changedIndex?: number, newKey?: string) => {
|
||||
const newInputs = produce(inputs, (draft: any) => {
|
||||
draft[varKey] = newVars
|
||||
})
|
||||
setInputs(newInputs)
|
||||
|
||||
if (changedIndex !== undefined) {
|
||||
const newOutputKeyOrders = produce(outputKeyOrders, (draft) => {
|
||||
draft[changedIndex] = newKey!
|
||||
})
|
||||
onOutputKeyOrdersChange(newOutputKeyOrders)
|
||||
}
|
||||
|
||||
if (newKey)
|
||||
handleOutVarRenameChange(id, [id, outputKeyOrders[changedIndex!]], [id, newKey])
|
||||
}, [inputs, setInputs, handleOutVarRenameChange, id, outputKeyOrders, varKey, onOutputKeyOrdersChange])
|
||||
|
||||
const handleAddVariable = useCallback(() => {
|
||||
const newKey = `var_${Object.keys((inputs as any)[varKey]).length + 1}`
|
||||
const newInputs = produce(inputs, (draft: any) => {
|
||||
draft[varKey] = {
|
||||
...draft[varKey],
|
||||
[newKey]: {
|
||||
type: VarType.string,
|
||||
children: null,
|
||||
},
|
||||
}
|
||||
})
|
||||
setInputs(newInputs)
|
||||
onOutputKeyOrdersChange([...outputKeyOrders, newKey])
|
||||
}, [inputs, setInputs, varKey, outputKeyOrders, onOutputKeyOrdersChange])
|
||||
|
||||
const [isShowRemoveVarConfirm, {
|
||||
setTrue: showRemoveVarConfirm,
|
||||
setFalse: hideRemoveVarConfirm,
|
||||
}] = useBoolean(false)
|
||||
const [removedVar, setRemovedVar] = useState<ValueSelector>([])
|
||||
const removeVarInNode = useCallback(() => {
|
||||
removeUsedVarInNodes(removedVar)
|
||||
hideRemoveVarConfirm()
|
||||
}, [hideRemoveVarConfirm, removeUsedVarInNodes, removedVar])
|
||||
const handleRemoveVariable = useCallback((index: number) => {
|
||||
const key = outputKeyOrders[index]
|
||||
|
||||
if (isVarUsedInNodes([id, key])) {
|
||||
showRemoveVarConfirm()
|
||||
setRemovedVar([id, key])
|
||||
return
|
||||
}
|
||||
|
||||
const newInputs = produce(inputs, (draft: any) => {
|
||||
delete draft[varKey][key]
|
||||
})
|
||||
setInputs(newInputs)
|
||||
onOutputKeyOrdersChange(outputKeyOrders.filter((_, i) => i !== index))
|
||||
}, [outputKeyOrders, isVarUsedInNodes, id, inputs, setInputs, onOutputKeyOrdersChange, showRemoveVarConfirm, varKey])
|
||||
|
||||
return {
|
||||
handleVarsChange,
|
||||
handleAddVariable,
|
||||
handleRemoveVariable,
|
||||
isShowRemoveVarConfirm,
|
||||
hideRemoveVarConfirm,
|
||||
onRemoveVarConfirm: removeVarInNode,
|
||||
}
|
||||
}
|
||||
|
||||
export default useOutputVarList
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
|
||||
export type UseResizePanelPrarams = {
|
||||
direction?: 'horizontal' | 'vertical' | 'both'
|
||||
triggerDirection?: 'top' | 'right' | 'bottom' | 'left' | 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'
|
||||
minWidth?: number
|
||||
maxWidth?: number
|
||||
minHeight?: number
|
||||
maxHeight?: number
|
||||
onResized?: (width: number, height: number) => void
|
||||
}
|
||||
export const useResizePanel = (params?: UseResizePanelPrarams) => {
|
||||
const {
|
||||
direction = 'both',
|
||||
triggerDirection = 'bottom-right',
|
||||
minWidth = -Infinity,
|
||||
maxWidth = Infinity,
|
||||
minHeight = -Infinity,
|
||||
maxHeight = Infinity,
|
||||
onResized,
|
||||
} = params || {}
|
||||
const triggerRef = useRef<HTMLDivElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const initXRef = useRef(0)
|
||||
const initYRef = useRef(0)
|
||||
const initContainerWidthRef = useRef(0)
|
||||
const initContainerHeightRef = useRef(0)
|
||||
const isResizingRef = useRef(false)
|
||||
const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(getComputedStyle(document.body).userSelect)
|
||||
|
||||
const handleStartResize = useCallback((e: MouseEvent) => {
|
||||
initXRef.current = e.clientX
|
||||
initYRef.current = e.clientY
|
||||
initContainerWidthRef.current = containerRef.current?.offsetWidth || minWidth
|
||||
initContainerHeightRef.current = containerRef.current?.offsetHeight || minHeight
|
||||
isResizingRef.current = true
|
||||
setPrevUserSelectStyle(getComputedStyle(document.body).userSelect)
|
||||
document.body.style.userSelect = 'none'
|
||||
}, [minWidth, minHeight])
|
||||
|
||||
const handleResize = useCallback((e: MouseEvent) => {
|
||||
if (!isResizingRef.current)
|
||||
return
|
||||
|
||||
if (!containerRef.current)
|
||||
return
|
||||
|
||||
if (direction === 'horizontal' || direction === 'both') {
|
||||
const offsetX = e.clientX - initXRef.current
|
||||
let width = 0
|
||||
if (triggerDirection === 'left' || triggerDirection === 'top-left' || triggerDirection === 'bottom-left')
|
||||
width = initContainerWidthRef.current - offsetX
|
||||
else if (triggerDirection === 'right' || triggerDirection === 'top-right' || triggerDirection === 'bottom-right')
|
||||
width = initContainerWidthRef.current + offsetX
|
||||
|
||||
if (width < minWidth)
|
||||
width = minWidth
|
||||
if (width > maxWidth)
|
||||
width = maxWidth
|
||||
containerRef.current.style.width = `${width}px`
|
||||
}
|
||||
|
||||
if (direction === 'vertical' || direction === 'both') {
|
||||
const offsetY = e.clientY - initYRef.current
|
||||
let height = 0
|
||||
if (triggerDirection === 'top' || triggerDirection === 'top-left' || triggerDirection === 'top-right')
|
||||
height = initContainerHeightRef.current - offsetY
|
||||
else if (triggerDirection === 'bottom' || triggerDirection === 'bottom-left' || triggerDirection === 'bottom-right')
|
||||
height = initContainerHeightRef.current + offsetY
|
||||
|
||||
if (height < minHeight)
|
||||
height = minHeight
|
||||
if (height > maxHeight)
|
||||
height = maxHeight
|
||||
|
||||
containerRef.current.style.height = `${height}px`
|
||||
}
|
||||
}, [
|
||||
direction,
|
||||
triggerDirection,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
minHeight,
|
||||
maxHeight,
|
||||
])
|
||||
|
||||
const handleStopResize = useCallback(() => {
|
||||
isResizingRef.current = false
|
||||
document.body.style.userSelect = prevUserSelectStyle
|
||||
|
||||
if (onResized && containerRef.current)
|
||||
onResized(containerRef.current.offsetWidth, containerRef.current.offsetHeight)
|
||||
}, [prevUserSelectStyle, onResized])
|
||||
|
||||
useEffect(() => {
|
||||
const element = triggerRef.current
|
||||
element?.addEventListener('mousedown', handleStartResize)
|
||||
document.addEventListener('mousemove', handleResize)
|
||||
document.addEventListener('mouseup', handleStopResize)
|
||||
return () => {
|
||||
if (element)
|
||||
element.removeEventListener('mousedown', handleStartResize)
|
||||
document.removeEventListener('mousemove', handleResize)
|
||||
}
|
||||
}, [handleStartResize, handleResize, handleStopResize])
|
||||
|
||||
return {
|
||||
triggerRef,
|
||||
containerRef,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
|
||||
type Params = {
|
||||
ref: React.RefObject<HTMLDivElement>
|
||||
hasFooter?: boolean
|
||||
}
|
||||
|
||||
const useToggleExpend = ({ ref, hasFooter = true }: Params) => {
|
||||
const [isExpand, setIsExpand] = useState(false)
|
||||
const [wrapHeight, setWrapHeight] = useState(ref.current?.clientHeight)
|
||||
const editorExpandHeight = isExpand ? wrapHeight! - (hasFooter ? 56 : 29) : 0
|
||||
useEffect(() => {
|
||||
setWrapHeight(ref.current?.clientHeight)
|
||||
}, [isExpand])
|
||||
|
||||
const wrapClassName = isExpand && 'absolute z-10 left-4 right-6 top-[52px] bottom-0 pb-4 bg-white'
|
||||
|
||||
return {
|
||||
wrapClassName,
|
||||
editorExpandHeight,
|
||||
isExpand,
|
||||
setIsExpand,
|
||||
}
|
||||
}
|
||||
|
||||
export default useToggleExpend
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import type { Variable } from '@/app/components/workflow/types'
|
||||
|
||||
type Params<T> = {
|
||||
inputs: T
|
||||
setInputs: (newInputs: T) => void
|
||||
varKey?: string
|
||||
}
|
||||
function useVarList<T>({
|
||||
inputs,
|
||||
setInputs,
|
||||
varKey = 'variables',
|
||||
}: Params<T>) {
|
||||
const handleVarListChange = useCallback((newList: Variable[] | string) => {
|
||||
const newInputs = produce(inputs, (draft: any) => {
|
||||
draft[varKey] = newList as Variable[]
|
||||
})
|
||||
setInputs(newInputs)
|
||||
}, [inputs, setInputs, varKey])
|
||||
|
||||
const handleAddVariable = useCallback(() => {
|
||||
const newInputs = produce(inputs, (draft: any) => {
|
||||
draft[varKey].push({
|
||||
variable: '',
|
||||
value_selector: [],
|
||||
})
|
||||
})
|
||||
setInputs(newInputs)
|
||||
}, [inputs, setInputs, varKey])
|
||||
return {
|
||||
handleVarListChange,
|
||||
handleAddVariable,
|
||||
}
|
||||
}
|
||||
|
||||
export default useVarList
|
||||
130
web/app/components/workflow/nodes/_base/node.tsx
Normal file
130
web/app/components/workflow/nodes/_base/node.tsx
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
import type {
|
||||
FC,
|
||||
ReactElement,
|
||||
} from 'react'
|
||||
import {
|
||||
cloneElement,
|
||||
memo,
|
||||
} from 'react'
|
||||
import type { NodeProps } from '../../types'
|
||||
import {
|
||||
BlockEnum,
|
||||
NodeRunningStatus,
|
||||
} from '../../types'
|
||||
import {
|
||||
useNodesReadOnly,
|
||||
useToolIcon,
|
||||
} from '../../hooks'
|
||||
import {
|
||||
NodeSourceHandle,
|
||||
NodeTargetHandle,
|
||||
} from './components/node-handle'
|
||||
import NodeControl from './components/node-control'
|
||||
import BlockIcon from '@/app/components/workflow/block-icon'
|
||||
import {
|
||||
CheckCircle,
|
||||
Loading02,
|
||||
} from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { AlertCircle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'
|
||||
|
||||
type BaseNodeProps = {
|
||||
children: ReactElement
|
||||
} & NodeProps
|
||||
|
||||
const BaseNode: FC<BaseNodeProps> = ({
|
||||
id,
|
||||
data,
|
||||
children,
|
||||
}) => {
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const toolIcon = useToolIcon(data)
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
flex border-[2px] rounded-2xl
|
||||
${(data.selected && !data._runningStatus && !data._isInvalidConnection) ? 'border-primary-600' : 'border-transparent'}
|
||||
`}
|
||||
>
|
||||
<div
|
||||
className={`
|
||||
group relative pb-1 w-[240px] bg-[#fcfdff] shadow-xs
|
||||
border border-transparent rounded-[15px]
|
||||
${!data._runningStatus && 'hover:shadow-lg'}
|
||||
${data._runningStatus === NodeRunningStatus.Running && '!border-primary-500'}
|
||||
${data._runningStatus === NodeRunningStatus.Succeeded && '!border-[#12B76A]'}
|
||||
${data._runningStatus === NodeRunningStatus.Failed && '!border-[#F04438]'}
|
||||
${data._runningStatus === NodeRunningStatus.Waiting && 'opacity-70'}
|
||||
${data._isInvalidConnection && '!border-[#F04438]'}
|
||||
`}
|
||||
>
|
||||
{
|
||||
data.type !== BlockEnum.VariableAssigner && !data._runningStatus && !nodesReadOnly && (
|
||||
<NodeTargetHandle
|
||||
id={id}
|
||||
data={data}
|
||||
handleClassName='!top-4 !-left-[9px] !translate-y-0'
|
||||
handleId='target'
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
data.type !== BlockEnum.IfElse && data.type !== BlockEnum.QuestionClassifier && !data._runningStatus && !nodesReadOnly && (
|
||||
<NodeSourceHandle
|
||||
id={id}
|
||||
data={data}
|
||||
handleClassName='!top-4 !-right-[9px] !translate-y-0'
|
||||
handleId='source'
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
!data._runningStatus && !nodesReadOnly && (
|
||||
<NodeControl
|
||||
id={id}
|
||||
data={data}
|
||||
/>
|
||||
)
|
||||
}
|
||||
<div className='flex items-center px-3 pt-3 pb-2'>
|
||||
<BlockIcon
|
||||
className='shrink-0 mr-2'
|
||||
type={data.type}
|
||||
size='md'
|
||||
toolIcon={toolIcon}
|
||||
/>
|
||||
<div
|
||||
title={data.title}
|
||||
className='grow mr-1 text-[13px] font-semibold text-gray-700 truncate'
|
||||
>
|
||||
{data.title}
|
||||
</div>
|
||||
{
|
||||
(data._runningStatus === NodeRunningStatus.Running || data._singleRunningStatus === NodeRunningStatus.Running) && (
|
||||
<Loading02 className='w-3.5 h-3.5 text-primary-600 animate-spin' />
|
||||
)
|
||||
}
|
||||
{
|
||||
data._runningStatus === NodeRunningStatus.Succeeded && (
|
||||
<CheckCircle className='w-3.5 h-3.5 text-[#12B76A]' />
|
||||
)
|
||||
}
|
||||
{
|
||||
data._runningStatus === NodeRunningStatus.Failed && (
|
||||
<AlertCircle className='w-3.5 h-3.5 text-[#F04438]' />
|
||||
)
|
||||
}
|
||||
</div>
|
||||
{cloneElement(children, { id, data })}
|
||||
{
|
||||
data.desc && (
|
||||
<div className='px-3 pt-1 pb-2 text-xs leading-[18px] text-gray-500 whitespace-pre-line break-words'>
|
||||
{data.desc}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(BaseNode)
|
||||
162
web/app/components/workflow/nodes/_base/panel.tsx
Normal file
162
web/app/components/workflow/nodes/_base/panel.tsx
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import type {
|
||||
FC,
|
||||
ReactElement,
|
||||
} from 'react'
|
||||
import {
|
||||
cloneElement,
|
||||
memo,
|
||||
useCallback,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import NextStep from './components/next-step'
|
||||
import PanelOperator from './components/panel-operator'
|
||||
import {
|
||||
DescriptionInput,
|
||||
TitleInput,
|
||||
} from './components/title-description-input'
|
||||
import { useResizePanel } from './hooks/use-resize-panel'
|
||||
import {
|
||||
XClose,
|
||||
} from '@/app/components/base/icons/src/vender/line/general'
|
||||
import BlockIcon from '@/app/components/workflow/block-icon'
|
||||
import {
|
||||
useNodeDataUpdate,
|
||||
useNodesExtraData,
|
||||
useNodesInteractions,
|
||||
useNodesReadOnly,
|
||||
useNodesSyncDraft,
|
||||
useToolIcon,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import { canRunBySingle } from '@/app/components/workflow/utils'
|
||||
import { Play } from '@/app/components/base/icons/src/vender/line/mediaAndDevices'
|
||||
import TooltipPlus from '@/app/components/base/tooltip-plus'
|
||||
import type { Node } from '@/app/components/workflow/types'
|
||||
|
||||
type BasePanelProps = {
|
||||
children: ReactElement
|
||||
} & Node
|
||||
|
||||
const BasePanel: FC<BasePanelProps> = ({
|
||||
id,
|
||||
data,
|
||||
children,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const initPanelWidth = localStorage.getItem('workflow-node-panel-width') || 420
|
||||
const { handleNodeSelect } = useNodesInteractions()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const nodesExtraData = useNodesExtraData()
|
||||
const availableNextNodes = nodesExtraData[data.type].availableNextNodes
|
||||
const toolIcon = useToolIcon(data)
|
||||
|
||||
const handleResized = useCallback((width: number) => {
|
||||
localStorage.setItem('workflow-node-panel-width', `${width}`)
|
||||
}, [])
|
||||
|
||||
const {
|
||||
triggerRef,
|
||||
containerRef,
|
||||
} = useResizePanel({
|
||||
direction: 'horizontal',
|
||||
triggerDirection: 'left',
|
||||
minWidth: 420,
|
||||
maxWidth: 720,
|
||||
onResized: handleResized,
|
||||
})
|
||||
|
||||
const {
|
||||
handleNodeDataUpdate,
|
||||
handleNodeDataUpdateWithSyncDraft,
|
||||
} = useNodeDataUpdate()
|
||||
|
||||
const handleTitleBlur = useCallback((title: string) => {
|
||||
handleNodeDataUpdateWithSyncDraft({ id, data: { title } })
|
||||
}, [handleNodeDataUpdateWithSyncDraft, id])
|
||||
const handleDescriptionChange = useCallback((desc: string) => {
|
||||
handleNodeDataUpdateWithSyncDraft({ id, data: { desc } })
|
||||
}, [handleNodeDataUpdateWithSyncDraft, id])
|
||||
|
||||
return (
|
||||
<div className='relative mr-2 h-full'>
|
||||
<div
|
||||
ref={triggerRef}
|
||||
className='absolute top-1/2 -translate-y-1/2 -left-2 w-3 h-6 cursor-col-resize resize-x'>
|
||||
<div className='w-1 h-6 bg-gray-300 rounded-sm'></div>
|
||||
</div>
|
||||
<div
|
||||
ref={containerRef}
|
||||
className='relative h-full bg-white shadow-lg border-[0.5px] border-gray-200 rounded-2xl overflow-y-auto'
|
||||
style={{
|
||||
width: `${initPanelWidth}px`,
|
||||
}}
|
||||
>
|
||||
<div className='sticky top-0 bg-white border-b-[0.5px] border-black/5 z-10'>
|
||||
<div className='flex items-center px-4 pt-4 pb-1'>
|
||||
<BlockIcon
|
||||
className='shrink-0 mr-1'
|
||||
type={data.type}
|
||||
toolIcon={toolIcon}
|
||||
size='md'
|
||||
/>
|
||||
<TitleInput
|
||||
value={data.title || ''}
|
||||
onBlur={handleTitleBlur}
|
||||
/>
|
||||
<div className='shrink-0 flex items-center text-gray-500'>
|
||||
{
|
||||
canRunBySingle(data.type) && !nodesReadOnly && (
|
||||
<TooltipPlus
|
||||
popupContent={t('workflow.panel.runThisStep')}
|
||||
>
|
||||
<div
|
||||
className='flex items-center justify-center mr-1 w-6 h-6 rounded-md hover:bg-black/5 cursor-pointer'
|
||||
onClick={() => {
|
||||
handleNodeDataUpdate({ id, data: { _isSingleRun: true } })
|
||||
handleSyncWorkflowDraft(true)
|
||||
}}
|
||||
>
|
||||
<Play className='w-4 h-4 text-gray-500' />
|
||||
</div>
|
||||
</TooltipPlus>
|
||||
)
|
||||
}
|
||||
<PanelOperator id={id} data={data} />
|
||||
<div className='mx-3 w-[1px] h-3.5 bg-gray-200' />
|
||||
<div
|
||||
className='flex items-center justify-center w-6 h-6 cursor-pointer'
|
||||
onClick={() => handleNodeSelect(id, true)}
|
||||
>
|
||||
<XClose className='w-4 h-4' />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='p-2'>
|
||||
<DescriptionInput
|
||||
value={data.desc || ''}
|
||||
onChange={handleDescriptionChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className='py-2'>
|
||||
{cloneElement(children, { id, data })}
|
||||
</div>
|
||||
{
|
||||
!!availableNextNodes.length && (
|
||||
<div className='p-4 border-t-[0.5px] border-t-black/5'>
|
||||
<div className='flex items-center mb-1 text-gray-700 text-[13px] font-semibold'>
|
||||
{t('workflow.panel.nextStep').toLocaleUpperCase()}
|
||||
</div>
|
||||
<div className='mb-2 text-xs text-gray-400'>
|
||||
{t('workflow.panel.addNextStep')}
|
||||
</div>
|
||||
<NextStep selectedNode={{ id, data } as Node} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(BasePanel)
|
||||
36
web/app/components/workflow/nodes/answer/default.ts
Normal file
36
web/app/components/workflow/nodes/answer/default.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { BlockEnum } from '../../types'
|
||||
import type { NodeDefault } from '../../types'
|
||||
import type { AnswerNodeType } from './types'
|
||||
import { ALL_CHAT_AVAILABLE_BLOCKS, ALL_COMPLETION_AVAILABLE_BLOCKS } from '@/app/components/workflow/constants'
|
||||
|
||||
const nodeDefault: NodeDefault<AnswerNodeType> = {
|
||||
defaultValue: {
|
||||
variables: [],
|
||||
answer: '',
|
||||
},
|
||||
getAvailablePrevNodes(isChatMode: boolean) {
|
||||
const nodes = isChatMode
|
||||
? ALL_CHAT_AVAILABLE_BLOCKS
|
||||
: ALL_COMPLETION_AVAILABLE_BLOCKS.filter(type => type !== BlockEnum.End)
|
||||
return nodes
|
||||
},
|
||||
getAvailableNextNodes(isChatMode: boolean) {
|
||||
const nodes = isChatMode
|
||||
? ALL_CHAT_AVAILABLE_BLOCKS
|
||||
: ALL_COMPLETION_AVAILABLE_BLOCKS
|
||||
return nodes
|
||||
},
|
||||
checkValid(payload: AnswerNodeType, t: any) {
|
||||
let errorMessages = ''
|
||||
const { answer } = payload
|
||||
if (!answer)
|
||||
errorMessages = t('workflow.errorMsg.fieldRequired', { field: t('workflow.nodes.answer.answer') })
|
||||
|
||||
return {
|
||||
isValid: !errorMessages,
|
||||
errorMessage: errorMessages,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export default nodeDefault
|
||||
26
web/app/components/workflow/nodes/answer/node.tsx
Normal file
26
web/app/components/workflow/nodes/answer/node.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import InfoPanel from '../_base/components/info-panel'
|
||||
import ReadonlyInputWithSelectVar from '../_base/components/readonly-input-with-select-var'
|
||||
import type { AnswerNodeType } from './types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
const Node: FC<NodeProps<AnswerNodeType>> = ({
|
||||
id,
|
||||
data,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<div className='mb-1 px-3 py-1'>
|
||||
<InfoPanel title={t('workflow.nodes.answer.answer')} content={
|
||||
<ReadonlyInputWithSelectVar
|
||||
value={data.answer}
|
||||
nodeId={id}
|
||||
/>
|
||||
} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Node)
|
||||
44
web/app/components/workflow/nodes/answer/panel.tsx
Normal file
44
web/app/components/workflow/nodes/answer/panel.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useConfig from './use-config'
|
||||
import type { AnswerNodeType } from './types'
|
||||
import Editor from '@/app/components/workflow/nodes/_base/components/prompt/editor'
|
||||
import type { NodePanelProps } from '@/app/components/workflow/types'
|
||||
import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'
|
||||
const i18nPrefix = 'workflow.nodes.answer'
|
||||
|
||||
const Panel: FC<NodePanelProps<AnswerNodeType>> = ({
|
||||
id,
|
||||
data,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const {
|
||||
readOnly,
|
||||
inputs,
|
||||
handleAnswerChange,
|
||||
filterVar,
|
||||
} = useConfig(id, data)
|
||||
|
||||
const { availableVars, availableNodes } = useAvailableVarList(id, {
|
||||
onlyLeafNodeVar: false,
|
||||
filterVar,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className='mt-2 mb-2 px-4 space-y-4'>
|
||||
<Editor
|
||||
readOnly={readOnly}
|
||||
justVar
|
||||
title={t(`${i18nPrefix}.answer`)!}
|
||||
value={inputs.answer}
|
||||
onChange={handleAnswerChange}
|
||||
nodesOutputVars={availableVars}
|
||||
availableNodes={availableNodes}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Panel)
|
||||
6
web/app/components/workflow/nodes/answer/types.ts
Normal file
6
web/app/components/workflow/nodes/answer/types.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import type { CommonNodeType, Variable } from '@/app/components/workflow/types'
|
||||
|
||||
export type AnswerNodeType = CommonNodeType & {
|
||||
variables: Variable[]
|
||||
answer: string
|
||||
}
|
||||
41
web/app/components/workflow/nodes/answer/use-config.ts
Normal file
41
web/app/components/workflow/nodes/answer/use-config.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import useVarList from '../_base/hooks/use-var-list'
|
||||
import type { Var } from '../../types'
|
||||
import { VarType } from '../../types'
|
||||
import type { AnswerNodeType } from './types'
|
||||
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
|
||||
import {
|
||||
useNodesReadOnly,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
|
||||
const useConfig = (id: string, payload: AnswerNodeType) => {
|
||||
const { nodesReadOnly: readOnly } = useNodesReadOnly()
|
||||
const { inputs, setInputs } = useNodeCrud<AnswerNodeType>(id, payload)
|
||||
// variables
|
||||
const { handleVarListChange, handleAddVariable } = useVarList<AnswerNodeType>({
|
||||
inputs,
|
||||
setInputs,
|
||||
})
|
||||
|
||||
const handleAnswerChange = useCallback((value: string) => {
|
||||
const newInputs = produce(inputs, (draft) => {
|
||||
draft.answer = value
|
||||
})
|
||||
setInputs(newInputs)
|
||||
}, [inputs, setInputs])
|
||||
|
||||
const filterVar = useCallback((varPayload: Var) => {
|
||||
return varPayload.type !== VarType.arrayObject
|
||||
}, [])
|
||||
return {
|
||||
readOnly,
|
||||
inputs,
|
||||
handleVarListChange,
|
||||
handleAddVariable,
|
||||
handleAnswerChange,
|
||||
filterVar,
|
||||
}
|
||||
}
|
||||
|
||||
export default useConfig
|
||||
5
web/app/components/workflow/nodes/answer/utils.ts
Normal file
5
web/app/components/workflow/nodes/answer/utils.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import type { AnswerNodeType } from './types'
|
||||
|
||||
export const checkNodeValid = (payload: AnswerNodeType) => {
|
||||
return true
|
||||
}
|
||||
43
web/app/components/workflow/nodes/code/default.ts
Normal file
43
web/app/components/workflow/nodes/code/default.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { BlockEnum } from '../../types'
|
||||
import type { NodeDefault } from '../../types'
|
||||
import { CodeLanguage, type CodeNodeType } from './types'
|
||||
import { ALL_CHAT_AVAILABLE_BLOCKS, ALL_COMPLETION_AVAILABLE_BLOCKS } from '@/app/components/workflow/constants'
|
||||
|
||||
const i18nPrefix = 'workflow.errorMsg'
|
||||
|
||||
const nodeDefault: NodeDefault<CodeNodeType> = {
|
||||
defaultValue: {
|
||||
code: '',
|
||||
code_language: CodeLanguage.python3,
|
||||
variables: [],
|
||||
outputs: {},
|
||||
},
|
||||
getAvailablePrevNodes(isChatMode: boolean) {
|
||||
const nodes = isChatMode
|
||||
? ALL_CHAT_AVAILABLE_BLOCKS
|
||||
: ALL_COMPLETION_AVAILABLE_BLOCKS.filter(type => type !== BlockEnum.End)
|
||||
return nodes
|
||||
},
|
||||
getAvailableNextNodes(isChatMode: boolean) {
|
||||
const nodes = isChatMode ? ALL_CHAT_AVAILABLE_BLOCKS : ALL_COMPLETION_AVAILABLE_BLOCKS
|
||||
return nodes
|
||||
},
|
||||
checkValid(payload: CodeNodeType, t: any) {
|
||||
let errorMessages = ''
|
||||
const { code, variables } = payload
|
||||
if (!errorMessages && variables.filter(v => !v.variable).length > 0)
|
||||
errorMessages = t(`${i18nPrefix}.fieldRequired`, { field: t(`${i18nPrefix}.fields.variable`) })
|
||||
if (!errorMessages && variables.filter(v => !v.value_selector.length).length > 0)
|
||||
errorMessages = t(`${i18nPrefix}.fieldRequired`, { field: t(`${i18nPrefix}.fields.variableValue`) })
|
||||
if (!errorMessages && !code)
|
||||
errorMessages = t(`${i18nPrefix}.fieldRequired`, { field: t(`${i18nPrefix}.fields.code`) })
|
||||
|
||||
return {
|
||||
isValid: !errorMessages,
|
||||
errorMessage: errorMessages,
|
||||
}
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
export default nodeDefault
|
||||
13
web/app/components/workflow/nodes/code/node.tsx
Normal file
13
web/app/components/workflow/nodes/code/node.tsx
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import type { CodeNodeType } from './types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
|
||||
const Node: FC<NodeProps<CodeNodeType>> = () => {
|
||||
return (
|
||||
// No summary content
|
||||
<div></div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Node)
|
||||
142
web/app/components/workflow/nodes/code/panel.tsx
Normal file
142
web/app/components/workflow/nodes/code/panel.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import RemoveEffectVarConfirm from '../_base/components/remove-effect-var-confirm'
|
||||
import useConfig from './use-config'
|
||||
import type { CodeNodeType } from './types'
|
||||
import { CodeLanguage } from './types'
|
||||
import VarList from '@/app/components/workflow/nodes/_base/components/variable/var-list'
|
||||
import OutputVarList from '@/app/components/workflow/nodes/_base/components/variable/output-var-list'
|
||||
import AddButton from '@/app/components/base/button/add-button'
|
||||
import Field from '@/app/components/workflow/nodes/_base/components/field'
|
||||
import Split from '@/app/components/workflow/nodes/_base/components/split'
|
||||
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
|
||||
import TypeSelector from '@/app/components/workflow/nodes/_base/components/selector'
|
||||
import type { NodePanelProps } from '@/app/components/workflow/types'
|
||||
import BeforeRunForm from '@/app/components/workflow/nodes/_base/components/before-run-form'
|
||||
import ResultPanel from '@/app/components/workflow/run/result-panel'
|
||||
|
||||
const i18nPrefix = 'workflow.nodes.code'
|
||||
|
||||
const codeLanguages = [
|
||||
{
|
||||
label: 'Python3',
|
||||
value: CodeLanguage.python3,
|
||||
},
|
||||
{
|
||||
label: 'JavaScript',
|
||||
value: CodeLanguage.javascript,
|
||||
},
|
||||
]
|
||||
const Panel: FC<NodePanelProps<CodeNodeType>> = ({
|
||||
id,
|
||||
data,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const {
|
||||
readOnly,
|
||||
inputs,
|
||||
outputKeyOrders,
|
||||
handleVarListChange,
|
||||
handleAddVariable,
|
||||
handleRemoveVariable,
|
||||
handleCodeChange,
|
||||
handleCodeLanguageChange,
|
||||
handleVarsChange,
|
||||
handleAddOutputVariable,
|
||||
filterVar,
|
||||
isShowRemoveVarConfirm,
|
||||
hideRemoveVarConfirm,
|
||||
onRemoveVarConfirm,
|
||||
// single run
|
||||
isShowSingleRun,
|
||||
hideSingleRun,
|
||||
runningStatus,
|
||||
handleRun,
|
||||
handleStop,
|
||||
runResult,
|
||||
varInputs,
|
||||
inputVarValues,
|
||||
setInputVarValues,
|
||||
} = useConfig(id, data)
|
||||
|
||||
return (
|
||||
<div className='mt-2'>
|
||||
<div className='px-4 pb-4 space-y-4'>
|
||||
<Field
|
||||
title={t(`${i18nPrefix}.inputVars`)}
|
||||
operations={
|
||||
!readOnly ? <AddButton onClick={handleAddVariable} /> : undefined
|
||||
}
|
||||
>
|
||||
<VarList
|
||||
readonly={readOnly}
|
||||
nodeId={id}
|
||||
list={inputs.variables}
|
||||
onChange={handleVarListChange}
|
||||
filterVar={filterVar}
|
||||
/>
|
||||
</Field>
|
||||
<Split />
|
||||
<CodeEditor
|
||||
readOnly={readOnly}
|
||||
title={
|
||||
<TypeSelector
|
||||
options={codeLanguages}
|
||||
value={inputs.code_language}
|
||||
onChange={handleCodeLanguageChange}
|
||||
/>
|
||||
}
|
||||
language={inputs.code_language}
|
||||
value={inputs.code}
|
||||
onChange={handleCodeChange}
|
||||
/>
|
||||
</div>
|
||||
<Split />
|
||||
<div className='px-4 pt-4 pb-2'>
|
||||
<Field
|
||||
title={t(`${i18nPrefix}.outputVars`)}
|
||||
operations={
|
||||
<AddButton onClick={handleAddOutputVariable} />
|
||||
}
|
||||
>
|
||||
|
||||
<OutputVarList
|
||||
readonly={readOnly}
|
||||
outputs={inputs.outputs}
|
||||
outputKeyOrders={outputKeyOrders}
|
||||
onChange={handleVarsChange}
|
||||
onRemove={handleRemoveVariable}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
{
|
||||
isShowSingleRun && (
|
||||
<BeforeRunForm
|
||||
nodeName={inputs.title}
|
||||
onHide={hideSingleRun}
|
||||
forms={[
|
||||
{
|
||||
inputs: varInputs,
|
||||
values: inputVarValues,
|
||||
onChange: setInputVarValues,
|
||||
},
|
||||
]}
|
||||
runningStatus={runningStatus}
|
||||
onRun={handleRun}
|
||||
onStop={handleStop}
|
||||
result={<ResultPanel {...runResult} showSteps={false} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
<RemoveEffectVarConfirm
|
||||
isShow={isShowRemoveVarConfirm}
|
||||
onCancel={hideRemoveVarConfirm}
|
||||
onConfirm={onRemoveVarConfirm}
|
||||
/>
|
||||
</div >
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Panel)
|
||||
19
web/app/components/workflow/nodes/code/types.ts
Normal file
19
web/app/components/workflow/nodes/code/types.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import type { CommonNodeType, VarType, Variable } from '@/app/components/workflow/types'
|
||||
|
||||
export enum CodeLanguage {
|
||||
python3 = 'python3',
|
||||
javascript = 'javascript',
|
||||
json = 'json',
|
||||
}
|
||||
|
||||
export type OutputVar = Record<string, {
|
||||
type: VarType
|
||||
children: null // support nest in the future,
|
||||
}>
|
||||
|
||||
export type CodeNodeType = CommonNodeType & {
|
||||
variables: Variable[]
|
||||
code_language: CodeLanguage
|
||||
code: string
|
||||
outputs: OutputVar
|
||||
}
|
||||
169
web/app/components/workflow/nodes/code/use-config.ts
Normal file
169
web/app/components/workflow/nodes/code/use-config.ts
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
import { useCallback, useEffect, useState } from 'react'
|
||||
import produce from 'immer'
|
||||
import useVarList from '../_base/hooks/use-var-list'
|
||||
import useOutputVarList from '../_base/hooks/use-output-var-list'
|
||||
import { BlockEnum, VarType } from '../../types'
|
||||
import type { Var } from '../../types'
|
||||
import { useStore } from '../../store'
|
||||
import type { CodeNodeType, OutputVar } from './types'
|
||||
import { CodeLanguage } from './types'
|
||||
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
|
||||
import useOneStepRun from '@/app/components/workflow/nodes/_base/hooks/use-one-step-run'
|
||||
import { fetchNodeDefault } from '@/service/workflow'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import {
|
||||
useNodesReadOnly,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
|
||||
const useConfig = (id: string, payload: CodeNodeType) => {
|
||||
const { nodesReadOnly: readOnly } = useNodesReadOnly()
|
||||
|
||||
const appId = useAppStore.getState().appDetail?.id
|
||||
|
||||
const [allLanguageDefault, setAllLanguageDefault] = useState<Record<CodeLanguage, CodeNodeType> | null>(null)
|
||||
useEffect(() => {
|
||||
if (appId) {
|
||||
(async () => {
|
||||
const { config: javaScriptConfig } = await fetchNodeDefault(appId, BlockEnum.Code, { code_language: CodeLanguage.javascript }) as any
|
||||
const { config: pythonConfig } = await fetchNodeDefault(appId, BlockEnum.Code, { code_language: CodeLanguage.python3 }) as any
|
||||
setAllLanguageDefault({
|
||||
[CodeLanguage.javascript]: javaScriptConfig as CodeNodeType,
|
||||
[CodeLanguage.python3]: pythonConfig as CodeNodeType,
|
||||
} as any)
|
||||
})()
|
||||
}
|
||||
}, [appId])
|
||||
|
||||
const defaultConfig = useStore(s => s.nodesDefaultConfigs)[payload.type]
|
||||
const { inputs, setInputs } = useNodeCrud<CodeNodeType>(id, payload)
|
||||
const { handleVarListChange, handleAddVariable } = useVarList<CodeNodeType>({
|
||||
inputs,
|
||||
setInputs,
|
||||
})
|
||||
|
||||
const [outputKeyOrders, setOutputKeyOrders] = useState<string[]>([])
|
||||
const syncOutputKeyOrders = useCallback((outputs: OutputVar) => {
|
||||
setOutputKeyOrders(Object.keys(outputs))
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
if (inputs.code) {
|
||||
if (inputs.outputs && Object.keys(inputs.outputs).length > 0)
|
||||
syncOutputKeyOrders(inputs.outputs)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const isReady = defaultConfig && Object.keys(defaultConfig).length > 0
|
||||
if (isReady) {
|
||||
setInputs({
|
||||
...inputs,
|
||||
...defaultConfig,
|
||||
})
|
||||
syncOutputKeyOrders(defaultConfig.outputs)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [defaultConfig])
|
||||
|
||||
const handleCodeChange = useCallback((code: string) => {
|
||||
const newInputs = produce(inputs, (draft) => {
|
||||
draft.code = code
|
||||
})
|
||||
setInputs(newInputs)
|
||||
}, [inputs, setInputs])
|
||||
|
||||
const handleCodeLanguageChange = useCallback((codeLanguage: CodeLanguage) => {
|
||||
const currDefaultConfig = allLanguageDefault?.[codeLanguage]
|
||||
|
||||
const newInputs = produce(inputs, (draft) => {
|
||||
draft.code_language = codeLanguage
|
||||
if (!currDefaultConfig)
|
||||
return
|
||||
draft.code = currDefaultConfig.code
|
||||
draft.variables = currDefaultConfig.variables
|
||||
draft.outputs = currDefaultConfig.outputs
|
||||
})
|
||||
setInputs(newInputs)
|
||||
}, [allLanguageDefault, inputs, setInputs])
|
||||
|
||||
const {
|
||||
handleVarsChange,
|
||||
handleAddVariable: handleAddOutputVariable,
|
||||
handleRemoveVariable,
|
||||
isShowRemoveVarConfirm,
|
||||
hideRemoveVarConfirm,
|
||||
onRemoveVarConfirm,
|
||||
} = useOutputVarList<CodeNodeType>({
|
||||
id,
|
||||
inputs,
|
||||
setInputs,
|
||||
outputKeyOrders,
|
||||
onOutputKeyOrdersChange: setOutputKeyOrders,
|
||||
})
|
||||
|
||||
const filterVar = useCallback((varPayload: Var) => {
|
||||
return [VarType.string, VarType.number, VarType.object, VarType.array, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject].includes(varPayload.type)
|
||||
}, [])
|
||||
|
||||
// single run
|
||||
const {
|
||||
isShowSingleRun,
|
||||
hideSingleRun,
|
||||
toVarInputs,
|
||||
runningStatus,
|
||||
isCompleted,
|
||||
handleRun,
|
||||
handleStop,
|
||||
runInputData,
|
||||
setRunInputData,
|
||||
runResult,
|
||||
} = useOneStepRun<CodeNodeType>({
|
||||
id,
|
||||
data: inputs,
|
||||
defaultRunInputData: {},
|
||||
})
|
||||
|
||||
const varInputs = toVarInputs(inputs.variables)
|
||||
|
||||
const inputVarValues = (() => {
|
||||
const vars: Record<string, any> = {}
|
||||
Object.keys(runInputData)
|
||||
.forEach((key) => {
|
||||
vars[key] = runInputData[key]
|
||||
})
|
||||
return vars
|
||||
})()
|
||||
|
||||
const setInputVarValues = useCallback((newPayload: Record<string, any>) => {
|
||||
setRunInputData(newPayload)
|
||||
}, [setRunInputData])
|
||||
|
||||
return {
|
||||
readOnly,
|
||||
inputs,
|
||||
outputKeyOrders,
|
||||
handleVarListChange,
|
||||
handleAddVariable,
|
||||
handleRemoveVariable,
|
||||
handleCodeChange,
|
||||
handleCodeLanguageChange,
|
||||
handleVarsChange,
|
||||
filterVar,
|
||||
handleAddOutputVariable,
|
||||
isShowRemoveVarConfirm,
|
||||
hideRemoveVarConfirm,
|
||||
onRemoveVarConfirm,
|
||||
// single run
|
||||
isShowSingleRun,
|
||||
hideSingleRun,
|
||||
runningStatus,
|
||||
isCompleted,
|
||||
handleRun,
|
||||
handleStop,
|
||||
varInputs,
|
||||
inputVarValues,
|
||||
setInputVarValues,
|
||||
runResult,
|
||||
}
|
||||
}
|
||||
|
||||
export default useConfig
|
||||
5
web/app/components/workflow/nodes/code/utils.ts
Normal file
5
web/app/components/workflow/nodes/code/utils.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import type { CodeNodeType } from './types'
|
||||
|
||||
export const checkNodeValid = (payload: CodeNodeType) => {
|
||||
return true
|
||||
}
|
||||
56
web/app/components/workflow/nodes/constants.ts
Normal file
56
web/app/components/workflow/nodes/constants.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import type { ComponentType } from 'react'
|
||||
import { BlockEnum } from '../types'
|
||||
import StartNode from './start/node'
|
||||
import StartPanel from './start/panel'
|
||||
import EndNode from './end/node'
|
||||
import EndPanel from './end/panel'
|
||||
import AnswerNode from './answer/node'
|
||||
import AnswerPanel from './answer/panel'
|
||||
import LLMNode from './llm/node'
|
||||
import LLMPanel from './llm/panel'
|
||||
import KnowledgeRetrievalNode from './knowledge-retrieval/node'
|
||||
import KnowledgeRetrievalPanel from './knowledge-retrieval/panel'
|
||||
import QuestionClassifierNode from './question-classifier/node'
|
||||
import QuestionClassifierPanel from './question-classifier/panel'
|
||||
import IfElseNode from './if-else/node'
|
||||
import IfElsePanel from './if-else/panel'
|
||||
import CodeNode from './code/node'
|
||||
import CodePanel from './code/panel'
|
||||
import TemplateTransformNode from './template-transform/node'
|
||||
import TemplateTransformPanel from './template-transform/panel'
|
||||
import HttpNode from './http/node'
|
||||
import HttpPanel from './http/panel'
|
||||
import ToolNode from './tool/node'
|
||||
import ToolPanel from './tool/panel'
|
||||
import VariableAssignerNode from './variable-assigner/node'
|
||||
import VariableAssignerPanel from './variable-assigner/panel'
|
||||
|
||||
export const NodeComponentMap: Record<string, ComponentType<any>> = {
|
||||
[BlockEnum.Start]: StartNode,
|
||||
[BlockEnum.End]: EndNode,
|
||||
[BlockEnum.Answer]: AnswerNode,
|
||||
[BlockEnum.LLM]: LLMNode,
|
||||
[BlockEnum.KnowledgeRetrieval]: KnowledgeRetrievalNode,
|
||||
[BlockEnum.QuestionClassifier]: QuestionClassifierNode,
|
||||
[BlockEnum.IfElse]: IfElseNode,
|
||||
[BlockEnum.Code]: CodeNode,
|
||||
[BlockEnum.TemplateTransform]: TemplateTransformNode,
|
||||
[BlockEnum.HttpRequest]: HttpNode,
|
||||
[BlockEnum.Tool]: ToolNode,
|
||||
[BlockEnum.VariableAssigner]: VariableAssignerNode,
|
||||
}
|
||||
|
||||
export const PanelComponentMap: Record<string, ComponentType<any>> = {
|
||||
[BlockEnum.Start]: StartPanel,
|
||||
[BlockEnum.End]: EndPanel,
|
||||
[BlockEnum.Answer]: AnswerPanel,
|
||||
[BlockEnum.LLM]: LLMPanel,
|
||||
[BlockEnum.KnowledgeRetrieval]: KnowledgeRetrievalPanel,
|
||||
[BlockEnum.QuestionClassifier]: QuestionClassifierPanel,
|
||||
[BlockEnum.IfElse]: IfElsePanel,
|
||||
[BlockEnum.Code]: CodePanel,
|
||||
[BlockEnum.TemplateTransform]: TemplateTransformPanel,
|
||||
[BlockEnum.HttpRequest]: HttpPanel,
|
||||
[BlockEnum.Tool]: ToolPanel,
|
||||
[BlockEnum.VariableAssigner]: VariableAssignerPanel,
|
||||
}
|
||||
33
web/app/components/workflow/nodes/end/default.ts
Normal file
33
web/app/components/workflow/nodes/end/default.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { BlockEnum } from '../../types'
|
||||
import type { NodeDefault } from '../../types'
|
||||
import { type EndNodeType } from './types'
|
||||
import { ALL_CHAT_AVAILABLE_BLOCKS, ALL_COMPLETION_AVAILABLE_BLOCKS } from '@/app/components/workflow/constants'
|
||||
|
||||
const nodeDefault: NodeDefault<EndNodeType> = {
|
||||
defaultValue: {
|
||||
outputs: [],
|
||||
},
|
||||
getAvailablePrevNodes(isChatMode: boolean) {
|
||||
const nodes = isChatMode
|
||||
? ALL_CHAT_AVAILABLE_BLOCKS
|
||||
: ALL_COMPLETION_AVAILABLE_BLOCKS.filter(type => type !== BlockEnum.End)
|
||||
return nodes
|
||||
},
|
||||
getAvailableNextNodes() {
|
||||
return []
|
||||
},
|
||||
checkValid(payload: EndNodeType) {
|
||||
let isValid = true
|
||||
let errorMessages = ''
|
||||
if (payload.type) {
|
||||
isValid = true
|
||||
errorMessages = ''
|
||||
}
|
||||
return {
|
||||
isValid,
|
||||
errorMessage: errorMessages,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export default nodeDefault
|
||||
93
web/app/components/workflow/nodes/end/node.tsx
Normal file
93
web/app/components/workflow/nodes/end/node.tsx
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import type { EndNodeType } from './types'
|
||||
import type { NodeProps, ValueSelector, Variable } from '@/app/components/workflow/types'
|
||||
import { isSystemVar, toNodeOutputVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useWorkflow,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
import { VarBlockIcon } from '@/app/components/workflow/block-icon'
|
||||
import { Line3 } from '@/app/components/base/icons/src/public/common'
|
||||
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
|
||||
const Node: FC<NodeProps<EndNodeType>> = ({
|
||||
id,
|
||||
data,
|
||||
}) => {
|
||||
const { getBeforeNodesInSameBranch } = useWorkflow()
|
||||
const availableNodes = getBeforeNodesInSameBranch(id)
|
||||
const isChatMode = useIsChatMode()
|
||||
const outputVars = toNodeOutputVars(availableNodes, isChatMode)
|
||||
|
||||
const startNode = availableNodes.find((node: any) => {
|
||||
return node.data.type === BlockEnum.Start
|
||||
})
|
||||
|
||||
const getNode = (id: string) => {
|
||||
return availableNodes.find(node => node.id === id) || startNode
|
||||
}
|
||||
|
||||
const getVarType = (nodeId: string, value: ValueSelector) => {
|
||||
const targetVar = outputVars.find(v => v.nodeId === nodeId)
|
||||
if (!targetVar)
|
||||
return 'undefined'
|
||||
|
||||
let type: VarType = VarType.string
|
||||
let curr: any = targetVar.vars
|
||||
const isSystem = isSystemVar(value);
|
||||
(value).slice(1).forEach((key, i) => {
|
||||
const isLast = i === value.length - 2
|
||||
curr = curr.find((v: any) => v.variable === isSystem ? `sys.${key}` : key)
|
||||
if (isLast) {
|
||||
type = curr.type
|
||||
}
|
||||
else {
|
||||
if (curr.type === VarType.object)
|
||||
curr = curr.children
|
||||
}
|
||||
})
|
||||
return type
|
||||
}
|
||||
const { outputs } = data
|
||||
const filteredOutputs = (outputs as Variable[]).filter(({ value_selector }) => value_selector.length > 0)
|
||||
|
||||
if (!filteredOutputs.length)
|
||||
return null
|
||||
|
||||
return (
|
||||
<div className='mb-1 px-3 py-1 space-y-0.5'>
|
||||
{filteredOutputs.map(({ value_selector }, index) => {
|
||||
const node = getNode(value_selector[0])
|
||||
const isSystem = isSystemVar(value_selector)
|
||||
const varName = isSystem ? `sys.${value_selector[value_selector.length - 1]}` : value_selector[value_selector.length - 1]
|
||||
return (
|
||||
<div key={index} className='flex items-center h-6 justify-between bg-gray-100 rounded-md px-1 space-x-1 text-xs font-normal text-gray-700'>
|
||||
<div className='flex items-center text-xs font-medium text-gray-500'>
|
||||
<div className='p-[1px]'>
|
||||
<VarBlockIcon
|
||||
className='!text-gray-900'
|
||||
type={node?.data.type || BlockEnum.Start}
|
||||
/>
|
||||
</div>
|
||||
<div className='max-w-[75px] truncate'>{node?.data.title}</div>
|
||||
<Line3 className='mr-0.5'></Line3>
|
||||
<div className='flex items-center text-primary-600'>
|
||||
<Variable02 className='w-3.5 h-3.5' />
|
||||
<div className='max-w-[50px] ml-0.5 text-xs font-medium truncate'>{varName}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='text-xs font-normal text-gray-700'>
|
||||
<div className='ml-0.5 text-xs font-normal text-gray-500 capitalize'>{getVarType(node?.id || '', value_selector)}</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Node)
|
||||
49
web/app/components/workflow/nodes/end/panel.tsx
Normal file
49
web/app/components/workflow/nodes/end/panel.tsx
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { type FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useConfig from './use-config'
|
||||
import type { EndNodeType } from './types'
|
||||
import VarList from '@/app/components/workflow/nodes/_base/components/variable/var-list'
|
||||
import Field from '@/app/components/workflow/nodes/_base/components/field'
|
||||
import AddButton from '@/app/components/base/button/add-button'
|
||||
import { type NodePanelProps } from '@/app/components/workflow/types'
|
||||
|
||||
const i18nPrefix = 'workflow.nodes.end'
|
||||
|
||||
const Panel: FC<NodePanelProps<EndNodeType>> = ({
|
||||
id,
|
||||
data,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const {
|
||||
readOnly,
|
||||
inputs,
|
||||
handleVarListChange,
|
||||
handleAddVariable,
|
||||
} = useConfig(id, data)
|
||||
|
||||
const outputs = inputs.outputs
|
||||
return (
|
||||
<div className='mt-2'>
|
||||
<div className='px-4 pb-4 space-y-4'>
|
||||
|
||||
<Field
|
||||
title={t(`${i18nPrefix}.output.variable`)}
|
||||
operations={
|
||||
!readOnly ? <AddButton onClick={handleAddVariable} /> : undefined
|
||||
}
|
||||
>
|
||||
<VarList
|
||||
nodeId={id}
|
||||
readonly={readOnly}
|
||||
list={outputs}
|
||||
onChange={handleVarListChange}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Panel)
|
||||
5
web/app/components/workflow/nodes/end/types.ts
Normal file
5
web/app/components/workflow/nodes/end/types.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import type { CommonNodeType, Variable } from '@/app/components/workflow/types'
|
||||
|
||||
export type EndNodeType = CommonNodeType & {
|
||||
outputs: Variable[]
|
||||
}
|
||||
27
web/app/components/workflow/nodes/end/use-config.ts
Normal file
27
web/app/components/workflow/nodes/end/use-config.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import useVarList from '../_base/hooks/use-var-list'
|
||||
import type { EndNodeType } from './types'
|
||||
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
|
||||
import {
|
||||
useNodesReadOnly,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
const useConfig = (id: string, payload: EndNodeType) => {
|
||||
const { nodesReadOnly: readOnly } = useNodesReadOnly()
|
||||
const { inputs, setInputs } = useNodeCrud<EndNodeType>(id, payload)
|
||||
|
||||
const { handleVarListChange, handleAddVariable } = useVarList<EndNodeType>({
|
||||
inputs,
|
||||
setInputs: (newInputs) => {
|
||||
setInputs(newInputs)
|
||||
},
|
||||
varKey: 'outputs',
|
||||
})
|
||||
|
||||
return {
|
||||
readOnly,
|
||||
inputs,
|
||||
handleVarListChange,
|
||||
handleAddVariable,
|
||||
}
|
||||
}
|
||||
|
||||
export default useConfig
|
||||
5
web/app/components/workflow/nodes/end/utils.ts
Normal file
5
web/app/components/workflow/nodes/end/utils.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import type { EndNodeType } from './types'
|
||||
|
||||
export const checkNodeValid = (payload: EndNodeType) => {
|
||||
return true
|
||||
}
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React, { useState } from 'react'
|
||||
import cn from 'classnames'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Method } from '../types'
|
||||
import Selector from '../../_base/components/selector'
|
||||
import useAvailableVarList from '../../_base/hooks/use-available-var-list'
|
||||
import { VarType } from '../../../types'
|
||||
import type { Var } from '../../../types'
|
||||
import Input from '@/app/components/workflow/nodes/_base/components/input-support-select-var'
|
||||
import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'
|
||||
|
||||
const MethodOptions = [
|
||||
{ label: 'GET', value: Method.get },
|
||||
{ label: 'POST', value: Method.post },
|
||||
{ label: 'HEAD', value: Method.head },
|
||||
{ label: 'PATCH', value: Method.patch },
|
||||
{ label: 'PUT', value: Method.put },
|
||||
{ label: 'DELETE', value: Method.delete },
|
||||
]
|
||||
type Props = {
|
||||
nodeId: string
|
||||
readonly: boolean
|
||||
method: Method
|
||||
onMethodChange: (method: Method) => void
|
||||
url: string
|
||||
onUrlChange: (url: string) => void
|
||||
}
|
||||
|
||||
const ApiInput: FC<Props> = ({
|
||||
nodeId,
|
||||
readonly,
|
||||
method,
|
||||
onMethodChange,
|
||||
url,
|
||||
onUrlChange,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const [isFocus, setIsFocus] = useState(false)
|
||||
const { availableVars, availableNodes } = useAvailableVarList(nodeId, {
|
||||
onlyLeafNodeVar: false,
|
||||
filterVar: (varPayload: Var) => {
|
||||
return [VarType.string, VarType.number].includes(varPayload.type)
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className='flex items-start space-x-1'>
|
||||
<Selector
|
||||
value={method}
|
||||
onChange={onMethodChange}
|
||||
options={MethodOptions}
|
||||
trigger={
|
||||
<div className={cn(readonly && 'cursor-pointer', 'h-8 shrink-0 flex items-center px-2.5 bg-gray-100 border-black/5 rounded-lg')} >
|
||||
<div className='w-12 pl-0.5 leading-[18px] text-xs font-medium text-gray-900 uppercase'>{method}</div>
|
||||
{!readonly && <ChevronDown className='ml-1 w-3.5 h-3.5 text-gray-700' />}
|
||||
</div>
|
||||
}
|
||||
popupClassName='top-[34px] w-[108px]'
|
||||
showChecked
|
||||
readonly={readonly}
|
||||
/>
|
||||
|
||||
<Input
|
||||
instanceId='http-api-url'
|
||||
className={cn(isFocus ? 'shadow-xs bg-gray-50 border-gray-300' : 'bg-gray-100 border-gray-100', 'w-0 grow rounded-lg px-3 py-[6px] border')}
|
||||
value={url}
|
||||
onChange={onUrlChange}
|
||||
readOnly={readonly}
|
||||
nodesOutputVars={availableVars}
|
||||
availableNodes={availableNodes}
|
||||
onFocusChange={setIsFocus}
|
||||
placeholder={!readonly ? t('workflow.nodes.http.apiPlaceholder')! : ''}
|
||||
placeholderClassName='!leading-[21px]'
|
||||
/>
|
||||
</div >
|
||||
)
|
||||
}
|
||||
export default React.memo(ApiInput)
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue