chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,113 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { CanvasNodesCatalogProbe } from '../../__tests__/canvas-nodes-catalog-probe'
|
||||
import { createNode } from '../../__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
|
||||
import { BlockEnum } from '../../types'
|
||||
import AddBlock from '../add-block'
|
||||
|
||||
vi.mock('@/service/use-plugins', () => ({
|
||||
useFeaturedToolsRecommendations: () => ({ plugins: [], isLoading: false }),
|
||||
useFeaturedTriggersRecommendations: () => ({ plugins: [], isLoading: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-triggers', () => ({
|
||||
useAllTriggerPlugins: () => ({ data: [] }),
|
||||
useInvalidateAllTriggerPlugins: () => vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.tools.builtin.get': async () => [],
|
||||
'workspaces.current.tools.api.get': async () => [],
|
||||
'workspaces.current.tools.workflow.get': async () => [],
|
||||
'workspaces.current.tools.mcp.get': async () => [],
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/app/components/plugins/marketplace/query', () => ({
|
||||
useMarketplacePlugins: () => ({ data: undefined }),
|
||||
}))
|
||||
|
||||
const renderWithReactFlow = (nodes: Array<ReturnType<typeof createNode>> = [], readonly = false) =>
|
||||
renderWorkflowFlowComponent(
|
||||
<>
|
||||
<CanvasNodesCatalogProbe />
|
||||
<AddBlock />
|
||||
</>,
|
||||
{
|
||||
resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' },
|
||||
nodes,
|
||||
edges: [],
|
||||
initialStoreState: { canvasReadOnly: readonly, contextMenuTarget: { type: 'panel' } },
|
||||
},
|
||||
)
|
||||
|
||||
describe('AddBlock', () => {
|
||||
it('opens the real selector and exposes its open state', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWithReactFlow()
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'workflow.common.addBlock' })
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||||
|
||||
await user.click(trigger)
|
||||
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(screen.getByRole('dialog', { name: 'workflow.common.addBlock' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'workflow.blocks.answer' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the disabled trigger focusable without opening the selector', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWithReactFlow([], true)
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'workflow.common.addBlock' })
|
||||
expect(trigger).toHaveAttribute('aria-disabled', 'true')
|
||||
|
||||
trigger.focus()
|
||||
expect(trigger).toHaveFocus()
|
||||
await user.click(trigger)
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'workflow.common.addBlock' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes the selector through the real trigger and cancels the pane menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWithReactFlow()
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'workflow.common.addBlock' })
|
||||
await user.click(trigger)
|
||||
await user.click(trigger)
|
||||
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'workflow.common.addBlock' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(store.getState().contextMenuTarget).toBeUndefined()
|
||||
})
|
||||
|
||||
it('creates a candidate node after selecting a real block option', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWithReactFlow([
|
||||
createNode({ id: 'node-1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Answer } }),
|
||||
createNode({ id: 'node-2', position: { x: 80, y: 0 }, data: { type: BlockEnum.Answer } }),
|
||||
])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.addBlock' }))
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.blocks.answer' }))
|
||||
|
||||
expect(store.getState()).toMatchObject({
|
||||
candidateNode: expect.objectContaining({
|
||||
id: expect.any(String),
|
||||
type: 'custom',
|
||||
data: expect.objectContaining({ type: BlockEnum.Answer, _isCandidate: true }),
|
||||
}),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { Shape } from '../../store/workflow'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createConsoleQueryWrapper } from '@/test/console/query-data'
|
||||
import { createNode } from '../../__tests__/fixtures'
|
||||
import { baseRunningData, renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
|
||||
import { CUSTOM_NOTE_NODE } from '../../note-node/constants'
|
||||
import { ControlMode, WorkflowRunningStatus } from '../../types'
|
||||
import Control from '../control'
|
||||
|
||||
vi.mock('../../hooks/use-nodes-sync-draft', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../hooks/use-nodes-sync-draft')>()
|
||||
return {
|
||||
...actual,
|
||||
useNodesSyncDraft: () => ({
|
||||
handleSyncWorkflowDraft: vi.fn(),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
// The add-block selector and image export own their own suites and service setup.
|
||||
vi.mock('../add-block', () => ({
|
||||
default: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('../export-image', () => ({
|
||||
ExportImage: () => null,
|
||||
}))
|
||||
|
||||
const renderControl = ({
|
||||
initialStoreState,
|
||||
collaborationEnabled = true,
|
||||
}: {
|
||||
initialStoreState?: Partial<Shape>
|
||||
collaborationEnabled?: boolean
|
||||
} = {}) => {
|
||||
const { queryClient } = createConsoleQueryWrapper({
|
||||
accountProfile: { name: 'Ada' },
|
||||
systemFeatures: { enable_collaboration_mode: collaborationEnabled },
|
||||
})
|
||||
return renderWorkflowFlowComponent(<Control />, {
|
||||
queryClient,
|
||||
nodes: [createNode({ id: 'node-1' })],
|
||||
initialStoreState: { controlMode: ControlMode.Pointer, ...initialStoreState },
|
||||
})
|
||||
}
|
||||
|
||||
const getModeButton = (mode: 'pointerMode' | 'handMode' | 'commentMode') =>
|
||||
screen.getByRole('button', { name: `workflow.common.${mode}` })
|
||||
|
||||
describe('Control', () => {
|
||||
it('switches the canvas between pointer, hand, and comment modes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderControl()
|
||||
|
||||
expect(getModeButton('pointerMode')).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
await user.click(getModeButton('handMode'))
|
||||
expect(store.getState().controlMode).toBe(ControlMode.Hand)
|
||||
expect(getModeButton('handMode')).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(getModeButton('pointerMode')).toHaveAttribute('aria-pressed', 'false')
|
||||
|
||||
await user.click(getModeButton('commentMode'))
|
||||
expect(store.getState().controlMode).toBe(ControlMode.Comment)
|
||||
expect(getModeButton('commentMode')).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
await user.click(getModeButton('pointerMode'))
|
||||
expect(store.getState().controlMode).toBe(ControlMode.Pointer)
|
||||
})
|
||||
|
||||
it('creates a note candidate attributed to the current user', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderControl()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.nodes.note.addNote' }))
|
||||
|
||||
expect(store.getState().candidateNode).toMatchObject({
|
||||
type: CUSTOM_NOTE_NODE,
|
||||
data: expect.objectContaining({ author: 'Ada', showAuthor: true, _isCandidate: true }),
|
||||
})
|
||||
})
|
||||
|
||||
it('starts organizing blocks when the canvas is editable', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderControl()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.panel.organizeBlocks' }))
|
||||
|
||||
await waitFor(() => expect(store.getState().nodeAnimation).toBe(true))
|
||||
})
|
||||
|
||||
it('keeps read-only editing actions focusable without changing the canvas', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderControl({ initialStoreState: { canvasReadOnly: true } })
|
||||
|
||||
const noteButton = screen.getByRole('button', { name: 'workflow.nodes.note.addNote' })
|
||||
expect(noteButton).toHaveAttribute('aria-disabled', 'true')
|
||||
noteButton.focus()
|
||||
expect(noteButton).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
await user.click(getModeButton('handMode'))
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.panel.organizeBlocks' }))
|
||||
|
||||
expect(store.getState()).toMatchObject({
|
||||
candidateNode: undefined,
|
||||
controlMode: ControlMode.Pointer,
|
||||
nodeAnimation: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('still allows comment mode on a read-only canvas', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderControl({ initialStoreState: { canvasReadOnly: true } })
|
||||
|
||||
await user.click(getModeButton('commentMode'))
|
||||
|
||||
expect(store.getState().controlMode).toBe(ControlMode.Comment)
|
||||
})
|
||||
|
||||
it('blocks comment mode while a workflow run is in progress', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderControl({
|
||||
initialStoreState: {
|
||||
workflowRunningData: baseRunningData({
|
||||
result: { status: WorkflowRunningStatus.Running },
|
||||
}),
|
||||
},
|
||||
})
|
||||
|
||||
const commentButton = getModeButton('commentMode')
|
||||
expect(commentButton).toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(commentButton)
|
||||
|
||||
expect(store.getState().controlMode).toBe(ControlMode.Pointer)
|
||||
})
|
||||
|
||||
it('hides comment mode when collaboration is unavailable', () => {
|
||||
renderControl({ collaborationEnabled: false })
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflow.common.commentMode' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,345 @@
|
||||
import { screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { act, useEffect } from 'react'
|
||||
import { useReactFlow } from 'reactflow'
|
||||
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'
|
||||
import { createAppDetailFixture } from '@/test/fixtures/app'
|
||||
import { ExportImage } from '../export-image'
|
||||
|
||||
const mockToPng = vi.fn()
|
||||
const mockToJpeg = vi.fn()
|
||||
const mockToSvg = vi.fn()
|
||||
const mockDownloadUrl = vi.fn()
|
||||
const { mockWorkflowState } = vi.hoisted(() => ({
|
||||
mockWorkflowState: {
|
||||
appName: 'Demo App',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('html-to-image', () => ({
|
||||
toPng: (...args: unknown[]) => mockToPng(...args),
|
||||
toJpeg: (...args: unknown[]) => mockToJpeg(...args),
|
||||
toSvg: (...args: unknown[]) => mockToSvg(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/utils/download', () => ({
|
||||
downloadUrl: (...args: unknown[]) => mockDownloadUrl(...args),
|
||||
}))
|
||||
|
||||
function createExportQueryClient() {
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedAppDetail(
|
||||
queryClient,
|
||||
createAppDetailFixture({ id: 'app-1', mode: 'workflow', name: mockWorkflowState.appName }),
|
||||
)
|
||||
return queryClient
|
||||
}
|
||||
|
||||
const originalViewport = { x: 137, y: -83, zoom: 0.65 }
|
||||
const fittedViewport = { x: -40, y: 68, zoom: 0.8 }
|
||||
|
||||
const nodes = [
|
||||
createNode({ id: 'left', position: { x: 100, y: 80 }, width: 400, height: 200 }),
|
||||
createNode({ id: 'right', position: { x: 900, y: 500 }, width: 300, height: 150 }),
|
||||
]
|
||||
|
||||
type Flow = ReturnType<typeof useReactFlow>
|
||||
|
||||
function ReactFlowProbe({ onReady }: { onReady: (flow: Flow) => void }) {
|
||||
const flow = useReactFlow()
|
||||
useEffect(() => onReady(flow), [flow, onReady])
|
||||
return null
|
||||
}
|
||||
|
||||
function renderExport(options: Parameters<typeof render>[1] = {}) {
|
||||
let flow: Flow | undefined
|
||||
const onReady = (instance: Flow) => {
|
||||
flow = instance
|
||||
}
|
||||
const rendered = render(
|
||||
<>
|
||||
<ExportImage />
|
||||
<ReactFlowProbe onReady={onReady} />
|
||||
</>,
|
||||
{
|
||||
nodes,
|
||||
reactFlowProps: { fitView: false, defaultViewport: originalViewport },
|
||||
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
|
||||
queryClient: createExportQueryClient(),
|
||||
...options,
|
||||
},
|
||||
)
|
||||
|
||||
if (!flow) throw new Error('ReactFlow probe did not mount')
|
||||
return { ...rendered, flow }
|
||||
}
|
||||
|
||||
describe('ExportImage', () => {
|
||||
beforeEach(() => {
|
||||
mockToPng.mockReset().mockResolvedValue('data:image/png;base64,current')
|
||||
mockToJpeg.mockReset().mockResolvedValue('data:image/jpeg;base64,current')
|
||||
mockToSvg.mockReset().mockResolvedValue('data:image/svg+xml;base64,current')
|
||||
mockDownloadUrl.mockReset()
|
||||
mockWorkflowState.appName = 'Demo App'
|
||||
vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(960)
|
||||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(720)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('opens the menu and exports the current view as png', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderExport()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
const menu = screen.getByRole('menu', { name: 'workflow.common.exportImage' })
|
||||
expect(within(menu).getAllByRole('menuitem')).toHaveLength(6)
|
||||
expect(
|
||||
within(menu).getByRole('group', { name: 'workflow.common.currentView' }),
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
within(menu).getByRole('group', { name: 'workflow.common.currentWorkflow' }),
|
||||
).toBeInTheDocument()
|
||||
expect(within(menu).queryByText('workflow.common.exportImage')).not.toBeInTheDocument()
|
||||
await user.click(
|
||||
within(within(menu).getByRole('group', { name: 'workflow.common.currentView' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: 'workflow.common.exportPNG' },
|
||||
),
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockDownloadUrl).toHaveBeenCalledWith({
|
||||
url: 'data:image/png;base64,current',
|
||||
fileName: 'Demo App.png',
|
||||
}),
|
||||
)
|
||||
expect(mockToPng).toHaveBeenCalledTimes(1)
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not open the menu when the workflow is read only', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderExport({ initialStoreState: { canvasReadOnly: true } })
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'workflow.common.exportImage' })
|
||||
expect(trigger).toHaveAttribute('aria-disabled', 'true')
|
||||
|
||||
trigger.focus()
|
||||
expect(trigger).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a preview when exporting the whole workflow', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
|
||||
|
||||
const { flow } = renderExport()
|
||||
let captureViewport: ReturnType<Flow['getViewport']> | undefined
|
||||
mockToPng.mockImplementationOnce(async () => {
|
||||
captureViewport = flow.getViewport()
|
||||
return 'data:image/png;base64,current'
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
await user.click(
|
||||
within(screen.getByRole('group', { name: 'workflow.common.currentWorkflow' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: 'workflow.common.exportPNG' },
|
||||
),
|
||||
)
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
})
|
||||
|
||||
expect(captureViewport).toEqual(fittedViewport)
|
||||
expect(mockToPng).toHaveBeenCalledWith(
|
||||
expect.any(HTMLElement),
|
||||
expect.objectContaining({
|
||||
backgroundColor: '#1a1a1a',
|
||||
height: 670,
|
||||
pixelRatio: 2,
|
||||
style: expect.objectContaining({
|
||||
height: '670px',
|
||||
transform: 'translate(-50px, -30px)',
|
||||
width: '1200px',
|
||||
}),
|
||||
width: 1200,
|
||||
}),
|
||||
)
|
||||
expect(flow.getViewport()).toEqual(originalViewport)
|
||||
expect(screen.getByRole('dialog', { name: 'Demo App-whole-workflow.png' })).toBeInTheDocument()
|
||||
expect(mockDownloadUrl).toHaveBeenCalledWith({
|
||||
url: 'data:image/png;base64,current',
|
||||
fileName: 'Demo App-whole-workflow.png',
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['workflow.common.exportJPEG', mockToJpeg, 'Demo App.jpeg'],
|
||||
['workflow.common.exportSVG', mockToSvg, 'Demo App.svg'],
|
||||
])('exports the current view with %s', async (label, exporter, fileName) => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderExport()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
await user.click(
|
||||
within(screen.getByRole('group', { name: 'workflow.common.currentView' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: label },
|
||||
),
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockDownloadUrl).toHaveBeenCalledWith({
|
||||
url: expect.any(String),
|
||||
fileName,
|
||||
}),
|
||||
)
|
||||
expect(exporter).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('exports the whole workflow as svg', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
|
||||
|
||||
const { flow } = renderExport()
|
||||
let captureViewport: ReturnType<Flow['getViewport']> | undefined
|
||||
mockToSvg.mockImplementationOnce(async () => {
|
||||
captureViewport = flow.getViewport()
|
||||
return 'data:image/svg+xml;base64,current'
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
await user.click(
|
||||
within(screen.getByRole('group', { name: 'workflow.common.currentWorkflow' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: 'workflow.common.exportSVG' },
|
||||
),
|
||||
)
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
})
|
||||
|
||||
expect(mockToSvg).toHaveBeenCalledTimes(1)
|
||||
expect(captureViewport).toEqual(fittedViewport)
|
||||
expect(flow.getViewport()).toEqual(originalViewport)
|
||||
expect(screen.getByRole('dialog', { name: 'Demo App-whole-workflow.svg' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the refreshed App name when exporting without restarting the editor', async () => {
|
||||
const user = userEvent.setup()
|
||||
const queryClient = createExportQueryClient()
|
||||
renderExport({ queryClient })
|
||||
await act(async () => {
|
||||
seedAppDetail(
|
||||
queryClient,
|
||||
createAppDetailFixture({ id: 'app-1', mode: 'workflow', name: 'Renamed App' }),
|
||||
)
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
const group = screen.getByRole('group', { name: 'workflow.common.currentView' })
|
||||
await user.click(within(group).getByRole('menuitem', { name: 'workflow.common.exportPNG' }))
|
||||
await waitFor(() =>
|
||||
expect(mockDownloadUrl).toHaveBeenCalledWith({
|
||||
url: 'data:image/png;base64,current',
|
||||
fileName: 'Renamed App.png',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns early when there is no app or knowledge name', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockWorkflowState.appName = ''
|
||||
|
||||
renderExport()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
await user.click(
|
||||
within(screen.getByRole('group', { name: 'workflow.common.currentView' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: 'workflow.common.exportPNG' },
|
||||
),
|
||||
)
|
||||
|
||||
expect(mockToPng).not.toHaveBeenCalled()
|
||||
expect(mockDownloadUrl).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('restores the viewport when rendering the whole workflow fails', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const { flow } = renderExport()
|
||||
let captureViewport: ReturnType<Flow['getViewport']> | undefined
|
||||
mockToPng.mockImplementationOnce(async () => {
|
||||
captureViewport = flow.getViewport()
|
||||
throw new Error('capture failed')
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
await user.click(
|
||||
within(screen.getByRole('group', { name: 'workflow.common.currentWorkflow' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: 'workflow.common.exportPNG' },
|
||||
),
|
||||
)
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
})
|
||||
|
||||
expect(mockToPng).toHaveBeenCalledTimes(1)
|
||||
expect(captureViewport).toEqual(fittedViewport)
|
||||
expect(flow.getViewport()).toEqual(originalViewport)
|
||||
expect(mockDownloadUrl).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('logs export failures and lets the preview close', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
mockToJpeg.mockRejectedValueOnce(new Error('boom'))
|
||||
|
||||
renderExport()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
await user.click(
|
||||
within(screen.getByRole('group', { name: 'workflow.common.currentView' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: 'workflow.common.exportJPEG' },
|
||||
),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
})
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Export image failed:', expect.any(Error))
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
|
||||
mockToPng.mockResolvedValueOnce('data:image/png;base64,current')
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))
|
||||
await user.click(
|
||||
within(screen.getByRole('group', { name: 'workflow.common.currentWorkflow' })).getByRole(
|
||||
'menuitem',
|
||||
{ name: 'workflow.common.exportPNG' },
|
||||
),
|
||||
)
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
})
|
||||
expect(screen.getByRole('dialog', { name: 'Demo App-whole-workflow.png' })).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
|
||||
consoleErrorSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
import { act, screen, waitFor } from '@testing-library/react'
|
||||
import { createNode } from '../../__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
|
||||
import { BlockEnum } from '../../types'
|
||||
import Operator from '../index'
|
||||
|
||||
const mockEmit = vi.fn()
|
||||
const mockDeleteAllInspectorVars = vi.fn()
|
||||
|
||||
vi.mock('../../hooks/use-nodes-sync-draft', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../hooks/use-nodes-sync-draft')>()
|
||||
return {
|
||||
...actual,
|
||||
useNodesSyncDraft: () => ({
|
||||
handleSyncWorkflowDraft: vi.fn(),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../hooks/use-workflow', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../hooks/use-workflow')>()
|
||||
return {
|
||||
...actual,
|
||||
useWorkflowReadOnly: () => ({
|
||||
workflowReadOnly: false,
|
||||
getWorkflowReadOnly: () => false,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../hooks/use-inspect-vars-crud', () => ({
|
||||
default: () => ({
|
||||
conversationVars: [],
|
||||
systemVars: [],
|
||||
nodesWithInspectVars: [],
|
||||
deleteAllInspectorVars: mockDeleteAllInspectorVars,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/context/event-emitter', () => ({
|
||||
useEventEmitterContextContext: () => ({
|
||||
eventEmitter: {
|
||||
emit: mockEmit,
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
const observers: MockResizeObserver[] = []
|
||||
|
||||
class MockResizeObserver implements ResizeObserver {
|
||||
target?: Element
|
||||
disconnect = vi.fn()
|
||||
readonly callback: ResizeObserverCallback
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
this.callback = callback
|
||||
observers.push(this)
|
||||
}
|
||||
observe(target: Element) {
|
||||
this.target = target
|
||||
}
|
||||
unobserve() {}
|
||||
}
|
||||
|
||||
const renderOperator = (initialStoreState: Record<string, unknown> = {}) => {
|
||||
return renderWorkflowFlowComponent(<Operator handleUndo={vi.fn()} handleRedo={vi.fn()} />, {
|
||||
nodes: [
|
||||
createNode({
|
||||
id: 'node-1',
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Code',
|
||||
desc: '',
|
||||
},
|
||||
}),
|
||||
],
|
||||
edges: [],
|
||||
initialStoreState,
|
||||
historyStore: {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('Operator', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
observers.length = 0
|
||||
vi.stubGlobal('ResizeObserver', MockResizeObserver)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('should sync the observed panel size back into the workflow store and disconnect on unmount', async () => {
|
||||
const { store, unmount } = renderOperator({
|
||||
workflowCanvasWidth: 900,
|
||||
rightPanelWidth: 260,
|
||||
})
|
||||
|
||||
const trigger = screen.getByText('workflowDebug.debug.variableInspect.trigger.normal')
|
||||
const observer = observers.find((candidate) => candidate.target?.contains(trigger))!
|
||||
expect(observer).toBeDefined()
|
||||
|
||||
act(() => {
|
||||
const size = { inlineSize: 512, blockSize: 188 }
|
||||
observer.callback(
|
||||
[
|
||||
{
|
||||
target: observer.target!,
|
||||
borderBoxSize: [size],
|
||||
contentBoxSize: [size],
|
||||
devicePixelContentBoxSize: [size],
|
||||
contentRect: new DOMRect(0, 0, 512, 188),
|
||||
},
|
||||
],
|
||||
observer,
|
||||
)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(store.getState().bottomPanelWidth).toBe(512)
|
||||
expect(store.getState().bottomPanelHeight).toBe(188)
|
||||
})
|
||||
|
||||
unmount()
|
||||
|
||||
expect(observer.disconnect).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
import type { Shape as HooksStoreShape } from '../../hooks-store/store'
|
||||
import { act, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { createConsoleQueryWrapper } from '@/test/console/query-data'
|
||||
import ZoomInOut from '../zoom-in-out'
|
||||
|
||||
let workflowReadOnly = false
|
||||
let collaborationEnabled = true
|
||||
|
||||
const renderZoomInOut = ({
|
||||
ui = <ZoomInOut />,
|
||||
initialZoom = 1,
|
||||
}: {
|
||||
ui?: React.ReactElement
|
||||
initialZoom?: number
|
||||
} = {}) => {
|
||||
const { queryClient } = createConsoleQueryWrapper({
|
||||
systemFeatures: { enable_collaboration_mode: collaborationEnabled },
|
||||
})
|
||||
const doSyncWorkflowDraft = vi
|
||||
.fn<HooksStoreShape['doSyncWorkflowDraft']>()
|
||||
.mockResolvedValue(undefined)
|
||||
const view = renderWorkflowFlowComponent(ui, {
|
||||
queryClient,
|
||||
nodes: [
|
||||
createNode({ id: 'left', position: { x: 0, y: 0 }, width: 240, height: 80 }),
|
||||
createNode({ id: 'right', position: { x: 1600, y: 400 }, width: 240, height: 80 }),
|
||||
],
|
||||
initialStoreState: { canvasReadOnly: workflowReadOnly },
|
||||
hooksStoreProps: { doSyncWorkflowDraft },
|
||||
reactFlowProps: {
|
||||
fitView: false,
|
||||
minZoom: 0.25,
|
||||
maxZoom: 2,
|
||||
defaultViewport: { x: 0, y: 0, zoom: initialZoom },
|
||||
},
|
||||
})
|
||||
return { ...view, doSyncWorkflowDraft }
|
||||
}
|
||||
|
||||
const getZoomControls = () => ({
|
||||
label: screen.getByRole('button', { name: /^\d+%$/ }),
|
||||
zoomOutTrigger: screen.getByRole('button', { name: 'workflow.operator.zoomOut' }),
|
||||
zoomInTrigger: screen.getByRole('button', { name: 'workflow.operator.zoomIn' }),
|
||||
})
|
||||
|
||||
const openZoomMenu = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await user.click(getZoomControls().label)
|
||||
return within(screen.getByRole('menu'))
|
||||
}
|
||||
|
||||
describe('workflow zoom controls', () => {
|
||||
beforeEach(() => {
|
||||
workflowReadOnly = false
|
||||
collaborationEnabled = true
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ key: '1', modifier: 'Shift', initialZoom: 0.75, expectedLabel: '100%' },
|
||||
{ key: '5', modifier: 'Shift', initialZoom: 1, expectedLabel: '50%' },
|
||||
])(
|
||||
'applies $modifier+$key from the focused zoom menu',
|
||||
async ({ key, modifier, initialZoom, expectedLabel }) => {
|
||||
const user = userEvent.setup()
|
||||
const { store, doSyncWorkflowDraft } = renderZoomInOut({ initialZoom })
|
||||
const menu = await openZoomMenu(user)
|
||||
const item = menu.getByRole('menuitem', { name: '200%' })
|
||||
act(() => item.focus())
|
||||
|
||||
await user.keyboard(`{${modifier}>}${key}{/${modifier}}`)
|
||||
|
||||
await waitFor(() => expect(getZoomControls().label).toHaveAccessibleName(expectedLabel))
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
act(() => store.getState().flushPendingSync())
|
||||
expect(doSyncWorkflowDraft).toHaveBeenCalledTimes(1)
|
||||
},
|
||||
)
|
||||
|
||||
it('fits the real graph from the menu item', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store, doSyncWorkflowDraft } = renderZoomInOut()
|
||||
const menu = await openZoomMenu(user)
|
||||
|
||||
await user.click(menu.getByRole('menuitem', { name: /^workflow\.operator\.zoomToFit/ }))
|
||||
|
||||
await waitFor(() => expect(getZoomControls().label).toHaveAccessibleName('25%'))
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
act(() => store.getState().flushPendingSync())
|
||||
expect(doSyncWorkflowDraft).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('zooms out and in through the inline controls and reports the real viewport', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderZoomInOut()
|
||||
|
||||
await user.click(getZoomControls().zoomOutTrigger)
|
||||
await waitFor(() => expect(getZoomControls().label).toHaveAccessibleName('83%'))
|
||||
|
||||
await user.click(getZoomControls().zoomInTrigger)
|
||||
await waitFor(() => expect(getZoomControls().label).toHaveAccessibleName('100%'))
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ itemLabel: '50%', initialZoom: 1 },
|
||||
{ itemLabel: '100%', initialZoom: 0.75 },
|
||||
{ itemLabel: '200%', initialZoom: 1 },
|
||||
])('zooms to the $itemLabel preset through its menu item', async ({ itemLabel, initialZoom }) => {
|
||||
const user = userEvent.setup()
|
||||
const { store, doSyncWorkflowDraft } = renderZoomInOut({ initialZoom })
|
||||
|
||||
const menu = await openZoomMenu(user)
|
||||
await user.click(menu.getByRole('menuitem', { name: new RegExp(`^${itemLabel}`) }))
|
||||
|
||||
await waitFor(() => expect(getZoomControls().label).toHaveAccessibleName(itemLabel))
|
||||
act(() => store.getState().flushPendingSync())
|
||||
expect(doSyncWorkflowDraft).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('updates controlled collaboration settings without saving the graph', async () => {
|
||||
const user = userEvent.setup()
|
||||
const DisplaySettings = () => {
|
||||
const [showMiniMap, setShowMiniMap] = useState(true)
|
||||
const [showUserCursors, setShowUserCursors] = useState(false)
|
||||
const [showUserComments, setShowUserComments] = useState(true)
|
||||
return (
|
||||
<ZoomInOut
|
||||
showMiniMap={showMiniMap}
|
||||
onToggleMiniMap={() => setShowMiniMap((value) => !value)}
|
||||
showUserCursors={showUserCursors}
|
||||
onToggleUserCursors={() => setShowUserCursors((value) => !value)}
|
||||
showUserComments={showUserComments}
|
||||
onToggleUserComments={() => setShowUserComments((value) => !value)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const { store, doSyncWorkflowDraft } = renderZoomInOut({ ui: <DisplaySettings /> })
|
||||
|
||||
let menu = await openZoomMenu(user)
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showMiniMap' }),
|
||||
).toBeChecked()
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showUserCursors' }),
|
||||
).not.toBeChecked()
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showUserComments' }),
|
||||
).toBeChecked()
|
||||
|
||||
await user.click(menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showMiniMap' }))
|
||||
menu = await openZoomMenu(user)
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showMiniMap' }),
|
||||
).not.toBeChecked()
|
||||
act(() => menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showMiniMap' }).focus())
|
||||
await user.keyboard('{Enter}')
|
||||
menu = await openZoomMenu(user)
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showMiniMap' }),
|
||||
).toBeChecked()
|
||||
await user.click(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showUserCursors' }),
|
||||
)
|
||||
menu = await openZoomMenu(user)
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showUserCursors' }),
|
||||
).toBeChecked()
|
||||
await user.click(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showUserComments' }),
|
||||
)
|
||||
menu = await openZoomMenu(user)
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showUserComments' }),
|
||||
).not.toBeChecked()
|
||||
act(() => store.getState().flushPendingSync())
|
||||
expect(doSyncWorkflowDraft).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the show-user-comments action disabled in comment mode', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onToggleUserComments = vi.fn()
|
||||
renderZoomInOut({
|
||||
ui: <ZoomInOut isCommentMode onToggleUserComments={onToggleUserComments} />,
|
||||
})
|
||||
|
||||
const menu = await openZoomMenu(user)
|
||||
const comments = menu.getByRole('menuitemcheckbox', {
|
||||
name: 'workflow.operator.showUserComments',
|
||||
})
|
||||
expect(comments).toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(comments)
|
||||
expect(onToggleUserComments).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not open the menu when the workflow is read only', async () => {
|
||||
const user = userEvent.setup()
|
||||
workflowReadOnly = true
|
||||
renderZoomInOut()
|
||||
|
||||
expect(getZoomControls().label).toBeDisabled()
|
||||
await user.click(getZoomControls().label)
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disables inline zoom controls at the supported viewport bounds', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderZoomInOut()
|
||||
|
||||
let menu = await openZoomMenu(user)
|
||||
await user.click(menu.getByRole('menuitem', { name: '25%' }))
|
||||
await waitFor(() => expect(getZoomControls().zoomOutTrigger).toBeDisabled())
|
||||
|
||||
menu = await openZoomMenu(user)
|
||||
await user.click(menu.getByRole('menuitem', { name: '200%' }))
|
||||
await waitFor(() => expect(getZoomControls().zoomInTrigger).toBeDisabled())
|
||||
})
|
||||
|
||||
it('renders collaboration menu entries only when collaboration is enabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
collaborationEnabled = false
|
||||
renderZoomInOut()
|
||||
|
||||
const menu = await openZoomMenu(user)
|
||||
expect(
|
||||
menu.getByRole('menuitemcheckbox', { name: 'workflow.operator.showMiniMap' }),
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
menu.queryByRole('menuitemcheckbox', { name: 'workflow.operator.showUserComments' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(
|
||||
menu.queryByRole('menuitemcheckbox', { name: 'workflow.operator.showUserCursors' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { BlockSelectorProps } from '@/app/components/workflow/block-selector'
|
||||
import type { Node, OnSelectBlock } from '@/app/components/workflow/types'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { memo, useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import BlockSelector from '@/app/components/workflow/block-selector'
|
||||
import {
|
||||
editorResourceKindAtom,
|
||||
isChatflowAtom,
|
||||
} from '@/app/components/workflow/editor-resource/state'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { useAvailableBlocks } from '../hooks/use-available-blocks'
|
||||
import { useNodesMetaData } from '../hooks/use-nodes-meta-data'
|
||||
import { usePanelInteractions } from '../hooks/use-panel-interactions'
|
||||
import { useNodesReadOnly } from '../hooks/use-workflow'
|
||||
import { useWorkflowStore } from '../store'
|
||||
import {
|
||||
generateNewNode,
|
||||
getNodeCustomTypeByNodeDataType,
|
||||
getNodesWithSameDefaultDataType,
|
||||
} from '../utils'
|
||||
|
||||
type AddBlockProps = Pick<
|
||||
BlockSelectorProps,
|
||||
'triggerClassName' | 'sideOffset' | 'alignOffset' | 'isolateKeyboardEvents'
|
||||
> & {
|
||||
renderTrigger?: BlockSelectorProps['trigger']
|
||||
onClose?: () => void
|
||||
}
|
||||
const AddBlock = ({
|
||||
renderTrigger,
|
||||
triggerClassName,
|
||||
sideOffset,
|
||||
alignOffset,
|
||||
onClose,
|
||||
isolateKeyboardEvents,
|
||||
}: AddBlockProps) => {
|
||||
const { t } = useTranslation(['workflow'] as const)
|
||||
const store = useStoreApi()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const isChatflow = useAtomValue(isChatflowAtom)
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const { handlePaneContextmenuCancel } = usePanelInteractions()
|
||||
const [open, setOpen] = useState(false)
|
||||
const { availableNextBlocks } = useAvailableBlocks(BlockEnum.Start, false)
|
||||
const { nodesMap: nodesMetaDataMap } = useNodesMetaData()
|
||||
const resourceKind = useAtomValue(editorResourceKindAtom)
|
||||
const showStartTab = resourceKind !== 'knowledge-pipeline' && !isChatflow
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setOpen(open)
|
||||
if (!open) (onClose ?? handlePaneContextmenuCancel)()
|
||||
},
|
||||
[handlePaneContextmenuCancel, onClose],
|
||||
)
|
||||
|
||||
const handleSelect = useCallback<OnSelectBlock>(
|
||||
(type, pluginDefaultValue) => {
|
||||
const { getNodes } = store.getState()
|
||||
const { defaultValue } = nodesMetaDataMap![type]
|
||||
const nodes = getNodes()
|
||||
const nodesWithSameType = getNodesWithSameDefaultDataType(nodes, type, defaultValue)
|
||||
const { newNode } = generateNewNode({
|
||||
type: getNodeCustomTypeByNodeDataType(type),
|
||||
data: {
|
||||
...(defaultValue as Node['data']),
|
||||
title:
|
||||
nodesWithSameType.length > 0
|
||||
? `${defaultValue.title} ${nodesWithSameType.length + 1}`
|
||||
: defaultValue.title,
|
||||
...pluginDefaultValue,
|
||||
_isCandidate: true,
|
||||
},
|
||||
position: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
})
|
||||
workflowStore.setState({
|
||||
candidateNode: newNode,
|
||||
})
|
||||
},
|
||||
[store, workflowStore, nodesMetaDataMap],
|
||||
)
|
||||
|
||||
const renderTriggerElement = (
|
||||
<IconButton
|
||||
aria-label={t(($) => $['common.addBlock'], { ns: 'workflow' })}
|
||||
size="lg"
|
||||
disabled={nodesReadOnly}
|
||||
focusableWhenDisabled
|
||||
data-block-selector-open={open ? '' : undefined}
|
||||
className="rounded-md data-block-selector-open:bg-state-accent-active data-block-selector-open:text-text-accent"
|
||||
>
|
||||
<span aria-hidden className="i-ri-add-circle-fill size-4" />
|
||||
</IconButton>
|
||||
)
|
||||
|
||||
return (
|
||||
<BlockSelector
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
disabled={nodesReadOnly}
|
||||
onSelect={handleSelect}
|
||||
align="start"
|
||||
sideOffset={sideOffset ?? 4}
|
||||
alignOffset={alignOffset ?? -8}
|
||||
trigger={renderTrigger || renderTriggerElement}
|
||||
triggerClassName={triggerClassName}
|
||||
triggerAriaLabel={t(($) => $['common.addBlock'], { ns: 'workflow' })}
|
||||
// A caller-provided trigger, such as a menu row, already shows its own label.
|
||||
triggerTooltip={
|
||||
renderTrigger ? undefined : t(($) => $['common.addBlock'], { ns: 'workflow' })
|
||||
}
|
||||
popupClassName="min-w-[256px]!"
|
||||
availableBlocksTypes={availableNextBlocks}
|
||||
showStartTab={showStartTab}
|
||||
isolateKeyboardEvents={isolateKeyboardEvents}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(AddBlock)
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { MouseEvent } from 'react'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { Toggle } from '@langgenius/dify-ui/toggle'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useNodesReadOnly } from '../hooks/use-workflow'
|
||||
import { useWorkflowOrganize } from '../hooks/use-workflow-organize'
|
||||
import { useWorkflowMoveMode } from '../hooks/use-workflow-panel-interactions'
|
||||
import { useStore } from '../store'
|
||||
import { ControlMode } from '../types'
|
||||
import AddBlock from './add-block'
|
||||
import { ExportImage } from './export-image'
|
||||
import { useOperator } from './hooks'
|
||||
import TipPopup from './tip-popup'
|
||||
|
||||
const pressedModeClassName =
|
||||
'data-pressed:bg-state-accent-active data-pressed:text-text-accent data-pressed:hover:bg-state-base-hover data-pressed:hover:text-text-secondary data-disabled:data-pressed:text-text-disabled data-disabled:data-pressed:hover:bg-transparent data-disabled:data-pressed:hover:text-text-disabled'
|
||||
|
||||
const Control = () => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const controlMode = useStore((s) => s.controlMode)
|
||||
const {
|
||||
handleModePointer,
|
||||
handleModeHand,
|
||||
handleModeComment,
|
||||
isCommentModeAvailable,
|
||||
canUseCommentMode,
|
||||
} = useWorkflowMoveMode()
|
||||
const { handleLayout } = useWorkflowOrganize()
|
||||
const { handleAddNote } = useOperator()
|
||||
const { nodesReadOnly, getNodesReadOnly } = useNodesReadOnly()
|
||||
|
||||
const addNote = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
if (getNodesReadOnly()) return
|
||||
|
||||
e.stopPropagation()
|
||||
handleAddNote()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pointer-events-auto flex flex-col items-center rounded-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 text-text-tertiary shadow-lg">
|
||||
<AddBlock />
|
||||
<TipPopup title={t(($) => $['nodes.note.addNote'], { ns: 'workflow' })}>
|
||||
<IconButton
|
||||
size="lg"
|
||||
aria-label={t(($) => $['nodes.note.addNote'], { ns: 'workflow' })}
|
||||
disabled={nodesReadOnly}
|
||||
focusableWhenDisabled
|
||||
className="ml-px rounded-md"
|
||||
onClick={addNote}
|
||||
>
|
||||
<span aria-hidden className="i-ri-sticky-note-add-line size-4" />
|
||||
</IconButton>
|
||||
</TipPopup>
|
||||
<Separator className="my-1 h-[0.5px] w-3.5" />
|
||||
<TipPopup
|
||||
title={t(($) => $['common.pointerMode'], { ns: 'workflow' })}
|
||||
shortcut="workflow.pointer-mode"
|
||||
>
|
||||
<Toggle
|
||||
pressed={controlMode === ControlMode.Pointer}
|
||||
onPressedChange={handleModePointer}
|
||||
disabled={nodesReadOnly}
|
||||
className={pressedModeClassName}
|
||||
render={
|
||||
<IconButton
|
||||
size="lg"
|
||||
aria-label={t(($) => $['common.pointerMode'], { ns: 'workflow' })}
|
||||
disabled={nodesReadOnly}
|
||||
focusableWhenDisabled
|
||||
className="mr-px rounded-md"
|
||||
>
|
||||
<span aria-hidden className="i-ri-cursor-line size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</TipPopup>
|
||||
<TipPopup
|
||||
title={t(($) => $['common.handMode'], { ns: 'workflow' })}
|
||||
shortcut="workflow.hand-mode"
|
||||
>
|
||||
<Toggle
|
||||
pressed={controlMode === ControlMode.Hand}
|
||||
onPressedChange={handleModeHand}
|
||||
disabled={nodesReadOnly}
|
||||
className={pressedModeClassName}
|
||||
render={
|
||||
<IconButton
|
||||
size="lg"
|
||||
aria-label={t(($) => $['common.handMode'], { ns: 'workflow' })}
|
||||
disabled={nodesReadOnly}
|
||||
focusableWhenDisabled
|
||||
className="rounded-md"
|
||||
>
|
||||
<span aria-hidden className="i-ri-hand size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</TipPopup>
|
||||
{isCommentModeAvailable && (
|
||||
<TipPopup
|
||||
title={t(($) => $['common.commentMode'], { ns: 'workflow' })}
|
||||
shortcut="workflow.comment-mode"
|
||||
>
|
||||
<Toggle
|
||||
pressed={controlMode === ControlMode.Comment}
|
||||
onPressedChange={handleModeComment}
|
||||
disabled={!canUseCommentMode}
|
||||
className={pressedModeClassName}
|
||||
render={
|
||||
<IconButton
|
||||
size="lg"
|
||||
aria-label={t(($) => $['common.commentMode'], { ns: 'workflow' })}
|
||||
disabled={!canUseCommentMode}
|
||||
focusableWhenDisabled
|
||||
className="ml-px rounded-md"
|
||||
>
|
||||
<span aria-hidden className="i-custom-public-other-comment size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</TipPopup>
|
||||
)}
|
||||
<Separator className="my-1 h-[0.5px] w-3.5" />
|
||||
<TipPopup
|
||||
title={t(($) => $['panel.organizeBlocks'], { ns: 'workflow' })}
|
||||
shortcut="workflow.organize"
|
||||
>
|
||||
<IconButton
|
||||
size="lg"
|
||||
aria-label={t(($) => $['panel.organizeBlocks'], { ns: 'workflow' })}
|
||||
disabled={nodesReadOnly}
|
||||
focusableWhenDisabled
|
||||
className="rounded-md"
|
||||
onClick={handleLayout}
|
||||
>
|
||||
<span aria-hidden className="i-ri-function-add-line size-4" />
|
||||
</IconButton>
|
||||
</TipPopup>
|
||||
<ExportImage />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Control)
|
||||
@@ -0,0 +1,212 @@
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import {
|
||||
Menu,
|
||||
MenuContent,
|
||||
MenuGroup,
|
||||
MenuGroupLabel,
|
||||
MenuItem,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from '@langgenius/dify-ui/menu'
|
||||
import { skipToken, useQuery } from '@tanstack/react-query'
|
||||
import { toJpeg, toPng, toSvg } from 'html-to-image'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { memo, useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getNodesBounds, useReactFlow } from 'reactflow'
|
||||
import ImagePreview from '@/app/components/base/image-uploader/image-preview'
|
||||
import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { downloadUrl } from '@/utils/download'
|
||||
import { useNodesReadOnly } from '../hooks/use-workflow'
|
||||
import TipPopup from './tip-popup'
|
||||
|
||||
const ExportImage = memo(() => {
|
||||
const { t } = useTranslation(['workflow'] as const)
|
||||
const { getNodesReadOnly } = useNodesReadOnly()
|
||||
const reactFlow = useReactFlow()
|
||||
|
||||
const [previewUrl, setPreviewUrl] = useState('')
|
||||
const [previewTitle, setPreviewTitle] = useState('')
|
||||
const knowledgeName = useStore((s) => s.knowledgeName)
|
||||
const appId = useAtomValue(editorAppIdAtom)
|
||||
const { data: appName } = useQuery(
|
||||
consoleQuery.apps.byAppId.get.queryOptions({
|
||||
input: appId ? { params: { app_id: appId } } : skipToken,
|
||||
select: (app) => app.name,
|
||||
}),
|
||||
)
|
||||
const isReadOnly = getNodesReadOnly()
|
||||
|
||||
const handleExportImage = useCallback(
|
||||
async (type: 'png' | 'jpeg' | 'svg', currentWorkflow = false) => {
|
||||
if (!appName && !knowledgeName) return
|
||||
|
||||
if (getNodesReadOnly()) return
|
||||
|
||||
const flowElement = document.querySelector('.react-flow__viewport') as HTMLElement
|
||||
if (!flowElement) return
|
||||
|
||||
try {
|
||||
let filename = appName || knowledgeName
|
||||
const filter = (node: HTMLElement) => {
|
||||
if (node instanceof HTMLImageElement) return node.complete && node.naturalHeight !== 0
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
let dataUrl
|
||||
|
||||
if (currentWorkflow) {
|
||||
const nodes = reactFlow.getNodes()
|
||||
const nodesBounds = getNodesBounds(nodes)
|
||||
|
||||
const currentViewport = reactFlow.getViewport()
|
||||
|
||||
const viewportWidth = window.innerWidth
|
||||
const viewportHeight = window.innerHeight
|
||||
const zoom = Math.min(
|
||||
viewportWidth / (nodesBounds.width + 100),
|
||||
viewportHeight / (nodesBounds.height + 100),
|
||||
1,
|
||||
)
|
||||
|
||||
const centerX = nodesBounds.x + nodesBounds.width / 2
|
||||
const centerY = nodesBounds.y + nodesBounds.height / 2
|
||||
|
||||
reactFlow.setViewport({
|
||||
x: viewportWidth / 2 - centerX * zoom,
|
||||
y: viewportHeight / 2 - centerY * zoom,
|
||||
zoom,
|
||||
})
|
||||
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
|
||||
const padding = 50
|
||||
const contentWidth = nodesBounds.width + padding * 2
|
||||
const contentHeight = nodesBounds.height + padding * 2
|
||||
|
||||
const exportOptions = {
|
||||
filter,
|
||||
backgroundColor: '#1a1a1a',
|
||||
pixelRatio: 2,
|
||||
width: contentWidth,
|
||||
height: contentHeight,
|
||||
style: {
|
||||
width: `${contentWidth}px`,
|
||||
height: `${contentHeight}px`,
|
||||
transform: `translate(${padding - nodesBounds.x}px, ${padding - nodesBounds.y}px)`,
|
||||
transformOrigin: 'top left',
|
||||
},
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case 'png':
|
||||
dataUrl = await toPng(flowElement, exportOptions)
|
||||
break
|
||||
case 'jpeg':
|
||||
dataUrl = await toJpeg(flowElement, exportOptions)
|
||||
break
|
||||
case 'svg':
|
||||
dataUrl = await toSvg(flowElement, { filter })
|
||||
break
|
||||
default:
|
||||
dataUrl = await toPng(flowElement, exportOptions)
|
||||
}
|
||||
|
||||
filename += '-whole-workflow'
|
||||
} finally {
|
||||
reactFlow.setViewport(currentViewport)
|
||||
}
|
||||
} else {
|
||||
// Current viewport export (existing functionality)
|
||||
switch (type) {
|
||||
case 'png':
|
||||
dataUrl = await toPng(flowElement, { filter })
|
||||
break
|
||||
case 'jpeg':
|
||||
dataUrl = await toJpeg(flowElement, { filter })
|
||||
break
|
||||
case 'svg':
|
||||
dataUrl = await toSvg(flowElement, { filter })
|
||||
break
|
||||
default:
|
||||
dataUrl = await toPng(flowElement, { filter })
|
||||
}
|
||||
}
|
||||
|
||||
const fileName = `${filename}.${type}`
|
||||
|
||||
if (currentWorkflow) {
|
||||
setPreviewUrl(dataUrl)
|
||||
setPreviewTitle(fileName)
|
||||
}
|
||||
|
||||
downloadUrl({ url: dataUrl, fileName })
|
||||
} catch (error) {
|
||||
console.error('Export image failed:', error)
|
||||
}
|
||||
},
|
||||
[getNodesReadOnly, appName, reactFlow, knowledgeName],
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Menu disabled={isReadOnly}>
|
||||
<TipPopup title={t(($) => $['common.exportImage'], { ns: 'workflow' })}>
|
||||
{/* Tooltip also sets data-popup-open; Menu alone sets data-pressed for its open state. */}
|
||||
<MenuTrigger
|
||||
render={
|
||||
<IconButton
|
||||
size="lg"
|
||||
aria-label={t(($) => $['common.exportImage'], { ns: 'workflow' })}
|
||||
focusableWhenDisabled
|
||||
className="rounded-md data-pressed:bg-state-base-hover data-pressed:text-text-secondary"
|
||||
>
|
||||
<span aria-hidden className="i-ri-export-line size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</TipPopup>
|
||||
<MenuContent side="right" className="min-w-45">
|
||||
<MenuGroup>
|
||||
<MenuGroupLabel>{t(($) => $['common.currentView'], { ns: 'workflow' })}</MenuGroupLabel>
|
||||
<MenuItem className="system-md-regular" onClick={() => handleExportImage('png')}>
|
||||
{t(($) => $['common.exportPNG'], { ns: 'workflow' })}
|
||||
</MenuItem>
|
||||
<MenuItem className="system-md-regular" onClick={() => handleExportImage('jpeg')}>
|
||||
{t(($) => $['common.exportJPEG'], { ns: 'workflow' })}
|
||||
</MenuItem>
|
||||
<MenuItem className="system-md-regular" onClick={() => handleExportImage('svg')}>
|
||||
{t(($) => $['common.exportSVG'], { ns: 'workflow' })}
|
||||
</MenuItem>
|
||||
</MenuGroup>
|
||||
<MenuSeparator className="mx-2" />
|
||||
|
||||
<MenuGroup>
|
||||
<MenuGroupLabel>
|
||||
{t(($) => $['common.currentWorkflow'], { ns: 'workflow' })}
|
||||
</MenuGroupLabel>
|
||||
<MenuItem className="system-md-regular" onClick={() => handleExportImage('png', true)}>
|
||||
{t(($) => $['common.exportPNG'], { ns: 'workflow' })}
|
||||
</MenuItem>
|
||||
<MenuItem className="system-md-regular" onClick={() => handleExportImage('jpeg', true)}>
|
||||
{t(($) => $['common.exportJPEG'], { ns: 'workflow' })}
|
||||
</MenuItem>
|
||||
<MenuItem className="system-md-regular" onClick={() => handleExportImage('svg', true)}>
|
||||
{t(($) => $['common.exportSVG'], { ns: 'workflow' })}
|
||||
</MenuItem>
|
||||
</MenuGroup>
|
||||
</MenuContent>
|
||||
</Menu>
|
||||
|
||||
{previewUrl && (
|
||||
<ImagePreview url={previewUrl} title={previewTitle} onCancel={() => setPreviewUrl('')} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
})
|
||||
|
||||
export { ExportImage }
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { NoteNodeType } from '../note-node/types'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useCallback } from 'react'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { CUSTOM_NOTE_NODE } from '../note-node/constants'
|
||||
import { NoteTheme } from '../note-node/types'
|
||||
import { useWorkflowNoteShowAuthorValue } from '../persistence/local-storage-options'
|
||||
import { useWorkflowStore } from '../store'
|
||||
import { generateNewNode } from '../utils'
|
||||
|
||||
export const useOperator = () => {
|
||||
const workflowStore = useWorkflowStore()
|
||||
const { data: userProfile } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.profile,
|
||||
})
|
||||
const showAuthorStorage = useWorkflowNoteShowAuthorValue()
|
||||
|
||||
const handleAddNote = useCallback(() => {
|
||||
const { newNode } = generateNewNode({
|
||||
type: CUSTOM_NOTE_NODE,
|
||||
data: {
|
||||
title: '',
|
||||
desc: '',
|
||||
type: '' as any,
|
||||
text: '',
|
||||
theme: NoteTheme.blue,
|
||||
author: userProfile?.name || '',
|
||||
showAuthor: showAuthorStorage !== 'false',
|
||||
width: 240,
|
||||
height: 88,
|
||||
_isCandidate: true,
|
||||
} as NoteNodeType,
|
||||
position: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
})
|
||||
workflowStore.setState({
|
||||
candidateNode: newNode,
|
||||
})
|
||||
}, [workflowStore, userProfile, showAuthorStorage])
|
||||
|
||||
return {
|
||||
handleAddNote,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { Node } from 'reactflow'
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { MiniMap } from 'reactflow'
|
||||
import UndoRedo from '../header/undo-redo'
|
||||
import { useStore } from '../store'
|
||||
import { ControlMode } from '../types'
|
||||
import VariableInspectPanel from '../variable-inspect'
|
||||
import VariableTrigger from '../variable-inspect/trigger'
|
||||
import ZoomInOut from './zoom-in-out'
|
||||
|
||||
type OperatorProps = {
|
||||
handleUndo: () => void
|
||||
handleRedo: () => void
|
||||
}
|
||||
|
||||
const Operator = ({ handleUndo, handleRedo }: OperatorProps) => {
|
||||
const bottomPanelRef = useRef<HTMLDivElement>(null)
|
||||
const bottomPanelSizeRef = useRef<{ width?: number; height?: number }>({})
|
||||
const bottomPanelResizeFrameRef = useRef<number | undefined>(undefined)
|
||||
const [showMiniMap, setShowMiniMap] = useState(true)
|
||||
const showUserCursors = useStore((s) => s.showUserCursors)
|
||||
const setShowUserCursors = useStore((s) => s.setShowUserCursors)
|
||||
const showUserComments = useStore((s) => s.showUserComments)
|
||||
const setShowUserComments = useStore((s) => s.setShowUserComments)
|
||||
const controlMode = useStore((s) => s.controlMode)
|
||||
const isCommentMode = controlMode === ControlMode.Comment
|
||||
|
||||
const handleToggleMiniMap = useCallback(() => {
|
||||
setShowMiniMap((prev) => !prev)
|
||||
}, [])
|
||||
|
||||
const handleToggleUserCursors = useCallback(() => {
|
||||
setShowUserCursors(!showUserCursors)
|
||||
}, [showUserCursors, setShowUserCursors])
|
||||
|
||||
const handleToggleUserComments = useCallback(() => {
|
||||
setShowUserComments(!showUserComments)
|
||||
}, [showUserComments, setShowUserComments])
|
||||
|
||||
const workflowCanvasWidth = useStore((s) => s.workflowCanvasWidth)
|
||||
const rightPanelWidth = useStore((s) => s.rightPanelWidth)
|
||||
const setBottomPanelWidth = useStore((s) => s.setBottomPanelWidth)
|
||||
const setBottomPanelHeight = useStore((s) => s.setBottomPanelHeight)
|
||||
|
||||
const bottomPanelWidth = useMemo(() => {
|
||||
if (!workflowCanvasWidth || !rightPanelWidth) return 'auto'
|
||||
return Math.max(workflowCanvasWidth - rightPanelWidth, 400)
|
||||
}, [workflowCanvasWidth, rightPanelWidth])
|
||||
|
||||
const getMiniMapNodeClassName = useCallback((node: Node) => {
|
||||
return node.data?.selected
|
||||
? 'bg-workflow-minimap-block border-components-option-card-option-selected-border'
|
||||
: 'bg-workflow-minimap-block'
|
||||
}, [])
|
||||
|
||||
// update bottom panel height
|
||||
useEffect(() => {
|
||||
if (bottomPanelRef.current) {
|
||||
const updateBottomPanelSize = (width: number, height: number) => {
|
||||
if (
|
||||
bottomPanelSizeRef.current.width === width &&
|
||||
bottomPanelSizeRef.current.height === height
|
||||
)
|
||||
return
|
||||
|
||||
bottomPanelSizeRef.current = { width, height }
|
||||
if (bottomPanelResizeFrameRef.current)
|
||||
cancelAnimationFrame(bottomPanelResizeFrameRef.current)
|
||||
|
||||
bottomPanelResizeFrameRef.current = requestAnimationFrame(() => {
|
||||
bottomPanelResizeFrameRef.current = undefined
|
||||
setBottomPanelWidth(width)
|
||||
setBottomPanelHeight(height)
|
||||
})
|
||||
}
|
||||
|
||||
const resizeContainerObserver = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const { inlineSize, blockSize } = entry.borderBoxSize[0]!
|
||||
updateBottomPanelSize(inlineSize, blockSize)
|
||||
}
|
||||
})
|
||||
resizeContainerObserver.observe(bottomPanelRef.current)
|
||||
return () => {
|
||||
if (bottomPanelResizeFrameRef.current) {
|
||||
cancelAnimationFrame(bottomPanelResizeFrameRef.current)
|
||||
bottomPanelResizeFrameRef.current = undefined
|
||||
}
|
||||
resizeContainerObserver.disconnect()
|
||||
}
|
||||
}
|
||||
}, [setBottomPanelHeight, setBottomPanelWidth])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={bottomPanelRef}
|
||||
className="absolute inset-x-0 bottom-0 z-10 px-1"
|
||||
style={{
|
||||
width: bottomPanelWidth,
|
||||
}}
|
||||
>
|
||||
<div className="flex justify-between px-1 pb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<UndoRedo handleUndo={handleUndo} handleRedo={handleRedo} />
|
||||
</div>
|
||||
<VariableTrigger />
|
||||
<div className="relative">
|
||||
{showMiniMap && (
|
||||
<MiniMap
|
||||
pannable
|
||||
zoomable
|
||||
style={{
|
||||
width: 102,
|
||||
height: 72,
|
||||
}}
|
||||
maskColor="var(--color-workflow-minimap-bg)"
|
||||
nodeClassName={getMiniMapNodeClassName}
|
||||
nodeStrokeWidth={3}
|
||||
className="absolute! bottom-10! z-9 m-0! h-18.25! w-25.75! rounded-lg! border-[0.5px]! border-divider-subtle! bg-background-default-subtle! shadow-md! shadow-shadow-shadow-5!"
|
||||
/>
|
||||
)}
|
||||
<ZoomInOut
|
||||
showMiniMap={showMiniMap}
|
||||
onToggleMiniMap={handleToggleMiniMap}
|
||||
showUserCursors={showUserCursors}
|
||||
onToggleUserCursors={handleToggleUserCursors}
|
||||
showUserComments={showUserComments}
|
||||
onToggleUserComments={handleToggleUserComments}
|
||||
isCommentMode={isCommentMode}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<VariableInspectPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Operator)
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ReactElement } from 'react'
|
||||
import type { WorkflowCanvasShortcutId } from '../shortcuts/definitions'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { memo } from 'react'
|
||||
import { ShortcutKbd } from '../shortcuts/shortcut-kbd'
|
||||
|
||||
type TipPopupProps = {
|
||||
title: string
|
||||
children: ReactElement
|
||||
shortcut?: WorkflowCanvasShortcutId
|
||||
}
|
||||
const TipPopup = ({ title, children, shortcut }: TipPopupProps) => {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={children} />
|
||||
<TooltipContent sideOffset={4} className="flex max-w-none items-center gap-1">
|
||||
<span className="px-0.5">{title}</span>
|
||||
{shortcut && <ShortcutKbd shortcut={shortcut} />}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(TipPopup)
|
||||
@@ -0,0 +1,298 @@
|
||||
import type { FC } from 'react'
|
||||
import {
|
||||
Menu,
|
||||
MenuCheckboxItem,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuPortal,
|
||||
MenuPositioner,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from '@langgenius/dify-ui/menu'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { Fragment, memo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useReactFlow, useViewport } from 'reactflow'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
import { useNodesSyncDraft } from '../hooks/use-nodes-sync-draft'
|
||||
import { useWorkflowReadOnly } from '../hooks/use-workflow'
|
||||
import { handleWorkflowMenuKeyDown } from '../shortcuts/handle-workflow-menu-key-down'
|
||||
import { ShortcutKbd } from '../shortcuts/shortcut-kbd'
|
||||
import TipPopup from './tip-popup'
|
||||
|
||||
const ZoomType = {
|
||||
zoomToFit: 'zoomToFit',
|
||||
zoomTo25: 'zoomTo25',
|
||||
zoomTo50: 'zoomTo50',
|
||||
zoomTo75: 'zoomTo75',
|
||||
zoomTo100: 'zoomTo100',
|
||||
zoomTo200: 'zoomTo200',
|
||||
toggleUserComments: 'toggleUserComments',
|
||||
toggleUserCursors: 'toggleUserCursors',
|
||||
toggleMiniMap: 'toggleMiniMap',
|
||||
} as const
|
||||
|
||||
type ZoomType = (typeof ZoomType)[keyof typeof ZoomType]
|
||||
|
||||
type ZoomInOutProps = {
|
||||
showMiniMap?: boolean
|
||||
onToggleMiniMap?: () => void
|
||||
showUserCursors?: boolean
|
||||
onToggleUserCursors?: () => void
|
||||
showUserComments?: boolean
|
||||
onToggleUserComments?: () => void
|
||||
isCommentMode?: boolean
|
||||
}
|
||||
|
||||
const ZoomInOut: FC<ZoomInOutProps> = ({
|
||||
showMiniMap = true,
|
||||
onToggleMiniMap,
|
||||
showUserCursors = true,
|
||||
onToggleUserCursors,
|
||||
showUserComments = true,
|
||||
onToggleUserComments,
|
||||
isCommentMode = false,
|
||||
}) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const [open, setOpen] = useState(false)
|
||||
const { zoomIn, zoomOut, zoomTo, fitView } = useReactFlow()
|
||||
const { zoom } = useViewport()
|
||||
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
|
||||
const { workflowReadOnly, getWorkflowReadOnly } = useWorkflowReadOnly()
|
||||
const { data: isCollaborationEnabled } = useSuspenseQuery({
|
||||
...systemFeaturesQueryOptions(),
|
||||
select: (s) => s.enable_collaboration_mode,
|
||||
})
|
||||
|
||||
const zoomOptions = [
|
||||
[
|
||||
{
|
||||
key: ZoomType.zoomTo200,
|
||||
text: '200%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo100,
|
||||
text: '100%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo75,
|
||||
text: '75%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo50,
|
||||
text: '50%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo25,
|
||||
text: '25%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomToFit,
|
||||
text: t(($) => $['operator.zoomToFit'], { ns: 'workflow' }),
|
||||
},
|
||||
],
|
||||
isCollaborationEnabled
|
||||
? [
|
||||
{
|
||||
key: ZoomType.toggleUserComments,
|
||||
text: t(($) => $['operator.showUserComments'], { ns: 'workflow' }),
|
||||
checked: showUserComments,
|
||||
},
|
||||
{
|
||||
key: ZoomType.toggleUserCursors,
|
||||
text: t(($) => $['operator.showUserCursors'], { ns: 'workflow' }),
|
||||
checked: showUserCursors,
|
||||
},
|
||||
{
|
||||
key: ZoomType.toggleMiniMap,
|
||||
text: t(($) => $['operator.showMiniMap'], { ns: 'workflow' }),
|
||||
checked: showMiniMap,
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
key: ZoomType.toggleMiniMap,
|
||||
text: t(($) => $['operator.showMiniMap'], { ns: 'workflow' }),
|
||||
checked: showMiniMap,
|
||||
},
|
||||
],
|
||||
]
|
||||
|
||||
const handleZoom = (type: ZoomType) => {
|
||||
if (workflowReadOnly) return
|
||||
|
||||
if (type === ZoomType.zoomToFit) fitView()
|
||||
|
||||
if (type === ZoomType.zoomTo25) zoomTo(0.25)
|
||||
|
||||
if (type === ZoomType.zoomTo50) zoomTo(0.5)
|
||||
|
||||
if (type === ZoomType.zoomTo75) zoomTo(0.75)
|
||||
|
||||
if (type === ZoomType.zoomTo100) zoomTo(1)
|
||||
|
||||
if (type === ZoomType.zoomTo200) zoomTo(2)
|
||||
|
||||
if (type === ZoomType.toggleUserComments) {
|
||||
if (!isCommentMode) onToggleUserComments?.()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (type === ZoomType.toggleUserCursors) {
|
||||
onToggleUserCursors?.()
|
||||
return
|
||||
}
|
||||
|
||||
if (type === ZoomType.toggleMiniMap) {
|
||||
onToggleMiniMap?.()
|
||||
return
|
||||
}
|
||||
|
||||
handleSyncWorkflowDraft()
|
||||
}
|
||||
|
||||
function selectZoom(type: ZoomType) {
|
||||
handleZoom(type)
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`h-9 cursor-pointer rounded-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 text-[13px] shadow-lg backdrop-blur-[5px] hover:bg-state-base-hover ${workflowReadOnly && 'cursor-not-allowed! opacity-50'} `}
|
||||
>
|
||||
<div className="flex h-8 w-24.5 items-center justify-between rounded-lg">
|
||||
<TipPopup
|
||||
title={t(($) => $['operator.zoomOut'], { ns: 'workflow' })}
|
||||
shortcut="workflow.zoom-out"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(($) => $['operator.zoomOut'], { ns: 'workflow' })}
|
||||
disabled={zoom <= 0.25}
|
||||
className={`flex size-8 items-center justify-center rounded-lg ${zoom <= 0.25 ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-black/5'}`}
|
||||
onClick={(e) => {
|
||||
if (zoom <= 0.25) return
|
||||
|
||||
e.stopPropagation()
|
||||
zoomOut()
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-zoom-out-line size-4 text-text-tertiary hover:text-text-secondary"
|
||||
/>
|
||||
</button>
|
||||
</TipPopup>
|
||||
<Menu open={open} onOpenChange={setOpen}>
|
||||
<MenuTrigger
|
||||
disabled={getWorkflowReadOnly()}
|
||||
className="flex h-8 w-8.5 items-center justify-center rounded-lg system-sm-medium text-text-tertiary hover:bg-black/5 hover:text-text-secondary data-popup-open:bg-black/5 data-popup-open:text-text-secondary"
|
||||
>
|
||||
{Number.parseFloat(`${zoom * 100}`).toFixed(0)}%
|
||||
</MenuTrigger>
|
||||
<MenuPortal>
|
||||
<MenuPositioner sideOffset={4} side="top" align="start" alignOffset={-2}>
|
||||
<MenuPopup
|
||||
onKeyDown={(event) => {
|
||||
if (workflowReadOnly) return
|
||||
handleWorkflowMenuKeyDown(event, [
|
||||
['workflow.zoom-to-fit', () => selectZoom(ZoomType.zoomToFit)],
|
||||
['workflow.zoom-to-100', () => selectZoom(ZoomType.zoomTo100)],
|
||||
['workflow.zoom-to-50', () => selectZoom(ZoomType.zoomTo50)],
|
||||
])
|
||||
}}
|
||||
>
|
||||
<div className="w-48 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-[5px]">
|
||||
{zoomOptions.map((options, groupIndex) => (
|
||||
<Fragment key={options[0]!.key}>
|
||||
{groupIndex !== 0 && <MenuSeparator className="my-0" />}
|
||||
<div className="p-1">
|
||||
{options.map((option) =>
|
||||
'checked' in option ? (
|
||||
<MenuCheckboxItem
|
||||
key={option.key}
|
||||
className="gap-2 px-3 py-1.5 system-md-regular text-text-secondary"
|
||||
checked={option.checked}
|
||||
disabled={option.key === ZoomType.toggleUserComments && isCommentMode}
|
||||
closeOnClick
|
||||
onCheckedChange={() => selectZoom(option.key)}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={
|
||||
option.checked
|
||||
? 'i-ri-check-line size-4 text-text-accent'
|
||||
: 'size-4'
|
||||
}
|
||||
/>
|
||||
<span>{option.text}</span>
|
||||
</MenuCheckboxItem>
|
||||
) : (
|
||||
<MenuItem
|
||||
key={option.key}
|
||||
className="justify-between px-3 py-1.5 system-md-regular text-text-secondary"
|
||||
onClick={() => selectZoom(option.key)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{option.key === ZoomType.zoomToFit && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-fullscreen-line size-4 text-text-tertiary"
|
||||
/>
|
||||
)}
|
||||
{option.key !== ZoomType.zoomToFit && (
|
||||
<span aria-hidden className="size-4" />
|
||||
)}
|
||||
<span>{option.text}</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-0.5">
|
||||
{option.key === ZoomType.zoomToFit && (
|
||||
<ShortcutKbd shortcut="workflow.zoom-to-fit" />
|
||||
)}
|
||||
{option.key === ZoomType.zoomTo50 && (
|
||||
<ShortcutKbd shortcut="workflow.zoom-to-50" />
|
||||
)}
|
||||
{option.key === ZoomType.zoomTo100 && (
|
||||
<ShortcutKbd shortcut="workflow.zoom-to-100" />
|
||||
)}
|
||||
</div>
|
||||
</MenuItem>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</MenuPopup>
|
||||
</MenuPositioner>
|
||||
</MenuPortal>
|
||||
</Menu>
|
||||
<TipPopup
|
||||
title={t(($) => $['operator.zoomIn'], { ns: 'workflow' })}
|
||||
shortcut="workflow.zoom-in"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(($) => $['operator.zoomIn'], { ns: 'workflow' })}
|
||||
disabled={zoom >= 2}
|
||||
className={`flex size-8 items-center justify-center rounded-lg ${zoom >= 2 ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-black/5'}`}
|
||||
onClick={(e) => {
|
||||
if (zoom >= 2) return
|
||||
|
||||
e.stopPropagation()
|
||||
zoomIn()
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-zoom-in-line size-4 text-text-tertiary hover:text-text-secondary"
|
||||
/>
|
||||
</button>
|
||||
</TipPopup>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ZoomInOut)
|
||||
Reference in new issue
Block a user