You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import {
  2. useCallback,
  3. useState,
  4. } from 'react'
  5. import { useTranslation } from 'react-i18next'
  6. import {
  7. DSL_EXPORT_CHECK,
  8. } from '@/app/components/workflow/constants'
  9. import { useNodesSyncDraft } from './use-nodes-sync-draft'
  10. import { useEventEmitterContextContext } from '@/context/event-emitter'
  11. import { fetchWorkflowDraft } from '@/service/workflow'
  12. import { exportAppConfig } from '@/service/apps'
  13. import { useToastContext } from '@/app/components/base/toast'
  14. import { useStore as useAppStore } from '@/app/components/app/store'
  15. export const useDSL = () => {
  16. const { t } = useTranslation()
  17. const { notify } = useToastContext()
  18. const { eventEmitter } = useEventEmitterContextContext()
  19. const [exporting, setExporting] = useState(false)
  20. const { doSyncWorkflowDraft } = useNodesSyncDraft()
  21. const appDetail = useAppStore(s => s.appDetail)
  22. const handleExportDSL = useCallback(async (include = false, workflowId?: string) => {
  23. if (!appDetail)
  24. return
  25. if (exporting)
  26. return
  27. try {
  28. setExporting(true)
  29. await doSyncWorkflowDraft()
  30. const { data } = await exportAppConfig({
  31. appID: appDetail.id,
  32. include,
  33. workflowID: workflowId,
  34. })
  35. const a = document.createElement('a')
  36. const file = new Blob([data], { type: 'application/yaml' })
  37. a.href = URL.createObjectURL(file)
  38. a.download = `${appDetail.name}.yml`
  39. a.click()
  40. }
  41. catch {
  42. notify({ type: 'error', message: t('app.exportFailed') })
  43. }
  44. finally {
  45. setExporting(false)
  46. }
  47. }, [appDetail, notify, t, doSyncWorkflowDraft, exporting])
  48. const exportCheck = useCallback(async () => {
  49. if (!appDetail)
  50. return
  51. try {
  52. const workflowDraft = await fetchWorkflowDraft(`/apps/${appDetail?.id}/workflows/draft`)
  53. const list = (workflowDraft.environment_variables || []).filter(env => env.value_type === 'secret')
  54. if (list.length === 0) {
  55. handleExportDSL()
  56. return
  57. }
  58. eventEmitter?.emit({
  59. type: DSL_EXPORT_CHECK,
  60. payload: {
  61. data: list,
  62. },
  63. } as any)
  64. }
  65. catch {
  66. notify({ type: 'error', message: t('app.exportFailed') })
  67. }
  68. }, [appDetail, eventEmitter, handleExportDSL, notify, t])
  69. return {
  70. exportCheck,
  71. handleExportDSL,
  72. }
  73. }