use-nodes-data.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { useMemo } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import produce from 'immer'
  4. import { BlockEnum } from '../types'
  5. import {
  6. NODES_EXTRA_DATA,
  7. NODES_INITIAL_DATA,
  8. } from '../constants'
  9. import { useIsChatMode } from './use-workflow'
  10. export const useNodesInitialData = () => {
  11. const { t } = useTranslation()
  12. return useMemo(() => produce(NODES_INITIAL_DATA, (draft) => {
  13. Object.keys(draft).forEach((key) => {
  14. draft[key as BlockEnum].title = t(`workflow.blocks.${key}`)
  15. })
  16. }), [t])
  17. }
  18. export const useNodesExtraData = () => {
  19. const { t } = useTranslation()
  20. const isChatMode = useIsChatMode()
  21. return useMemo(() => produce(NODES_EXTRA_DATA, (draft) => {
  22. Object.keys(draft).forEach((key) => {
  23. draft[key as BlockEnum].about = t(`workflow.blocksAbout.${key}`)
  24. draft[key as BlockEnum].availablePrevNodes = draft[key as BlockEnum].getAvailablePrevNodes(isChatMode)
  25. draft[key as BlockEnum].availableNextNodes = draft[key as BlockEnum].getAvailableNextNodes(isChatMode)
  26. })
  27. }), [t, isChatMode])
  28. }
  29. export const useAvailableBlocks = (nodeType?: BlockEnum, isInIteration?: boolean) => {
  30. const nodesExtraData = useNodesExtraData()
  31. const availablePrevBlocks = useMemo(() => {
  32. if (!nodeType)
  33. return []
  34. return nodesExtraData[nodeType].availablePrevNodes || []
  35. }, [nodeType, nodesExtraData])
  36. const availableNextBlocks = useMemo(() => {
  37. if (!nodeType)
  38. return []
  39. return nodesExtraData[nodeType].availableNextNodes || []
  40. }, [nodeType, nodesExtraData])
  41. return useMemo(() => {
  42. return {
  43. availablePrevBlocks: availablePrevBlocks.filter((nType) => {
  44. if (isInIteration && (nType === BlockEnum.Iteration || nType === BlockEnum.End))
  45. return false
  46. return true
  47. }),
  48. availableNextBlocks: availableNextBlocks.filter((nType) => {
  49. if (isInIteration && (nType === BlockEnum.Iteration || nType === BlockEnum.End))
  50. return false
  51. return true
  52. }),
  53. }
  54. }, [isInIteration, availablePrevBlocks, availableNextBlocks])
  55. }