mirror of
https://github.com/langgenius/dify.git
synced 2026-03-25 09:46:53 +00:00
Compare commits
13 Commits
fix/editor
...
feat/ee-ad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21585f1317 | ||
|
|
242da1ee6b | ||
|
|
0e6d97acf9 | ||
|
|
7fbb1c96db | ||
|
|
fc35e913fd | ||
|
|
f87dafa229 | ||
|
|
a8e1ff85db | ||
|
|
b5a9cdf678 | ||
|
|
a7da6578f8 | ||
|
|
fd2fd3def4 | ||
|
|
cb8a3ca196 | ||
|
|
e57ee4bcbe | ||
|
|
0ba464e820 |
@@ -16,12 +16,14 @@ api = ExternalApi(
|
||||
inner_api_ns = Namespace("inner_api", description="Internal API operations", path="/")
|
||||
|
||||
from . import mail as _mail
|
||||
from .app import dsl as _app_dsl
|
||||
from .plugin import plugin as _plugin
|
||||
from .workspace import workspace as _workspace
|
||||
|
||||
api.add_namespace(inner_api_ns)
|
||||
|
||||
__all__ = [
|
||||
"_app_dsl",
|
||||
"_mail",
|
||||
"_plugin",
|
||||
"_workspace",
|
||||
|
||||
1
api/controllers/inner_api/app/__init__.py
Normal file
1
api/controllers/inner_api/app/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
110
api/controllers/inner_api/app/dsl.py
Normal file
110
api/controllers/inner_api/app/dsl.py
Normal file
@@ -0,0 +1,110 @@
|
||||
"""Inner API endpoints for app DSL import/export.
|
||||
|
||||
Called by the enterprise admin-api service. Import requires ``creator_email``
|
||||
to attribute the created app; workspace/membership validation is done by the
|
||||
Go admin-api caller.
|
||||
"""
|
||||
|
||||
from flask import request
|
||||
from flask_restx import Resource
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.common.schema import register_schema_model
|
||||
from controllers.console.wraps import setup_required
|
||||
from controllers.inner_api import inner_api_ns
|
||||
from controllers.inner_api.wraps import enterprise_inner_api_only
|
||||
from extensions.ext_database import db
|
||||
from models import Account, App
|
||||
from models.account import AccountStatus
|
||||
from services.app_dsl_service import AppDslService, ImportMode, ImportStatus
|
||||
|
||||
|
||||
class InnerAppDSLImportPayload(BaseModel):
|
||||
yaml_content: str = Field(description="YAML DSL content")
|
||||
creator_email: str = Field(description="Email of the workspace member who will own the imported app")
|
||||
name: str | None = Field(default=None, description="Override app name from DSL")
|
||||
description: str | None = Field(default=None, description="Override app description from DSL")
|
||||
|
||||
|
||||
register_schema_model(inner_api_ns, InnerAppDSLImportPayload)
|
||||
|
||||
|
||||
@inner_api_ns.route("/enterprise/workspaces/<string:workspace_id>/dsl/import")
|
||||
class EnterpriseAppDSLImport(Resource):
|
||||
@setup_required
|
||||
@enterprise_inner_api_only
|
||||
@inner_api_ns.doc("enterprise_app_dsl_import")
|
||||
@inner_api_ns.expect(inner_api_ns.models[InnerAppDSLImportPayload.__name__])
|
||||
@inner_api_ns.doc(
|
||||
responses={
|
||||
200: "Import completed",
|
||||
202: "Import pending (DSL version mismatch requires confirmation)",
|
||||
400: "Import failed (business error)",
|
||||
404: "Creator account not found or inactive",
|
||||
}
|
||||
)
|
||||
def post(self, workspace_id: str):
|
||||
"""Import a DSL into a workspace on behalf of a specified creator."""
|
||||
args = InnerAppDSLImportPayload.model_validate(inner_api_ns.payload or {})
|
||||
|
||||
account = _get_active_account(args.creator_email)
|
||||
if account is None:
|
||||
return {"message": f"account '{args.creator_email}' not found or inactive"}, 404
|
||||
|
||||
account.set_tenant_id(workspace_id)
|
||||
|
||||
with Session(db.engine) as session:
|
||||
dsl_service = AppDslService(session)
|
||||
result = dsl_service.import_app(
|
||||
account=account,
|
||||
import_mode=ImportMode.YAML_CONTENT,
|
||||
yaml_content=args.yaml_content,
|
||||
name=args.name,
|
||||
description=args.description,
|
||||
)
|
||||
session.commit()
|
||||
|
||||
if result.status == ImportStatus.FAILED:
|
||||
return result.model_dump(mode="json"), 400
|
||||
if result.status == ImportStatus.PENDING:
|
||||
return result.model_dump(mode="json"), 202
|
||||
return result.model_dump(mode="json"), 200
|
||||
|
||||
|
||||
@inner_api_ns.route("/enterprise/apps/<string:app_id>/dsl")
|
||||
class EnterpriseAppDSLExport(Resource):
|
||||
@setup_required
|
||||
@enterprise_inner_api_only
|
||||
@inner_api_ns.doc(
|
||||
"enterprise_app_dsl_export",
|
||||
responses={
|
||||
200: "Export successful",
|
||||
404: "App not found",
|
||||
},
|
||||
)
|
||||
def get(self, app_id: str):
|
||||
"""Export an app's DSL as YAML."""
|
||||
include_secret = request.args.get("include_secret", "false").lower() == "true"
|
||||
|
||||
app_model = db.session.query(App).filter_by(id=app_id).first()
|
||||
if not app_model:
|
||||
return {"message": "app not found"}, 404
|
||||
|
||||
data = AppDslService.export_dsl(
|
||||
app_model=app_model,
|
||||
include_secret=include_secret,
|
||||
)
|
||||
|
||||
return {"data": data}, 200
|
||||
|
||||
|
||||
def _get_active_account(email: str) -> Account | None:
|
||||
"""Look up an active account by email.
|
||||
|
||||
Workspace membership is already validated by the Go admin-api caller.
|
||||
"""
|
||||
account = db.session.query(Account).filter_by(email=email).first()
|
||||
if account is None or account.status != AccountStatus.ACTIVE:
|
||||
return None
|
||||
return account
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
245
api/tests/unit_tests/controllers/inner_api/app/test_dsl.py
Normal file
245
api/tests/unit_tests/controllers/inner_api/app/test_dsl.py
Normal file
@@ -0,0 +1,245 @@
|
||||
"""Unit tests for inner_api app DSL import/export endpoints.
|
||||
|
||||
Tests Pydantic model validation, endpoint handler logic, and the
|
||||
_get_active_account helper. Auth/setup decorators are tested separately
|
||||
in test_auth_wraps.py; handler tests use inspect.unwrap() to bypass them.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from pydantic import ValidationError
|
||||
|
||||
from controllers.inner_api.app.dsl import (
|
||||
EnterpriseAppDSLExport,
|
||||
EnterpriseAppDSLImport,
|
||||
InnerAppDSLImportPayload,
|
||||
_get_active_account,
|
||||
)
|
||||
from services.app_dsl_service import ImportStatus
|
||||
|
||||
|
||||
class TestInnerAppDSLImportPayload:
|
||||
"""Test InnerAppDSLImportPayload Pydantic model validation."""
|
||||
|
||||
def test_valid_payload_all_fields(self):
|
||||
data = {
|
||||
"yaml_content": "version: 0.6.0\nkind: app\n",
|
||||
"creator_email": "user@example.com",
|
||||
"name": "My App",
|
||||
"description": "A test app",
|
||||
}
|
||||
payload = InnerAppDSLImportPayload.model_validate(data)
|
||||
assert payload.yaml_content == data["yaml_content"]
|
||||
assert payload.creator_email == "user@example.com"
|
||||
assert payload.name == "My App"
|
||||
assert payload.description == "A test app"
|
||||
|
||||
def test_valid_payload_optional_fields_omitted(self):
|
||||
data = {
|
||||
"yaml_content": "version: 0.6.0\n",
|
||||
"creator_email": "user@example.com",
|
||||
}
|
||||
payload = InnerAppDSLImportPayload.model_validate(data)
|
||||
assert payload.name is None
|
||||
assert payload.description is None
|
||||
|
||||
def test_missing_yaml_content_fails(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
InnerAppDSLImportPayload.model_validate({"creator_email": "a@b.com"})
|
||||
assert "yaml_content" in str(exc_info.value)
|
||||
|
||||
def test_missing_creator_email_fails(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
InnerAppDSLImportPayload.model_validate({"yaml_content": "test"})
|
||||
assert "creator_email" in str(exc_info.value)
|
||||
|
||||
|
||||
class TestGetActiveAccount:
|
||||
"""Test the _get_active_account helper function."""
|
||||
|
||||
@patch("controllers.inner_api.app.dsl.db")
|
||||
def test_returns_active_account(self, mock_db):
|
||||
mock_account = MagicMock()
|
||||
mock_account.status = "active"
|
||||
mock_db.session.query.return_value.filter_by.return_value.first.return_value = mock_account
|
||||
|
||||
result = _get_active_account("user@example.com")
|
||||
|
||||
assert result is mock_account
|
||||
mock_db.session.query.return_value.filter_by.assert_called_once_with(email="user@example.com")
|
||||
|
||||
@patch("controllers.inner_api.app.dsl.db")
|
||||
def test_returns_none_for_inactive_account(self, mock_db):
|
||||
mock_account = MagicMock()
|
||||
mock_account.status = "banned"
|
||||
mock_db.session.query.return_value.filter_by.return_value.first.return_value = mock_account
|
||||
|
||||
result = _get_active_account("banned@example.com")
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("controllers.inner_api.app.dsl.db")
|
||||
def test_returns_none_for_nonexistent_email(self, mock_db):
|
||||
mock_db.session.query.return_value.filter_by.return_value.first.return_value = None
|
||||
|
||||
result = _get_active_account("missing@example.com")
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestEnterpriseAppDSLImport:
|
||||
"""Test EnterpriseAppDSLImport endpoint handler logic.
|
||||
|
||||
Uses inspect.unwrap() to bypass auth/setup decorators.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def api_instance(self):
|
||||
return EnterpriseAppDSLImport()
|
||||
|
||||
@pytest.fixture
|
||||
def _mock_import_deps(self):
|
||||
"""Patch db, Session, and AppDslService for import handler tests."""
|
||||
with (
|
||||
patch("controllers.inner_api.app.dsl.db"),
|
||||
patch("controllers.inner_api.app.dsl.Session") as mock_session,
|
||||
patch("controllers.inner_api.app.dsl.AppDslService") as mock_dsl_cls,
|
||||
):
|
||||
mock_session.return_value.__enter__ = MagicMock(return_value=MagicMock())
|
||||
mock_session.return_value.__exit__ = MagicMock(return_value=False)
|
||||
self._mock_dsl = MagicMock()
|
||||
mock_dsl_cls.return_value = self._mock_dsl
|
||||
yield
|
||||
|
||||
def _make_import_result(self, status: ImportStatus, **kwargs) -> "Import":
|
||||
from services.app_dsl_service import Import
|
||||
|
||||
result = Import(
|
||||
id="import-id",
|
||||
status=status,
|
||||
app_id=kwargs.get("app_id", "app-123"),
|
||||
app_mode=kwargs.get("app_mode", "workflow"),
|
||||
)
|
||||
return result
|
||||
|
||||
@pytest.mark.usefixtures("_mock_import_deps")
|
||||
@patch("controllers.inner_api.app.dsl._get_active_account")
|
||||
def test_import_success_returns_200(self, mock_get_account, api_instance, app: Flask):
|
||||
mock_account = MagicMock()
|
||||
mock_get_account.return_value = mock_account
|
||||
self._mock_dsl.import_app.return_value = self._make_import_result(ImportStatus.COMPLETED)
|
||||
|
||||
unwrapped = inspect.unwrap(api_instance.post)
|
||||
with app.test_request_context():
|
||||
with patch("controllers.inner_api.app.dsl.inner_api_ns") as mock_ns:
|
||||
mock_ns.payload = {
|
||||
"yaml_content": "version: 0.6.0\n",
|
||||
"creator_email": "user@example.com",
|
||||
}
|
||||
result = unwrapped(api_instance, workspace_id="ws-123")
|
||||
|
||||
body, status_code = result
|
||||
assert status_code == 200
|
||||
assert body["status"] == "completed"
|
||||
mock_account.set_tenant_id.assert_called_once_with("ws-123")
|
||||
|
||||
@pytest.mark.usefixtures("_mock_import_deps")
|
||||
@patch("controllers.inner_api.app.dsl._get_active_account")
|
||||
def test_import_pending_returns_202(self, mock_get_account, api_instance, app: Flask):
|
||||
mock_get_account.return_value = MagicMock()
|
||||
self._mock_dsl.import_app.return_value = self._make_import_result(ImportStatus.PENDING)
|
||||
|
||||
unwrapped = inspect.unwrap(api_instance.post)
|
||||
with app.test_request_context():
|
||||
with patch("controllers.inner_api.app.dsl.inner_api_ns") as mock_ns:
|
||||
mock_ns.payload = {"yaml_content": "test", "creator_email": "u@e.com"}
|
||||
body, status_code = unwrapped(api_instance, workspace_id="ws-123")
|
||||
|
||||
assert status_code == 202
|
||||
assert body["status"] == "pending"
|
||||
|
||||
@pytest.mark.usefixtures("_mock_import_deps")
|
||||
@patch("controllers.inner_api.app.dsl._get_active_account")
|
||||
def test_import_failed_returns_400(self, mock_get_account, api_instance, app: Flask):
|
||||
mock_get_account.return_value = MagicMock()
|
||||
self._mock_dsl.import_app.return_value = self._make_import_result(ImportStatus.FAILED)
|
||||
|
||||
unwrapped = inspect.unwrap(api_instance.post)
|
||||
with app.test_request_context():
|
||||
with patch("controllers.inner_api.app.dsl.inner_api_ns") as mock_ns:
|
||||
mock_ns.payload = {"yaml_content": "test", "creator_email": "u@e.com"}
|
||||
body, status_code = unwrapped(api_instance, workspace_id="ws-123")
|
||||
|
||||
assert status_code == 400
|
||||
assert body["status"] == "failed"
|
||||
|
||||
@patch("controllers.inner_api.app.dsl._get_active_account")
|
||||
def test_import_account_not_found_returns_404(self, mock_get_account, api_instance, app: Flask):
|
||||
mock_get_account.return_value = None
|
||||
|
||||
unwrapped = inspect.unwrap(api_instance.post)
|
||||
with app.test_request_context():
|
||||
with patch("controllers.inner_api.app.dsl.inner_api_ns") as mock_ns:
|
||||
mock_ns.payload = {"yaml_content": "test", "creator_email": "missing@e.com"}
|
||||
result = unwrapped(api_instance, workspace_id="ws-123")
|
||||
|
||||
body, status_code = result
|
||||
assert status_code == 404
|
||||
assert "missing@e.com" in body["message"]
|
||||
|
||||
|
||||
class TestEnterpriseAppDSLExport:
|
||||
"""Test EnterpriseAppDSLExport endpoint handler logic.
|
||||
|
||||
Uses inspect.unwrap() to bypass auth/setup decorators.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def api_instance(self):
|
||||
return EnterpriseAppDSLExport()
|
||||
|
||||
@patch("controllers.inner_api.app.dsl.AppDslService")
|
||||
@patch("controllers.inner_api.app.dsl.db")
|
||||
def test_export_success_returns_200(self, mock_db, mock_dsl_cls, api_instance, app: Flask):
|
||||
mock_app = MagicMock()
|
||||
mock_db.session.query.return_value.filter_by.return_value.first.return_value = mock_app
|
||||
mock_dsl_cls.export_dsl.return_value = "version: 0.6.0\nkind: app\n"
|
||||
|
||||
unwrapped = inspect.unwrap(api_instance.get)
|
||||
with app.test_request_context("?include_secret=false"):
|
||||
result = unwrapped(api_instance, app_id="app-123")
|
||||
|
||||
body, status_code = result
|
||||
assert status_code == 200
|
||||
assert body["data"] == "version: 0.6.0\nkind: app\n"
|
||||
mock_dsl_cls.export_dsl.assert_called_once_with(app_model=mock_app, include_secret=False)
|
||||
|
||||
@patch("controllers.inner_api.app.dsl.AppDslService")
|
||||
@patch("controllers.inner_api.app.dsl.db")
|
||||
def test_export_with_secret(self, mock_db, mock_dsl_cls, api_instance, app: Flask):
|
||||
mock_app = MagicMock()
|
||||
mock_db.session.query.return_value.filter_by.return_value.first.return_value = mock_app
|
||||
mock_dsl_cls.export_dsl.return_value = "yaml-data"
|
||||
|
||||
unwrapped = inspect.unwrap(api_instance.get)
|
||||
with app.test_request_context("?include_secret=true"):
|
||||
result = unwrapped(api_instance, app_id="app-123")
|
||||
|
||||
body, status_code = result
|
||||
assert status_code == 200
|
||||
mock_dsl_cls.export_dsl.assert_called_once_with(app_model=mock_app, include_secret=True)
|
||||
|
||||
@patch("controllers.inner_api.app.dsl.db")
|
||||
def test_export_app_not_found_returns_404(self, mock_db, api_instance, app: Flask):
|
||||
mock_db.session.query.return_value.filter_by.return_value.first.return_value = None
|
||||
|
||||
unwrapped = inspect.unwrap(api_instance.get)
|
||||
with app.test_request_context("?include_secret=false"):
|
||||
result = unwrapped(api_instance, app_id="nonexistent")
|
||||
|
||||
body, status_code = result
|
||||
assert status_code == 404
|
||||
assert "app not found" in body["message"]
|
||||
@@ -7,7 +7,7 @@ import { I18nClientProvider as I18N } from '../app/components/provider/i18n'
|
||||
import commonEnUS from '../i18n/en-US/common.json'
|
||||
|
||||
import '../app/styles/globals.css'
|
||||
import '../app/styles/markdown.scss'
|
||||
import '../app/styles/markdown.css'
|
||||
import './storybook.css'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
|
||||
@@ -774,7 +774,7 @@ export default translation`
|
||||
const endTime = Date.now()
|
||||
|
||||
expect(keys.length).toBe(1000)
|
||||
expect(endTime - startTime).toBeLessThan(1000) // Should complete in under 1 second
|
||||
expect(endTime - startTime).toBeLessThan(10000)
|
||||
})
|
||||
|
||||
it('should handle multiple translation files concurrently', async () => {
|
||||
@@ -796,7 +796,7 @@ export default translation`
|
||||
const endTime = Date.now()
|
||||
|
||||
expect(keys.length).toBe(20) // 10 files * 2 keys each
|
||||
expect(endTime - startTime).toBeLessThan(500)
|
||||
expect(endTime - startTime).toBeLessThan(10000)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -12,15 +12,15 @@ vi.mock('ahooks', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('react-slider', () => ({
|
||||
default: (props: { className?: string, min?: number, max?: number, value: number, onChange: (value: number) => void }) => (
|
||||
vi.mock('@/app/components/base/ui/slider', () => ({
|
||||
Slider: (props: { className?: string, min?: number, max?: number, value: number, onValueChange: (value: number) => void }) => (
|
||||
<input
|
||||
type="range"
|
||||
className={props.className}
|
||||
className={`slider ${props.className ?? ''}`}
|
||||
min={props.min}
|
||||
max={props.max}
|
||||
value={props.value}
|
||||
onChange={e => props.onChange(Number(e.target.value))}
|
||||
onChange={e => props.onValueChange(Number(e.target.value))}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useTranslation } from 'react-i18next'
|
||||
import Button from '@/app/components/base/button'
|
||||
import { CuteRobot } from '@/app/components/base/icons/src/vender/solid/communication'
|
||||
import { Unblur } from '@/app/components/base/icons/src/vender/solid/education'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
import { DEFAULT_AGENT_PROMPT, MAX_ITERATIONS_NUM } from '@/config'
|
||||
import ItemPanel from './item-panel'
|
||||
|
||||
@@ -105,12 +105,13 @@ const AgentSetting: FC<Props> = ({
|
||||
min={maxIterationsMin}
|
||||
max={MAX_ITERATIONS_NUM}
|
||||
value={tempPayload.max_iteration}
|
||||
onChange={(value) => {
|
||||
onValueChange={(value) => {
|
||||
setTempPayload({
|
||||
...tempPayload,
|
||||
max_iteration: value,
|
||||
})
|
||||
}}
|
||||
aria-label={t('agent.setting.maximumIterations.name', { ns: 'appDebug' })}
|
||||
/>
|
||||
|
||||
<input
|
||||
|
||||
@@ -288,10 +288,8 @@ describe('ConfigContent', () => {
|
||||
/>,
|
||||
)
|
||||
|
||||
const weightedScoreSlider = screen.getAllByRole('slider')
|
||||
.find(slider => slider.getAttribute('aria-valuemax') === '1')
|
||||
expect(weightedScoreSlider).toBeDefined()
|
||||
await user.click(weightedScoreSlider!)
|
||||
const weightedScoreSlider = screen.getByLabelText('dataset.weightedScore.semantic')
|
||||
weightedScoreSlider.focus()
|
||||
const callsBefore = onChange.mock.calls.length
|
||||
await user.keyboard('{ArrowRight}')
|
||||
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
.weightedScoreSliderTrack {
|
||||
background: var(--color-util-colors-blue-light-blue-light-500) !important;
|
||||
}
|
||||
|
||||
.weightedScoreSliderTrack-1 {
|
||||
background: transparent !important;
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import userEvent from '@testing-library/user-event'
|
||||
import WeightedScore from './weighted-score'
|
||||
|
||||
describe('WeightedScore', () => {
|
||||
const getSliderInput = () => screen.getByLabelText('dataset.weightedScore.semantic')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
@@ -48,8 +50,8 @@ describe('WeightedScore', () => {
|
||||
render(<WeightedScore value={value} onChange={onChange} />)
|
||||
|
||||
// Act
|
||||
await user.tab()
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSliderInput()
|
||||
slider.focus()
|
||||
expect(slider).toHaveFocus()
|
||||
const callsBefore = onChange.mock.calls.length
|
||||
await user.keyboard('{ArrowRight}')
|
||||
@@ -69,9 +71,8 @@ describe('WeightedScore', () => {
|
||||
render(<WeightedScore value={value} onChange={onChange} readonly />)
|
||||
|
||||
// Act
|
||||
await user.tab()
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveFocus()
|
||||
const slider = getSliderInput()
|
||||
expect(slider).toBeDisabled()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
|
||||
// Assert
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
import { noop } from 'es-toolkit/function'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import './weighted-score.css'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
|
||||
const weightedScoreSliderStyle: CSSProperties & Record<'--slider-track' | '--slider-range', string> = {
|
||||
'--slider-track': 'var(--color-util-colors-teal-teal-500)',
|
||||
'--slider-range': 'var(--color-util-colors-blue-light-blue-light-500)',
|
||||
}
|
||||
|
||||
const formatNumber = (value: number) => {
|
||||
if (value > 0 && value < 1)
|
||||
@@ -33,24 +37,26 @@ const WeightedScore = ({
|
||||
return (
|
||||
<div>
|
||||
<div className="space-x-3 rounded-lg border border-components-panel-border px-3 pb-2 pt-5">
|
||||
<Slider
|
||||
className={cn('h-0.5 grow rounded-full !bg-util-colors-teal-teal-500')}
|
||||
max={1.0}
|
||||
min={0}
|
||||
step={0.1}
|
||||
value={value.value[0]}
|
||||
onChange={v => !readonly && onChange({ value: [v, (10 - v * 10) / 10] })}
|
||||
trackClassName="weightedScoreSliderTrack"
|
||||
disabled={readonly}
|
||||
/>
|
||||
<div className="grow" style={weightedScoreSliderStyle}>
|
||||
<Slider
|
||||
className="grow"
|
||||
max={1.0}
|
||||
min={0}
|
||||
step={0.1}
|
||||
value={value.value[0]}
|
||||
onValueChange={v => !readonly && onChange({ value: [v, (10 - v * 10) / 10] })}
|
||||
disabled={readonly}
|
||||
aria-label={t('weightedScore.semantic', { ns: 'dataset' })}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-3 flex justify-between">
|
||||
<div className="system-xs-semibold-uppercase flex w-[90px] shrink-0 items-center text-util-colors-blue-light-blue-light-500">
|
||||
<div className="flex w-[90px] shrink-0 items-center text-util-colors-blue-light-blue-light-500 system-xs-semibold-uppercase">
|
||||
<div className="mr-1 truncate uppercase" title={t('weightedScore.semantic', { ns: 'dataset' }) || ''}>
|
||||
{t('weightedScore.semantic', { ns: 'dataset' })}
|
||||
</div>
|
||||
{formatNumber(value.value[0])}
|
||||
</div>
|
||||
<div className="system-xs-semibold-uppercase flex w-[90px] shrink-0 items-center justify-end text-util-colors-teal-teal-500">
|
||||
<div className="flex w-[90px] shrink-0 items-center justify-end text-util-colors-teal-teal-500 system-xs-semibold-uppercase">
|
||||
{formatNumber(value.value[1])}
|
||||
<div className="ml-1 truncate uppercase" title={t('weightedScore.keyword', { ns: 'dataset' }) || ''}>
|
||||
{t('weightedScore.keyword', { ns: 'dataset' })}
|
||||
|
||||
@@ -93,7 +93,6 @@ const ConfigParamModal: FC<Props> = ({
|
||||
className="mt-1"
|
||||
value={(annotationConfig.score_threshold || ANNOTATION_DEFAULT.score_threshold) * 100}
|
||||
onChange={(val) => {
|
||||
/* v8 ignore next -- callback dispatch depends on react-slider drag mechanics that are flaky in jsdom. @preserve */
|
||||
setAnnotationConfig({
|
||||
...annotationConfig,
|
||||
score_threshold: val / 100,
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import ScoreSlider from '../index'
|
||||
|
||||
vi.mock('@/app/components/base/features/new-feature-panel/annotation-reply/score-slider/base-slider', () => ({
|
||||
default: ({ value, onChange, min, max }: { value: number, onChange: (v: number) => void, min: number, max: number }) => (
|
||||
<input
|
||||
type="range"
|
||||
data-testid="slider"
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
onChange={e => onChange(Number(e.target.value))}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('ScoreSlider', () => {
|
||||
const getSliderInput = () => screen.getByLabelText('appDebug.feature.annotation.scoreThreshold.title')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
@@ -22,7 +11,7 @@ describe('ScoreSlider', () => {
|
||||
it('should render the slider', () => {
|
||||
render(<ScoreSlider value={90} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByTestId('slider')).toBeInTheDocument()
|
||||
expect(getSliderInput()).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display easy match and accurate match labels', () => {
|
||||
@@ -37,14 +26,14 @@ describe('ScoreSlider', () => {
|
||||
it('should render with custom className', () => {
|
||||
const { container } = render(<ScoreSlider className="custom-class" value={90} onChange={vi.fn()} />)
|
||||
|
||||
// Verifying the component renders successfully with a custom className
|
||||
expect(screen.getByTestId('slider')).toBeInTheDocument()
|
||||
expect(getSliderInput()).toBeInTheDocument()
|
||||
expect(container.firstChild).toHaveClass('custom-class')
|
||||
})
|
||||
|
||||
it('should pass value to the slider', () => {
|
||||
render(<ScoreSlider value={95} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByTestId('slider')).toHaveValue('95')
|
||||
expect(getSliderInput()).toHaveValue('95')
|
||||
expect(screen.getByText('0.95')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import Slider from '../index'
|
||||
|
||||
describe('BaseSlider', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should render the slider component', () => {
|
||||
render(<Slider value={50} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByRole('slider')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the formatted value in the thumb', () => {
|
||||
render(<Slider value={85} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('0.85')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should use default min/max/step when not provided', () => {
|
||||
render(<Slider value={50} onChange={vi.fn()} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemin', '0')
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '100')
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '50')
|
||||
})
|
||||
|
||||
it('should use custom min/max/step when provided', () => {
|
||||
render(<Slider value={90} min={80} max={100} step={5} onChange={vi.fn()} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemin', '80')
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '100')
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '90')
|
||||
})
|
||||
|
||||
it('should handle NaN value as 0', () => {
|
||||
render(<Slider value={Number.NaN} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '0')
|
||||
})
|
||||
|
||||
it('should pass disabled prop', () => {
|
||||
render(<Slider value={50} disabled onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByRole('slider')).toHaveAttribute('aria-disabled', 'true')
|
||||
})
|
||||
})
|
||||
@@ -1,40 +0,0 @@
|
||||
import ReactSlider from 'react-slider'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import s from './style.module.css'
|
||||
|
||||
type ISliderProps = {
|
||||
className?: string
|
||||
value: number
|
||||
max?: number
|
||||
min?: number
|
||||
step?: number
|
||||
disabled?: boolean
|
||||
onChange: (value: number) => void
|
||||
}
|
||||
|
||||
const Slider: React.FC<ISliderProps> = ({ className, max, min, step, value, disabled, onChange }) => {
|
||||
return (
|
||||
<ReactSlider
|
||||
disabled={disabled}
|
||||
value={isNaN(value) ? 0 : value}
|
||||
min={min || 0}
|
||||
max={max || 100}
|
||||
step={step || 1}
|
||||
className={cn(className, s.slider)}
|
||||
thumbClassName={cn(s['slider-thumb'], 'top-[-7px] h-[18px] w-2 cursor-pointer rounded-[36px] border !border-black/8 bg-white shadow-md')}
|
||||
trackClassName={s['slider-track']}
|
||||
onChange={onChange}
|
||||
renderThumb={(props, state) => (
|
||||
<div {...props}>
|
||||
<div className="relative h-full w-full">
|
||||
<div className="absolute left-[50%] top-[-16px] translate-x-[-50%] text-text-primary system-sm-semibold">
|
||||
{(state.valueNow / 100).toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default Slider
|
||||
@@ -1,20 +0,0 @@
|
||||
.slider {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.slider.disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.slider-thumb:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.slider-track {
|
||||
background-color: #528BFF;
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
.slider-track-1 {
|
||||
background-color: #E5E7EB;
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
import type { FC } from 'react'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Slider from '@/app/components/base/features/new-feature-panel/annotation-reply/score-slider/base-slider'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
@@ -10,23 +10,42 @@ type Props = {
|
||||
onChange: (value: number) => void
|
||||
}
|
||||
|
||||
const clamp = (value: number, min: number, max: number) => {
|
||||
if (!Number.isFinite(value))
|
||||
return min
|
||||
|
||||
return Math.min(Math.max(value, min), max)
|
||||
}
|
||||
|
||||
const ScoreSlider: FC<Props> = ({
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const safeValue = clamp(value, 80, 100)
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<div className="mt-[14px] h-px">
|
||||
<div className="relative mt-[14px]">
|
||||
<Slider
|
||||
max={100}
|
||||
className="w-full"
|
||||
value={safeValue}
|
||||
min={80}
|
||||
max={100}
|
||||
step={1}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onValueChange={onChange}
|
||||
aria-label={t('feature.annotation.scoreThreshold.title', { ns: 'appDebug' })}
|
||||
/>
|
||||
<div
|
||||
className="pointer-events-none absolute top-[-16px] text-text-primary system-sm-semibold"
|
||||
style={{
|
||||
left: `calc(4px + ${(safeValue - 80) / 20} * (100% - 8px))`,
|
||||
transform: 'translateX(-50%)',
|
||||
}}
|
||||
>
|
||||
{(safeValue / 100).toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-[10px] flex items-center justify-between system-xs-semibold-uppercase">
|
||||
<div className="flex space-x-1 text-util-colors-cyan-cyan-500">
|
||||
|
||||
@@ -14,12 +14,14 @@ describe('ParamItem Slider onChange', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const getSlider = () => screen.getByLabelText('Test Param')
|
||||
|
||||
it('should divide slider value by 100 when max < 5', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<ParamItem {...defaultProps} value={0.5} min={0} max={1} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
|
||||
await user.click(slider)
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
|
||||
// max=1 < 5, so slider value change (50->51) becomes 0.51
|
||||
@@ -29,9 +31,9 @@ describe('ParamItem Slider onChange', () => {
|
||||
it('should not divide slider value when max >= 5', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<ParamItem {...defaultProps} value={5} min={1} max={10} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
|
||||
await user.click(slider)
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
|
||||
// max=10 >= 5, so value remains raw (5->6)
|
||||
|
||||
@@ -17,6 +17,8 @@ describe('ParamItem', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const getSlider = () => screen.getByLabelText('Test Param')
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render the parameter name', () => {
|
||||
render(<ParamItem {...defaultProps} />)
|
||||
@@ -54,7 +56,7 @@ describe('ParamItem', () => {
|
||||
render(<ParamItem {...defaultProps} />)
|
||||
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument()
|
||||
expect(screen.getByRole('slider')).toBeInTheDocument()
|
||||
expect(getSlider()).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -74,7 +76,7 @@ describe('ParamItem', () => {
|
||||
it('should disable Slider when enable is false', () => {
|
||||
render(<ParamItem {...defaultProps} enable={false} />)
|
||||
|
||||
expect(screen.getByRole('slider')).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(getSlider()).toBeDisabled()
|
||||
})
|
||||
|
||||
it('should set switch value based on enable prop', () => {
|
||||
@@ -135,7 +137,7 @@ describe('ParamItem', () => {
|
||||
await user.clear(input)
|
||||
|
||||
expect(defaultProps.onChange).toHaveBeenLastCalledWith('test_param', 0)
|
||||
expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '0')
|
||||
expect(getSlider()).toHaveAttribute('aria-valuenow', '0')
|
||||
|
||||
await user.tab()
|
||||
|
||||
@@ -166,12 +168,12 @@ describe('ParamItem', () => {
|
||||
await user.type(input, '1.5')
|
||||
|
||||
expect(defaultProps.onChange).toHaveBeenLastCalledWith('test_param', 1)
|
||||
expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '100')
|
||||
expect(getSlider()).toHaveAttribute('aria-valuenow', '100')
|
||||
})
|
||||
|
||||
it('should pass scaled value to slider when max < 5', () => {
|
||||
render(<ParamItem {...defaultProps} value={0.5} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
|
||||
// When max < 5, slider value = value * 100 = 50
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '50')
|
||||
@@ -179,7 +181,7 @@ describe('ParamItem', () => {
|
||||
|
||||
it('should pass raw value to slider when max >= 5', () => {
|
||||
render(<ParamItem {...defaultProps} value={5} max={10} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
|
||||
// When max >= 5, slider value = value = 5
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '5')
|
||||
@@ -212,15 +214,15 @@ describe('ParamItem', () => {
|
||||
render(<ParamItem {...defaultProps} value={0.5} min={0} />)
|
||||
|
||||
// Slider should get value * 100 = 50, min * 100 = 0, max * 100 = 100
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '100')
|
||||
const slider = getSlider()
|
||||
expect(slider).toHaveAttribute('max', '100')
|
||||
})
|
||||
|
||||
it('should not scale slider value when max >= 5', () => {
|
||||
render(<ParamItem {...defaultProps} value={5} min={1} max={10} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '10')
|
||||
const slider = getSlider()
|
||||
expect(slider).toHaveAttribute('max', '10')
|
||||
})
|
||||
|
||||
it('should expose default minimum of 0 when min is not provided', () => {
|
||||
|
||||
@@ -14,6 +14,8 @@ describe('ScoreThresholdItem', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const getSlider = () => screen.getByLabelText('appDebug.datasetConfig.score_threshold')
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render the translated parameter name', () => {
|
||||
render(<ScoreThresholdItem {...defaultProps} />)
|
||||
@@ -32,7 +34,7 @@ describe('ScoreThresholdItem', () => {
|
||||
render(<ScoreThresholdItem {...defaultProps} />)
|
||||
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument()
|
||||
expect(screen.getByRole('slider')).toBeInTheDocument()
|
||||
expect(getSlider()).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,7 +65,7 @@ describe('ScoreThresholdItem', () => {
|
||||
render(<ScoreThresholdItem {...defaultProps} enable={false} />)
|
||||
|
||||
expect(screen.getByRole('textbox')).toBeDisabled()
|
||||
expect(screen.getByRole('slider')).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(getSlider()).toBeDisabled()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ describe('TopKItem', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const getSlider = () => screen.getByLabelText('appDebug.datasetConfig.top_k')
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render the translated parameter name', () => {
|
||||
render(<TopKItem {...defaultProps} />)
|
||||
@@ -37,7 +39,7 @@ describe('TopKItem', () => {
|
||||
render(<TopKItem {...defaultProps} />)
|
||||
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument()
|
||||
expect(screen.getByRole('slider')).toBeInTheDocument()
|
||||
expect(getSlider()).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -52,7 +54,7 @@ describe('TopKItem', () => {
|
||||
render(<TopKItem {...defaultProps} enable={false} />)
|
||||
|
||||
expect(screen.getByRole('textbox')).toBeDisabled()
|
||||
expect(screen.getByRole('slider')).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(getSlider()).toBeDisabled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -77,10 +79,10 @@ describe('TopKItem', () => {
|
||||
|
||||
it('should render slider with max >= 5 so no scaling is applied', () => {
|
||||
render(<TopKItem {...defaultProps} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
|
||||
// max=10 >= 5 so slider shows raw values
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '10')
|
||||
expect(slider).toHaveAttribute('max', '10')
|
||||
})
|
||||
|
||||
it('should not render a switch (no hasSwitch prop)', () => {
|
||||
@@ -116,9 +118,9 @@ describe('TopKItem', () => {
|
||||
it('should call onChange with integer value when slider changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<TopKItem {...defaultProps} value={2} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
|
||||
await user.click(slider)
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
|
||||
expect(defaultProps.onChange).toHaveBeenLastCalledWith('top_k', 3)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import Switch from '@/app/components/base/switch'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldControls,
|
||||
@@ -78,7 +78,8 @@ const ParamItem: FC<Props> = ({ className, id, name, noTooltip, tip, step = 0.1,
|
||||
value={max < 5 ? value * 100 : value}
|
||||
min={min < 1 ? min * 100 : min}
|
||||
max={max < 5 ? max * 100 : max}
|
||||
onChange={value => onChange(id, value / (max < 5 ? 100 : 1))}
|
||||
onValueChange={value => onChange(id, value / (max < 5 ? 100 : 1))}
|
||||
aria-label={name}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,10 +3,13 @@ import { LexicalComposer } from '@lexical/react/LexicalComposer'
|
||||
import { act, render, waitFor } from '@testing-library/react'
|
||||
import {
|
||||
BLUR_COMMAND,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
FOCUS_COMMAND,
|
||||
KEY_ESCAPE_COMMAND,
|
||||
} from 'lexical'
|
||||
import OnBlurBlock from '../on-blur-or-focus-block'
|
||||
import { CaptureEditorPlugin } from '../test-utils'
|
||||
import { CLEAR_HIDE_MENU_TIMEOUT } from '../workflow-variable-block'
|
||||
|
||||
const renderOnBlurBlock = (props?: {
|
||||
onBlur?: () => void
|
||||
@@ -72,7 +75,7 @@ describe('OnBlurBlock', () => {
|
||||
expect(onFocus).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should call onBlur when blur target is not var-search-input', async () => {
|
||||
it('should call onBlur and dispatch escape after delay when blur target is not var-search-input', async () => {
|
||||
const onBlur = vi.fn()
|
||||
const { getEditor } = renderOnBlurBlock({ onBlur })
|
||||
|
||||
@@ -82,6 +85,14 @@ describe('OnBlurBlock', () => {
|
||||
|
||||
const editor = getEditor()
|
||||
expect(editor).not.toBeNull()
|
||||
vi.useFakeTimers()
|
||||
|
||||
const onEscape = vi.fn(() => true)
|
||||
const unregister = editor!.registerCommand(
|
||||
KEY_ESCAPE_COMMAND,
|
||||
onEscape,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
)
|
||||
|
||||
let handled = false
|
||||
act(() => {
|
||||
@@ -90,9 +101,18 @@ describe('OnBlurBlock', () => {
|
||||
|
||||
expect(handled).toBe(true)
|
||||
expect(onBlur).toHaveBeenCalledTimes(1)
|
||||
expect(onEscape).not.toHaveBeenCalled()
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(onEscape).toHaveBeenCalledTimes(1)
|
||||
unregister()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should handle blur when onBlur callback is not provided', async () => {
|
||||
it('should dispatch delayed escape when onBlur callback is not provided', async () => {
|
||||
const { getEditor } = renderOnBlurBlock()
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -101,16 +121,28 @@ describe('OnBlurBlock', () => {
|
||||
|
||||
const editor = getEditor()
|
||||
expect(editor).not.toBeNull()
|
||||
vi.useFakeTimers()
|
||||
|
||||
const onEscape = vi.fn(() => true)
|
||||
const unregister = editor!.registerCommand(
|
||||
KEY_ESCAPE_COMMAND,
|
||||
onEscape,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
)
|
||||
|
||||
let handled = false
|
||||
act(() => {
|
||||
handled = editor!.dispatchCommand(BLUR_COMMAND, createBlurEvent(document.createElement('div')))
|
||||
editor!.dispatchCommand(BLUR_COMMAND, createBlurEvent(document.createElement('div')))
|
||||
})
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(handled).toBe(true)
|
||||
expect(onEscape).toHaveBeenCalledTimes(1)
|
||||
unregister()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should skip onBlur when blur target is var-search-input', async () => {
|
||||
it('should skip onBlur and delayed escape when blur target is var-search-input', async () => {
|
||||
const onBlur = vi.fn()
|
||||
const { getEditor } = renderOnBlurBlock({ onBlur })
|
||||
|
||||
@@ -120,17 +152,31 @@ describe('OnBlurBlock', () => {
|
||||
|
||||
const editor = getEditor()
|
||||
expect(editor).not.toBeNull()
|
||||
vi.useFakeTimers()
|
||||
|
||||
const target = document.createElement('input')
|
||||
target.classList.add('var-search-input')
|
||||
|
||||
const onEscape = vi.fn(() => true)
|
||||
const unregister = editor!.registerCommand(
|
||||
KEY_ESCAPE_COMMAND,
|
||||
onEscape,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
)
|
||||
|
||||
let handled = false
|
||||
act(() => {
|
||||
handled = editor!.dispatchCommand(BLUR_COMMAND, createBlurEvent(target))
|
||||
})
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(handled).toBe(true)
|
||||
expect(onBlur).not.toHaveBeenCalled()
|
||||
expect(onEscape).not.toHaveBeenCalled()
|
||||
unregister()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should handle focus command when onFocus callback is not provided', async () => {
|
||||
@@ -152,6 +198,59 @@ describe('OnBlurBlock', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Clear timeout command', () => {
|
||||
it('should clear scheduled escape timeout when clear command is dispatched', async () => {
|
||||
const { getEditor } = renderOnBlurBlock({ onBlur: vi.fn() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getEditor()).not.toBeNull()
|
||||
})
|
||||
|
||||
const editor = getEditor()
|
||||
expect(editor).not.toBeNull()
|
||||
vi.useFakeTimers()
|
||||
|
||||
const onEscape = vi.fn(() => true)
|
||||
const unregister = editor!.registerCommand(
|
||||
KEY_ESCAPE_COMMAND,
|
||||
onEscape,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
)
|
||||
|
||||
act(() => {
|
||||
editor!.dispatchCommand(BLUR_COMMAND, createBlurEvent(document.createElement('div')))
|
||||
})
|
||||
act(() => {
|
||||
editor!.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
|
||||
})
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(onEscape).not.toHaveBeenCalled()
|
||||
unregister()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should handle clear command when no timeout is scheduled', async () => {
|
||||
const { getEditor } = renderOnBlurBlock()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getEditor()).not.toBeNull()
|
||||
})
|
||||
|
||||
const editor = getEditor()
|
||||
expect(editor).not.toBeNull()
|
||||
|
||||
let handled = false
|
||||
act(() => {
|
||||
handled = editor!.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
|
||||
})
|
||||
|
||||
expect(handled).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Lifecycle cleanup', () => {
|
||||
it('should unregister commands when component unmounts', async () => {
|
||||
const { getEditor, unmount } = renderOnBlurBlock()
|
||||
@@ -167,13 +266,16 @@ describe('OnBlurBlock', () => {
|
||||
|
||||
let blurHandled = true
|
||||
let focusHandled = true
|
||||
let clearHandled = true
|
||||
act(() => {
|
||||
blurHandled = editor!.dispatchCommand(BLUR_COMMAND, createBlurEvent(document.createElement('div')))
|
||||
focusHandled = editor!.dispatchCommand(FOCUS_COMMAND, createFocusEvent())
|
||||
clearHandled = editor!.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
|
||||
})
|
||||
|
||||
expect(blurHandled).toBe(false)
|
||||
expect(focusHandled).toBe(false)
|
||||
expect(clearHandled).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { LexicalEditor } from 'lexical'
|
||||
import { LexicalComposer } from '@lexical/react/LexicalComposer'
|
||||
import { act, render, waitFor } from '@testing-library/react'
|
||||
import { $getRoot } from 'lexical'
|
||||
import { $getRoot, COMMAND_PRIORITY_EDITOR } from 'lexical'
|
||||
import { CustomTextNode } from '../custom-text/node'
|
||||
import { CaptureEditorPlugin } from '../test-utils'
|
||||
import UpdateBlock, {
|
||||
PROMPT_EDITOR_INSERT_QUICKLY,
|
||||
PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER,
|
||||
} from '../update-block'
|
||||
import { CLEAR_HIDE_MENU_TIMEOUT } from '../workflow-variable-block'
|
||||
|
||||
const { mockUseEventEmitterContextContext } = vi.hoisted(() => ({
|
||||
mockUseEventEmitterContextContext: vi.fn(),
|
||||
@@ -156,7 +157,7 @@ describe('UpdateBlock', () => {
|
||||
})
|
||||
|
||||
describe('Quick insert event', () => {
|
||||
it('should insert slash when quick insert event matches instance id', async () => {
|
||||
it('should insert slash and dispatch clear command when quick insert event matches instance id', async () => {
|
||||
const { emit, getEditor } = setup({ instanceId: 'instance-1' })
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -167,6 +168,13 @@ describe('UpdateBlock', () => {
|
||||
|
||||
selectRootEnd(editor!)
|
||||
|
||||
const clearCommandHandler = vi.fn(() => true)
|
||||
const unregister = editor!.registerCommand(
|
||||
CLEAR_HIDE_MENU_TIMEOUT,
|
||||
clearCommandHandler,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
)
|
||||
|
||||
emit({
|
||||
type: PROMPT_EDITOR_INSERT_QUICKLY,
|
||||
instanceId: 'instance-1',
|
||||
@@ -175,6 +183,9 @@ describe('UpdateBlock', () => {
|
||||
await waitFor(() => {
|
||||
expect(readEditorText(editor!)).toBe('/')
|
||||
})
|
||||
expect(clearCommandHandler).toHaveBeenCalledTimes(1)
|
||||
|
||||
unregister()
|
||||
})
|
||||
|
||||
it('should ignore quick insert event when instance id does not match', async () => {
|
||||
|
||||
@@ -23,8 +23,6 @@ import {
|
||||
$createTextNode,
|
||||
$getRoot,
|
||||
$setSelection,
|
||||
BLUR_COMMAND,
|
||||
FOCUS_COMMAND,
|
||||
KEY_ESCAPE_COMMAND,
|
||||
} from 'lexical'
|
||||
import * as React from 'react'
|
||||
@@ -633,180 +631,4 @@ describe('ComponentPicker (component-picker-block/index.tsx)', () => {
|
||||
// With a single option group, the only divider should be the workflow-var/options separator.
|
||||
expect(document.querySelectorAll('.bg-divider-subtle')).toHaveLength(1)
|
||||
})
|
||||
|
||||
describe('blur/focus menu visibility', () => {
|
||||
it('hides the menu after a 200ms delay when blur command is dispatched', async () => {
|
||||
const captures: Captures = { editor: null, eventEmitter: null }
|
||||
|
||||
render((
|
||||
<MinimalEditor
|
||||
triggerString="{"
|
||||
contextBlock={makeContextBlock()}
|
||||
captures={captures}
|
||||
/>
|
||||
))
|
||||
|
||||
const editor = await waitForEditor(captures)
|
||||
await setEditorText(editor, '{', true)
|
||||
expect(await screen.findByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(BLUR_COMMAND, new FocusEvent('blur', { relatedTarget: document.createElement('button') }))
|
||||
})
|
||||
|
||||
expect(screen.queryByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(screen.queryByText('common.promptEditor.context.item.title')).not.toBeInTheDocument()
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('restores menu visibility when focus command is dispatched after blur hides it', async () => {
|
||||
const captures: Captures = { editor: null, eventEmitter: null }
|
||||
|
||||
render((
|
||||
<MinimalEditor
|
||||
triggerString="{"
|
||||
contextBlock={makeContextBlock()}
|
||||
captures={captures}
|
||||
/>
|
||||
))
|
||||
|
||||
const editor = await waitForEditor(captures)
|
||||
await setEditorText(editor, '{', true)
|
||||
expect(await screen.findByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(BLUR_COMMAND, new FocusEvent('blur', { relatedTarget: document.createElement('button') }))
|
||||
})
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(screen.queryByText('common.promptEditor.context.item.title')).not.toBeInTheDocument()
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(FOCUS_COMMAND, new FocusEvent('focus'))
|
||||
})
|
||||
|
||||
vi.useRealTimers()
|
||||
|
||||
await setEditorText(editor, '{', true)
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('cancels the blur timer when focus arrives before the 200ms timeout', async () => {
|
||||
const captures: Captures = { editor: null, eventEmitter: null }
|
||||
|
||||
render((
|
||||
<MinimalEditor
|
||||
triggerString="{"
|
||||
contextBlock={makeContextBlock()}
|
||||
captures={captures}
|
||||
/>
|
||||
))
|
||||
|
||||
const editor = await waitForEditor(captures)
|
||||
await setEditorText(editor, '{', true)
|
||||
expect(await screen.findByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(BLUR_COMMAND, new FocusEvent('blur', { relatedTarget: document.createElement('button') }))
|
||||
})
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(FOCUS_COMMAND, new FocusEvent('focus'))
|
||||
})
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(screen.queryByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('cancels a pending blur timer when a subsequent blur targets var-search-input', async () => {
|
||||
const captures: Captures = { editor: null, eventEmitter: null }
|
||||
|
||||
render((
|
||||
<MinimalEditor
|
||||
triggerString="{"
|
||||
contextBlock={makeContextBlock()}
|
||||
captures={captures}
|
||||
/>
|
||||
))
|
||||
|
||||
const editor = await waitForEditor(captures)
|
||||
await setEditorText(editor, '{', true)
|
||||
expect(await screen.findByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(BLUR_COMMAND, new FocusEvent('blur', { relatedTarget: document.createElement('button') }))
|
||||
})
|
||||
|
||||
const varInput = document.createElement('input')
|
||||
varInput.classList.add('var-search-input')
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(BLUR_COMMAND, new FocusEvent('blur', { relatedTarget: varInput }))
|
||||
})
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(screen.queryByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('does not hide the menu when blur target is var-search-input', async () => {
|
||||
const captures: Captures = { editor: null, eventEmitter: null }
|
||||
|
||||
render((
|
||||
<MinimalEditor
|
||||
triggerString="{"
|
||||
contextBlock={makeContextBlock()}
|
||||
captures={captures}
|
||||
/>
|
||||
))
|
||||
|
||||
const editor = await waitForEditor(captures)
|
||||
await setEditorText(editor, '{', true)
|
||||
expect(await screen.findByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const target = document.createElement('input')
|
||||
target.classList.add('var-search-input')
|
||||
|
||||
act(() => {
|
||||
editor.dispatchCommand(BLUR_COMMAND, new FocusEvent('blur', { relatedTarget: target }))
|
||||
})
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200)
|
||||
})
|
||||
|
||||
expect(screen.queryByText('common.promptEditor.context.item.title')).toBeInTheDocument()
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -21,19 +21,11 @@ import {
|
||||
} from '@floating-ui/react'
|
||||
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
|
||||
import { LexicalTypeaheadMenuPlugin } from '@lexical/react/LexicalTypeaheadMenuPlugin'
|
||||
import { mergeRegister } from '@lexical/utils'
|
||||
import {
|
||||
BLUR_COMMAND,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
FOCUS_COMMAND,
|
||||
KEY_ESCAPE_COMMAND,
|
||||
} from 'lexical'
|
||||
import { KEY_ESCAPE_COMMAND } from 'lexical'
|
||||
import {
|
||||
Fragment,
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
@@ -95,46 +87,6 @@ const ComponentPicker = ({
|
||||
})
|
||||
|
||||
const [queryString, setQueryString] = useState<string | null>(null)
|
||||
const [blurHidden, setBlurHidden] = useState(false)
|
||||
const blurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const clearBlurTimer = useCallback(() => {
|
||||
if (blurTimerRef.current) {
|
||||
clearTimeout(blurTimerRef.current)
|
||||
blurTimerRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const unregister = mergeRegister(
|
||||
editor.registerCommand(
|
||||
BLUR_COMMAND,
|
||||
(event) => {
|
||||
clearBlurTimer()
|
||||
const target = event?.relatedTarget as HTMLElement
|
||||
if (!target?.classList?.contains('var-search-input'))
|
||||
blurTimerRef.current = setTimeout(() => setBlurHidden(true), 200)
|
||||
return false
|
||||
},
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
),
|
||||
editor.registerCommand(
|
||||
FOCUS_COMMAND,
|
||||
() => {
|
||||
clearBlurTimer()
|
||||
setBlurHidden(false)
|
||||
return false
|
||||
},
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
),
|
||||
)
|
||||
|
||||
return () => {
|
||||
if (blurTimerRef.current)
|
||||
clearTimeout(blurTimerRef.current)
|
||||
unregister()
|
||||
}
|
||||
}, [editor, clearBlurTimer])
|
||||
|
||||
eventEmitter?.useSubscription((v: any) => {
|
||||
if (v.type === INSERT_VARIABLE_VALUE_BLOCK_COMMAND)
|
||||
@@ -207,8 +159,6 @@ const ComponentPicker = ({
|
||||
anchorElementRef,
|
||||
{ options, selectedIndex, selectOptionAndCleanUp, setHighlightedIndex },
|
||||
) => {
|
||||
if (blurHidden)
|
||||
return null
|
||||
if (!(anchorElementRef.current && (allFlattenOptions.length || workflowVariableBlock?.show)))
|
||||
return null
|
||||
|
||||
@@ -290,7 +240,7 @@ const ComponentPicker = ({
|
||||
}
|
||||
</>
|
||||
)
|
||||
}, [blurHidden, allFlattenOptions.length, workflowVariableBlock?.show, floatingStyles, isPositioned, refs, workflowVariableOptions, isSupportFileVar, handleClose, currentBlock?.generatorType, handleSelectWorkflowVariable, queryString, workflowVariableBlock?.showManageInputField, workflowVariableBlock?.onManageInputField])
|
||||
}, [allFlattenOptions.length, workflowVariableBlock?.show, floatingStyles, isPositioned, refs, workflowVariableOptions, isSupportFileVar, handleClose, currentBlock?.generatorType, handleSelectWorkflowVariable, queryString, workflowVariableBlock?.showManageInputField, workflowVariableBlock?.onManageInputField])
|
||||
|
||||
return (
|
||||
<LexicalTypeaheadMenuPlugin
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
BLUR_COMMAND,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
FOCUS_COMMAND,
|
||||
KEY_ESCAPE_COMMAND,
|
||||
} from 'lexical'
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { CLEAR_HIDE_MENU_TIMEOUT } from './workflow-variable-block'
|
||||
|
||||
type OnBlurBlockProps = {
|
||||
onBlur?: () => void
|
||||
@@ -18,13 +20,35 @@ const OnBlurBlock: FC<OnBlurBlockProps> = ({
|
||||
}) => {
|
||||
const [editor] = useLexicalComposerContext()
|
||||
|
||||
const ref = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
return mergeRegister(
|
||||
const clearHideMenuTimeout = () => {
|
||||
if (ref.current) {
|
||||
clearTimeout(ref.current)
|
||||
ref.current = null
|
||||
}
|
||||
}
|
||||
|
||||
const unregister = mergeRegister(
|
||||
editor.registerCommand(
|
||||
CLEAR_HIDE_MENU_TIMEOUT,
|
||||
() => {
|
||||
clearHideMenuTimeout()
|
||||
return true
|
||||
},
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
),
|
||||
editor.registerCommand(
|
||||
BLUR_COMMAND,
|
||||
(event) => {
|
||||
// Check if the clicked target element is var-search-input
|
||||
const target = event?.relatedTarget as HTMLElement
|
||||
if (!target?.classList?.contains('var-search-input')) {
|
||||
clearHideMenuTimeout()
|
||||
ref.current = setTimeout(() => {
|
||||
editor.dispatchCommand(KEY_ESCAPE_COMMAND, new KeyboardEvent('keydown', { key: 'Escape' }))
|
||||
}, 200)
|
||||
if (onBlur)
|
||||
onBlur()
|
||||
}
|
||||
@@ -42,6 +66,11 @@ const OnBlurBlock: FC<OnBlurBlockProps> = ({
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
),
|
||||
)
|
||||
|
||||
return () => {
|
||||
clearHideMenuTimeout()
|
||||
unregister()
|
||||
}
|
||||
}, [editor, onBlur, onFocus])
|
||||
|
||||
return null
|
||||
|
||||
@@ -3,6 +3,7 @@ import { $insertNodes } from 'lexical'
|
||||
import { useEventEmitterContextContext } from '@/context/event-emitter'
|
||||
import { textToEditorState } from '../utils'
|
||||
import { CustomTextNode } from './custom-text/node'
|
||||
import { CLEAR_HIDE_MENU_TIMEOUT } from './workflow-variable-block'
|
||||
|
||||
export const PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER = 'PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER'
|
||||
export const PROMPT_EDITOR_INSERT_QUICKLY = 'PROMPT_EDITOR_INSERT_QUICKLY'
|
||||
@@ -29,6 +30,8 @@ const UpdateBlock = ({
|
||||
editor.update(() => {
|
||||
const textNode = new CustomTextNode('/')
|
||||
$insertNodes([textNode])
|
||||
|
||||
editor.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ import { $insertNodes, COMMAND_PRIORITY_EDITOR } from 'lexical'
|
||||
import { Type } from '@/app/components/workflow/nodes/llm/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import {
|
||||
CLEAR_HIDE_MENU_TIMEOUT,
|
||||
DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND,
|
||||
INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND,
|
||||
UPDATE_WORKFLOW_NODES_MAP,
|
||||
@@ -133,6 +134,7 @@ describe('WorkflowVariableBlock', () => {
|
||||
const insertHandler = mockRegisterCommand.mock.calls[0][1] as (variables: string[]) => boolean
|
||||
const result = insertHandler(['node-1', 'answer'])
|
||||
|
||||
expect(mockDispatchCommand).toHaveBeenCalledWith(CLEAR_HIDE_MENU_TIMEOUT, undefined)
|
||||
expect($createWorkflowVariableBlockNode).toHaveBeenCalledWith(
|
||||
['node-1', 'answer'],
|
||||
workflowNodesMap,
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
|
||||
export const INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND = createCommand('INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND')
|
||||
export const DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND = createCommand('DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND')
|
||||
export const CLEAR_HIDE_MENU_TIMEOUT = createCommand('CLEAR_HIDE_MENU_TIMEOUT')
|
||||
export const UPDATE_WORKFLOW_NODES_MAP = createCommand('UPDATE_WORKFLOW_NODES_MAP')
|
||||
|
||||
export type WorkflowVariableBlockProps = {
|
||||
@@ -48,6 +49,7 @@ const WorkflowVariableBlock = memo(({
|
||||
editor.registerCommand(
|
||||
INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND,
|
||||
(variables: string[]) => {
|
||||
editor.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
|
||||
const workflowVariableBlockNode = $createWorkflowVariableBlockNode(variables, workflowNodesMap, getVarType)
|
||||
|
||||
$insertNodes([workflowVariableBlockNode])
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import Slider from '../index'
|
||||
|
||||
describe('Slider Component', () => {
|
||||
it('should render with correct default ARIA limits and current value', () => {
|
||||
render(<Slider value={50} onChange={vi.fn()} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemin', '0')
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '100')
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '50')
|
||||
})
|
||||
|
||||
it('should apply custom min, max, and step values', () => {
|
||||
render(<Slider value={10} min={5} max={20} step={5} onChange={vi.fn()} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemin', '5')
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '20')
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '10')
|
||||
})
|
||||
|
||||
it('should default to 0 if the value prop is NaN', () => {
|
||||
render(<Slider value={Number.NaN} onChange={vi.fn()} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '0')
|
||||
})
|
||||
|
||||
it('should call onChange when arrow keys are pressed', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<Slider value={20} onChange={onChange} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
|
||||
await act(async () => {
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
})
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1)
|
||||
expect(onChange).toHaveBeenCalledWith(21, 0)
|
||||
})
|
||||
|
||||
it('should not trigger onChange when disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<Slider value={20} onChange={onChange} disabled />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
|
||||
expect(slider).toHaveAttribute('aria-disabled', 'true')
|
||||
|
||||
await act(async () => {
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
})
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should apply custom class names', () => {
|
||||
render(
|
||||
<Slider value={10} onChange={vi.fn()} className="outer-test" thumbClassName="thumb-test" />,
|
||||
)
|
||||
|
||||
const sliderWrapper = screen.getByRole('slider').closest('.outer-test')
|
||||
expect(sliderWrapper).toBeInTheDocument()
|
||||
|
||||
const thumb = screen.getByRole('slider')
|
||||
expect(thumb).toHaveClass('thumb-test')
|
||||
})
|
||||
})
|
||||
@@ -1,635 +0,0 @@
|
||||
import type { Meta, StoryObj } from '@storybook/nextjs-vite'
|
||||
import { useState } from 'react'
|
||||
import Slider from '.'
|
||||
|
||||
const meta = {
|
||||
title: 'Base/Data Entry/Slider',
|
||||
component: Slider,
|
||||
parameters: {
|
||||
layout: 'centered',
|
||||
docs: {
|
||||
description: {
|
||||
component: 'Slider component for selecting a numeric value within a range. Built on react-slider with customizable min/max/step values.',
|
||||
},
|
||||
},
|
||||
},
|
||||
tags: ['autodocs'],
|
||||
argTypes: {
|
||||
value: {
|
||||
control: 'number',
|
||||
description: 'Current slider value',
|
||||
},
|
||||
min: {
|
||||
control: 'number',
|
||||
description: 'Minimum value (default: 0)',
|
||||
},
|
||||
max: {
|
||||
control: 'number',
|
||||
description: 'Maximum value (default: 100)',
|
||||
},
|
||||
step: {
|
||||
control: 'number',
|
||||
description: 'Step increment (default: 1)',
|
||||
},
|
||||
disabled: {
|
||||
control: 'boolean',
|
||||
description: 'Disabled state',
|
||||
},
|
||||
},
|
||||
args: {
|
||||
onChange: (value) => {
|
||||
console.log('Slider value:', value)
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof Slider>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
// Interactive demo wrapper
|
||||
const SliderDemo = (args: any) => {
|
||||
const [value, setValue] = useState(args.value || 50)
|
||||
|
||||
return (
|
||||
<div style={{ width: '400px' }}>
|
||||
<Slider
|
||||
{...args}
|
||||
value={value}
|
||||
onChange={(v) => {
|
||||
setValue(v)
|
||||
console.log('Slider value:', v)
|
||||
}}
|
||||
/>
|
||||
<div className="mt-4 text-center text-sm text-gray-600">
|
||||
Value:
|
||||
{' '}
|
||||
<span className="text-lg font-semibold">{value}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Default state
|
||||
export const Default: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 50,
|
||||
min: 0,
|
||||
max: 100,
|
||||
step: 1,
|
||||
disabled: false,
|
||||
},
|
||||
}
|
||||
|
||||
// With custom range
|
||||
export const CustomRange: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 25,
|
||||
min: 0,
|
||||
max: 50,
|
||||
step: 1,
|
||||
disabled: false,
|
||||
},
|
||||
}
|
||||
|
||||
// With step increment
|
||||
export const WithStepIncrement: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 50,
|
||||
min: 0,
|
||||
max: 100,
|
||||
step: 10,
|
||||
disabled: false,
|
||||
},
|
||||
}
|
||||
|
||||
// Decimal values
|
||||
export const DecimalValues: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 2.5,
|
||||
min: 0,
|
||||
max: 5,
|
||||
step: 0.5,
|
||||
disabled: false,
|
||||
},
|
||||
}
|
||||
|
||||
// Disabled state
|
||||
export const Disabled: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 75,
|
||||
min: 0,
|
||||
max: 100,
|
||||
step: 1,
|
||||
disabled: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Real-world example - Volume control
|
||||
const VolumeControlDemo = () => {
|
||||
const [volume, setVolume] = useState(70)
|
||||
|
||||
const getVolumeIcon = (vol: number) => {
|
||||
if (vol === 0)
|
||||
return '🔇'
|
||||
if (vol < 33)
|
||||
return '🔈'
|
||||
if (vol < 66)
|
||||
return '🔉'
|
||||
return '🔊'
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ width: '400px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Volume Control</h3>
|
||||
<span className="text-2xl">{getVolumeIcon(volume)}</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={volume}
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
onChange={setVolume}
|
||||
/>
|
||||
<div className="mt-4 flex items-center justify-between text-sm text-gray-600">
|
||||
<span>Mute</span>
|
||||
<span className="text-lg font-semibold">
|
||||
{volume}
|
||||
%
|
||||
</span>
|
||||
<span>Max</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const VolumeControl: Story = {
|
||||
render: () => <VolumeControlDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Real-world example - Brightness control
|
||||
const BrightnessControlDemo = () => {
|
||||
const [brightness, setBrightness] = useState(80)
|
||||
|
||||
return (
|
||||
<div style={{ width: '400px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Screen Brightness</h3>
|
||||
<span className="text-2xl">☀️</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={brightness}
|
||||
min={0}
|
||||
max={100}
|
||||
step={5}
|
||||
onChange={setBrightness}
|
||||
/>
|
||||
<div className="mt-4 rounded-lg bg-gray-50 p-4" style={{ opacity: brightness / 100 }}>
|
||||
<div className="text-sm text-gray-700">
|
||||
Preview at
|
||||
{' '}
|
||||
{brightness}
|
||||
% brightness
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const BrightnessControl: Story = {
|
||||
render: () => <BrightnessControlDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Real-world example - Price range filter
|
||||
const PriceRangeFilterDemo = () => {
|
||||
const [maxPrice, setMaxPrice] = useState(500)
|
||||
const minPrice = 0
|
||||
|
||||
const products = [
|
||||
{ name: 'Product A', price: 150 },
|
||||
{ name: 'Product B', price: 350 },
|
||||
{ name: 'Product C', price: 600 },
|
||||
{ name: 'Product D', price: 250 },
|
||||
{ name: 'Product E', price: 450 },
|
||||
]
|
||||
|
||||
const filteredProducts = products.filter(p => p.price >= minPrice && p.price <= maxPrice)
|
||||
|
||||
return (
|
||||
<div style={{ width: '500px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<h3 className="mb-4 text-lg font-semibold">Filter by Price</h3>
|
||||
<div className="mb-2">
|
||||
<div className="mb-2 flex items-center justify-between text-sm text-gray-600">
|
||||
<span>Maximum Price</span>
|
||||
<span className="font-semibold text-gray-900">
|
||||
$
|
||||
{maxPrice}
|
||||
</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={maxPrice}
|
||||
min={0}
|
||||
max={1000}
|
||||
step={50}
|
||||
onChange={setMaxPrice}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<div className="mb-3 text-sm font-medium text-gray-700">
|
||||
Showing
|
||||
{' '}
|
||||
{filteredProducts.length}
|
||||
{' '}
|
||||
of
|
||||
{' '}
|
||||
{products.length}
|
||||
{' '}
|
||||
products
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{filteredProducts.map(product => (
|
||||
<div key={product.name} className="flex items-center justify-between rounded-lg bg-gray-50 p-3">
|
||||
<span className="text-sm">{product.name}</span>
|
||||
<span className="font-semibold text-gray-900">
|
||||
$
|
||||
{product.price}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const PriceRangeFilter: Story = {
|
||||
render: () => <PriceRangeFilterDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Real-world example - Temperature selector
|
||||
const TemperatureSelectorDemo = () => {
|
||||
const [temperature, setTemperature] = useState(22)
|
||||
const fahrenheit = ((temperature * 9) / 5 + 32).toFixed(1)
|
||||
|
||||
return (
|
||||
<div style={{ width: '400px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<h3 className="mb-4 text-lg font-semibold">Thermostat Control</h3>
|
||||
<div className="mb-6">
|
||||
<Slider
|
||||
value={temperature}
|
||||
min={16}
|
||||
max={30}
|
||||
step={0.5}
|
||||
onChange={setTemperature}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="rounded-lg bg-blue-50 p-4 text-center">
|
||||
<div className="mb-1 text-xs text-gray-600">Celsius</div>
|
||||
<div className="text-3xl font-bold text-blue-600">
|
||||
{temperature}
|
||||
°C
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg bg-orange-50 p-4 text-center">
|
||||
<div className="mb-1 text-xs text-gray-600">Fahrenheit</div>
|
||||
<div className="text-3xl font-bold text-orange-600">
|
||||
{fahrenheit}
|
||||
°F
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 text-center text-xs text-gray-500">
|
||||
{temperature < 18 && '🥶 Too cold'}
|
||||
{temperature >= 18 && temperature <= 24 && '😊 Comfortable'}
|
||||
{temperature > 24 && '🥵 Too warm'}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const TemperatureSelector: Story = {
|
||||
render: () => <TemperatureSelectorDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Real-world example - Progress/completion slider
|
||||
const ProgressSliderDemo = () => {
|
||||
const [progress, setProgress] = useState(65)
|
||||
|
||||
return (
|
||||
<div style={{ width: '450px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<h3 className="mb-4 text-lg font-semibold">Project Completion</h3>
|
||||
<Slider
|
||||
value={progress}
|
||||
min={0}
|
||||
max={100}
|
||||
step={5}
|
||||
onChange={setProgress}
|
||||
/>
|
||||
<div className="mt-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<span className="text-sm text-gray-600">Progress</span>
|
||||
<span className="text-lg font-bold text-blue-600">
|
||||
{progress}
|
||||
%
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={progress >= 25 ? '✅' : '⏳'}>Planning</span>
|
||||
<span className="text-xs text-gray-500">25%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={progress >= 50 ? '✅' : '⏳'}>Development</span>
|
||||
<span className="text-xs text-gray-500">50%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={progress >= 75 ? '✅' : '⏳'}>Testing</span>
|
||||
<span className="text-xs text-gray-500">75%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={progress >= 100 ? '✅' : '⏳'}>Deployment</span>
|
||||
<span className="text-xs text-gray-500">100%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const ProgressSlider: Story = {
|
||||
render: () => <ProgressSliderDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Real-world example - Zoom control
|
||||
const ZoomControlDemo = () => {
|
||||
const [zoom, setZoom] = useState(100)
|
||||
|
||||
return (
|
||||
<div style={{ width: '500px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<h3 className="mb-4 text-lg font-semibold">Zoom Level</h3>
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
className="rounded bg-gray-200 px-3 py-1 text-sm hover:bg-gray-300"
|
||||
onClick={() => setZoom(Math.max(50, zoom - 10))}
|
||||
>
|
||||
-
|
||||
</button>
|
||||
<div className="flex-1">
|
||||
<Slider
|
||||
value={zoom}
|
||||
min={50}
|
||||
max={200}
|
||||
step={10}
|
||||
onChange={setZoom}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
className="rounded bg-gray-200 px-3 py-1 text-sm hover:bg-gray-300"
|
||||
onClick={() => setZoom(Math.min(200, zoom + 10))}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-between text-sm text-gray-600">
|
||||
<span>50%</span>
|
||||
<span className="text-lg font-semibold">
|
||||
{zoom}
|
||||
%
|
||||
</span>
|
||||
<span>200%</span>
|
||||
</div>
|
||||
<div className="mt-4 rounded-lg bg-gray-50 p-4 text-center" style={{ transform: `scale(${zoom / 100})`, transformOrigin: 'center' }}>
|
||||
<div className="text-sm">Preview content</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const ZoomControl: Story = {
|
||||
render: () => <ZoomControlDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Real-world example - AI model parameters
|
||||
const AIModelParametersDemo = () => {
|
||||
const [temperature, setTemperature] = useState(0.7)
|
||||
const [maxTokens, setMaxTokens] = useState(2000)
|
||||
const [topP, setTopP] = useState(0.9)
|
||||
|
||||
return (
|
||||
<div style={{ width: '500px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<h3 className="mb-4 text-lg font-semibold">Model Configuration</h3>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<label className="text-sm font-medium text-gray-700">Temperature</label>
|
||||
<span className="text-sm font-semibold">{temperature}</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={temperature}
|
||||
min={0}
|
||||
max={2}
|
||||
step={0.1}
|
||||
onChange={setTemperature}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
Controls randomness. Lower is more focused, higher is more creative.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<label className="text-sm font-medium text-gray-700">Max Tokens</label>
|
||||
<span className="text-sm font-semibold">{maxTokens}</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={maxTokens}
|
||||
min={100}
|
||||
max={4000}
|
||||
step={100}
|
||||
onChange={setMaxTokens}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
Maximum length of generated response.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<label className="text-sm font-medium text-gray-700">Top P</label>
|
||||
<span className="text-sm font-semibold">{topP}</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={topP}
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
onChange={setTopP}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
Nucleus sampling threshold.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 rounded-lg bg-blue-50 p-4 text-xs text-gray-700">
|
||||
<div>
|
||||
<strong>Temperature:</strong>
|
||||
{' '}
|
||||
{temperature}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Max Tokens:</strong>
|
||||
{' '}
|
||||
{maxTokens}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Top P:</strong>
|
||||
{' '}
|
||||
{topP}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const AIModelParameters: Story = {
|
||||
render: () => <AIModelParametersDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Real-world example - Image quality selector
|
||||
const ImageQualitySelectorDemo = () => {
|
||||
const [quality, setQuality] = useState(80)
|
||||
|
||||
const getQualityLabel = (q: number) => {
|
||||
if (q < 50)
|
||||
return 'Low'
|
||||
if (q < 70)
|
||||
return 'Medium'
|
||||
if (q < 90)
|
||||
return 'High'
|
||||
return 'Maximum'
|
||||
}
|
||||
|
||||
const estimatedSize = Math.round((quality / 100) * 5)
|
||||
|
||||
return (
|
||||
<div style={{ width: '450px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<h3 className="mb-4 text-lg font-semibold">Image Export Quality</h3>
|
||||
<Slider
|
||||
value={quality}
|
||||
min={10}
|
||||
max={100}
|
||||
step={10}
|
||||
onChange={setQuality}
|
||||
/>
|
||||
<div className="mt-4 grid grid-cols-2 gap-4">
|
||||
<div className="rounded-lg bg-gray-50 p-3">
|
||||
<div className="text-xs text-gray-600">Quality</div>
|
||||
<div className="text-lg font-semibold">{getQualityLabel(quality)}</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{quality}
|
||||
%
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg bg-gray-50 p-3">
|
||||
<div className="text-xs text-gray-600">File Size</div>
|
||||
<div className="text-lg font-semibold">
|
||||
~
|
||||
{estimatedSize}
|
||||
{' '}
|
||||
MB
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">Estimated</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const ImageQualitySelector: Story = {
|
||||
render: () => <ImageQualitySelectorDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Multiple sliders
|
||||
const MultipleSlidersDemo = () => {
|
||||
const [red, setRed] = useState(128)
|
||||
const [green, setGreen] = useState(128)
|
||||
const [blue, setBlue] = useState(128)
|
||||
|
||||
const rgbColor = `rgb(${red}, ${green}, ${blue})`
|
||||
|
||||
return (
|
||||
<div style={{ width: '450px' }} className="rounded-lg border border-gray-200 bg-white p-6">
|
||||
<h3 className="mb-4 text-lg font-semibold">RGB Color Picker</h3>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<label className="text-sm font-medium text-red-600">Red</label>
|
||||
<span className="text-sm font-semibold">{red}</span>
|
||||
</div>
|
||||
<Slider value={red} min={0} max={255} step={1} onChange={setRed} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<label className="text-sm font-medium text-green-600">Green</label>
|
||||
<span className="text-sm font-semibold">{green}</span>
|
||||
</div>
|
||||
<Slider value={green} min={0} max={255} step={1} onChange={setGreen} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<label className="text-sm font-medium text-blue-600">Blue</label>
|
||||
<span className="text-sm font-semibold">{blue}</span>
|
||||
</div>
|
||||
<Slider value={blue} min={0} max={255} step={1} onChange={setBlue} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 flex items-center justify-between">
|
||||
<div
|
||||
className="h-24 w-24 rounded-lg border-2 border-gray-300"
|
||||
style={{ backgroundColor: rgbColor }}
|
||||
/>
|
||||
<div className="text-right">
|
||||
<div className="mb-1 text-xs text-gray-600">Color Value</div>
|
||||
<div className="font-mono text-sm font-semibold">{rgbColor}</div>
|
||||
<div className="mt-1 font-mono text-xs text-gray-500">
|
||||
#
|
||||
{red.toString(16).padStart(2, '0')}
|
||||
{green.toString(16).padStart(2, '0')}
|
||||
{blue.toString(16).padStart(2, '0')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const MultipleSliders: Story = {
|
||||
render: () => <MultipleSlidersDemo />,
|
||||
parameters: { controls: { disable: true } },
|
||||
} as unknown as Story
|
||||
|
||||
// Interactive playground
|
||||
export const Playground: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 50,
|
||||
min: 0,
|
||||
max: 100,
|
||||
step: 1,
|
||||
disabled: false,
|
||||
},
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import ReactSlider from 'react-slider'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import './style.css'
|
||||
|
||||
type ISliderProps = {
|
||||
className?: string
|
||||
thumbClassName?: string
|
||||
trackClassName?: string
|
||||
value: number
|
||||
max?: number
|
||||
min?: number
|
||||
step?: number
|
||||
disabled?: boolean
|
||||
onChange: (value: number) => void
|
||||
}
|
||||
|
||||
const Slider: React.FC<ISliderProps> = ({
|
||||
className,
|
||||
thumbClassName,
|
||||
trackClassName,
|
||||
max,
|
||||
min,
|
||||
step,
|
||||
value,
|
||||
disabled,
|
||||
onChange,
|
||||
}) => {
|
||||
return (
|
||||
<ReactSlider
|
||||
disabled={disabled}
|
||||
value={Number.isNaN(value) ? 0 : value}
|
||||
min={min || 0}
|
||||
max={max || 100}
|
||||
step={step || 1}
|
||||
className={cn('slider relative', className)}
|
||||
thumbClassName={cn('absolute top-[-9px] h-5 w-2 rounded-[3px] border-[0.5px] border-components-slider-knob-border bg-components-slider-knob shadow-sm focus:outline-none', !disabled && 'cursor-pointer', thumbClassName)}
|
||||
trackClassName={cn('h-0.5 rounded-full', 'slider-track', trackClassName)}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default Slider
|
||||
@@ -1,11 +0,0 @@
|
||||
.slider.disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.slider-track {
|
||||
background-color: var(--color-components-slider-range);
|
||||
}
|
||||
|
||||
.slider-track-1 {
|
||||
background-color: var(--color-components-slider-track);
|
||||
}
|
||||
73
web/app/components/base/ui/slider/__tests__/index.spec.tsx
Normal file
73
web/app/components/base/ui/slider/__tests__/index.spec.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Slider } from '../index'
|
||||
|
||||
describe('Slider', () => {
|
||||
const getSliderInput = () => screen.getByLabelText('Value')
|
||||
|
||||
it('should render with correct default ARIA limits and current value', () => {
|
||||
render(<Slider value={50} onValueChange={vi.fn()} aria-label="Value" />)
|
||||
|
||||
const slider = getSliderInput()
|
||||
expect(slider).toHaveAttribute('min', '0')
|
||||
expect(slider).toHaveAttribute('max', '100')
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '50')
|
||||
})
|
||||
|
||||
it('should apply custom min, max, and step values', () => {
|
||||
render(<Slider value={10} min={5} max={20} step={5} onValueChange={vi.fn()} aria-label="Value" />)
|
||||
|
||||
const slider = getSliderInput()
|
||||
expect(slider).toHaveAttribute('min', '5')
|
||||
expect(slider).toHaveAttribute('max', '20')
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '10')
|
||||
})
|
||||
|
||||
it('should clamp non-finite values to min', () => {
|
||||
render(<Slider value={Number.NaN} min={5} onValueChange={vi.fn()} aria-label="Value" />)
|
||||
|
||||
expect(getSliderInput()).toHaveAttribute('aria-valuenow', '5')
|
||||
})
|
||||
|
||||
it('should call onValueChange when arrow keys are pressed', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onValueChange = vi.fn()
|
||||
|
||||
render(<Slider value={20} onValueChange={onValueChange} aria-label="Value" />)
|
||||
|
||||
const slider = getSliderInput()
|
||||
|
||||
await act(async () => {
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
})
|
||||
|
||||
expect(onValueChange).toHaveBeenCalledTimes(1)
|
||||
expect(onValueChange).toHaveBeenLastCalledWith(21, expect.anything())
|
||||
})
|
||||
|
||||
it('should not trigger onValueChange when disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onValueChange = vi.fn()
|
||||
render(<Slider value={20} onValueChange={onValueChange} disabled aria-label="Value" />)
|
||||
|
||||
const slider = getSliderInput()
|
||||
|
||||
expect(slider).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
})
|
||||
|
||||
expect(onValueChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should apply custom class names on root', () => {
|
||||
const { container } = render(<Slider value={10} onValueChange={vi.fn()} className="outer-test" aria-label="Value" />)
|
||||
|
||||
const sliderWrapper = container.querySelector('.outer-test')
|
||||
expect(sliderWrapper).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
92
web/app/components/base/ui/slider/index.stories.tsx
Normal file
92
web/app/components/base/ui/slider/index.stories.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import type { Meta, StoryObj } from '@storybook/nextjs-vite'
|
||||
import type * as React from 'react'
|
||||
import { useState } from 'react'
|
||||
import { Slider } from '.'
|
||||
|
||||
const meta = {
|
||||
title: 'Base UI/Data Entry/Slider',
|
||||
component: Slider,
|
||||
parameters: {
|
||||
layout: 'centered',
|
||||
docs: {
|
||||
description: {
|
||||
component: 'Single-value horizontal slider built on Base UI.',
|
||||
},
|
||||
},
|
||||
},
|
||||
tags: ['autodocs'],
|
||||
argTypes: {
|
||||
value: {
|
||||
control: 'number',
|
||||
},
|
||||
min: {
|
||||
control: 'number',
|
||||
},
|
||||
max: {
|
||||
control: 'number',
|
||||
},
|
||||
step: {
|
||||
control: 'number',
|
||||
},
|
||||
disabled: {
|
||||
control: 'boolean',
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof Slider>
|
||||
|
||||
export default meta
|
||||
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
function SliderDemo({
|
||||
value: initialValue = 50,
|
||||
defaultValue: _defaultValue,
|
||||
...args
|
||||
}: React.ComponentProps<typeof Slider>) {
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
return (
|
||||
<div className="w-[320px] space-y-3">
|
||||
<Slider
|
||||
{...args}
|
||||
value={value}
|
||||
onValueChange={setValue}
|
||||
aria-label="Demo slider"
|
||||
/>
|
||||
<div className="text-center text-text-secondary system-sm-medium">
|
||||
{value}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Default: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 50,
|
||||
min: 0,
|
||||
max: 100,
|
||||
step: 1,
|
||||
},
|
||||
}
|
||||
|
||||
export const Decimal: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 0.5,
|
||||
min: 0,
|
||||
max: 1,
|
||||
step: 0.1,
|
||||
},
|
||||
}
|
||||
|
||||
export const Disabled: Story = {
|
||||
render: args => <SliderDemo {...args} />,
|
||||
args: {
|
||||
value: 75,
|
||||
min: 0,
|
||||
max: 100,
|
||||
step: 1,
|
||||
disabled: true,
|
||||
},
|
||||
}
|
||||
100
web/app/components/base/ui/slider/index.tsx
Normal file
100
web/app/components/base/ui/slider/index.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
'use client'
|
||||
|
||||
import { Slider as BaseSlider } from '@base-ui/react/slider'
|
||||
import * as React from 'react'
|
||||
import { cn } from '@/utils/classnames'
|
||||
|
||||
type SliderRootProps = BaseSlider.Root.Props<number>
|
||||
type SliderThumbProps = BaseSlider.Thumb.Props
|
||||
|
||||
type SliderBaseProps = Pick<
|
||||
SliderRootProps,
|
||||
'onValueChange' | 'min' | 'max' | 'step' | 'disabled' | 'name'
|
||||
> & Pick<SliderThumbProps, 'aria-label' | 'aria-labelledby'> & {
|
||||
className?: string
|
||||
}
|
||||
|
||||
type ControlledSliderProps = SliderBaseProps & {
|
||||
value: number
|
||||
defaultValue?: never
|
||||
}
|
||||
|
||||
type UncontrolledSliderProps = SliderBaseProps & {
|
||||
value?: never
|
||||
defaultValue?: number
|
||||
}
|
||||
|
||||
export type SliderProps = ControlledSliderProps | UncontrolledSliderProps
|
||||
|
||||
const sliderRootClassName = 'group/slider relative inline-flex w-full data-[disabled]:opacity-30'
|
||||
const sliderControlClassName = cn(
|
||||
'relative flex h-5 w-full touch-none select-none items-center',
|
||||
'data-[disabled]:cursor-not-allowed',
|
||||
)
|
||||
const sliderTrackClassName = cn(
|
||||
'relative h-1 w-full overflow-hidden rounded-full',
|
||||
'bg-[var(--slider-track,var(--color-components-slider-track))]',
|
||||
)
|
||||
const sliderIndicatorClassName = cn(
|
||||
'h-full rounded-full',
|
||||
'bg-[var(--slider-range,var(--color-components-slider-range))]',
|
||||
)
|
||||
const sliderThumbClassName = cn(
|
||||
'block h-5 w-2 shrink-0 rounded-[3px] border-[0.5px]',
|
||||
'border-[var(--slider-knob-border,var(--color-components-slider-knob-border))]',
|
||||
'bg-[var(--slider-knob,var(--color-components-slider-knob))] shadow-sm',
|
||||
'transition-[background-color,border-color,box-shadow,opacity] motion-reduce:transition-none',
|
||||
'hover:bg-[var(--slider-knob-hover,var(--color-components-slider-knob-hover))]',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-components-slider-knob-border-hover focus-visible:ring-offset-0',
|
||||
'active:shadow-md',
|
||||
'group-data-[disabled]/slider:bg-[var(--slider-knob-disabled,var(--color-components-slider-knob-disabled))]',
|
||||
'group-data-[disabled]/slider:border-[var(--slider-knob-border,var(--color-components-slider-knob-border))]',
|
||||
'group-data-[disabled]/slider:shadow-none',
|
||||
)
|
||||
|
||||
const getSafeValue = (value: number | undefined, min: number) => {
|
||||
if (value === undefined)
|
||||
return undefined
|
||||
|
||||
return Number.isFinite(value) ? value : min
|
||||
}
|
||||
|
||||
export function Slider({
|
||||
value,
|
||||
defaultValue,
|
||||
onValueChange,
|
||||
min = 0,
|
||||
max = 100,
|
||||
step = 1,
|
||||
disabled = false,
|
||||
name,
|
||||
className,
|
||||
'aria-label': ariaLabel,
|
||||
'aria-labelledby': ariaLabelledby,
|
||||
}: SliderProps) {
|
||||
return (
|
||||
<BaseSlider.Root
|
||||
value={getSafeValue(value, min)}
|
||||
defaultValue={getSafeValue(defaultValue, min)}
|
||||
onValueChange={onValueChange}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
disabled={disabled}
|
||||
name={name}
|
||||
thumbAlignment="edge"
|
||||
className={cn(sliderRootClassName, className)}
|
||||
>
|
||||
<BaseSlider.Control className={sliderControlClassName}>
|
||||
<BaseSlider.Track className={sliderTrackClassName}>
|
||||
<BaseSlider.Indicator className={sliderIndicatorClassName} />
|
||||
</BaseSlider.Track>
|
||||
<BaseSlider.Thumb
|
||||
aria-label={ariaLabel}
|
||||
aria-labelledby={ariaLabelledby}
|
||||
className={sliderThumbClassName}
|
||||
/>
|
||||
</BaseSlider.Control>
|
||||
</BaseSlider.Root>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { render } from '@testing-library/react'
|
||||
import PartnerStackCookieRecorder from '../cookie-recorder'
|
||||
|
||||
let isCloudEdition = true
|
||||
|
||||
const saveOrUpdate = vi.fn()
|
||||
|
||||
vi.mock('@/config', () => ({
|
||||
get IS_CLOUD_EDITION() {
|
||||
return isCloudEdition
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../use-ps-info', () => ({
|
||||
default: () => ({
|
||||
saveOrUpdate,
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('PartnerStackCookieRecorder', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
isCloudEdition = true
|
||||
})
|
||||
|
||||
it('should call saveOrUpdate once on mount when running in cloud edition', () => {
|
||||
render(<PartnerStackCookieRecorder />)
|
||||
|
||||
expect(saveOrUpdate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should not call saveOrUpdate when not running in cloud edition', () => {
|
||||
isCloudEdition = false
|
||||
|
||||
render(<PartnerStackCookieRecorder />)
|
||||
|
||||
expect(saveOrUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should render null', () => {
|
||||
const { container } = render(<PartnerStackCookieRecorder />)
|
||||
|
||||
expect(container.innerHTML).toBe('')
|
||||
})
|
||||
})
|
||||
19
web/app/components/billing/partner-stack/cookie-recorder.tsx
Normal file
19
web/app/components/billing/partner-stack/cookie-recorder.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import { IS_CLOUD_EDITION } from '@/config'
|
||||
import usePSInfo from './use-ps-info'
|
||||
|
||||
const PartnerStackCookieRecorder = () => {
|
||||
const { saveOrUpdate } = usePSInfo()
|
||||
|
||||
useEffect(() => {
|
||||
if (!IS_CLOUD_EDITION)
|
||||
return
|
||||
saveOrUpdate()
|
||||
}, [])
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export default PartnerStackCookieRecorder
|
||||
@@ -24,7 +24,7 @@ const usePSInfo = () => {
|
||||
}] = useBoolean(false)
|
||||
const { mutateAsync } = useBindPartnerStackInfo()
|
||||
// Save to top domain. cloud.dify.ai => .dify.ai
|
||||
const domain = globalThis.location.hostname.replace('cloud', '')
|
||||
const domain = globalThis.location?.hostname.replace('cloud', '')
|
||||
|
||||
const saveOrUpdate = useCallback(() => {
|
||||
if (!psPartnerKey || !psClickId)
|
||||
@@ -39,7 +39,7 @@ const usePSInfo = () => {
|
||||
path: '/',
|
||||
domain,
|
||||
})
|
||||
}, [psPartnerKey, psClickId, isPSChanged])
|
||||
}, [psPartnerKey, psClickId, isPSChanged, domain])
|
||||
|
||||
const bind = useCallback(async () => {
|
||||
if (psPartnerKey && psClickId && !hasBind) {
|
||||
@@ -59,7 +59,7 @@ const usePSInfo = () => {
|
||||
Cookies.remove(PARTNER_STACK_CONFIG.cookieName, { path: '/', domain })
|
||||
setBind()
|
||||
}
|
||||
}, [psPartnerKey, psClickId, mutateAsync, hasBind, setBind])
|
||||
}, [psPartnerKey, psClickId, hasBind, domain, setBind, mutateAsync])
|
||||
return {
|
||||
psPartnerKey,
|
||||
psClickId,
|
||||
|
||||
@@ -14,6 +14,8 @@ describe('IndexMethod', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const getKeywordSlider = () => screen.getByLabelText('datasetSettings.form.numberOfKeywords')
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render without crashing', () => {
|
||||
render(<IndexMethod {...defaultProps} />)
|
||||
@@ -123,8 +125,7 @@ describe('IndexMethod', () => {
|
||||
describe('KeywordNumber', () => {
|
||||
it('should render KeywordNumber component inside Economy option', () => {
|
||||
render(<IndexMethod {...defaultProps} />)
|
||||
// KeywordNumber has a slider
|
||||
expect(screen.getByRole('slider')).toBeInTheDocument()
|
||||
expect(getKeywordSlider()).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should pass keywordNumber to KeywordNumber component', () => {
|
||||
|
||||
@@ -11,6 +11,8 @@ describe('KeyWordNumber', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const getSlider = () => screen.getByLabelText('datasetSettings.form.numberOfKeywords')
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render without crashing', () => {
|
||||
render(<KeyWordNumber {...defaultProps} />)
|
||||
@@ -31,8 +33,7 @@ describe('KeyWordNumber', () => {
|
||||
|
||||
it('should render slider', () => {
|
||||
render(<KeyWordNumber {...defaultProps} />)
|
||||
// Slider has a slider role
|
||||
expect(screen.getByRole('slider')).toBeInTheDocument()
|
||||
expect(getSlider()).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render input number field', () => {
|
||||
@@ -61,7 +62,7 @@ describe('KeyWordNumber', () => {
|
||||
|
||||
it('should pass correct value to slider', () => {
|
||||
render(<KeyWordNumber {...defaultProps} keywordNumber={30} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
expect(slider).toHaveAttribute('aria-valuenow', '30')
|
||||
})
|
||||
})
|
||||
@@ -71,8 +72,7 @@ describe('KeyWordNumber', () => {
|
||||
const handleChange = vi.fn()
|
||||
render(<KeyWordNumber {...defaultProps} onKeywordNumberChange={handleChange} />)
|
||||
|
||||
const slider = screen.getByRole('slider')
|
||||
// Verify slider is rendered and interactive
|
||||
const slider = getSlider()
|
||||
expect(slider).toBeInTheDocument()
|
||||
expect(slider).not.toBeDisabled()
|
||||
})
|
||||
@@ -109,14 +109,14 @@ describe('KeyWordNumber', () => {
|
||||
describe('Slider Configuration', () => {
|
||||
it('should have max value of 50', () => {
|
||||
render(<KeyWordNumber {...defaultProps} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemax', '50')
|
||||
const slider = getSlider()
|
||||
expect(slider).toHaveAttribute('max', '50')
|
||||
})
|
||||
|
||||
it('should have min value of 0', () => {
|
||||
render(<KeyWordNumber {...defaultProps} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
expect(slider).toHaveAttribute('aria-valuemin', '0')
|
||||
const slider = getSlider()
|
||||
expect(slider).toHaveAttribute('min', '0')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -162,7 +162,7 @@ describe('KeyWordNumber', () => {
|
||||
describe('Accessibility', () => {
|
||||
it('should have accessible slider', () => {
|
||||
render(<KeyWordNumber {...defaultProps} />)
|
||||
const slider = screen.getByRole('slider')
|
||||
const slider = getSlider()
|
||||
expect(slider).toBeInTheDocument()
|
||||
})
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
import {
|
||||
NumberField,
|
||||
@@ -11,6 +10,7 @@ import {
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/app/components/base/ui/number-field'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
|
||||
const MIN_KEYWORD_NUMBER = 0
|
||||
const MAX_KEYWORD_NUMBER = 50
|
||||
@@ -47,7 +47,8 @@ const KeyWordNumber = ({
|
||||
value={keywordNumber}
|
||||
min={MIN_KEYWORD_NUMBER}
|
||||
max={MAX_KEYWORD_NUMBER}
|
||||
onChange={onKeywordNumberChange}
|
||||
onValueChange={onKeywordNumberChange}
|
||||
aria-label={t('form.numberOfKeywords', { ns: 'datasetSettings' })}
|
||||
/>
|
||||
<NumberField
|
||||
className="w-12 shrink-0"
|
||||
|
||||
@@ -11,9 +11,9 @@ vi.mock('../../hooks', () => ({
|
||||
useLanguage: () => 'en_US',
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/base/slider', () => ({
|
||||
default: ({ onChange }: { onChange: (v: number) => void }) => (
|
||||
<button onClick={() => onChange(2)} data-testid="slider-btn">Slide 2</button>
|
||||
vi.mock('@/app/components/base/ui/slider', () => ({
|
||||
Slider: ({ onValueChange }: { onValueChange: (v: number) => void }) => (
|
||||
<button onClick={() => onValueChange(2)} data-testid="slider-btn">Slide 2</button>
|
||||
),
|
||||
}))
|
||||
|
||||
|
||||
@@ -7,10 +7,10 @@ import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import PromptEditor from '@/app/components/base/prompt-editor'
|
||||
import Radio from '@/app/components/base/radio'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import Switch from '@/app/components/base/switch'
|
||||
import TagInput from '@/app/components/base/tag-input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/app/components/base/ui/select'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { cn } from '@/utils/classnames'
|
||||
@@ -78,6 +78,7 @@ function ParameterItem({
|
||||
}
|
||||
|
||||
const renderValue = value ?? localValue ?? getDefaultValue()
|
||||
const sliderLabel = parameterRule.label[language] || parameterRule.label.en_US
|
||||
|
||||
const handleInputChange = (newValue: ParameterValue) => {
|
||||
setLocalValue(newValue)
|
||||
@@ -170,7 +171,8 @@ function ParameterItem({
|
||||
min={parameterRule.min}
|
||||
max={parameterRule.max}
|
||||
step={step}
|
||||
onChange={handleSlideChange}
|
||||
onValueChange={handleSlideChange}
|
||||
aria-label={sliderLabel}
|
||||
/>
|
||||
)}
|
||||
<input
|
||||
@@ -197,7 +199,8 @@ function ParameterItem({
|
||||
min={parameterRule.min}
|
||||
max={parameterRule.max}
|
||||
step={0.1}
|
||||
onChange={handleSlideChange}
|
||||
onValueChange={handleSlideChange}
|
||||
aria-label={sliderLabel}
|
||||
/>
|
||||
)}
|
||||
<input
|
||||
@@ -337,9 +340,9 @@ function ParameterItem({
|
||||
}
|
||||
<div
|
||||
className="mr-0.5 truncate text-text-secondary system-xs-regular"
|
||||
title={parameterRule.label[language] || parameterRule.label.en_US}
|
||||
title={sliderLabel}
|
||||
>
|
||||
{parameterRule.label[language] || parameterRule.label.en_US}
|
||||
{sliderLabel}
|
||||
</div>
|
||||
{
|
||||
parameterRule.help && (
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import CandidateNodeMain from '../candidate-node-main'
|
||||
import { CUSTOM_NODE } from '../constants'
|
||||
import { CUSTOM_NOTE_NODE } from '../note-node/constants'
|
||||
import { BlockEnum } from '../types'
|
||||
import { createNode } from './fixtures'
|
||||
|
||||
const mockUseEventListener = vi.hoisted(() => vi.fn())
|
||||
const mockUseStoreApi = vi.hoisted(() => vi.fn())
|
||||
const mockUseReactFlow = vi.hoisted(() => vi.fn())
|
||||
const mockUseViewport = vi.hoisted(() => vi.fn())
|
||||
const mockUseStore = vi.hoisted(() => vi.fn())
|
||||
const mockUseWorkflowStore = vi.hoisted(() => vi.fn())
|
||||
const mockUseHooks = vi.hoisted(() => vi.fn())
|
||||
const mockCustomNode = vi.hoisted(() => vi.fn())
|
||||
const mockCustomNoteNode = vi.hoisted(() => vi.fn())
|
||||
const mockGetIterationStartNode = vi.hoisted(() => vi.fn())
|
||||
const mockGetLoopStartNode = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ahooks', () => ({
|
||||
useEventListener: (...args: unknown[]) => mockUseEventListener(...args),
|
||||
}))
|
||||
|
||||
vi.mock('reactflow', () => ({
|
||||
useStoreApi: () => mockUseStoreApi(),
|
||||
useReactFlow: () => mockUseReactFlow(),
|
||||
useViewport: () => mockUseViewport(),
|
||||
Position: {
|
||||
Left: 'left',
|
||||
Right: 'right',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/store', () => ({
|
||||
useStore: (selector: (state: { mousePosition: {
|
||||
pageX: number
|
||||
pageY: number
|
||||
elementX: number
|
||||
elementY: number
|
||||
} }) => unknown) => mockUseStore(selector),
|
||||
useWorkflowStore: () => mockUseWorkflowStore(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks', () => ({
|
||||
useNodesInteractions: () => mockUseHooks().useNodesInteractions(),
|
||||
useNodesSyncDraft: () => mockUseHooks().useNodesSyncDraft(),
|
||||
useWorkflowHistory: () => mockUseHooks().useWorkflowHistory(),
|
||||
useAutoGenerateWebhookUrl: () => mockUseHooks().useAutoGenerateWebhookUrl(),
|
||||
WorkflowHistoryEvent: {
|
||||
NodeAdd: 'NodeAdd',
|
||||
NoteAdd: 'NoteAdd',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes', () => ({
|
||||
__esModule: true,
|
||||
default: (props: { id: string }) => {
|
||||
mockCustomNode(props)
|
||||
return <div data-testid="candidate-custom-node">{props.id}</div>
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/note-node', () => ({
|
||||
__esModule: true,
|
||||
default: (props: { id: string }) => {
|
||||
mockCustomNoteNode(props)
|
||||
return <div data-testid="candidate-note-node">{props.id}</div>
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/utils', () => ({
|
||||
getIterationStartNode: (...args: unknown[]) => mockGetIterationStartNode(...args),
|
||||
getLoopStartNode: (...args: unknown[]) => mockGetLoopStartNode(...args),
|
||||
}))
|
||||
|
||||
describe('CandidateNodeMain', () => {
|
||||
const mockSetNodes = vi.fn()
|
||||
const mockHandleNodeSelect = vi.fn()
|
||||
const mockSaveStateToHistory = vi.fn()
|
||||
const mockHandleSyncWorkflowDraft = vi.fn()
|
||||
const mockAutoGenerateWebhookUrl = vi.fn()
|
||||
const mockWorkflowStoreSetState = vi.fn()
|
||||
const createNodesInteractions = () => ({
|
||||
handleNodeSelect: mockHandleNodeSelect,
|
||||
})
|
||||
const createWorkflowHistory = () => ({
|
||||
saveStateToHistory: mockSaveStateToHistory,
|
||||
})
|
||||
const createNodesSyncDraft = () => ({
|
||||
handleSyncWorkflowDraft: mockHandleSyncWorkflowDraft,
|
||||
})
|
||||
const createAutoGenerateWebhookUrl = () => mockAutoGenerateWebhookUrl
|
||||
const eventHandlers: Partial<Record<'click' | 'contextmenu', (event: { preventDefault: () => void }) => void>> = {}
|
||||
let nodes = [createNode({ id: 'existing-node' })]
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
nodes = [createNode({ id: 'existing-node' })]
|
||||
eventHandlers.click = undefined
|
||||
eventHandlers.contextmenu = undefined
|
||||
|
||||
mockUseEventListener.mockImplementation((event: 'click' | 'contextmenu', handler: (event: { preventDefault: () => void }) => void) => {
|
||||
eventHandlers[event] = handler
|
||||
})
|
||||
mockUseStoreApi.mockReturnValue({
|
||||
getState: () => ({
|
||||
getNodes: () => nodes,
|
||||
setNodes: mockSetNodes,
|
||||
}),
|
||||
})
|
||||
mockUseReactFlow.mockReturnValue({
|
||||
screenToFlowPosition: ({ x, y }: { x: number, y: number }) => ({ x: x + 10, y: y + 20 }),
|
||||
})
|
||||
mockUseViewport.mockReturnValue({ zoom: 1.5 })
|
||||
mockUseStore.mockImplementation((selector: (state: { mousePosition: {
|
||||
pageX: number
|
||||
pageY: number
|
||||
elementX: number
|
||||
elementY: number
|
||||
} }) => unknown) => selector({
|
||||
mousePosition: {
|
||||
pageX: 100,
|
||||
pageY: 200,
|
||||
elementX: 30,
|
||||
elementY: 40,
|
||||
},
|
||||
}))
|
||||
mockUseWorkflowStore.mockReturnValue({
|
||||
setState: mockWorkflowStoreSetState,
|
||||
})
|
||||
mockUseHooks.mockReturnValue({
|
||||
useNodesInteractions: createNodesInteractions,
|
||||
useWorkflowHistory: createWorkflowHistory,
|
||||
useNodesSyncDraft: createNodesSyncDraft,
|
||||
useAutoGenerateWebhookUrl: createAutoGenerateWebhookUrl,
|
||||
})
|
||||
mockHandleSyncWorkflowDraft.mockImplementation((_isSync: boolean, _force: boolean, options?: { onSuccess?: () => void }) => {
|
||||
options?.onSuccess?.()
|
||||
})
|
||||
mockGetIterationStartNode.mockReturnValue(createNode({ id: 'iteration-start' }))
|
||||
mockGetLoopStartNode.mockReturnValue(createNode({ id: 'loop-start' }))
|
||||
})
|
||||
|
||||
it('should render the candidate node and commit a webhook node on click', () => {
|
||||
const candidateNode = createNode({
|
||||
id: 'candidate-webhook',
|
||||
type: CUSTOM_NODE,
|
||||
data: {
|
||||
type: BlockEnum.TriggerWebhook,
|
||||
title: 'Webhook Candidate',
|
||||
_isCandidate: true,
|
||||
},
|
||||
})
|
||||
|
||||
const { container } = render(<CandidateNodeMain candidateNode={candidateNode} />)
|
||||
|
||||
expect(screen.getByTestId('candidate-custom-node')).toHaveTextContent('candidate-webhook')
|
||||
expect(container.firstChild).toHaveStyle({
|
||||
left: '30px',
|
||||
top: '40px',
|
||||
transform: 'scale(1.5)',
|
||||
})
|
||||
|
||||
eventHandlers.click?.({ preventDefault: vi.fn() })
|
||||
|
||||
expect(mockSetNodes).toHaveBeenCalledWith(expect.arrayContaining([
|
||||
expect.objectContaining({ id: 'existing-node' }),
|
||||
expect.objectContaining({
|
||||
id: 'candidate-webhook',
|
||||
position: { x: 110, y: 220 },
|
||||
data: expect.objectContaining({ _isCandidate: false }),
|
||||
}),
|
||||
]))
|
||||
expect(mockSaveStateToHistory).toHaveBeenCalledWith('NodeAdd', { nodeId: 'candidate-webhook' })
|
||||
expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ candidateNode: undefined })
|
||||
expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true, true, expect.objectContaining({
|
||||
onSuccess: expect.any(Function),
|
||||
}))
|
||||
expect(mockAutoGenerateWebhookUrl).toHaveBeenCalledWith('candidate-webhook')
|
||||
expect(mockHandleNodeSelect).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should save note candidates as notes and select the inserted note', () => {
|
||||
const candidateNode = createNode({
|
||||
id: 'candidate-note',
|
||||
type: CUSTOM_NOTE_NODE,
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Note Candidate',
|
||||
_isCandidate: true,
|
||||
},
|
||||
})
|
||||
|
||||
render(<CandidateNodeMain candidateNode={candidateNode} />)
|
||||
|
||||
expect(screen.getByTestId('candidate-note-node')).toHaveTextContent('candidate-note')
|
||||
|
||||
eventHandlers.click?.({ preventDefault: vi.fn() })
|
||||
|
||||
expect(mockSaveStateToHistory).toHaveBeenCalledWith('NoteAdd', { nodeId: 'candidate-note' })
|
||||
expect(mockHandleNodeSelect).toHaveBeenCalledWith('candidate-note')
|
||||
})
|
||||
|
||||
it('should append iteration and loop start helper nodes for control-flow candidates', () => {
|
||||
const iterationNode = createNode({
|
||||
id: 'candidate-iteration',
|
||||
type: CUSTOM_NODE,
|
||||
data: {
|
||||
type: BlockEnum.Iteration,
|
||||
title: 'Iteration Candidate',
|
||||
_isCandidate: true,
|
||||
},
|
||||
})
|
||||
const loopNode = createNode({
|
||||
id: 'candidate-loop',
|
||||
type: CUSTOM_NODE,
|
||||
data: {
|
||||
type: BlockEnum.Loop,
|
||||
title: 'Loop Candidate',
|
||||
_isCandidate: true,
|
||||
},
|
||||
})
|
||||
|
||||
const { rerender } = render(<CandidateNodeMain candidateNode={iterationNode} />)
|
||||
|
||||
eventHandlers.click?.({ preventDefault: vi.fn() })
|
||||
expect(mockGetIterationStartNode).toHaveBeenCalledWith('candidate-iteration')
|
||||
expect(mockSetNodes.mock.calls[0][0]).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ id: 'candidate-iteration' }),
|
||||
expect.objectContaining({ id: 'iteration-start' }),
|
||||
]))
|
||||
|
||||
rerender(<CandidateNodeMain candidateNode={loopNode} />)
|
||||
eventHandlers.click?.({ preventDefault: vi.fn() })
|
||||
|
||||
expect(mockGetLoopStartNode).toHaveBeenCalledWith('candidate-loop')
|
||||
expect(mockSetNodes.mock.calls[1][0]).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ id: 'candidate-loop' }),
|
||||
expect.objectContaining({ id: 'loop-start' }),
|
||||
]))
|
||||
})
|
||||
|
||||
it('should clear the candidate node on contextmenu', () => {
|
||||
const candidateNode = createNode({
|
||||
id: 'candidate-context',
|
||||
type: CUSTOM_NODE,
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Context Candidate',
|
||||
_isCandidate: true,
|
||||
},
|
||||
})
|
||||
|
||||
render(<CandidateNodeMain candidateNode={candidateNode} />)
|
||||
|
||||
eventHandlers.contextmenu?.({ preventDefault: vi.fn() })
|
||||
|
||||
expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ candidateNode: undefined })
|
||||
})
|
||||
})
|
||||
235
web/app/components/workflow/__tests__/custom-edge.spec.tsx
Normal file
235
web/app/components/workflow/__tests__/custom-edge.spec.tsx
Normal file
@@ -0,0 +1,235 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { Position } from 'reactflow'
|
||||
import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
|
||||
import CustomEdge from '../custom-edge'
|
||||
import { BlockEnum, NodeRunningStatus } from '../types'
|
||||
|
||||
const mockUseAvailableBlocks = vi.hoisted(() => vi.fn())
|
||||
const mockUseNodesInteractions = vi.hoisted(() => vi.fn())
|
||||
const mockBlockSelector = vi.hoisted(() => vi.fn())
|
||||
const mockGradientRender = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('reactflow', () => ({
|
||||
BaseEdge: (props: {
|
||||
id: string
|
||||
path: string
|
||||
style: {
|
||||
stroke: string
|
||||
strokeWidth: number
|
||||
opacity: number
|
||||
strokeDasharray?: string
|
||||
}
|
||||
}) => (
|
||||
<div
|
||||
data-testid="base-edge"
|
||||
data-id={props.id}
|
||||
data-path={props.path}
|
||||
data-stroke={props.style.stroke}
|
||||
data-stroke-width={props.style.strokeWidth}
|
||||
data-opacity={props.style.opacity}
|
||||
data-dasharray={props.style.strokeDasharray}
|
||||
/>
|
||||
),
|
||||
EdgeLabelRenderer: ({ children }: { children?: ReactNode }) => <div data-testid="edge-label">{children}</div>,
|
||||
getBezierPath: () => ['M 0 0', 24, 48],
|
||||
Position: {
|
||||
Right: 'right',
|
||||
Left: 'left',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks', () => ({
|
||||
useAvailableBlocks: (...args: unknown[]) => mockUseAvailableBlocks(...args),
|
||||
useNodesInteractions: () => mockUseNodesInteractions(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/block-selector', () => ({
|
||||
__esModule: true,
|
||||
default: (props: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSelect: (nodeType: string, pluginDefaultValue?: Record<string, unknown>) => void
|
||||
availableBlocksTypes: string[]
|
||||
triggerClassName?: () => string
|
||||
}) => {
|
||||
mockBlockSelector(props)
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="block-selector"
|
||||
data-trigger-class={props.triggerClassName?.()}
|
||||
onClick={() => {
|
||||
props.onOpenChange(true)
|
||||
props.onSelect('llm', { provider: 'openai' })
|
||||
}}
|
||||
>
|
||||
{props.availableBlocksTypes.join(',')}
|
||||
</button>
|
||||
)
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/custom-edge-linear-gradient-render', () => ({
|
||||
__esModule: true,
|
||||
default: (props: {
|
||||
id: string
|
||||
startColor: string
|
||||
stopColor: string
|
||||
}) => {
|
||||
mockGradientRender(props)
|
||||
return <div data-testid="edge-gradient">{props.id}</div>
|
||||
},
|
||||
}))
|
||||
|
||||
describe('CustomEdge', () => {
|
||||
const mockHandleNodeAdd = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockUseNodesInteractions.mockReturnValue({
|
||||
handleNodeAdd: mockHandleNodeAdd,
|
||||
})
|
||||
mockUseAvailableBlocks.mockImplementation((nodeType: BlockEnum) => {
|
||||
if (nodeType === BlockEnum.Code)
|
||||
return { availablePrevBlocks: ['code', 'llm'] }
|
||||
|
||||
return { availableNextBlocks: ['llm', 'tool'] }
|
||||
})
|
||||
})
|
||||
|
||||
it('should render a gradient edge and insert a node between the source and target', () => {
|
||||
render(
|
||||
<CustomEdge
|
||||
id="edge-1"
|
||||
source="source-node"
|
||||
sourceHandleId="source"
|
||||
target="target-node"
|
||||
targetHandleId="target"
|
||||
sourceX={100}
|
||||
sourceY={120}
|
||||
sourcePosition={Position.Right}
|
||||
targetX={300}
|
||||
targetY={220}
|
||||
targetPosition={Position.Left}
|
||||
selected={false}
|
||||
data={{
|
||||
sourceType: BlockEnum.Start,
|
||||
targetType: BlockEnum.Code,
|
||||
_sourceRunningStatus: NodeRunningStatus.Succeeded,
|
||||
_targetRunningStatus: NodeRunningStatus.Failed,
|
||||
_hovering: true,
|
||||
_waitingRun: true,
|
||||
_dimmed: true,
|
||||
_isTemp: true,
|
||||
isInIteration: true,
|
||||
isInLoop: true,
|
||||
} as never}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('edge-gradient')).toHaveTextContent('edge-1')
|
||||
expect(mockGradientRender).toHaveBeenCalledWith(expect.objectContaining({
|
||||
id: 'edge-1',
|
||||
startColor: 'var(--color-workflow-link-line-success-handle)',
|
||||
stopColor: 'var(--color-workflow-link-line-error-handle)',
|
||||
}))
|
||||
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-stroke', 'url(#edge-1)')
|
||||
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-opacity', '0.3')
|
||||
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-dasharray', '8 8')
|
||||
expect(screen.getByTestId('block-selector')).toHaveTextContent('llm')
|
||||
expect(screen.getByTestId('block-selector').parentElement).toHaveStyle({
|
||||
transform: 'translate(-50%, -50%) translate(24px, 48px)',
|
||||
opacity: '0.7',
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('block-selector'))
|
||||
|
||||
expect(mockHandleNodeAdd).toHaveBeenCalledWith(
|
||||
{
|
||||
nodeType: 'llm',
|
||||
pluginDefaultValue: { provider: 'openai' },
|
||||
},
|
||||
{
|
||||
prevNodeId: 'source-node',
|
||||
prevNodeSourceHandle: 'source',
|
||||
nextNodeId: 'target-node',
|
||||
nextNodeTargetHandle: 'target',
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
it('should prefer the running stroke color when the edge is selected', () => {
|
||||
render(
|
||||
<CustomEdge
|
||||
id="edge-selected"
|
||||
source="source-node"
|
||||
target="target-node"
|
||||
sourceX={0}
|
||||
sourceY={0}
|
||||
sourcePosition={Position.Right}
|
||||
targetX={100}
|
||||
targetY={100}
|
||||
targetPosition={Position.Left}
|
||||
selected
|
||||
data={{
|
||||
sourceType: BlockEnum.Start,
|
||||
targetType: BlockEnum.Code,
|
||||
_sourceRunningStatus: NodeRunningStatus.Succeeded,
|
||||
_targetRunningStatus: NodeRunningStatus.Running,
|
||||
} as never}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-stroke', 'var(--color-workflow-link-line-handle)')
|
||||
})
|
||||
|
||||
it('should use the fail-branch running color while the connected node is hovering', () => {
|
||||
render(
|
||||
<CustomEdge
|
||||
id="edge-hover"
|
||||
source="source-node"
|
||||
sourceHandleId={ErrorHandleTypeEnum.failBranch}
|
||||
target="target-node"
|
||||
sourceX={0}
|
||||
sourceY={0}
|
||||
sourcePosition={Position.Right}
|
||||
targetX={100}
|
||||
targetY={100}
|
||||
targetPosition={Position.Left}
|
||||
selected={false}
|
||||
data={{
|
||||
sourceType: BlockEnum.Start,
|
||||
targetType: BlockEnum.Code,
|
||||
_connectedNodeIsHovering: true,
|
||||
} as never}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-stroke', 'var(--color-workflow-link-line-failure-handle)')
|
||||
})
|
||||
|
||||
it('should fall back to the default edge color when no highlight state is active', () => {
|
||||
render(
|
||||
<CustomEdge
|
||||
id="edge-default"
|
||||
source="source-node"
|
||||
target="target-node"
|
||||
sourceX={0}
|
||||
sourceY={0}
|
||||
sourcePosition={Position.Right}
|
||||
targetX={100}
|
||||
targetY={100}
|
||||
targetPosition={Position.Left}
|
||||
selected={false}
|
||||
data={{
|
||||
sourceType: BlockEnum.Start,
|
||||
targetType: BlockEnum.Code,
|
||||
} as never}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-stroke', 'var(--color-workflow-link-line-normal)')
|
||||
expect(screen.getByTestId('block-selector')).toHaveAttribute('data-trigger-class', 'hover:scale-150 transition-all')
|
||||
})
|
||||
})
|
||||
114
web/app/components/workflow/__tests__/node-contextmenu.spec.tsx
Normal file
114
web/app/components/workflow/__tests__/node-contextmenu.spec.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import type { Node } from '../types'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import NodeContextmenu from '../node-contextmenu'
|
||||
|
||||
const mockUseClickAway = vi.hoisted(() => vi.fn())
|
||||
const mockUseNodes = vi.hoisted(() => vi.fn())
|
||||
const mockUsePanelInteractions = vi.hoisted(() => vi.fn())
|
||||
const mockUseStore = vi.hoisted(() => vi.fn())
|
||||
const mockPanelOperatorPopup = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ahooks', () => ({
|
||||
useClickAway: (...args: unknown[]) => mockUseClickAway(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({
|
||||
__esModule: true,
|
||||
default: () => mockUseNodes(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks', () => ({
|
||||
usePanelInteractions: () => mockUsePanelInteractions(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/store', () => ({
|
||||
useStore: (selector: (state: { nodeMenu?: { nodeId: string, left: number, top: number } }) => unknown) => mockUseStore(selector),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/_base/components/panel-operator/panel-operator-popup', () => ({
|
||||
__esModule: true,
|
||||
default: (props: {
|
||||
id: string
|
||||
data: Node['data']
|
||||
showHelpLink: boolean
|
||||
onClosePopup: () => void
|
||||
}) => {
|
||||
mockPanelOperatorPopup(props)
|
||||
return (
|
||||
<button type="button" onClick={props.onClosePopup}>
|
||||
{props.id}
|
||||
:
|
||||
{props.data.title}
|
||||
</button>
|
||||
)
|
||||
},
|
||||
}))
|
||||
|
||||
describe('NodeContextmenu', () => {
|
||||
const mockHandleNodeContextmenuCancel = vi.fn()
|
||||
let nodeMenu: { nodeId: string, left: number, top: number } | undefined
|
||||
let nodes: Node[]
|
||||
let clickAwayHandler: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
nodeMenu = undefined
|
||||
nodes = [{
|
||||
id: 'node-1',
|
||||
type: 'custom',
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
title: 'Node 1',
|
||||
desc: '',
|
||||
type: 'code' as never,
|
||||
},
|
||||
} as Node]
|
||||
clickAwayHandler = undefined
|
||||
|
||||
mockUseClickAway.mockImplementation((handler: () => void) => {
|
||||
clickAwayHandler = handler
|
||||
})
|
||||
mockUseNodes.mockImplementation(() => nodes)
|
||||
mockUsePanelInteractions.mockReturnValue({
|
||||
handleNodeContextmenuCancel: mockHandleNodeContextmenuCancel,
|
||||
})
|
||||
mockUseStore.mockImplementation((selector: (state: { nodeMenu?: { nodeId: string, left: number, top: number } }) => unknown) => selector({ nodeMenu }))
|
||||
})
|
||||
|
||||
it('should stay hidden when the node menu is absent', () => {
|
||||
render(<NodeContextmenu />)
|
||||
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(mockPanelOperatorPopup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should stay hidden when the referenced node cannot be found', () => {
|
||||
nodeMenu = { nodeId: 'missing-node', left: 80, top: 120 }
|
||||
|
||||
render(<NodeContextmenu />)
|
||||
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(mockPanelOperatorPopup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should render the popup at the stored position and close on popup/click-away actions', () => {
|
||||
nodeMenu = { nodeId: 'node-1', left: 80, top: 120 }
|
||||
const { container } = render(<NodeContextmenu />)
|
||||
|
||||
expect(screen.getByRole('button')).toHaveTextContent('node-1:Node 1')
|
||||
expect(mockPanelOperatorPopup).toHaveBeenCalledWith(expect.objectContaining({
|
||||
id: 'node-1',
|
||||
data: expect.objectContaining({ title: 'Node 1' }),
|
||||
showHelpLink: true,
|
||||
}))
|
||||
expect(container.firstChild).toHaveStyle({
|
||||
left: '80px',
|
||||
top: '120px',
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
clickAwayHandler?.()
|
||||
|
||||
expect(mockHandleNodeContextmenuCancel).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
151
web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx
Normal file
151
web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import PanelContextmenu from '../panel-contextmenu'
|
||||
|
||||
const mockUseClickAway = vi.hoisted(() => vi.fn())
|
||||
const mockUseTranslation = vi.hoisted(() => vi.fn())
|
||||
const mockUseStore = vi.hoisted(() => vi.fn())
|
||||
const mockUseNodesInteractions = vi.hoisted(() => vi.fn())
|
||||
const mockUsePanelInteractions = vi.hoisted(() => vi.fn())
|
||||
const mockUseWorkflowStartRun = vi.hoisted(() => vi.fn())
|
||||
const mockUseOperator = vi.hoisted(() => vi.fn())
|
||||
const mockUseDSL = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ahooks', () => ({
|
||||
useClickAway: (...args: unknown[]) => mockUseClickAway(...args),
|
||||
}))
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => mockUseTranslation(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/store', () => ({
|
||||
useStore: (selector: (state: {
|
||||
panelMenu?: { left: number, top: number }
|
||||
clipboardElements: unknown[]
|
||||
setShowImportDSLModal: (visible: boolean) => void
|
||||
}) => unknown) => mockUseStore(selector),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks', () => ({
|
||||
useNodesInteractions: () => mockUseNodesInteractions(),
|
||||
usePanelInteractions: () => mockUsePanelInteractions(),
|
||||
useWorkflowStartRun: () => mockUseWorkflowStartRun(),
|
||||
useDSL: () => mockUseDSL(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/operator/hooks', () => ({
|
||||
useOperator: () => mockUseOperator(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/operator/add-block', () => ({
|
||||
__esModule: true,
|
||||
default: ({ renderTrigger }: { renderTrigger: () => ReactNode }) => (
|
||||
<div data-testid="add-block">{renderTrigger()}</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/base/divider', () => ({
|
||||
__esModule: true,
|
||||
default: ({ className }: { className?: string }) => <div data-testid="divider" className={className} />,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/shortcuts-name', () => ({
|
||||
__esModule: true,
|
||||
default: ({ keys }: { keys: string[] }) => <span data-testid={`shortcut-${keys.join('-')}`}>{keys.join('+')}</span>,
|
||||
}))
|
||||
|
||||
describe('PanelContextmenu', () => {
|
||||
const mockHandleNodesPaste = vi.fn()
|
||||
const mockHandlePaneContextmenuCancel = vi.fn()
|
||||
const mockHandleStartWorkflowRun = vi.fn()
|
||||
const mockHandleAddNote = vi.fn()
|
||||
const mockExportCheck = vi.fn()
|
||||
const mockSetShowImportDSLModal = vi.fn()
|
||||
let panelMenu: { left: number, top: number } | undefined
|
||||
let clipboardElements: unknown[]
|
||||
let clickAwayHandler: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
panelMenu = undefined
|
||||
clipboardElements = []
|
||||
clickAwayHandler = undefined
|
||||
|
||||
mockUseClickAway.mockImplementation((handler: () => void) => {
|
||||
clickAwayHandler = handler
|
||||
})
|
||||
mockUseTranslation.mockReturnValue({
|
||||
t: (key: string) => key,
|
||||
})
|
||||
mockUseStore.mockImplementation((selector: (state: {
|
||||
panelMenu?: { left: number, top: number }
|
||||
clipboardElements: unknown[]
|
||||
setShowImportDSLModal: (visible: boolean) => void
|
||||
}) => unknown) => selector({
|
||||
panelMenu,
|
||||
clipboardElements,
|
||||
setShowImportDSLModal: mockSetShowImportDSLModal,
|
||||
}))
|
||||
mockUseNodesInteractions.mockReturnValue({
|
||||
handleNodesPaste: mockHandleNodesPaste,
|
||||
})
|
||||
mockUsePanelInteractions.mockReturnValue({
|
||||
handlePaneContextmenuCancel: mockHandlePaneContextmenuCancel,
|
||||
})
|
||||
mockUseWorkflowStartRun.mockReturnValue({
|
||||
handleStartWorkflowRun: mockHandleStartWorkflowRun,
|
||||
})
|
||||
mockUseOperator.mockReturnValue({
|
||||
handleAddNote: mockHandleAddNote,
|
||||
})
|
||||
mockUseDSL.mockReturnValue({
|
||||
exportCheck: mockExportCheck,
|
||||
})
|
||||
})
|
||||
|
||||
it('should stay hidden when the panel menu is absent', () => {
|
||||
render(<PanelContextmenu />)
|
||||
|
||||
expect(screen.queryByTestId('add-block')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should keep paste disabled when the clipboard is empty', () => {
|
||||
panelMenu = { left: 24, top: 48 }
|
||||
|
||||
render(<PanelContextmenu />)
|
||||
|
||||
fireEvent.click(screen.getByText('common.pasteHere'))
|
||||
|
||||
expect(mockHandleNodesPaste).not.toHaveBeenCalled()
|
||||
expect(mockHandlePaneContextmenuCancel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should render actions, position the menu, and execute each action', () => {
|
||||
panelMenu = { left: 24, top: 48 }
|
||||
clipboardElements = [{ id: 'copied-node' }]
|
||||
const { container } = render(<PanelContextmenu />)
|
||||
|
||||
expect(screen.getByTestId('add-block')).toHaveTextContent('common.addBlock')
|
||||
expect(screen.getByTestId('shortcut-alt-r')).toHaveTextContent('alt+r')
|
||||
expect(screen.getByTestId('shortcut-ctrl-v')).toHaveTextContent('ctrl+v')
|
||||
expect(container.firstChild).toHaveStyle({
|
||||
left: '24px',
|
||||
top: '48px',
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('nodes.note.addNote'))
|
||||
fireEvent.click(screen.getByText('common.run'))
|
||||
fireEvent.click(screen.getByText('common.pasteHere'))
|
||||
fireEvent.click(screen.getByText('export'))
|
||||
fireEvent.click(screen.getByText('common.importDSL'))
|
||||
clickAwayHandler?.()
|
||||
|
||||
expect(mockHandleAddNote).toHaveBeenCalledTimes(1)
|
||||
expect(mockHandleStartWorkflowRun).toHaveBeenCalledTimes(1)
|
||||
expect(mockHandleNodesPaste).toHaveBeenCalledTimes(1)
|
||||
expect(mockExportCheck).toHaveBeenCalledTimes(1)
|
||||
expect(mockSetShowImportDSLModal).toHaveBeenCalledWith(true)
|
||||
expect(mockHandlePaneContextmenuCancel).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,275 @@
|
||||
import type { Edge, Node } from '../types'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { useEffect } from 'react'
|
||||
import { useNodes } from 'reactflow'
|
||||
import SelectionContextmenu from '../selection-contextmenu'
|
||||
import { useWorkflowHistoryStore } from '../workflow-history-store'
|
||||
import { createEdge, createNode } from './fixtures'
|
||||
import { renderWorkflowFlowComponent } from './workflow-test-env'
|
||||
|
||||
let latestNodes: Node[] = []
|
||||
let latestHistoryEvent: string | undefined
|
||||
const mockGetNodesReadOnly = vi.fn()
|
||||
|
||||
vi.mock('../hooks', async () => {
|
||||
const actual = await vi.importActual<typeof import('../hooks')>('../hooks')
|
||||
return {
|
||||
...actual,
|
||||
useNodesReadOnly: () => ({
|
||||
getNodesReadOnly: mockGetNodesReadOnly,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const RuntimeProbe = () => {
|
||||
latestNodes = useNodes() as Node[]
|
||||
const { store } = useWorkflowHistoryStore()
|
||||
|
||||
useEffect(() => {
|
||||
latestHistoryEvent = store.getState().workflowHistoryEvent
|
||||
return store.subscribe((state) => {
|
||||
latestHistoryEvent = state.workflowHistoryEvent
|
||||
})
|
||||
}, [store])
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const hooksStoreProps = {
|
||||
doSyncWorkflowDraft: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
|
||||
const renderSelectionMenu = (options?: {
|
||||
nodes?: Node[]
|
||||
edges?: Edge[]
|
||||
initialStoreState?: Record<string, unknown>
|
||||
}) => {
|
||||
latestNodes = []
|
||||
latestHistoryEvent = undefined
|
||||
|
||||
const nodes = options?.nodes ?? []
|
||||
const edges = options?.edges ?? []
|
||||
|
||||
return renderWorkflowFlowComponent(
|
||||
<div id="workflow-container" style={{ width: 800, height: 600 }}>
|
||||
<RuntimeProbe />
|
||||
<SelectionContextmenu />
|
||||
</div>,
|
||||
{
|
||||
nodes,
|
||||
edges,
|
||||
hooksStoreProps,
|
||||
historyStore: { nodes, edges },
|
||||
initialStoreState: options?.initialStoreState,
|
||||
reactFlowProps: { fitView: false },
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
describe('SelectionContextmenu', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
latestNodes = []
|
||||
latestHistoryEvent = undefined
|
||||
mockGetNodesReadOnly.mockReset()
|
||||
mockGetNodesReadOnly.mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('should not render when selectionMenu is absent', () => {
|
||||
renderSelectionMenu()
|
||||
|
||||
expect(screen.queryByText('operator.vertical')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should keep the menu inside the workflow container bounds', () => {
|
||||
const nodes = [
|
||||
createNode({ id: 'n1', selected: true, width: 80, height: 40 }),
|
||||
createNode({ id: 'n2', selected: true, position: { x: 140, y: 0 }, width: 80, height: 40 }),
|
||||
]
|
||||
const { store } = renderSelectionMenu({ nodes })
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 780, top: 590 } })
|
||||
})
|
||||
|
||||
const menu = screen.getByTestId('selection-contextmenu')
|
||||
expect(menu).toHaveStyle({ left: '540px', top: '210px' })
|
||||
})
|
||||
|
||||
it('should close itself when only one node is selected', async () => {
|
||||
const nodes = [
|
||||
createNode({ id: 'n1', selected: true, width: 80, height: 40 }),
|
||||
]
|
||||
|
||||
const { store } = renderSelectionMenu({ nodes })
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 120, top: 120 } })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(store.getState().selectionMenu).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('should align selected nodes to the left and save history', async () => {
|
||||
vi.useFakeTimers()
|
||||
const nodes = [
|
||||
createNode({ id: 'n1', selected: true, position: { x: 20, y: 40 }, width: 40, height: 20 }),
|
||||
createNode({ id: 'n2', selected: true, position: { x: 140, y: 90 }, width: 60, height: 30 }),
|
||||
]
|
||||
|
||||
const { store } = renderSelectionMenu({
|
||||
nodes,
|
||||
edges: [createEdge({ source: 'n1', target: 'n2' })],
|
||||
initialStoreState: {
|
||||
helpLineHorizontal: { y: 10 } as never,
|
||||
helpLineVertical: { x: 10 } as never,
|
||||
},
|
||||
})
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 100, top: 100 } })
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('selection-contextmenu-item-left'))
|
||||
|
||||
expect(latestNodes.find(node => node.id === 'n1')?.position.x).toBe(20)
|
||||
expect(latestNodes.find(node => node.id === 'n2')?.position.x).toBe(20)
|
||||
expect(store.getState().selectionMenu).toBeUndefined()
|
||||
expect(store.getState().helpLineHorizontal).toBeUndefined()
|
||||
expect(store.getState().helpLineVertical).toBeUndefined()
|
||||
|
||||
act(() => {
|
||||
store.getState().flushPendingSync()
|
||||
vi.advanceTimersByTime(600)
|
||||
})
|
||||
|
||||
expect(hooksStoreProps.doSyncWorkflowDraft).toHaveBeenCalled()
|
||||
expect(latestHistoryEvent).toBe('NodeDragStop')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should distribute selected nodes horizontally', async () => {
|
||||
const nodes = [
|
||||
createNode({ id: 'n1', selected: true, position: { x: 0, y: 10 }, width: 20, height: 20 }),
|
||||
createNode({ id: 'n2', selected: true, position: { x: 100, y: 20 }, width: 20, height: 20 }),
|
||||
createNode({ id: 'n3', selected: true, position: { x: 300, y: 30 }, width: 20, height: 20 }),
|
||||
]
|
||||
|
||||
const { store } = renderSelectionMenu({
|
||||
nodes,
|
||||
})
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 160, top: 120 } })
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('selection-contextmenu-item-distributeHorizontal'))
|
||||
|
||||
expect(latestNodes.find(node => node.id === 'n2')?.position.x).toBe(150)
|
||||
})
|
||||
|
||||
it('should ignore child nodes when the selected container is aligned', async () => {
|
||||
const nodes = [
|
||||
createNode({
|
||||
id: 'container',
|
||||
selected: true,
|
||||
position: { x: 200, y: 0 },
|
||||
width: 100,
|
||||
height: 80,
|
||||
data: { _children: [{ nodeId: 'child', nodeType: 'code' as never }] },
|
||||
}),
|
||||
createNode({
|
||||
id: 'child',
|
||||
selected: true,
|
||||
position: { x: 210, y: 10 },
|
||||
width: 30,
|
||||
height: 20,
|
||||
}),
|
||||
createNode({
|
||||
id: 'other',
|
||||
selected: true,
|
||||
position: { x: 40, y: 60 },
|
||||
width: 40,
|
||||
height: 20,
|
||||
}),
|
||||
]
|
||||
|
||||
const { store } = renderSelectionMenu({
|
||||
nodes,
|
||||
})
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 180, top: 120 } })
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('selection-contextmenu-item-left'))
|
||||
|
||||
expect(latestNodes.find(node => node.id === 'container')?.position.x).toBe(40)
|
||||
expect(latestNodes.find(node => node.id === 'other')?.position.x).toBe(40)
|
||||
expect(latestNodes.find(node => node.id === 'child')?.position.x).toBe(210)
|
||||
})
|
||||
|
||||
it('should cancel when align bounds cannot be resolved', () => {
|
||||
const nodes = [
|
||||
createNode({ id: 'n1', selected: true }),
|
||||
createNode({ id: 'n2', selected: true, position: { x: 80, y: 20 } }),
|
||||
]
|
||||
|
||||
const { store } = renderSelectionMenu({ nodes })
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 100, top: 100 } })
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('selection-contextmenu-item-left'))
|
||||
|
||||
expect(store.getState().selectionMenu).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should cancel without aligning when nodes are read only', () => {
|
||||
mockGetNodesReadOnly.mockReturnValue(true)
|
||||
const nodes = [
|
||||
createNode({ id: 'n1', selected: true, width: 40, height: 20 }),
|
||||
createNode({ id: 'n2', selected: true, position: { x: 80, y: 20 }, width: 40, height: 20 }),
|
||||
]
|
||||
|
||||
const { store } = renderSelectionMenu({ nodes })
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 100, top: 100 } })
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('selection-contextmenu-item-left'))
|
||||
|
||||
expect(store.getState().selectionMenu).toBeUndefined()
|
||||
expect(latestNodes.find(node => node.id === 'n1')?.position.x).toBe(0)
|
||||
expect(latestNodes.find(node => node.id === 'n2')?.position.x).toBe(80)
|
||||
})
|
||||
|
||||
it('should cancel when alignable nodes shrink to one item', () => {
|
||||
const nodes = [
|
||||
createNode({
|
||||
id: 'container',
|
||||
selected: true,
|
||||
width: 40,
|
||||
height: 20,
|
||||
data: { _children: [{ nodeId: 'child', nodeType: 'code' as never }] },
|
||||
}),
|
||||
createNode({ id: 'child', selected: true, position: { x: 80, y: 20 }, width: 40, height: 20 }),
|
||||
]
|
||||
|
||||
const { store } = renderSelectionMenu({ nodes })
|
||||
|
||||
act(() => {
|
||||
store.setState({ selectionMenu: { left: 100, top: 100 } })
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('selection-contextmenu-item-left'))
|
||||
|
||||
expect(store.getState().selectionMenu).toBeUndefined()
|
||||
expect(latestNodes.find(node => node.id === 'container')?.position.x).toBe(0)
|
||||
expect(latestNodes.find(node => node.id === 'child')?.position.x).toBe(80)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { DSLImportStatus } from '@/models/app'
|
||||
import { AppModeEnum } from '@/types/app'
|
||||
import { BlockEnum } from '../types'
|
||||
import {
|
||||
getInvalidNodeTypes,
|
||||
isImportCompleted,
|
||||
normalizeWorkflowFeatures,
|
||||
validateDSLContent,
|
||||
} from '../update-dsl-modal.helpers'
|
||||
|
||||
describe('update-dsl-modal helpers', () => {
|
||||
describe('dsl validation', () => {
|
||||
it('should reject advanced chat dsl content with disallowed trigger nodes', () => {
|
||||
const content = `
|
||||
workflow:
|
||||
graph:
|
||||
nodes:
|
||||
- data:
|
||||
type: trigger-webhook
|
||||
`
|
||||
|
||||
expect(validateDSLContent(content, AppModeEnum.ADVANCED_CHAT)).toBe(false)
|
||||
})
|
||||
|
||||
it('should reject malformed yaml and answer nodes in non-advanced mode', () => {
|
||||
expect(validateDSLContent('[', AppModeEnum.CHAT)).toBe(false)
|
||||
expect(validateDSLContent(`
|
||||
workflow:
|
||||
graph:
|
||||
nodes:
|
||||
- data:
|
||||
type: answer
|
||||
`, AppModeEnum.CHAT)).toBe(false)
|
||||
})
|
||||
|
||||
it('should accept valid node types for advanced chat mode', () => {
|
||||
expect(validateDSLContent(`
|
||||
workflow:
|
||||
graph:
|
||||
nodes:
|
||||
- data:
|
||||
type: tool
|
||||
`, AppModeEnum.ADVANCED_CHAT)).toBe(true)
|
||||
})
|
||||
|
||||
it('should expose the invalid node sets per mode', () => {
|
||||
expect(getInvalidNodeTypes(AppModeEnum.ADVANCED_CHAT)).toEqual(
|
||||
expect.arrayContaining([BlockEnum.End, BlockEnum.TriggerWebhook]),
|
||||
)
|
||||
expect(getInvalidNodeTypes(AppModeEnum.CHAT)).toEqual([BlockEnum.Answer])
|
||||
})
|
||||
})
|
||||
|
||||
describe('status and feature normalization', () => {
|
||||
it('should treat completed statuses as successful imports', () => {
|
||||
expect(isImportCompleted(DSLImportStatus.COMPLETED)).toBe(true)
|
||||
expect(isImportCompleted(DSLImportStatus.COMPLETED_WITH_WARNINGS)).toBe(true)
|
||||
expect(isImportCompleted(DSLImportStatus.PENDING)).toBe(false)
|
||||
})
|
||||
|
||||
it('should normalize workflow features with defaults', () => {
|
||||
const features = normalizeWorkflowFeatures({
|
||||
file_upload: {
|
||||
image: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
opening_statement: 'hello',
|
||||
suggested_questions: ['what can you do?'],
|
||||
})
|
||||
|
||||
expect(features.file.enabled).toBe(true)
|
||||
expect(features.file.number_limits).toBe(3)
|
||||
expect(features.opening.enabled).toBe(true)
|
||||
expect(features.suggested).toEqual({ enabled: false })
|
||||
expect(features.text2speech).toEqual({ enabled: false })
|
||||
})
|
||||
})
|
||||
})
|
||||
365
web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
Normal file
365
web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
Normal file
@@ -0,0 +1,365 @@
|
||||
import type { EventEmitter } from 'ahooks/lib/useEventEmitter'
|
||||
import type { EventEmitterValue } from '@/context/event-emitter'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { toast } from '@/app/components/base/ui/toast'
|
||||
import { EventEmitterContext } from '@/context/event-emitter'
|
||||
import { DSLImportStatus } from '@/models/app'
|
||||
import UpdateDSLModal from '../update-dsl-modal'
|
||||
|
||||
class MockFileReader {
|
||||
onload: ((this: FileReader, event: ProgressEvent<FileReader>) => void) | null = null
|
||||
|
||||
readAsText(_file: Blob) {
|
||||
const event = { target: { result: 'workflow:\n graph:\n nodes:\n - data:\n type: tool\n' } } as unknown as ProgressEvent<FileReader>
|
||||
this.onload?.call(this as unknown as FileReader, event)
|
||||
}
|
||||
}
|
||||
|
||||
vi.stubGlobal('FileReader', MockFileReader as unknown as typeof FileReader)
|
||||
const mockEmit = vi.fn()
|
||||
|
||||
vi.mock('@/app/components/base/ui/toast', () => ({
|
||||
toast: {
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
success: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockImportDSL = vi.fn()
|
||||
const mockImportDSLConfirm = vi.fn()
|
||||
vi.mock('@/service/apps', () => ({
|
||||
importDSL: (payload: unknown) => mockImportDSL(payload),
|
||||
importDSLConfirm: (payload: unknown) => mockImportDSLConfirm(payload),
|
||||
}))
|
||||
|
||||
const mockFetchWorkflowDraft = vi.fn()
|
||||
vi.mock('@/service/workflow', () => ({
|
||||
fetchWorkflowDraft: (path: string) => mockFetchWorkflowDraft(path),
|
||||
}))
|
||||
|
||||
const mockHandleCheckPluginDependencies = vi.fn()
|
||||
vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
|
||||
usePluginDependencies: () => ({
|
||||
handleCheckPluginDependencies: mockHandleCheckPluginDependencies,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/app/store', () => ({
|
||||
useStore: (selector: (state: { appDetail: { id: string, mode: string } }) => unknown) => selector({
|
||||
appDetail: {
|
||||
id: 'app-1',
|
||||
mode: 'chat',
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({
|
||||
default: ({ updateFile }: { updateFile: (file?: File) => void }) => (
|
||||
<input
|
||||
data-testid="dsl-file-input"
|
||||
type="file"
|
||||
onChange={event => updateFile(event.target.files?.[0])}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('UpdateDSLModal', () => {
|
||||
const mockToastError = vi.mocked(toast.error)
|
||||
const defaultProps = {
|
||||
onCancel: vi.fn(),
|
||||
onBackup: vi.fn(),
|
||||
onImport: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.useRealTimers()
|
||||
mockFetchWorkflowDraft.mockResolvedValue({
|
||||
graph: { nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } },
|
||||
features: {},
|
||||
hash: 'hash-1',
|
||||
conversation_variables: [],
|
||||
environment_variables: [],
|
||||
})
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-1',
|
||||
status: DSLImportStatus.COMPLETED,
|
||||
app_id: 'app-1',
|
||||
})
|
||||
mockImportDSLConfirm.mockResolvedValue({
|
||||
status: DSLImportStatus.COMPLETED,
|
||||
app_id: 'app-1',
|
||||
})
|
||||
mockHandleCheckPluginDependencies.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
const renderModal = (props = defaultProps) => {
|
||||
const eventEmitter = { emit: mockEmit } as unknown as EventEmitter<EventEmitterValue>
|
||||
|
||||
return render(
|
||||
<EventEmitterContext.Provider value={{ eventEmitter }}>
|
||||
<UpdateDSLModal {...props} />
|
||||
</EventEmitterContext.Provider>,
|
||||
)
|
||||
}
|
||||
|
||||
it('should keep import disabled until a file is selected', () => {
|
||||
renderModal()
|
||||
|
||||
expect(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('should call backup handler from the warning area', () => {
|
||||
renderModal()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.backupCurrentDraft' }))
|
||||
|
||||
expect(defaultProps.onBackup).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should import a valid file and emit workflow update payload', async () => {
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockImportDSL).toHaveBeenCalledWith(expect.objectContaining({
|
||||
app_id: 'app-1',
|
||||
yaml_content: expect.stringContaining('workflow:'),
|
||||
}))
|
||||
})
|
||||
|
||||
expect(mockEmit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
type: 'WORKFLOW_DATA_UPDATE',
|
||||
}))
|
||||
expect(defaultProps.onImport).toHaveBeenCalledTimes(1)
|
||||
expect(defaultProps.onCancel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should show an error notification when import fails', async () => {
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-1',
|
||||
status: DSLImportStatus.FAILED,
|
||||
app_id: 'app-1',
|
||||
})
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['invalid'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('should open the version warning modal for pending imports and confirm them', async () => {
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-2',
|
||||
status: DSLImportStatus.PENDING,
|
||||
imported_dsl_version: '1.0.0',
|
||||
current_dsl_version: '2.0.0',
|
||||
})
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'app.newApp.Confirm' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'app.newApp.Confirm' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockImportDSLConfirm).toHaveBeenCalledWith({ import_id: 'import-2' })
|
||||
})
|
||||
})
|
||||
|
||||
it('should open the pending modal after the timeout and allow dismissing it', async () => {
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-5',
|
||||
status: DSLImportStatus.PENDING,
|
||||
imported_dsl_version: '1.0.0',
|
||||
current_dsl_version: '2.0.0',
|
||||
})
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockImportDSL).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'app.newApp.Cancel' })).toBeInTheDocument()
|
||||
}, { timeout: 1000 })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'app.newApp.Cancel' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('button', { name: 'app.newApp.Confirm' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('should show an error when the selected file content is invalid for the current app mode', async () => {
|
||||
class InvalidDSLFileReader extends MockFileReader {
|
||||
readAsText(_file: Blob) {
|
||||
const event = { target: { result: 'workflow:\n graph:\n nodes:\n - data:\n type: answer\n' } } as unknown as ProgressEvent<FileReader>
|
||||
this.onload?.call(this as unknown as FileReader, event)
|
||||
}
|
||||
}
|
||||
|
||||
vi.stubGlobal('FileReader', InvalidDSLFileReader as unknown as typeof FileReader)
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
expect(mockImportDSL).not.toHaveBeenCalled()
|
||||
|
||||
vi.stubGlobal('FileReader', MockFileReader as unknown as typeof FileReader)
|
||||
})
|
||||
|
||||
it('should show an error notification when import throws', async () => {
|
||||
mockImportDSL.mockRejectedValue(new Error('boom'))
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('should show an error when completed import does not return an app id', async () => {
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-3',
|
||||
status: DSLImportStatus.COMPLETED,
|
||||
})
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('should show an error when confirming a pending import fails', async () => {
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-4',
|
||||
status: DSLImportStatus.PENDING,
|
||||
imported_dsl_version: '1.0.0',
|
||||
current_dsl_version: '2.0.0',
|
||||
})
|
||||
mockImportDSLConfirm.mockResolvedValue({
|
||||
status: DSLImportStatus.FAILED,
|
||||
})
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'app.newApp.Confirm' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'app.newApp.Confirm' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('should show an error when confirming a pending import throws', async () => {
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-6',
|
||||
status: DSLImportStatus.PENDING,
|
||||
imported_dsl_version: '1.0.0',
|
||||
current_dsl_version: '2.0.0',
|
||||
})
|
||||
mockImportDSLConfirm.mockRejectedValue(new Error('boom'))
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'app.newApp.Confirm' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'app.newApp.Confirm' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('should show an error when a confirmed pending import completes without an app id', async () => {
|
||||
mockImportDSL.mockResolvedValue({
|
||||
id: 'import-7',
|
||||
status: DSLImportStatus.PENDING,
|
||||
imported_dsl_version: '1.0.0',
|
||||
current_dsl_version: '2.0.0',
|
||||
})
|
||||
mockImportDSLConfirm.mockResolvedValue({
|
||||
status: DSLImportStatus.COMPLETED,
|
||||
})
|
||||
|
||||
renderModal()
|
||||
|
||||
fireEvent.change(screen.getByTestId('dsl-file-input'), {
|
||||
target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'app.newApp.Confirm' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'app.newApp.Confirm' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { render } from '@testing-library/react'
|
||||
import HelpLine from '../index'
|
||||
|
||||
const mockUseViewport = vi.hoisted(() => vi.fn())
|
||||
const mockUseStore = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('reactflow', () => ({
|
||||
useViewport: () => mockUseViewport(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/store', () => ({
|
||||
useStore: (selector: (state: {
|
||||
helpLineHorizontal?: { top: number, left: number, width: number }
|
||||
helpLineVertical?: { top: number, left: number, height: number }
|
||||
}) => unknown) => mockUseStore(selector),
|
||||
}))
|
||||
|
||||
describe('HelpLine', () => {
|
||||
let helpLineHorizontal: { top: number, left: number, width: number } | undefined
|
||||
let helpLineVertical: { top: number, left: number, height: number } | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
helpLineHorizontal = undefined
|
||||
helpLineVertical = undefined
|
||||
|
||||
mockUseViewport.mockReturnValue({ x: 10, y: 20, zoom: 2 })
|
||||
mockUseStore.mockImplementation((selector: (state: {
|
||||
helpLineHorizontal?: { top: number, left: number, width: number }
|
||||
helpLineVertical?: { top: number, left: number, height: number }
|
||||
}) => unknown) => selector({
|
||||
helpLineHorizontal,
|
||||
helpLineVertical,
|
||||
}))
|
||||
})
|
||||
|
||||
it('should render nothing when both help lines are absent', () => {
|
||||
const { container } = render(<HelpLine />)
|
||||
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('should render the horizontal and vertical guide lines using viewport offsets and zoom', () => {
|
||||
helpLineHorizontal = { top: 30, left: 40, width: 50 }
|
||||
helpLineVertical = { top: 60, left: 70, height: 80 }
|
||||
|
||||
const { container } = render(<HelpLine />)
|
||||
const [horizontal, vertical] = Array.from(container.querySelectorAll('div'))
|
||||
|
||||
expect(horizontal).toHaveStyle({
|
||||
top: '80px',
|
||||
left: '90px',
|
||||
width: '100px',
|
||||
})
|
||||
expect(vertical).toHaveStyle({
|
||||
top: '140px',
|
||||
left: '150px',
|
||||
height: '160px',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { ModelConfig, VisionSetting } from '@/app/components/workflow/types'
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { Resolution } from '@/types/app'
|
||||
import useConfigVision from '../use-config-vision'
|
||||
|
||||
const mockUseTextGenerationCurrentProviderAndModelAndModelList = vi.hoisted(() => vi.fn())
|
||||
const mockUseIsChatMode = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
|
||||
useTextGenerationCurrentProviderAndModelAndModelList: (...args: unknown[]) =>
|
||||
mockUseTextGenerationCurrentProviderAndModelAndModelList(...args),
|
||||
}))
|
||||
|
||||
vi.mock('../use-workflow', () => ({
|
||||
useIsChatMode: () => mockUseIsChatMode(),
|
||||
}))
|
||||
|
||||
const createModel = (overrides: Partial<ModelConfig> = {}): ModelConfig => ({
|
||||
provider: 'openai',
|
||||
name: 'gpt-4o',
|
||||
mode: 'chat',
|
||||
completion_params: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const createVisionPayload = (overrides: Partial<{ enabled: boolean, configs?: VisionSetting }> = {}) => ({
|
||||
enabled: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('useConfigVision', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockUseIsChatMode.mockReturnValue(false)
|
||||
mockUseTextGenerationCurrentProviderAndModelAndModelList.mockReturnValue({
|
||||
currentModel: {
|
||||
features: [],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should expose vision capability and enable default chat configs for vision models', () => {
|
||||
const onChange = vi.fn()
|
||||
mockUseIsChatMode.mockReturnValue(true)
|
||||
mockUseTextGenerationCurrentProviderAndModelAndModelList.mockReturnValue({
|
||||
currentModel: {
|
||||
features: [ModelFeatureEnum.vision],
|
||||
},
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useConfigVision(createModel(), {
|
||||
payload: createVisionPayload(),
|
||||
onChange,
|
||||
}))
|
||||
|
||||
expect(result.current.isVisionModel).toBe(true)
|
||||
|
||||
act(() => {
|
||||
result.current.handleVisionResolutionEnabledChange(true)
|
||||
})
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
enabled: true,
|
||||
configs: {
|
||||
detail: Resolution.high,
|
||||
variable_selector: ['sys', 'files'],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should clear configs when disabling vision resolution', () => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
const { result } = renderHook(() => useConfigVision(createModel(), {
|
||||
payload: createVisionPayload({
|
||||
enabled: true,
|
||||
configs: {
|
||||
detail: Resolution.low,
|
||||
variable_selector: ['node', 'files'],
|
||||
},
|
||||
}),
|
||||
onChange,
|
||||
}))
|
||||
|
||||
act(() => {
|
||||
result.current.handleVisionResolutionEnabledChange(false)
|
||||
})
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
enabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('should update the resolution config payload directly', () => {
|
||||
const onChange = vi.fn()
|
||||
const config: VisionSetting = {
|
||||
detail: Resolution.low,
|
||||
variable_selector: ['upstream', 'images'],
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useConfigVision(createModel(), {
|
||||
payload: createVisionPayload({ enabled: true }),
|
||||
onChange,
|
||||
}))
|
||||
|
||||
act(() => {
|
||||
result.current.handleVisionResolutionChange(config)
|
||||
})
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
enabled: true,
|
||||
configs: config,
|
||||
})
|
||||
})
|
||||
|
||||
it('should disable vision settings when the selected model is no longer a vision model', () => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
const { result } = renderHook(() => useConfigVision(createModel(), {
|
||||
payload: createVisionPayload({
|
||||
enabled: true,
|
||||
configs: {
|
||||
detail: Resolution.high,
|
||||
variable_selector: ['sys', 'files'],
|
||||
},
|
||||
}),
|
||||
onChange,
|
||||
}))
|
||||
|
||||
act(() => {
|
||||
result.current.handleModelChanged()
|
||||
})
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
enabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('should reset enabled vision configs when the model changes but still supports vision', () => {
|
||||
const onChange = vi.fn()
|
||||
mockUseTextGenerationCurrentProviderAndModelAndModelList.mockReturnValue({
|
||||
currentModel: {
|
||||
features: [ModelFeatureEnum.vision],
|
||||
},
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useConfigVision(createModel(), {
|
||||
payload: createVisionPayload({
|
||||
enabled: true,
|
||||
configs: {
|
||||
detail: Resolution.low,
|
||||
variable_selector: ['old', 'files'],
|
||||
},
|
||||
}),
|
||||
onChange,
|
||||
}))
|
||||
|
||||
act(() => {
|
||||
result.current.handleModelChanged()
|
||||
})
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
enabled: true,
|
||||
configs: {
|
||||
detail: Resolution.high,
|
||||
variable_selector: [],
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { BlockEnum } from '../../types'
|
||||
import { useDynamicTestRunOptions } from '../use-dynamic-test-run-options'
|
||||
|
||||
const mockUseTranslation = vi.hoisted(() => vi.fn())
|
||||
const mockUseNodes = vi.hoisted(() => vi.fn())
|
||||
const mockUseStore = vi.hoisted(() => vi.fn())
|
||||
const mockUseAllTriggerPlugins = vi.hoisted(() => vi.fn())
|
||||
const mockGetWorkflowEntryNode = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => mockUseTranslation(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({
|
||||
__esModule: true,
|
||||
default: () => mockUseNodes(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/store', () => ({
|
||||
useStore: (selector: (state: {
|
||||
buildInTools: unknown[]
|
||||
customTools: unknown[]
|
||||
workflowTools: unknown[]
|
||||
mcpTools: unknown[]
|
||||
}) => unknown) => mockUseStore(selector),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-triggers', () => ({
|
||||
useAllTriggerPlugins: () => mockUseAllTriggerPlugins(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/utils/workflow-entry', () => ({
|
||||
getWorkflowEntryNode: (...args: unknown[]) => mockGetWorkflowEntryNode(...args),
|
||||
}))
|
||||
|
||||
describe('useDynamicTestRunOptions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockUseTranslation.mockReturnValue({
|
||||
t: (key: string) => key,
|
||||
})
|
||||
mockUseStore.mockImplementation((selector: (state: {
|
||||
buildInTools: unknown[]
|
||||
customTools: unknown[]
|
||||
workflowTools: unknown[]
|
||||
mcpTools: unknown[]
|
||||
}) => unknown) => selector({
|
||||
buildInTools: [],
|
||||
customTools: [],
|
||||
workflowTools: [],
|
||||
mcpTools: [],
|
||||
}))
|
||||
mockUseAllTriggerPlugins.mockReturnValue({
|
||||
data: [{
|
||||
name: 'plugin-provider',
|
||||
icon: '/plugin-icon.png',
|
||||
}],
|
||||
})
|
||||
})
|
||||
|
||||
it('should build user input, trigger options, and a run-all option from workflow nodes', () => {
|
||||
mockUseNodes.mockReturnValue([
|
||||
{
|
||||
id: 'start-1',
|
||||
data: { type: BlockEnum.Start, title: 'User Input' },
|
||||
},
|
||||
{
|
||||
id: 'schedule-1',
|
||||
data: { type: BlockEnum.TriggerSchedule, title: 'Daily Schedule' },
|
||||
},
|
||||
{
|
||||
id: 'webhook-1',
|
||||
data: { type: BlockEnum.TriggerWebhook, title: 'Webhook Trigger' },
|
||||
},
|
||||
{
|
||||
id: 'plugin-1',
|
||||
data: {
|
||||
type: BlockEnum.TriggerPlugin,
|
||||
title: '',
|
||||
plugin_name: 'Plugin Trigger',
|
||||
provider_id: 'plugin-provider',
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const { result } = renderHook(() => useDynamicTestRunOptions())
|
||||
|
||||
expect(result.current.userInput).toEqual(expect.objectContaining({
|
||||
id: 'start-1',
|
||||
type: 'user_input',
|
||||
name: 'User Input',
|
||||
nodeId: 'start-1',
|
||||
enabled: true,
|
||||
}))
|
||||
expect(result.current.triggers).toEqual([
|
||||
expect.objectContaining({
|
||||
id: 'schedule-1',
|
||||
type: 'schedule',
|
||||
name: 'Daily Schedule',
|
||||
nodeId: 'schedule-1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: 'webhook-1',
|
||||
type: 'webhook',
|
||||
name: 'Webhook Trigger',
|
||||
nodeId: 'webhook-1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: 'plugin-1',
|
||||
type: 'plugin',
|
||||
name: 'Plugin Trigger',
|
||||
nodeId: 'plugin-1',
|
||||
}),
|
||||
])
|
||||
expect(result.current.runAll).toEqual(expect.objectContaining({
|
||||
id: 'run-all',
|
||||
type: 'all',
|
||||
relatedNodeIds: ['schedule-1', 'webhook-1', 'plugin-1'],
|
||||
}))
|
||||
})
|
||||
|
||||
it('should fall back to the workflow entry node and omit run-all when only one trigger exists', () => {
|
||||
mockUseNodes.mockReturnValue([
|
||||
{
|
||||
id: 'webhook-1',
|
||||
data: { type: BlockEnum.TriggerWebhook, title: 'Webhook Trigger' },
|
||||
},
|
||||
])
|
||||
mockGetWorkflowEntryNode.mockReturnValue({
|
||||
id: 'fallback-start',
|
||||
data: { type: BlockEnum.Start, title: '' },
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useDynamicTestRunOptions())
|
||||
|
||||
expect(result.current.userInput).toEqual(expect.objectContaining({
|
||||
id: 'fallback-start',
|
||||
type: 'user_input',
|
||||
name: 'blocks.start',
|
||||
nodeId: 'fallback-start',
|
||||
}))
|
||||
expect(result.current.triggers).toHaveLength(1)
|
||||
expect(result.current.runAll).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1820,21 +1820,26 @@ export const useNodesInteractions = () => {
|
||||
newChildren.push(newLoopStartNode!)
|
||||
}
|
||||
else {
|
||||
// single node paste
|
||||
// Paste a single regular node. Loop/Iteration nodes are handled above.
|
||||
const selectedNode = nodes.find(node => node.selected)
|
||||
let pastedToNestedBlock = false
|
||||
|
||||
if (selectedNode) {
|
||||
// Keep this list aligned with availableBlocksFilter(inContainer)
|
||||
// in use-available-blocks.ts.
|
||||
const commonNestedDisallowPasteNodes = [
|
||||
// end node only can be placed outermost layer
|
||||
BlockEnum.End,
|
||||
BlockEnum.Iteration,
|
||||
BlockEnum.Loop,
|
||||
BlockEnum.DataSource,
|
||||
BlockEnum.KnowledgeBase,
|
||||
BlockEnum.HumanInput,
|
||||
]
|
||||
|
||||
// handle disallow paste node
|
||||
if (commonNestedDisallowPasteNodes.includes(nodeToPaste.data.type))
|
||||
return
|
||||
|
||||
// handle paste to nested block
|
||||
// If a Loop/Iteration container is selected, paste into it as a child.
|
||||
if (selectedNode.data.type === BlockEnum.Iteration || selectedNode.data.type === BlockEnum.Loop) {
|
||||
const isIteration = selectedNode.data.type === BlockEnum.Iteration
|
||||
|
||||
@@ -1849,10 +1854,10 @@ export const useNodesInteractions = () => {
|
||||
x: newNode.position.x,
|
||||
y: newNode.position.y,
|
||||
}
|
||||
// set position base on parent node
|
||||
// Rebase position into the selected container coordinate system.
|
||||
newNode.position = getNestedNodePosition(newNode, selectedNode)
|
||||
|
||||
// update parent children array like native add
|
||||
// Mirror native add behavior by appending parent._children.
|
||||
parentChildrenToAppend.push({ parentId: selectedNode.id, childId: newNode.id, childType: newNode.data.type })
|
||||
|
||||
pastedToNestedBlock = true
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { TFunction } from 'i18next'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import { NodeBody, NodeDescription, NodeHeaderMeta } from '../node-sections'
|
||||
|
||||
describe('node sections', () => {
|
||||
it('should render loop and loading metadata in the header section', () => {
|
||||
const t = ((key: string) => key) as unknown as TFunction
|
||||
|
||||
render(
|
||||
<NodeHeaderMeta
|
||||
data={{
|
||||
type: BlockEnum.Loop,
|
||||
_loopIndex: 2,
|
||||
_runningStatus: NodeRunningStatus.Running,
|
||||
} as never}
|
||||
hasVarValue={false}
|
||||
isLoading
|
||||
loopIndex={<div>loop-index</div>}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('loop-index')).toBeInTheDocument()
|
||||
expect(document.querySelector('.i-ri-loader-2-line')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render the container node body and description branches', () => {
|
||||
const { rerender } = render(
|
||||
<NodeBody
|
||||
data={{ type: BlockEnum.Loop } as never}
|
||||
child={<div>body-content</div>}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('body-content').parentElement).toHaveClass('grow')
|
||||
|
||||
rerender(<NodeDescription data={{ type: BlockEnum.Tool, desc: 'node description' } as never} />)
|
||||
expect(screen.getByText('node description')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render iteration parallel metadata and running progress', async () => {
|
||||
const t = ((key: string) => key) as unknown as TFunction
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<NodeHeaderMeta
|
||||
data={{
|
||||
type: BlockEnum.Iteration,
|
||||
is_parallel: true,
|
||||
_iterationLength: 3,
|
||||
_iterationIndex: 5,
|
||||
_runningStatus: NodeRunningStatus.Running,
|
||||
} as never}
|
||||
hasVarValue={false}
|
||||
isLoading={false}
|
||||
loopIndex={null}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('nodes.iteration.parallelModeUpper')).toBeInTheDocument()
|
||||
await user.hover(screen.getByText('nodes.iteration.parallelModeUpper'))
|
||||
expect(await screen.findByText('nodes.iteration.parallelModeEnableTitle')).toBeInTheDocument()
|
||||
expect(screen.getByText('nodes.iteration.parallelModeEnableDesc')).toBeInTheDocument()
|
||||
expect(screen.getByText('3/3')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render failed, exception, success and paused status icons', () => {
|
||||
const t = ((key: string) => key) as unknown as TFunction
|
||||
const { rerender } = render(
|
||||
<NodeHeaderMeta
|
||||
data={{ type: BlockEnum.Tool, _runningStatus: NodeRunningStatus.Failed } as never}
|
||||
hasVarValue={false}
|
||||
isLoading={false}
|
||||
loopIndex={null}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(document.querySelector('.i-ri-error-warning-fill')).toBeInTheDocument()
|
||||
|
||||
rerender(
|
||||
<NodeHeaderMeta
|
||||
data={{ type: BlockEnum.Tool, _runningStatus: NodeRunningStatus.Exception } as never}
|
||||
hasVarValue={false}
|
||||
isLoading={false}
|
||||
loopIndex={null}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
expect(document.querySelector('.i-ri-alert-fill')).toBeInTheDocument()
|
||||
|
||||
rerender(
|
||||
<NodeHeaderMeta
|
||||
data={{ type: BlockEnum.Tool, _runningStatus: NodeRunningStatus.Succeeded } as never}
|
||||
hasVarValue={false}
|
||||
isLoading={false}
|
||||
loopIndex={null}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
expect(document.querySelector('.i-ri-checkbox-circle-fill')).toBeInTheDocument()
|
||||
|
||||
rerender(
|
||||
<NodeHeaderMeta
|
||||
data={{ type: BlockEnum.Tool, _runningStatus: NodeRunningStatus.Paused } as never}
|
||||
hasVarValue={false}
|
||||
isLoading={false}
|
||||
loopIndex={null}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
expect(document.querySelector('.i-ri-pause-circle-fill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render success icon when inspect vars exist without running status and hide description for loop nodes', () => {
|
||||
const t = ((key: string) => key) as unknown as TFunction
|
||||
const { rerender } = render(
|
||||
<NodeHeaderMeta
|
||||
data={{ type: BlockEnum.Tool } as never}
|
||||
hasVarValue
|
||||
isLoading={false}
|
||||
loopIndex={null}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(document.querySelector('.i-ri-checkbox-circle-fill')).toBeInTheDocument()
|
||||
|
||||
rerender(<NodeDescription data={{ type: BlockEnum.Loop, desc: 'hidden' } as never} />)
|
||||
expect(screen.queryByText('hidden')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import {
|
||||
getLoopIndexTextKey,
|
||||
getNodeStatusBorders,
|
||||
isContainerNode,
|
||||
isEntryWorkflowNode,
|
||||
} from '../node.helpers'
|
||||
|
||||
describe('node helpers', () => {
|
||||
it('should derive node border states from running status and selection state', () => {
|
||||
expect(getNodeStatusBorders(NodeRunningStatus.Running, false, false).showRunningBorder).toBe(true)
|
||||
expect(getNodeStatusBorders(NodeRunningStatus.Succeeded, false, false).showSuccessBorder).toBe(true)
|
||||
expect(getNodeStatusBorders(NodeRunningStatus.Failed, false, false).showFailedBorder).toBe(true)
|
||||
expect(getNodeStatusBorders(NodeRunningStatus.Exception, false, false).showExceptionBorder).toBe(true)
|
||||
expect(getNodeStatusBorders(NodeRunningStatus.Succeeded, false, true).showSuccessBorder).toBe(false)
|
||||
})
|
||||
|
||||
it('should expose the correct loop translation key per running status', () => {
|
||||
expect(getLoopIndexTextKey(NodeRunningStatus.Running)).toBe('nodes.loop.currentLoopCount')
|
||||
expect(getLoopIndexTextKey(NodeRunningStatus.Succeeded)).toBe('nodes.loop.totalLoopCount')
|
||||
expect(getLoopIndexTextKey(NodeRunningStatus.Failed)).toBe('nodes.loop.totalLoopCount')
|
||||
expect(getLoopIndexTextKey(NodeRunningStatus.Paused)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should identify entry and container nodes', () => {
|
||||
expect(isEntryWorkflowNode(BlockEnum.Start)).toBe(true)
|
||||
expect(isEntryWorkflowNode(BlockEnum.TriggerWebhook)).toBe(true)
|
||||
expect(isEntryWorkflowNode(BlockEnum.Tool)).toBe(false)
|
||||
|
||||
expect(isContainerNode(BlockEnum.Iteration)).toBe(true)
|
||||
expect(isContainerNode(BlockEnum.Loop)).toBe(true)
|
||||
expect(isContainerNode(BlockEnum.Tool)).toBe(false)
|
||||
})
|
||||
})
|
||||
218
web/app/components/workflow/nodes/_base/__tests__/node.spec.tsx
Normal file
218
web/app/components/workflow/nodes/_base/__tests__/node.spec.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
import type { PropsWithChildren } from 'react'
|
||||
import type { CommonNodeType } from '@/app/components/workflow/types'
|
||||
import { fireEvent, screen } from '@testing-library/react'
|
||||
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import BaseNode from '../node'
|
||||
|
||||
const mockHasNodeInspectVars = vi.fn()
|
||||
const mockUseNodePluginInstallation = vi.fn()
|
||||
const mockHandleNodeIterationChildSizeChange = vi.fn()
|
||||
const mockHandleNodeLoopChildSizeChange = vi.fn()
|
||||
const mockUseNodeResizeObserver = vi.fn()
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks', () => ({
|
||||
useNodesReadOnly: () => ({ nodesReadOnly: false }),
|
||||
useToolIcon: () => undefined,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud', () => ({
|
||||
default: () => ({
|
||||
hasNodeInspectVars: mockHasNodeInspectVars,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks/use-node-plugin-installation', () => ({
|
||||
useNodePluginInstallation: (...args: unknown[]) => mockUseNodePluginInstallation(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/iteration/use-interactions', () => ({
|
||||
useNodeIterationInteractions: () => ({
|
||||
handleNodeIterationChildSizeChange: mockHandleNodeIterationChildSizeChange,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/loop/use-interactions', () => ({
|
||||
useNodeLoopInteractions: () => ({
|
||||
handleNodeLoopChildSizeChange: mockHandleNodeLoopChildSizeChange,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('../use-node-resize-observer', () => ({
|
||||
default: (options: { enabled: boolean, onResize: () => void }) => {
|
||||
mockUseNodeResizeObserver(options)
|
||||
if (options.enabled)
|
||||
options.onResize()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../components/add-variable-popup-with-position', () => ({
|
||||
default: () => <div data-testid="add-var-popup" />,
|
||||
}))
|
||||
vi.mock('../components/entry-node-container', () => ({
|
||||
__esModule: true,
|
||||
StartNodeTypeEnum: { Start: 'start', Trigger: 'trigger' },
|
||||
default: ({ children }: PropsWithChildren) => <div data-testid="entry-node-container">{children}</div>,
|
||||
}))
|
||||
vi.mock('../components/error-handle/error-handle-on-node', () => ({
|
||||
default: () => <div data-testid="error-handle-node" />,
|
||||
}))
|
||||
vi.mock('../components/node-control', () => ({
|
||||
default: () => <div data-testid="node-control" />,
|
||||
}))
|
||||
vi.mock('../components/node-handle', () => ({
|
||||
NodeSourceHandle: () => <div data-testid="node-source-handle" />,
|
||||
NodeTargetHandle: () => <div data-testid="node-target-handle" />,
|
||||
}))
|
||||
vi.mock('../components/node-resizer', () => ({
|
||||
default: () => <div data-testid="node-resizer" />,
|
||||
}))
|
||||
vi.mock('../components/retry/retry-on-node', () => ({
|
||||
default: () => <div data-testid="retry-node" />,
|
||||
}))
|
||||
vi.mock('@/app/components/workflow/block-icon', () => ({
|
||||
default: () => <div data-testid="block-icon" />,
|
||||
}))
|
||||
vi.mock('@/app/components/workflow/nodes/tool/components/copy-id', () => ({
|
||||
default: ({ content }: { content: string }) => <div>{content}</div>,
|
||||
}))
|
||||
|
||||
const createData = (overrides: Record<string, unknown> = {}) => ({
|
||||
type: BlockEnum.Tool,
|
||||
title: 'Node title',
|
||||
desc: 'Node description',
|
||||
selected: false,
|
||||
width: 280,
|
||||
height: 180,
|
||||
provider_type: 'builtin',
|
||||
provider_id: 'tool-1',
|
||||
_runningStatus: undefined,
|
||||
_singleRunningStatus: undefined,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const toNodeData = (data: ReturnType<typeof createData>) => data as CommonNodeType
|
||||
|
||||
describe('BaseNode', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockHasNodeInspectVars.mockReturnValue(false)
|
||||
mockUseNodeResizeObserver.mockReset()
|
||||
mockUseNodePluginInstallation.mockReturnValue({
|
||||
shouldDim: false,
|
||||
isChecking: false,
|
||||
isMissing: false,
|
||||
canInstall: false,
|
||||
uniqueIdentifier: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('should render content, handles and description for a regular node', () => {
|
||||
renderWorkflowComponent(
|
||||
<BaseNode id="node-1" data={toNodeData(createData())}>
|
||||
<div>Body</div>
|
||||
</BaseNode>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Node title')).toBeInTheDocument()
|
||||
expect(screen.getByText('Node description')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('node-control')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('node-source-handle')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('node-target-handle')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render entry nodes inside the entry container', () => {
|
||||
renderWorkflowComponent(
|
||||
<BaseNode id="node-1" data={toNodeData(createData({ type: BlockEnum.Start }))}>
|
||||
<div>Body</div>
|
||||
</BaseNode>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('entry-node-container')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should block interaction when plugin installation is required', () => {
|
||||
mockUseNodePluginInstallation.mockReturnValue({
|
||||
shouldDim: false,
|
||||
isChecking: false,
|
||||
isMissing: true,
|
||||
canInstall: true,
|
||||
uniqueIdentifier: 'plugin-1',
|
||||
})
|
||||
|
||||
renderWorkflowComponent(
|
||||
<BaseNode id="node-1" data={toNodeData(createData())}>
|
||||
<div>Body</div>
|
||||
</BaseNode>,
|
||||
)
|
||||
|
||||
const overlay = screen.getByTestId('workflow-node-install-overlay')
|
||||
expect(overlay).toBeInTheDocument()
|
||||
fireEvent.click(overlay)
|
||||
})
|
||||
|
||||
it('should render running status indicators for loop nodes', () => {
|
||||
renderWorkflowComponent(
|
||||
<BaseNode
|
||||
id="node-1"
|
||||
data={toNodeData(createData({
|
||||
type: BlockEnum.Loop,
|
||||
_loopIndex: 3,
|
||||
_runningStatus: NodeRunningStatus.Running,
|
||||
width: 320,
|
||||
height: 220,
|
||||
}))}
|
||||
>
|
||||
<div>Loop body</div>
|
||||
</BaseNode>,
|
||||
)
|
||||
|
||||
expect(screen.getByText(/workflow\.nodes\.loop\.currentLoopCount/)).toBeInTheDocument()
|
||||
expect(screen.getByTestId('node-resizer')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render an iteration node resizer and dimmed overlay', () => {
|
||||
mockUseNodePluginInstallation.mockReturnValue({
|
||||
shouldDim: true,
|
||||
isChecking: false,
|
||||
isMissing: false,
|
||||
canInstall: false,
|
||||
uniqueIdentifier: undefined,
|
||||
})
|
||||
|
||||
renderWorkflowComponent(
|
||||
<BaseNode
|
||||
id="node-1"
|
||||
data={toNodeData(createData({
|
||||
type: BlockEnum.Iteration,
|
||||
selected: true,
|
||||
isInIteration: true,
|
||||
}))}
|
||||
>
|
||||
<div>Iteration body</div>
|
||||
</BaseNode>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('node-resizer')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('workflow-node-install-overlay')).toBeInTheDocument()
|
||||
expect(mockHandleNodeIterationChildSizeChange).toHaveBeenCalledWith('node-1')
|
||||
})
|
||||
|
||||
it('should trigger loop resize updates when the selected node is inside a loop', () => {
|
||||
renderWorkflowComponent(
|
||||
<BaseNode
|
||||
id="node-2"
|
||||
data={toNodeData(createData({
|
||||
type: BlockEnum.Loop,
|
||||
selected: true,
|
||||
isInLoop: true,
|
||||
}))}
|
||||
>
|
||||
<div>Loop body</div>
|
||||
</BaseNode>,
|
||||
)
|
||||
|
||||
expect(mockHandleNodeLoopChildSizeChange).toHaveBeenCalledWith('node-2')
|
||||
expect(mockUseNodeResizeObserver).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import useNodeResizeObserver from '../use-node-resize-observer'
|
||||
|
||||
describe('useNodeResizeObserver', () => {
|
||||
it('should observe and disconnect when enabled with a mounted node ref', () => {
|
||||
const observe = vi.fn()
|
||||
const disconnect = vi.fn()
|
||||
const onResize = vi.fn()
|
||||
let resizeCallback: (() => void) | undefined
|
||||
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
constructor(callback: () => void) {
|
||||
resizeCallback = callback
|
||||
}
|
||||
|
||||
observe = observe
|
||||
disconnect = disconnect
|
||||
unobserve = vi.fn()
|
||||
})
|
||||
|
||||
const node = document.createElement('div')
|
||||
const nodeRef = { current: node }
|
||||
|
||||
const { unmount } = renderHook(() => useNodeResizeObserver({
|
||||
enabled: true,
|
||||
nodeRef,
|
||||
onResize,
|
||||
}))
|
||||
|
||||
expect(observe).toHaveBeenCalledWith(node)
|
||||
resizeCallback?.()
|
||||
expect(onResize).toHaveBeenCalledTimes(1)
|
||||
|
||||
unmount()
|
||||
expect(disconnect).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should do nothing when disabled', () => {
|
||||
const observe = vi.fn()
|
||||
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
observe = observe
|
||||
disconnect = vi.fn()
|
||||
unobserve = vi.fn()
|
||||
})
|
||||
|
||||
renderHook(() => useNodeResizeObserver({
|
||||
enabled: false,
|
||||
nodeRef: { current: document.createElement('div') },
|
||||
onResize: vi.fn(),
|
||||
}))
|
||||
|
||||
expect(observe).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -145,7 +145,7 @@ describe('AgentStrategy', () => {
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('slider')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Count')).toBeInTheDocument()
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { CredentialFormSchema, FormOption } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { PluginCategoryEnum } from '@/app/components/plugins/types'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { VarKindType } from '../../types'
|
||||
import FormInputItem from '../form-input-item'
|
||||
|
||||
const {
|
||||
mockFetchDynamicOptions,
|
||||
mockTriggerDynamicOptionsState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFetchDynamicOptions: vi.fn(),
|
||||
mockTriggerDynamicOptionsState: {
|
||||
data: undefined as { options: FormOption[] } | undefined,
|
||||
isLoading: false,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
|
||||
useLanguage: () => 'en_US',
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-plugins', () => ({
|
||||
useFetchDynamicOptions: () => ({
|
||||
mutateAsync: mockFetchDynamicOptions,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-triggers', () => ({
|
||||
useTriggerPluginDynamicOptions: () => mockTriggerDynamicOptionsState,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/plugins/plugin-detail-panel/app-selector', () => ({
|
||||
default: ({ onSelect }: { onSelect: (value: string) => void }) => (
|
||||
<button onClick={() => onSelect('app-1')}>app-selector</button>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/plugins/plugin-detail-panel/model-selector', () => ({
|
||||
default: ({ setModel }: { setModel: (value: string) => void }) => (
|
||||
<button onClick={() => setModel('model-1')}>model-selector</button>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/tool/components/mixed-variable-text-input', () => ({
|
||||
default: ({ onChange, value }: { onChange: (value: string) => void, value: string }) => (
|
||||
<input aria-label="mixed-variable-input" value={value} onChange={e => onChange(e.target.value)} />
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
|
||||
default: ({ onChange, value }: { onChange: (value: string) => void, value: string }) => (
|
||||
<textarea aria-label="json-editor" value={value} onChange={e => onChange(e.target.value)} />
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
|
||||
default: ({ onChange }: { onChange: (value: string[]) => void }) => (
|
||||
<button onClick={() => onChange(['node-2', 'asset'])}>variable-picker</button>
|
||||
),
|
||||
}))
|
||||
|
||||
const createSchema = (
|
||||
overrides: Partial<CredentialFormSchema & {
|
||||
_type?: FormTypeEnum
|
||||
multiple?: boolean
|
||||
options?: FormOption[]
|
||||
}> = {},
|
||||
) => ({
|
||||
label: { en_US: 'Field', zh_Hans: '字段' },
|
||||
name: 'field',
|
||||
required: false,
|
||||
show_on: [],
|
||||
type: FormTypeEnum.textInput,
|
||||
variable: 'field',
|
||||
...overrides,
|
||||
}) as CredentialFormSchema & {
|
||||
_type?: FormTypeEnum
|
||||
multiple?: boolean
|
||||
options?: FormOption[]
|
||||
}
|
||||
|
||||
const createOption = (
|
||||
value: string,
|
||||
overrides: Partial<FormOption> = {},
|
||||
): FormOption => ({
|
||||
label: { en_US: value, zh_Hans: value },
|
||||
show_on: [],
|
||||
value,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderFormInputItem = (props: Partial<ComponentProps<typeof FormInputItem>> = {}) => {
|
||||
const onChange = vi.fn()
|
||||
const result = renderWorkflowFlowComponent(
|
||||
<FormInputItem
|
||||
readOnly={false}
|
||||
nodeId="node-1"
|
||||
schema={createSchema()}
|
||||
value={{
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: '',
|
||||
},
|
||||
}}
|
||||
onChange={onChange}
|
||||
{...props}
|
||||
/>,
|
||||
{
|
||||
edges: [],
|
||||
hooksStoreProps: {},
|
||||
nodes: [],
|
||||
},
|
||||
)
|
||||
|
||||
return { ...result, onChange }
|
||||
}
|
||||
|
||||
describe('FormInputItem branches', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockFetchDynamicOptions.mockResolvedValue({ options: [] })
|
||||
mockTriggerDynamicOptionsState.data = undefined
|
||||
mockTriggerDynamicOptionsState.isLoading = false
|
||||
})
|
||||
|
||||
it('should update mixed string inputs via the shared text input', () => {
|
||||
const { onChange } = renderFormInputItem()
|
||||
|
||||
fireEvent.change(screen.getByLabelText('mixed-variable-input'), { target: { value: 'hello world' } })
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.mixed,
|
||||
value: 'hello world',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should switch from variable mode back to constant mode with the schema default value', () => {
|
||||
const { container, onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
default: 7 as never,
|
||||
type: FormTypeEnum.textNumber,
|
||||
}),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.variable,
|
||||
value: ['node-1', 'count'],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const switchRoot = container.querySelector('.inline-flex.h-8.shrink-0.gap-px')
|
||||
const clickableItems = switchRoot?.querySelectorAll('.cursor-pointer') ?? []
|
||||
fireEvent.click(clickableItems[1] as HTMLElement)
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: 7,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should render static select options with icons and update the selected item', () => {
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
type: FormTypeEnum.select,
|
||||
options: [
|
||||
createOption('basic', { icon: '/basic.svg' }),
|
||||
createOption('pro'),
|
||||
],
|
||||
}),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: '',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
expect(document.querySelector('img[src="/basic.svg"]')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByText('basic'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: 'basic',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should render static multi-select values and update selected labels', () => {
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
multiple: true,
|
||||
type: FormTypeEnum.select,
|
||||
options: [
|
||||
createOption('alpha'),
|
||||
createOption('beta'),
|
||||
],
|
||||
}),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: ['alpha'],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
expect(screen.getByText('alpha')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
fireEvent.click(screen.getByText('beta'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: ['alpha', 'beta'],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should fetch tool dynamic options, render them, and update the value', async () => {
|
||||
mockFetchDynamicOptions.mockResolvedValueOnce({
|
||||
options: [
|
||||
createOption('remote', { icon: '/remote.svg' }),
|
||||
],
|
||||
})
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
type: FormTypeEnum.dynamicSelect,
|
||||
}),
|
||||
currentProvider: { plugin_id: 'provider-1', name: 'provider-1' } as never,
|
||||
currentTool: { name: 'tool-1' } as never,
|
||||
providerType: PluginCategoryEnum.tool,
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: '',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchDynamicOptions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
expect(document.querySelector('img[src="/remote.svg"]')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByText('remote'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: 'remote',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should recover when fetching dynamic tool options fails', async () => {
|
||||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
mockFetchDynamicOptions.mockRejectedValueOnce(new Error('network'))
|
||||
|
||||
renderFormInputItem({
|
||||
schema: createSchema({
|
||||
type: FormTypeEnum.dynamicSelect,
|
||||
}),
|
||||
currentProvider: { plugin_id: 'provider-1', name: 'provider-1' } as never,
|
||||
currentTool: { name: 'tool-1' } as never,
|
||||
providerType: PluginCategoryEnum.tool,
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(consoleSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
consoleSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should use trigger dynamic options for multi-select values', async () => {
|
||||
mockTriggerDynamicOptionsState.data = {
|
||||
options: [
|
||||
createOption('trigger-option'),
|
||||
],
|
||||
}
|
||||
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
multiple: true,
|
||||
type: FormTypeEnum.dynamicSelect,
|
||||
}),
|
||||
currentProvider: { plugin_id: 'provider-2', name: 'provider-2', credential_id: 'credential-1' } as never,
|
||||
currentTool: { name: 'trigger-tool' } as never,
|
||||
providerType: PluginCategoryEnum.trigger,
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button')).not.toBeDisabled()
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
fireEvent.click(screen.getByText('trigger-option'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: ['trigger-option'],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should delegate app and model selection to their dedicated controls', () => {
|
||||
const app = renderFormInputItem({
|
||||
schema: createSchema({ type: FormTypeEnum.appSelector }),
|
||||
})
|
||||
fireEvent.click(screen.getByText('app-selector'))
|
||||
expect(app.onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: 'app-1',
|
||||
},
|
||||
})
|
||||
|
||||
app.unmount()
|
||||
|
||||
const model = renderFormInputItem({
|
||||
schema: createSchema({ type: FormTypeEnum.modelSelector }),
|
||||
})
|
||||
fireEvent.click(screen.getByText('model-selector'))
|
||||
expect(model.onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: 'model-1',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should render the JSON editor and variable picker specialized branches', () => {
|
||||
const json = renderFormInputItem({
|
||||
schema: createSchema({ type: FormTypeEnum.object }),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: '{"enabled":false}',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
fireEvent.change(screen.getByLabelText('json-editor'), { target: { value: '{"enabled":true}' } })
|
||||
expect(json.onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: '{"enabled":true}',
|
||||
},
|
||||
})
|
||||
|
||||
json.unmount()
|
||||
|
||||
const picker = renderFormInputItem({
|
||||
schema: createSchema({ type: FormTypeEnum.file }),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: '',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('variable-picker'))
|
||||
expect(picker.onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.variable,
|
||||
value: ['node-2', 'asset'],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should render variable selectors for boolean variable inputs', () => {
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
_type: FormTypeEnum.boolean,
|
||||
type: FormTypeEnum.textInput,
|
||||
}),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.variable,
|
||||
value: ['node-3', 'flag'],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('variable-picker'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.variable,
|
||||
value: ['node-2', 'asset'],
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
import type { CredentialFormSchema, FormOption } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { Var } from '@/app/components/workflow/types'
|
||||
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { VarKindType } from '../../types'
|
||||
import {
|
||||
filterVisibleOptions,
|
||||
getCheckboxListOptions,
|
||||
getCheckboxListValue,
|
||||
getFilterVar,
|
||||
getFormInputState,
|
||||
getNumberInputValue,
|
||||
getSelectedLabels,
|
||||
getTargetVarType,
|
||||
getVarKindType,
|
||||
hasOptionIcon,
|
||||
mapSelectItems,
|
||||
normalizeVariableSelectorValue,
|
||||
} from '../form-input-item.helpers'
|
||||
|
||||
const createSchema = (
|
||||
overrides: Partial<CredentialFormSchema & {
|
||||
_type?: FormTypeEnum
|
||||
multiple?: boolean
|
||||
options?: FormOption[]
|
||||
}> = {},
|
||||
) => ({
|
||||
label: { en_US: 'Field', zh_Hans: '字段' },
|
||||
name: 'field',
|
||||
required: false,
|
||||
show_on: [],
|
||||
type: FormTypeEnum.textInput,
|
||||
variable: 'field',
|
||||
...overrides,
|
||||
}) as CredentialFormSchema & {
|
||||
_type?: FormTypeEnum
|
||||
multiple?: boolean
|
||||
options?: FormOption[]
|
||||
}
|
||||
|
||||
const createOption = (
|
||||
value: string,
|
||||
overrides: Partial<FormOption> = {},
|
||||
): FormOption => ({
|
||||
label: { en_US: value, zh_Hans: value },
|
||||
show_on: [],
|
||||
value,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('form-input-item helpers', () => {
|
||||
it('should derive field state and target var type', () => {
|
||||
const numberState = getFormInputState(
|
||||
createSchema({ type: FormTypeEnum.textNumber }),
|
||||
{ type: VarKindType.constant, value: 1 },
|
||||
)
|
||||
const filesState = getFormInputState(
|
||||
createSchema({ type: FormTypeEnum.files }),
|
||||
{ type: VarKindType.variable, value: ['node', 'files'] },
|
||||
)
|
||||
|
||||
expect(numberState.isNumber).toBe(true)
|
||||
expect(numberState.showTypeSwitch).toBe(true)
|
||||
expect(getTargetVarType(numberState)).toBe(VarType.number)
|
||||
expect(filesState.isFile).toBe(true)
|
||||
expect(filesState.showVariableSelector).toBe(true)
|
||||
expect(getTargetVarType(filesState)).toBe(VarType.arrayFile)
|
||||
})
|
||||
|
||||
it('should return filter functions and var kind types by schema mode', () => {
|
||||
const stringFilter = getFilterVar(getFormInputState(createSchema(), { type: VarKindType.mixed, value: '' }))
|
||||
const booleanState = getFormInputState(
|
||||
createSchema({ _type: FormTypeEnum.boolean, type: FormTypeEnum.textInput }),
|
||||
{ type: VarKindType.constant, value: true },
|
||||
)
|
||||
|
||||
expect(stringFilter?.({ type: VarType.secret } as Var)).toBe(true)
|
||||
expect(stringFilter?.({ type: VarType.file } as Var)).toBe(false)
|
||||
expect(getVarKindType(booleanState)).toBe(VarKindType.constant)
|
||||
expect(getFilterVar(booleanState)?.({ type: VarType.boolean } as Var)).toBe(false)
|
||||
|
||||
const fileState = getFormInputState(
|
||||
createSchema({ type: FormTypeEnum.file }),
|
||||
{ type: VarKindType.variable, value: ['node', 'file'] },
|
||||
)
|
||||
const objectState = getFormInputState(
|
||||
createSchema({ type: FormTypeEnum.object }),
|
||||
{ type: VarKindType.constant, value: '{}' },
|
||||
)
|
||||
const arrayState = getFormInputState(
|
||||
createSchema({ type: FormTypeEnum.array }),
|
||||
{ type: VarKindType.constant, value: '[]' },
|
||||
)
|
||||
const dynamicState = getFormInputState(
|
||||
createSchema({ type: FormTypeEnum.dynamicSelect }),
|
||||
{ type: VarKindType.constant, value: 'selected' },
|
||||
)
|
||||
|
||||
expect(getFilterVar(fileState)?.({ type: VarType.file } as Var)).toBe(true)
|
||||
expect(getFilterVar(objectState)?.({ type: VarType.object } as Var)).toBe(true)
|
||||
expect(getFilterVar(arrayState)?.({ type: VarType.arrayString } as Var)).toBe(true)
|
||||
expect(getVarKindType(fileState)).toBe(VarKindType.variable)
|
||||
expect(getVarKindType(dynamicState)).toBe(VarKindType.constant)
|
||||
expect(getVarKindType(getFormInputState(createSchema({ type: FormTypeEnum.appSelector }), undefined))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should filter and map visible options using show_on rules', () => {
|
||||
const options = [
|
||||
createOption('always'),
|
||||
createOption('premium', {
|
||||
show_on: [{ variable: 'mode', value: 'pro' }],
|
||||
}),
|
||||
]
|
||||
const values = {
|
||||
mode: {
|
||||
type: VarKindType.constant,
|
||||
value: 'pro',
|
||||
},
|
||||
}
|
||||
|
||||
const visibleOptions = filterVisibleOptions(options, values)
|
||||
expect(visibleOptions).toHaveLength(2)
|
||||
expect(mapSelectItems(visibleOptions, 'en_US')).toEqual([
|
||||
{ name: 'always', value: 'always' },
|
||||
{ name: 'premium', value: 'premium' },
|
||||
])
|
||||
expect(hasOptionIcon(visibleOptions)).toBe(false)
|
||||
})
|
||||
|
||||
it('should compute selected labels and checkbox state from visible options', () => {
|
||||
const options = [
|
||||
createOption('alpha'),
|
||||
createOption('beta'),
|
||||
createOption('gamma'),
|
||||
]
|
||||
|
||||
expect(getSelectedLabels(['alpha', 'beta'], options, 'en_US')).toBe('alpha, beta')
|
||||
expect(getSelectedLabels(['alpha', 'beta', 'gamma'], options, 'en_US')).toBe('3 selected')
|
||||
expect(getCheckboxListOptions(options, 'en_US')).toEqual([
|
||||
{ label: 'alpha', value: 'alpha' },
|
||||
{ label: 'beta', value: 'beta' },
|
||||
{ label: 'gamma', value: 'gamma' },
|
||||
])
|
||||
expect(getCheckboxListValue(['alpha', 'missing'], ['beta'], options)).toEqual(['alpha'])
|
||||
})
|
||||
|
||||
it('should normalize number and variable selector values', () => {
|
||||
expect(getNumberInputValue(Number.NaN)).toBe('')
|
||||
expect(getNumberInputValue(2)).toBe(2)
|
||||
expect(getNumberInputValue('3')).toBe('3')
|
||||
expect(getNumberInputValue(undefined)).toBe('')
|
||||
expect(normalizeVariableSelectorValue([])).toEqual([])
|
||||
expect(normalizeVariableSelectorValue(['node', 'answer'])).toEqual(['node', 'answer'])
|
||||
expect(normalizeVariableSelectorValue('')).toBe('')
|
||||
})
|
||||
|
||||
it('should derive remaining target variable types and label states', () => {
|
||||
const objectState = getFormInputState(createSchema({ type: FormTypeEnum.object }), undefined)
|
||||
const arrayState = getFormInputState(createSchema({ type: FormTypeEnum.array }), undefined)
|
||||
|
||||
expect(getTargetVarType(objectState)).toBe(VarType.object)
|
||||
expect(getTargetVarType(arrayState)).toBe(VarType.arrayObject)
|
||||
expect(getSelectedLabels(undefined, [], 'en_US')).toBe('')
|
||||
expect(getCheckboxListValue('alpha', [], [createOption('alpha')])).toEqual(['alpha'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
import { fireEvent, screen } from '@testing-library/react'
|
||||
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import {
|
||||
JsonEditorField,
|
||||
MultiSelectField,
|
||||
} from '../form-input-item.sections'
|
||||
|
||||
describe('form-input-item sections', () => {
|
||||
it('should render a loading multi-select label', () => {
|
||||
renderWorkflowComponent(
|
||||
<MultiSelectField
|
||||
disabled={false}
|
||||
isLoading
|
||||
items={[{ name: 'Alpha', value: 'alpha' }]}
|
||||
onChange={vi.fn()}
|
||||
selectedLabel=""
|
||||
value={[]}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render the shared json editor section', () => {
|
||||
renderWorkflowComponent(
|
||||
<JsonEditorField
|
||||
value={'{"enabled":true}'}
|
||||
onChange={vi.fn()}
|
||||
placeholder={<div>JSON placeholder</div>}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('JSON')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render placeholder, icons, and select multi-select options', () => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
renderWorkflowComponent(
|
||||
<MultiSelectField
|
||||
disabled={false}
|
||||
items={[
|
||||
{ name: 'Alpha', value: 'alpha', icon: '/alpha.svg' },
|
||||
{ name: 'Beta', value: 'beta' },
|
||||
]}
|
||||
onChange={onChange}
|
||||
placeholder="Choose options"
|
||||
selectedLabel=""
|
||||
value={[]}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Choose options')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
fireEvent.click(screen.getByText('Alpha'))
|
||||
|
||||
expect(document.querySelector('img[src="/alpha.svg"]')).toBeInTheDocument()
|
||||
expect(onChange).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { CredentialFormSchema, FormOption } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { fireEvent, screen } from '@testing-library/react'
|
||||
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { VarKindType } from '../../types'
|
||||
import FormInputItem from '../form-input-item'
|
||||
|
||||
const createSchema = (
|
||||
overrides: Partial<CredentialFormSchema & {
|
||||
_type?: FormTypeEnum
|
||||
multiple?: boolean
|
||||
options?: FormOption[]
|
||||
}> = {},
|
||||
) => ({
|
||||
label: { en_US: 'Field', zh_Hans: '字段' },
|
||||
name: 'field',
|
||||
required: false,
|
||||
show_on: [],
|
||||
type: FormTypeEnum.textInput,
|
||||
variable: 'field',
|
||||
...overrides,
|
||||
}) as CredentialFormSchema & {
|
||||
_type?: FormTypeEnum
|
||||
multiple?: boolean
|
||||
options?: FormOption[]
|
||||
}
|
||||
|
||||
const createOption = (
|
||||
value: string,
|
||||
overrides: Partial<FormOption> = {},
|
||||
): FormOption => ({
|
||||
label: { en_US: value, zh_Hans: value },
|
||||
show_on: [],
|
||||
value,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderFormInputItem = (props: Partial<ComponentProps<typeof FormInputItem>> = {}) => {
|
||||
const onChange = vi.fn()
|
||||
renderWorkflowFlowComponent(
|
||||
<FormInputItem
|
||||
readOnly={false}
|
||||
nodeId="node-1"
|
||||
schema={createSchema()}
|
||||
value={{
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: '',
|
||||
},
|
||||
}}
|
||||
onChange={onChange}
|
||||
{...props}
|
||||
/>,
|
||||
{
|
||||
edges: [],
|
||||
hooksStoreProps: {},
|
||||
nodes: [],
|
||||
},
|
||||
)
|
||||
|
||||
return { onChange }
|
||||
}
|
||||
|
||||
describe('FormInputItem', () => {
|
||||
it('should parse number inputs as numbers', () => {
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({ type: FormTypeEnum.textNumber }),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '3.5' } })
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: 3.5,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should toggle boolean fields using the shared boolean input', () => {
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
_type: FormTypeEnum.boolean,
|
||||
type: FormTypeEnum.textInput,
|
||||
}),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('False'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: false,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should filter checkbox options by show_on and update selected values', () => {
|
||||
const { onChange } = renderFormInputItem({
|
||||
schema: createSchema({
|
||||
_type: FormTypeEnum.checkbox,
|
||||
options: [
|
||||
createOption('basic'),
|
||||
createOption('pro', {
|
||||
show_on: [{ variable: 'mode', value: 'pro' }],
|
||||
}),
|
||||
],
|
||||
type: FormTypeEnum.textInput,
|
||||
}),
|
||||
value: {
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: ['basic'],
|
||||
},
|
||||
mode: {
|
||||
type: VarKindType.constant,
|
||||
value: 'pro',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('pro'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
field: {
|
||||
type: VarKindType.constant,
|
||||
value: ['basic', 'pro'],
|
||||
},
|
||||
mode: {
|
||||
type: VarKindType.constant,
|
||||
value: 'pro',
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,6 @@ import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Agent } from '@/app/components/base/icons/src/vender/workflow'
|
||||
import ListEmpty from '@/app/components/base/list-empty'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldControls,
|
||||
@@ -18,6 +17,7 @@ import {
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/app/components/base/ui/number-field'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
import { FormTypeEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
|
||||
import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'
|
||||
@@ -147,10 +147,11 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
|
||||
<div className="flex w-[200px] items-center gap-3">
|
||||
<Slider
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onValueChange={onChange}
|
||||
className="w-full"
|
||||
min={def.min}
|
||||
max={def.max}
|
||||
aria-label={renderI18nObject(def.label)}
|
||||
/>
|
||||
<NumberField
|
||||
value={value}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { InputVar } from '@/app/components/workflow/types'
|
||||
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
|
||||
import { TransferMethod } from '@/types/app'
|
||||
import {
|
||||
buildSubmitData,
|
||||
formatValue,
|
||||
getFormErrorMessage,
|
||||
isFilesLoaded,
|
||||
shouldAutoRunBeforeRunForm,
|
||||
shouldAutoShowGeneratedForm,
|
||||
} from '../helpers'
|
||||
|
||||
type FormArg = Parameters<typeof buildSubmitData>[0][number]
|
||||
|
||||
describe('before-run-form helpers', () => {
|
||||
const createValues = (values: Record<string, unknown>) => values as unknown as Record<string, string>
|
||||
const createInput = (input: Partial<InputVar>): InputVar => ({
|
||||
variable: 'field',
|
||||
label: 'Field',
|
||||
type: InputVarType.textInput,
|
||||
required: false,
|
||||
...input,
|
||||
})
|
||||
const createForm = (form: Partial<FormArg>): FormArg => ({
|
||||
inputs: [],
|
||||
values: createValues({}),
|
||||
onChange: vi.fn(),
|
||||
...form,
|
||||
} as FormArg)
|
||||
|
||||
it('should format values by input type', () => {
|
||||
expect(formatValue('12.5', InputVarType.number)).toBe(12.5)
|
||||
expect(formatValue('{"foo":1}', InputVarType.json)).toEqual({ foo: 1 })
|
||||
expect(formatValue('', InputVarType.checkbox)).toBe(false)
|
||||
expect(formatValue(['{"foo":1}'], InputVarType.contexts)).toEqual([{ foo: 1 }])
|
||||
expect(formatValue(null, InputVarType.singleFile)).toBeNull()
|
||||
expect(formatValue([{ transfer_method: TransferMethod.remote_url, related_id: '3' }], InputVarType.singleFile)).toEqual(expect.any(Array))
|
||||
expect(formatValue('', InputVarType.singleFile)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should detect when file uploads are still in progress', () => {
|
||||
expect(isFilesLoaded([])).toBe(true)
|
||||
expect(isFilesLoaded([createForm({ inputs: [], values: {} })])).toBe(true)
|
||||
expect(isFilesLoaded([createForm({
|
||||
inputs: [],
|
||||
values: createValues({
|
||||
'#files#': [{ transfer_method: TransferMethod.local_file }],
|
||||
}),
|
||||
})])).toBe(false)
|
||||
})
|
||||
|
||||
it('should report required and uploading file errors', () => {
|
||||
const t = (key: string, options?: Record<string, unknown>) => `${key}:${options?.field ?? ''}`
|
||||
|
||||
expect(getFormErrorMessage([createForm({
|
||||
inputs: [createInput({ variable: 'query', label: 'Query', required: true })],
|
||||
values: createValues({ query: '' }),
|
||||
})], [{}], t)).toContain('errorMsg.fieldRequired')
|
||||
|
||||
expect(getFormErrorMessage([createForm({
|
||||
inputs: [createInput({ variable: 'file', label: 'File', type: InputVarType.singleFile })],
|
||||
values: createValues({ file: { transferMethod: TransferMethod.local_file } }),
|
||||
})], [{}], t)).toContain('errorMessage.waitForFileUpload')
|
||||
|
||||
expect(getFormErrorMessage([createForm({
|
||||
inputs: [createInput({ variable: 'files', label: 'Files', type: InputVarType.multiFiles })],
|
||||
values: createValues({ files: [{ transferMethod: TransferMethod.local_file }] }),
|
||||
})], [{}], t)).toContain('errorMessage.waitForFileUpload')
|
||||
|
||||
expect(getFormErrorMessage([createForm({
|
||||
inputs: [createInput({
|
||||
variable: 'config',
|
||||
label: { nodeType: BlockEnum.Tool, nodeName: 'Tool', variable: 'Config' },
|
||||
required: true,
|
||||
})],
|
||||
values: createValues({ config: '' }),
|
||||
})], [{}], t)).toContain('Config')
|
||||
})
|
||||
|
||||
it('should build submit data and keep parse errors', () => {
|
||||
expect(buildSubmitData([createForm({
|
||||
inputs: [createInput({ variable: 'query' })],
|
||||
values: createValues({ query: 'hello' }),
|
||||
})])).toEqual({
|
||||
submitData: { query: 'hello' },
|
||||
parseErrorJsonField: '',
|
||||
})
|
||||
|
||||
expect(buildSubmitData([createForm({
|
||||
inputs: [createInput({ variable: 'payload', type: InputVarType.json })],
|
||||
values: createValues({ payload: '{' }),
|
||||
})]).parseErrorJsonField).toBe('payload')
|
||||
|
||||
expect(buildSubmitData([createForm({
|
||||
inputs: [
|
||||
createInput({ variable: 'files', type: InputVarType.multiFiles }),
|
||||
createInput({ variable: 'file', type: InputVarType.singleFile }),
|
||||
],
|
||||
values: createValues({
|
||||
files: [{ transfer_method: TransferMethod.remote_url, related_id: '1' }],
|
||||
file: { transfer_method: TransferMethod.remote_url, related_id: '2' },
|
||||
}),
|
||||
})]).submitData).toEqual(expect.objectContaining({
|
||||
files: expect.any(Array),
|
||||
file: expect.any(Object),
|
||||
}))
|
||||
})
|
||||
|
||||
it('should derive the zero-form auto behaviors', () => {
|
||||
expect(shouldAutoRunBeforeRunForm([], false)).toBe(true)
|
||||
expect(shouldAutoRunBeforeRunForm([], true)).toBe(false)
|
||||
expect(shouldAutoShowGeneratedForm([], true)).toBe(true)
|
||||
expect(shouldAutoShowGeneratedForm([createForm({})], true)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { Props as FormProps } from '../form'
|
||||
import type { BeforeRunFormProps } from '../index'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { toast } from '@/app/components/base/ui/toast'
|
||||
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
|
||||
import BeforeRunForm from '../index'
|
||||
|
||||
vi.mock('@/app/components/base/ui/toast', () => ({
|
||||
toast: {
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../form', () => ({
|
||||
default: ({ values }: { values: Record<string, unknown> }) => <div>{Object.keys(values).join(',')}</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../panel-wrap', () => ({
|
||||
default: ({ children, nodeName }: { children: React.ReactNode, nodeName: string }) => (
|
||||
<div>
|
||||
<div>{nodeName}</div>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/human-input/components/single-run-form', () => ({
|
||||
default: ({ onSubmit, handleBack }: { onSubmit: (data: Record<string, unknown>) => void, handleBack?: () => void }) => (
|
||||
<div>
|
||||
<div>single-run-form</div>
|
||||
<button onClick={() => onSubmit({ approved: true })}>submit-generated-form</button>
|
||||
<button onClick={handleBack}>back-generated-form</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('BeforeRunForm', () => {
|
||||
const mockToastError = vi.mocked(toast.error)
|
||||
|
||||
const createForm = (form: Partial<FormProps>): FormProps => ({
|
||||
inputs: [],
|
||||
values: {},
|
||||
onChange: vi.fn(),
|
||||
...form,
|
||||
})
|
||||
const createProps = (props: Partial<BeforeRunFormProps>): BeforeRunFormProps => ({
|
||||
nodeName: 'Tool',
|
||||
onHide: vi.fn(),
|
||||
onRun: vi.fn(),
|
||||
onStop: vi.fn(),
|
||||
runningStatus: 'idle' as BeforeRunFormProps['runningStatus'],
|
||||
forms: [],
|
||||
filteredExistVarForms: [],
|
||||
existVarValuesInForms: [],
|
||||
...props,
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should auto run and render nothing when there are no filtered forms', () => {
|
||||
const onRun = vi.fn()
|
||||
const { container } = render(
|
||||
<BeforeRunForm
|
||||
{...createProps({
|
||||
onRun,
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(onRun).toHaveBeenCalledWith({})
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('should show an error toast when required fields are missing', () => {
|
||||
render(
|
||||
<BeforeRunForm
|
||||
{...createProps({
|
||||
forms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: '' },
|
||||
})],
|
||||
filteredExistVarForms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: '' },
|
||||
})],
|
||||
existVarValuesInForms: [{}],
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))
|
||||
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should generate the human input form instead of running immediately', () => {
|
||||
const handleShowGeneratedForm = vi.fn()
|
||||
|
||||
render(
|
||||
<BeforeRunForm
|
||||
{...createProps({
|
||||
nodeName: 'Human input',
|
||||
nodeType: BlockEnum.HumanInput,
|
||||
forms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: 'hello' },
|
||||
})],
|
||||
filteredExistVarForms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: 'hello' },
|
||||
})],
|
||||
existVarValuesInForms: [{}],
|
||||
handleShowGeneratedForm,
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.humanInput.singleRun.button' }))
|
||||
|
||||
expect(handleShowGeneratedForm).toHaveBeenCalledWith({ query: 'hello' })
|
||||
})
|
||||
|
||||
it('should render the generated human input form and submit it', async () => {
|
||||
const handleSubmitHumanInputForm = vi.fn().mockResolvedValue(undefined)
|
||||
const handleAfterHumanInputStepRun = vi.fn()
|
||||
const handleHideGeneratedForm = vi.fn()
|
||||
|
||||
render(
|
||||
<BeforeRunForm
|
||||
{...createProps({
|
||||
nodeName: 'Human input',
|
||||
nodeType: BlockEnum.HumanInput,
|
||||
forms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: 'hello' },
|
||||
})],
|
||||
filteredExistVarForms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: 'hello' },
|
||||
})],
|
||||
existVarValuesInForms: [{}],
|
||||
showGeneratedForm: true,
|
||||
formData: {} as BeforeRunFormProps['formData'],
|
||||
handleSubmitHumanInputForm,
|
||||
handleAfterHumanInputStepRun,
|
||||
handleHideGeneratedForm,
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('single-run-form')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByText('submit-generated-form'))
|
||||
|
||||
await Promise.resolve()
|
||||
expect(handleSubmitHumanInputForm).toHaveBeenCalledWith({ approved: true })
|
||||
expect(handleAfterHumanInputStepRun).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.click(screen.getByText('back-generated-form'))
|
||||
expect(handleHideGeneratedForm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should run immediately when the form is valid', () => {
|
||||
const onRun = vi.fn()
|
||||
|
||||
render(
|
||||
<BeforeRunForm
|
||||
{...createProps({
|
||||
onRun,
|
||||
forms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: 'hello' },
|
||||
})],
|
||||
filteredExistVarForms: [createForm({
|
||||
inputs: [{ variable: 'query', label: 'Query', type: InputVarType.textInput, required: true }],
|
||||
values: { query: 'hello' },
|
||||
})],
|
||||
existVarValuesInForms: [{}],
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))
|
||||
|
||||
expect(onRun).toHaveBeenCalledWith({ query: 'hello' })
|
||||
})
|
||||
|
||||
it('should auto show the generated form when human input has no filtered vars', () => {
|
||||
const handleShowGeneratedForm = vi.fn()
|
||||
render(
|
||||
<BeforeRunForm
|
||||
{...createProps({
|
||||
nodeName: 'Human input',
|
||||
nodeType: BlockEnum.HumanInput,
|
||||
handleShowGeneratedForm,
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(handleShowGeneratedForm).toHaveBeenCalledWith({})
|
||||
expect(screen.getByRole('button', { name: 'workflow.nodes.humanInput.singleRun.button' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show an error toast when json input is invalid', () => {
|
||||
render(
|
||||
<BeforeRunForm
|
||||
{...createProps({
|
||||
forms: [createForm({
|
||||
inputs: [{ variable: 'payload', label: 'Payload', type: InputVarType.json, required: true }],
|
||||
values: { payload: '{' },
|
||||
})],
|
||||
filteredExistVarForms: [createForm({
|
||||
inputs: [{ variable: 'payload', label: 'Payload', type: InputVarType.json, required: true }],
|
||||
values: { payload: '{' },
|
||||
})],
|
||||
existVarValuesInForms: [{}],
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))
|
||||
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { Props as FormProps } from './form'
|
||||
import type { FileEntity } from '@/app/components/base/file-uploader/types'
|
||||
import { getProcessedFiles } from '@/app/components/base/file-uploader/utils'
|
||||
import { InputVarType } from '@/app/components/workflow/types'
|
||||
import { TransferMethod } from '@/types/app'
|
||||
|
||||
export function formatValue(value: unknown, type: InputVarType) {
|
||||
if (type === InputVarType.checkbox)
|
||||
return !!value
|
||||
if (value === undefined || value === null)
|
||||
return value
|
||||
if (type === InputVarType.number)
|
||||
return Number.parseFloat(String(value))
|
||||
if (type === InputVarType.json)
|
||||
return JSON.parse(String(value))
|
||||
if (type === InputVarType.contexts)
|
||||
return (value as string[]).map(item => JSON.parse(item))
|
||||
if (type === InputVarType.multiFiles)
|
||||
return getProcessedFiles(value as FileEntity[])
|
||||
|
||||
if (type === InputVarType.singleFile) {
|
||||
if (Array.isArray(value))
|
||||
return getProcessedFiles(value as FileEntity[])
|
||||
if (!value)
|
||||
return undefined
|
||||
return getProcessedFiles([value as FileEntity])[0]
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
export const isFilesLoaded = (forms: FormProps[]) => {
|
||||
if (!forms.length)
|
||||
return true
|
||||
|
||||
const filesForm = forms.find(item => !!item.values['#files#'])
|
||||
if (!filesForm)
|
||||
return true
|
||||
|
||||
const files = filesForm.values['#files#'] as unknown as Array<{ transfer_method?: TransferMethod, upload_file_id?: string }> | undefined
|
||||
return !files?.some(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)
|
||||
}
|
||||
|
||||
export const getFormErrorMessage = (
|
||||
forms: FormProps[],
|
||||
existVarValuesInForms: Record<string, unknown>[],
|
||||
t: (key: string, options?: Record<string, unknown>) => string,
|
||||
) => {
|
||||
let errMsg = ''
|
||||
|
||||
forms.forEach((form, index) => {
|
||||
const existVarValuesInForm = existVarValuesInForms[index]
|
||||
|
||||
form.inputs.forEach((input) => {
|
||||
const value = form.values[input.variable] as unknown
|
||||
const missingRequired = input.required
|
||||
&& input.type !== InputVarType.checkbox
|
||||
&& !(input.variable in existVarValuesInForm)
|
||||
&& (value === '' || value === undefined || value === null || (input.type === InputVarType.files && Array.isArray(value) && value.length === 0))
|
||||
|
||||
if (!errMsg && missingRequired) {
|
||||
errMsg = t('errorMsg.fieldRequired', { ns: 'workflow', field: typeof input.label === 'object' ? input.label.variable : input.label })
|
||||
return
|
||||
}
|
||||
|
||||
if (!errMsg && (input.type === InputVarType.singleFile || input.type === InputVarType.multiFiles) && value) {
|
||||
const fileIsUploading = Array.isArray(value)
|
||||
? value.find((item: { transferMethod?: TransferMethod, uploadedId?: string }) => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
|
||||
: (value as { transferMethod?: TransferMethod, uploadedId?: string }).transferMethod === TransferMethod.local_file
|
||||
&& !(value as { transferMethod?: TransferMethod, uploadedId?: string }).uploadedId
|
||||
|
||||
if (fileIsUploading)
|
||||
errMsg = t('errorMessage.waitForFileUpload', { ns: 'appDebug' })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return errMsg
|
||||
}
|
||||
|
||||
export const buildSubmitData = (forms: FormProps[]) => {
|
||||
const submitData: Record<string, unknown> = {}
|
||||
let parseErrorJsonField = ''
|
||||
|
||||
forms.forEach((form) => {
|
||||
form.inputs.forEach((input) => {
|
||||
try {
|
||||
submitData[input.variable] = formatValue(form.values[input.variable], input.type)
|
||||
}
|
||||
catch {
|
||||
parseErrorJsonField = input.variable
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return { submitData, parseErrorJsonField }
|
||||
}
|
||||
|
||||
export const shouldAutoRunBeforeRunForm = (filteredExistVarForms: FormProps[], isHumanInput: boolean) => {
|
||||
return filteredExistVarForms.length === 0 && !isHumanInput
|
||||
}
|
||||
|
||||
export const shouldAutoShowGeneratedForm = (filteredExistVarForms: FormProps[], isHumanInput: boolean) => {
|
||||
return filteredExistVarForms.length === 0 && isHumanInput
|
||||
}
|
||||
@@ -9,14 +9,19 @@ import * as React from 'react'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Button from '@/app/components/base/button'
|
||||
import { getProcessedFiles } from '@/app/components/base/file-uploader/utils'
|
||||
import { toast } from '@/app/components/base/ui/toast'
|
||||
import Split from '@/app/components/workflow/nodes/_base/components/split'
|
||||
import SingleRunForm from '@/app/components/workflow/nodes/human-input/components/single-run-form'
|
||||
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
|
||||
import { TransferMethod } from '@/types/app'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import Form from './form'
|
||||
import {
|
||||
buildSubmitData,
|
||||
getFormErrorMessage,
|
||||
isFilesLoaded,
|
||||
shouldAutoRunBeforeRunForm,
|
||||
shouldAutoShowGeneratedForm,
|
||||
} from './helpers'
|
||||
import PanelWrap from './panel-wrap'
|
||||
|
||||
const i18nPrefix = 'singleRun'
|
||||
@@ -41,33 +46,6 @@ export type BeforeRunFormProps = {
|
||||
handleAfterHumanInputStepRun?: () => void
|
||||
} & Partial<SpecialResultPanelProps>
|
||||
|
||||
function formatValue(value: string | any, type: InputVarType) {
|
||||
if (type === InputVarType.checkbox)
|
||||
return !!value
|
||||
if (value === undefined || value === null)
|
||||
return value
|
||||
if (type === InputVarType.number)
|
||||
return Number.parseFloat(value)
|
||||
if (type === InputVarType.json)
|
||||
return JSON.parse(value)
|
||||
if (type === InputVarType.contexts) {
|
||||
return value.map((item: any) => {
|
||||
return JSON.parse(item)
|
||||
})
|
||||
}
|
||||
if (type === InputVarType.multiFiles)
|
||||
return getProcessedFiles(value)
|
||||
|
||||
if (type === InputVarType.singleFile) {
|
||||
if (Array.isArray(value))
|
||||
return getProcessedFiles(value)
|
||||
if (!value)
|
||||
return undefined
|
||||
return getProcessedFiles([value])[0]
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
const BeforeRunForm: FC<BeforeRunFormProps> = ({
|
||||
nodeName,
|
||||
nodeType,
|
||||
@@ -88,61 +66,16 @@ const BeforeRunForm: FC<BeforeRunFormProps> = ({
|
||||
const isHumanInput = nodeType === BlockEnum.HumanInput
|
||||
const showBackButton = filteredExistVarForms.length > 0
|
||||
|
||||
const isFileLoaded = (() => {
|
||||
if (!forms || forms.length === 0)
|
||||
return true
|
||||
// system files
|
||||
const filesForm = forms.find(item => !!item.values['#files#'])
|
||||
if (!filesForm)
|
||||
return true
|
||||
|
||||
const files = filesForm.values['#files#'] as any
|
||||
if (files?.some((item: any) => item.transfer_method === TransferMethod.local_file && !item.upload_file_id))
|
||||
return false
|
||||
|
||||
return true
|
||||
})()
|
||||
const isFileLoaded = isFilesLoaded(forms)
|
||||
|
||||
const handleRunOrGenerateForm = () => {
|
||||
let errMsg = ''
|
||||
forms.forEach((form, i) => {
|
||||
const existVarValuesInForm = existVarValuesInForms[i]
|
||||
|
||||
form.inputs.forEach((input) => {
|
||||
const value = form.values[input.variable] as any
|
||||
if (!errMsg && input.required && (input.type !== InputVarType.checkbox) && !(input.variable in existVarValuesInForm) && (value === '' || value === undefined || value === null || (input.type === InputVarType.files && value.length === 0)))
|
||||
errMsg = t('errorMsg.fieldRequired', { ns: 'workflow', field: typeof input.label === 'object' ? input.label.variable : input.label })
|
||||
|
||||
if (!errMsg && (input.type === InputVarType.singleFile || input.type === InputVarType.multiFiles) && value) {
|
||||
let fileIsUploading = false
|
||||
if (Array.isArray(value))
|
||||
fileIsUploading = value.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
|
||||
else
|
||||
fileIsUploading = value.transferMethod === TransferMethod.local_file && !value.uploadedId
|
||||
|
||||
if (fileIsUploading)
|
||||
errMsg = t('errorMessage.waitForFileUpload', { ns: 'appDebug' })
|
||||
}
|
||||
})
|
||||
})
|
||||
const errMsg = getFormErrorMessage(forms, existVarValuesInForms, t)
|
||||
if (errMsg) {
|
||||
toast.error(errMsg)
|
||||
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 {
|
||||
parseErrorJsonField = input.variable
|
||||
}
|
||||
})
|
||||
})
|
||||
const { submitData, parseErrorJsonField } = buildSubmitData(forms)
|
||||
if (parseErrorJsonField) {
|
||||
toast.error(t('errorMsg.invalidJson', { ns: 'workflow', field: parseErrorJsonField }))
|
||||
return
|
||||
@@ -165,13 +98,13 @@ const BeforeRunForm: FC<BeforeRunFormProps> = ({
|
||||
if (hasRun.current)
|
||||
return
|
||||
hasRun.current = true
|
||||
if (filteredExistVarForms.length === 0 && !isHumanInput)
|
||||
if (shouldAutoRunBeforeRunForm(filteredExistVarForms, isHumanInput))
|
||||
onRun({})
|
||||
if (filteredExistVarForms.length === 0 && isHumanInput)
|
||||
if (shouldAutoShowGeneratedForm(filteredExistVarForms, isHumanInput))
|
||||
handleShowGeneratedForm?.({})
|
||||
}, [filteredExistVarForms, handleShowGeneratedForm, isHumanInput, onRun])
|
||||
|
||||
if (filteredExistVarForms.length === 0 && !isHumanInput)
|
||||
if (shouldAutoRunBeforeRunForm(filteredExistVarForms, isHumanInput))
|
||||
return null
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
'use client'
|
||||
|
||||
import type { ResourceVarInputs } from '../types'
|
||||
import type {
|
||||
CredentialFormSchema,
|
||||
FormOption,
|
||||
TypeWithI18N,
|
||||
} from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { VarKindType } from '../types'
|
||||
|
||||
type FormInputSchema = CredentialFormSchema & Partial<{
|
||||
_type: FormTypeEnum
|
||||
multiple: boolean
|
||||
options: FormOption[]
|
||||
placeholder: TypeWithI18N
|
||||
scope: string
|
||||
}>
|
||||
|
||||
type FormInputValue = ResourceVarInputs[string] | undefined
|
||||
|
||||
type ShowOnCondition = {
|
||||
value: unknown
|
||||
variable: string
|
||||
}
|
||||
|
||||
type OptionLabel = string | TypeWithI18N
|
||||
|
||||
type SelectableOption = {
|
||||
icon?: string
|
||||
label: OptionLabel
|
||||
show_on?: ShowOnCondition[]
|
||||
value: string
|
||||
}
|
||||
|
||||
export type SelectItem = {
|
||||
icon?: string
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export type FormInputState = {
|
||||
defaultValue: unknown
|
||||
isAppSelector: boolean
|
||||
isArray: boolean
|
||||
isBoolean: boolean
|
||||
isCheckbox: boolean
|
||||
isConstant: boolean
|
||||
isDynamicSelect: boolean
|
||||
isFile: boolean
|
||||
isFiles: boolean
|
||||
isModelSelector: boolean
|
||||
isMultipleSelect: boolean
|
||||
isNumber: boolean
|
||||
isObject: boolean
|
||||
isSelect: boolean
|
||||
isShowJSONEditor: boolean
|
||||
isString: boolean
|
||||
options: FormOption[]
|
||||
placeholder?: TypeWithI18N
|
||||
scope?: string
|
||||
showVariableSelector: boolean
|
||||
showTypeSwitch: boolean
|
||||
variable: string
|
||||
}
|
||||
|
||||
const optionMatchesValue = (
|
||||
values: ResourceVarInputs,
|
||||
showOnItem: ShowOnCondition,
|
||||
) => values[showOnItem.variable]?.value === showOnItem.value || values[showOnItem.variable] === showOnItem.value
|
||||
|
||||
const getOptionLabel = (option: SelectableOption, language: string) => {
|
||||
if (typeof option.label === 'string')
|
||||
return option.label
|
||||
|
||||
return option.label[language] || option.label.en_US || option.value
|
||||
}
|
||||
|
||||
export const getFormInputState = (
|
||||
schema: FormInputSchema,
|
||||
varInput: FormInputValue,
|
||||
): FormInputState => {
|
||||
const {
|
||||
default: defaultValue,
|
||||
multiple = false,
|
||||
options = [],
|
||||
placeholder,
|
||||
scope,
|
||||
type,
|
||||
variable,
|
||||
_type,
|
||||
} = schema
|
||||
|
||||
const isString = type === FormTypeEnum.textInput || type === FormTypeEnum.secretInput
|
||||
const isNumber = type === FormTypeEnum.textNumber
|
||||
const isObject = type === FormTypeEnum.object
|
||||
const isArray = type === FormTypeEnum.array
|
||||
const isShowJSONEditor = isObject || isArray
|
||||
const isFile = type === FormTypeEnum.file || type === FormTypeEnum.files
|
||||
const isFiles = type === FormTypeEnum.files
|
||||
const isBoolean = _type === FormTypeEnum.boolean
|
||||
const isCheckbox = _type === FormTypeEnum.checkbox
|
||||
const isSelect = type === FormTypeEnum.select
|
||||
const isDynamicSelect = type === FormTypeEnum.dynamicSelect
|
||||
const isAppSelector = type === FormTypeEnum.appSelector
|
||||
const isModelSelector = type === FormTypeEnum.modelSelector
|
||||
const showTypeSwitch = isNumber || isBoolean || isObject || isArray || isSelect
|
||||
const isConstant = varInput?.type === VarKindType.constant || !varInput?.type
|
||||
const showVariableSelector = isFile || varInput?.type === VarKindType.variable
|
||||
const isMultipleSelect = multiple && (isSelect || isDynamicSelect)
|
||||
|
||||
return {
|
||||
defaultValue,
|
||||
isAppSelector,
|
||||
isArray,
|
||||
isBoolean,
|
||||
isCheckbox,
|
||||
isConstant,
|
||||
isDynamicSelect,
|
||||
isFile,
|
||||
isFiles,
|
||||
isModelSelector,
|
||||
isMultipleSelect,
|
||||
isNumber,
|
||||
isObject,
|
||||
isSelect,
|
||||
isShowJSONEditor,
|
||||
isString,
|
||||
options,
|
||||
placeholder,
|
||||
scope,
|
||||
showTypeSwitch,
|
||||
showVariableSelector,
|
||||
variable,
|
||||
}
|
||||
}
|
||||
|
||||
export const getTargetVarType = (state: FormInputState) => {
|
||||
if (state.isString)
|
||||
return VarType.string
|
||||
if (state.isNumber)
|
||||
return VarType.number
|
||||
if (state.isFile)
|
||||
return state.isFiles ? VarType.arrayFile : VarType.file
|
||||
if (state.isSelect)
|
||||
return VarType.string
|
||||
if (state.isBoolean)
|
||||
return VarType.boolean
|
||||
if (state.isObject)
|
||||
return VarType.object
|
||||
if (state.isArray)
|
||||
return VarType.arrayObject
|
||||
return VarType.string
|
||||
}
|
||||
|
||||
export const getFilterVar = (state: FormInputState) => {
|
||||
if (state.isNumber)
|
||||
return (varPayload: Var) => varPayload.type === VarType.number
|
||||
if (state.isString)
|
||||
return (varPayload: Var) => [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
|
||||
if (state.isFile)
|
||||
return (varPayload: Var) => [VarType.file, VarType.arrayFile].includes(varPayload.type)
|
||||
if (state.isBoolean)
|
||||
return (varPayload: Var) => varPayload.type === VarType.boolean
|
||||
if (state.isObject)
|
||||
return (varPayload: Var) => varPayload.type === VarType.object
|
||||
if (state.isArray)
|
||||
return (varPayload: Var) => [VarType.array, VarType.arrayString, VarType.arrayNumber, VarType.arrayObject].includes(varPayload.type)
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const getVarKindType = (state: FormInputState) => {
|
||||
if (state.isFile)
|
||||
return VarKindType.variable
|
||||
if (state.isSelect || state.isDynamicSelect || state.isBoolean || state.isNumber || state.isArray || state.isObject)
|
||||
return VarKindType.constant
|
||||
if (state.isString)
|
||||
return VarKindType.mixed
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const filterVisibleOptions = (
|
||||
options: SelectableOption[],
|
||||
values: ResourceVarInputs,
|
||||
) => options.filter((option) => {
|
||||
if (option.show_on?.length)
|
||||
return option.show_on.every(showOnItem => optionMatchesValue(values, showOnItem))
|
||||
return true
|
||||
})
|
||||
|
||||
export const mapSelectItems = (
|
||||
options: SelectableOption[],
|
||||
language: string,
|
||||
): SelectItem[] => options.map(option => ({
|
||||
icon: option.icon,
|
||||
name: getOptionLabel(option, language),
|
||||
value: option.value,
|
||||
}))
|
||||
|
||||
export const hasOptionIcon = (options: SelectableOption[]) => options.some(option => !!option.icon)
|
||||
|
||||
export const getSelectedLabels = (
|
||||
selectedValues: string[] | undefined,
|
||||
options: SelectableOption[],
|
||||
language: string,
|
||||
) => {
|
||||
if (!selectedValues?.length)
|
||||
return ''
|
||||
|
||||
const selectedOptions = options.filter(option => selectedValues.includes(option.value))
|
||||
if (selectedOptions.length <= 2) {
|
||||
return selectedOptions
|
||||
.map(option => getOptionLabel(option, language))
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
return `${selectedOptions.length} selected`
|
||||
}
|
||||
|
||||
export const getCheckboxListOptions = (
|
||||
options: SelectableOption[],
|
||||
language: string,
|
||||
) => options.map(option => ({
|
||||
label: getOptionLabel(option, language),
|
||||
value: option.value,
|
||||
}))
|
||||
|
||||
export const getCheckboxListValue = (
|
||||
currentValue: unknown,
|
||||
defaultValue: unknown,
|
||||
availableOptions: SelectableOption[],
|
||||
) => {
|
||||
let current: string[] = []
|
||||
|
||||
if (Array.isArray(currentValue))
|
||||
current = currentValue as string[]
|
||||
else if (typeof currentValue === 'string')
|
||||
current = [currentValue]
|
||||
else if (Array.isArray(defaultValue))
|
||||
current = defaultValue as string[]
|
||||
|
||||
const allowedValues = new Set(availableOptions.map(option => option.value))
|
||||
return current.filter(item => allowedValues.has(item))
|
||||
}
|
||||
|
||||
export const getNumberInputValue = (currentValue: unknown): number | string => {
|
||||
if (typeof currentValue === 'number')
|
||||
return Number.isNaN(currentValue) ? '' : currentValue
|
||||
|
||||
if (typeof currentValue === 'string')
|
||||
return currentValue
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
export const normalizeVariableSelectorValue = (value: ValueSelector | string) =>
|
||||
value || ''
|
||||
@@ -0,0 +1,129 @@
|
||||
'use client'
|
||||
|
||||
import type { FC, ReactElement } from 'react'
|
||||
import type { SelectItem } from './form-input-item.helpers'
|
||||
import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import { RiCheckLine, RiLoader4Line } from '@remixicon/react'
|
||||
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
|
||||
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
|
||||
import { cn } from '@/utils/classnames'
|
||||
|
||||
type MultiSelectFieldProps = {
|
||||
disabled: boolean
|
||||
isLoading?: boolean
|
||||
items: SelectItem[]
|
||||
onChange: (value: string[]) => void
|
||||
placeholder?: string
|
||||
selectedLabel: string
|
||||
value: string[]
|
||||
}
|
||||
|
||||
const LoadingIndicator = () => (
|
||||
<RiLoader4Line className="h-3.5 w-3.5 animate-spin text-text-secondary" />
|
||||
)
|
||||
|
||||
const ToggleIndicator = () => (
|
||||
<ChevronDownIcon
|
||||
className="h-4 w-4 text-text-quaternary group-hover/simple-select:text-text-secondary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)
|
||||
|
||||
const SelectedMark = () => (
|
||||
<span className="absolute inset-y-0 right-0 flex items-center pr-2 text-text-accent">
|
||||
<RiCheckLine className="h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
)
|
||||
|
||||
export const MultiSelectField: FC<MultiSelectFieldProps> = ({
|
||||
disabled,
|
||||
isLoading = false,
|
||||
items,
|
||||
onChange,
|
||||
placeholder,
|
||||
selectedLabel,
|
||||
value,
|
||||
}) => {
|
||||
const textClassName = cn(
|
||||
'block truncate text-left system-sm-regular',
|
||||
isLoading
|
||||
? 'text-components-input-text-placeholder'
|
||||
: value.length > 0
|
||||
? 'text-components-input-text-filled'
|
||||
: 'text-components-input-text-placeholder',
|
||||
)
|
||||
|
||||
const renderLabel = () => {
|
||||
if (isLoading)
|
||||
return 'Loading...'
|
||||
|
||||
return selectedLabel || placeholder || 'Select options'
|
||||
}
|
||||
|
||||
return (
|
||||
<Listbox multiple value={value} onChange={onChange} disabled={disabled}>
|
||||
<div className="group/simple-select relative h-8 grow">
|
||||
<ListboxButton className="flex h-full w-full cursor-pointer items-center rounded-lg border-0 bg-components-input-bg-normal pl-3 pr-10 focus-visible:bg-state-base-hover-alt focus-visible:outline-none group-hover/simple-select:bg-state-base-hover-alt sm:text-sm sm:leading-6">
|
||||
<span className={textClassName}>
|
||||
{renderLabel()}
|
||||
</span>
|
||||
<span className="absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
{isLoading ? <LoadingIndicator /> : <ToggleIndicator />}
|
||||
</span>
|
||||
</ListboxButton>
|
||||
<ListboxOptions className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur px-1 py-1 text-base shadow-lg backdrop-blur-sm focus:outline-none sm:text-sm">
|
||||
{items.map(item => (
|
||||
<ListboxOption
|
||||
key={item.value}
|
||||
value={item.value}
|
||||
className={({ focus }) =>
|
||||
cn('relative cursor-pointer select-none rounded-lg py-2 pl-3 pr-9 text-text-secondary hover:bg-state-base-hover', focus && 'bg-state-base-hover')}
|
||||
>
|
||||
{({ selected }) => (
|
||||
<>
|
||||
<div className="flex items-center">
|
||||
{item.icon && (
|
||||
<img src={item.icon} alt="" className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
<span className={cn('block truncate', selected && 'font-normal')}>
|
||||
{item.name}
|
||||
</span>
|
||||
</div>
|
||||
{selected && <SelectedMark />}
|
||||
</>
|
||||
)}
|
||||
</ListboxOption>
|
||||
))}
|
||||
</ListboxOptions>
|
||||
</div>
|
||||
</Listbox>
|
||||
)
|
||||
}
|
||||
|
||||
type JsonEditorFieldProps = {
|
||||
onChange: (value: string) => void
|
||||
placeholder?: ReactElement | string
|
||||
value: string
|
||||
}
|
||||
|
||||
export const JsonEditorField: FC<JsonEditorFieldProps> = ({
|
||||
onChange,
|
||||
placeholder,
|
||||
value,
|
||||
}) => {
|
||||
return (
|
||||
<div className="mt-1 w-full">
|
||||
<CodeEditor
|
||||
title="JSON"
|
||||
value={value}
|
||||
isExpand
|
||||
isInNode
|
||||
language={CodeLanguage.json}
|
||||
onChange={onChange}
|
||||
className="w-full"
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,27 +1,20 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { ResourceVarInputs } from '../types'
|
||||
import type { CredentialFormSchema, FormOption } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { CredentialFormSchema, FormOption, FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { Event, Tool } from '@/app/components/tools/types'
|
||||
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
|
||||
import type { ToolWithProvider, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
import { RiCheckLine, RiLoader4Line } from '@remixicon/react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import CheckboxList from '@/app/components/base/checkbox-list'
|
||||
import Input from '@/app/components/base/input'
|
||||
import { SimpleSelect } from '@/app/components/base/select'
|
||||
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
|
||||
import AppSelector from '@/app/components/plugins/plugin-detail-panel/app-selector'
|
||||
import ModelParameterModal from '@/app/components/plugins/plugin-detail-panel/model-selector'
|
||||
import { PluginCategoryEnum } from '@/app/components/plugins/types'
|
||||
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
|
||||
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
|
||||
import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'
|
||||
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
|
||||
import MixedVariableTextInput from '@/app/components/workflow/nodes/tool/components/mixed-variable-text-input'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { useFetchDynamicOptions } from '@/service/use-plugins'
|
||||
@@ -29,6 +22,24 @@ import { useTriggerPluginDynamicOptions } from '@/service/use-triggers'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import { VarKindType } from '../types'
|
||||
import FormInputBoolean from './form-input-boolean'
|
||||
import {
|
||||
filterVisibleOptions,
|
||||
getCheckboxListOptions,
|
||||
getCheckboxListValue,
|
||||
getFilterVar,
|
||||
getFormInputState,
|
||||
getNumberInputValue,
|
||||
getSelectedLabels,
|
||||
getTargetVarType,
|
||||
getVarKindType,
|
||||
hasOptionIcon,
|
||||
mapSelectItems,
|
||||
normalizeVariableSelectorValue,
|
||||
} from './form-input-item.helpers'
|
||||
import {
|
||||
JsonEditorField,
|
||||
MultiSelectField,
|
||||
} from './form-input-item.sections'
|
||||
import FormInputTypeSwitch from './form-input-type-switch'
|
||||
|
||||
type Props = {
|
||||
@@ -66,33 +77,34 @@ const FormInputItem: FC<Props> = ({
|
||||
const [toolsOptions, setToolsOptions] = useState<FormOption[] | null>(null)
|
||||
const [isLoadingToolsOptions, setIsLoadingToolsOptions] = useState(false)
|
||||
|
||||
const formState = getFormInputState(schema as CredentialFormSchema & {
|
||||
_type?: FormTypeEnum
|
||||
multiple?: boolean
|
||||
options?: FormOption[]
|
||||
scope?: string
|
||||
}, value[schema.variable])
|
||||
|
||||
const {
|
||||
placeholder,
|
||||
variable,
|
||||
type,
|
||||
_type,
|
||||
default: defaultValue,
|
||||
defaultValue,
|
||||
isAppSelector,
|
||||
isBoolean,
|
||||
isCheckbox,
|
||||
isConstant,
|
||||
isDynamicSelect,
|
||||
isModelSelector,
|
||||
isMultipleSelect,
|
||||
isNumber,
|
||||
isSelect,
|
||||
isShowJSONEditor,
|
||||
isString,
|
||||
options,
|
||||
multiple,
|
||||
placeholder,
|
||||
scope,
|
||||
} = schema as any
|
||||
showTypeSwitch,
|
||||
showVariableSelector,
|
||||
variable,
|
||||
} = formState
|
||||
const varInput = value[variable]
|
||||
const isString = type === FormTypeEnum.textInput || type === FormTypeEnum.secretInput
|
||||
const isNumber = type === FormTypeEnum.textNumber
|
||||
const isObject = type === FormTypeEnum.object
|
||||
const isArray = type === FormTypeEnum.array
|
||||
const isShowJSONEditor = isObject || isArray
|
||||
const isFile = type === FormTypeEnum.file || type === FormTypeEnum.files
|
||||
const isBoolean = _type === FormTypeEnum.boolean
|
||||
const isCheckbox = _type === FormTypeEnum.checkbox
|
||||
const isSelect = type === FormTypeEnum.select
|
||||
const isDynamicSelect = type === FormTypeEnum.dynamicSelect
|
||||
const isAppSelector = type === FormTypeEnum.appSelector
|
||||
const isModelSelector = type === FormTypeEnum.modelSelector
|
||||
const showTypeSwitch = isNumber || isBoolean || isObject || isArray || isSelect
|
||||
const isConstant = varInput?.type === VarKindType.constant || !varInput?.type
|
||||
const showVariableSelector = isFile || varInput?.type === VarKindType.variable
|
||||
const isMultipleSelect = multiple && (isSelect || isDynamicSelect)
|
||||
|
||||
const { availableVars, availableNodesWithParent } = useAvailableVarList(nodeId, {
|
||||
onlyLeafNodeVar: false,
|
||||
@@ -101,56 +113,6 @@ const FormInputItem: FC<Props> = ({
|
||||
},
|
||||
})
|
||||
|
||||
const targetVarType = () => {
|
||||
if (isString)
|
||||
return VarType.string
|
||||
else if (isNumber)
|
||||
return VarType.number
|
||||
else if (type === FormTypeEnum.files)
|
||||
return VarType.arrayFile
|
||||
else if (type === FormTypeEnum.file)
|
||||
return VarType.file
|
||||
else if (isSelect)
|
||||
return VarType.string
|
||||
// else if (isAppSelector)
|
||||
// return VarType.appSelector
|
||||
// else if (isModelSelector)
|
||||
// return VarType.modelSelector
|
||||
else if (isBoolean)
|
||||
return VarType.boolean
|
||||
else if (isObject)
|
||||
return VarType.object
|
||||
else if (isArray)
|
||||
return VarType.arrayObject
|
||||
else
|
||||
return VarType.string
|
||||
}
|
||||
|
||||
const getFilterVar = () => {
|
||||
if (isNumber)
|
||||
return (varPayload: any) => varPayload.type === VarType.number
|
||||
else if (isString)
|
||||
return (varPayload: any) => [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
|
||||
else if (isFile)
|
||||
return (varPayload: any) => [VarType.file, VarType.arrayFile].includes(varPayload.type)
|
||||
else if (isBoolean)
|
||||
return (varPayload: any) => varPayload.type === VarType.boolean
|
||||
else if (isObject)
|
||||
return (varPayload: any) => varPayload.type === VarType.object
|
||||
else if (isArray)
|
||||
return (varPayload: any) => [VarType.array, VarType.arrayString, VarType.arrayNumber, VarType.arrayObject].includes(varPayload.type)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const getVarKindType = () => {
|
||||
if (isFile)
|
||||
return VarKindType.variable
|
||||
if (isSelect || isDynamicSelect || isBoolean || isNumber || isArray || isObject)
|
||||
return VarKindType.constant
|
||||
if (isString)
|
||||
return VarKindType.mixed
|
||||
}
|
||||
|
||||
// Fetch dynamic options hook for tools
|
||||
const { mutateAsync: fetchDynamicOptions } = useFetchDynamicOptions(
|
||||
currentProvider?.plugin_id || '',
|
||||
@@ -238,30 +200,12 @@ const FormInputItem: FC<Props> = ({
|
||||
...value,
|
||||
[variable]: {
|
||||
...varInput,
|
||||
type: getVarKindType(),
|
||||
type: getVarKindType(formState),
|
||||
value: isNumber ? Number.parseFloat(newValue) : newValue,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const getSelectedLabels = (selectedValues: any[]) => {
|
||||
if (!selectedValues || selectedValues.length === 0)
|
||||
return ''
|
||||
|
||||
const optionsList = isDynamicSelect ? (dynamicOptions || options || []) : (options || [])
|
||||
const selectedOptions = optionsList.filter((opt: any) =>
|
||||
selectedValues.includes(opt.value),
|
||||
)
|
||||
|
||||
if (selectedOptions.length <= 2) {
|
||||
return selectedOptions
|
||||
.map((opt: any) => opt.label?.[language] || opt.label?.en_US || opt.value)
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
return `${selectedOptions.length} selected`
|
||||
}
|
||||
|
||||
const handleAppOrModelSelect = (newValue: any) => {
|
||||
onChange({
|
||||
...value,
|
||||
@@ -278,38 +222,44 @@ const FormInputItem: FC<Props> = ({
|
||||
[variable]: {
|
||||
...varInput,
|
||||
type: VarKindType.variable,
|
||||
value: newValue || '',
|
||||
value: normalizeVariableSelectorValue(newValue),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const availableCheckboxOptions = useMemo(() => (
|
||||
(options || []).filter((option: { show_on?: Array<{ variable: string, value: any }> }) => {
|
||||
if (option.show_on?.length)
|
||||
return option.show_on.every(showOnItem => value[showOnItem.variable]?.value === showOnItem.value || value[showOnItem.variable] === showOnItem.value)
|
||||
return true
|
||||
})
|
||||
), [options, value])
|
||||
const availableCheckboxOptions = useMemo(
|
||||
() => filterVisibleOptions(options, value),
|
||||
[options, value],
|
||||
)
|
||||
const checkboxListOptions = useMemo(
|
||||
() => getCheckboxListOptions(availableCheckboxOptions, language),
|
||||
[availableCheckboxOptions, language],
|
||||
)
|
||||
const checkboxListValue = useMemo(
|
||||
() => getCheckboxListValue(varInput?.value, defaultValue, availableCheckboxOptions),
|
||||
[availableCheckboxOptions, defaultValue, varInput?.value],
|
||||
)
|
||||
|
||||
const checkboxListOptions = useMemo(() => (
|
||||
availableCheckboxOptions.map((option: { value: string, label: Record<string, string> }) => ({
|
||||
value: option.value,
|
||||
label: option.label?.[language] || option.label?.en_US || option.value,
|
||||
}))
|
||||
), [availableCheckboxOptions, language])
|
||||
|
||||
const checkboxListValue = useMemo(() => {
|
||||
let current: string[] = []
|
||||
if (Array.isArray(varInput?.value))
|
||||
current = varInput.value as string[]
|
||||
else if (typeof varInput?.value === 'string')
|
||||
current = [varInput.value as string]
|
||||
else if (Array.isArray(defaultValue))
|
||||
current = defaultValue as string[]
|
||||
|
||||
const allowedValues = new Set(availableCheckboxOptions.map((option: { value: string }) => option.value))
|
||||
return current.filter(item => allowedValues.has(item))
|
||||
}, [varInput?.value, defaultValue, availableCheckboxOptions])
|
||||
const visibleSelectOptions = useMemo(
|
||||
() => filterVisibleOptions(options, value),
|
||||
[options, value],
|
||||
)
|
||||
const visibleDynamicOptions = useMemo(
|
||||
() => filterVisibleOptions(dynamicOptions || options || [], value),
|
||||
[dynamicOptions, options, value],
|
||||
)
|
||||
const staticSelectItems = useMemo(
|
||||
() => mapSelectItems(visibleSelectOptions, language),
|
||||
[language, visibleSelectOptions],
|
||||
)
|
||||
const dynamicSelectItems = useMemo(
|
||||
() => mapSelectItems(visibleDynamicOptions, language),
|
||||
[language, visibleDynamicOptions],
|
||||
)
|
||||
const selectedLabels = useMemo(
|
||||
() => getSelectedLabels(varInput?.value as string[] | undefined, isDynamicSelect ? visibleDynamicOptions : visibleSelectOptions, language),
|
||||
[isDynamicSelect, language, varInput?.value, visibleDynamicOptions, visibleSelectOptions],
|
||||
)
|
||||
|
||||
const handleCheckboxListChange = (selected: string[]) => {
|
||||
onChange({
|
||||
@@ -343,7 +293,7 @@ const FormInputItem: FC<Props> = ({
|
||||
<Input
|
||||
className="h-8 grow"
|
||||
type="number"
|
||||
value={Number.isNaN(varInput?.value) ? '' : varInput?.value}
|
||||
value={getNumberInputValue(varInput?.value)}
|
||||
onChange={e => handleValueChange(e.target.value)}
|
||||
placeholder={placeholder?.[language] || placeholder?.en_US}
|
||||
/>
|
||||
@@ -368,20 +318,11 @@ const FormInputItem: FC<Props> = ({
|
||||
<SimpleSelect
|
||||
wrapperClassName="h-8 grow"
|
||||
disabled={readOnly}
|
||||
defaultValue={varInput?.value}
|
||||
items={options.filter((option: { show_on: any[] }) => {
|
||||
if (option.show_on.length)
|
||||
return option.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value)
|
||||
|
||||
return true
|
||||
}).map((option: { value: any, label: { [x: string]: any, en_US: any }, icon?: string }) => ({
|
||||
value: option.value,
|
||||
name: option.label[language] || option.label.en_US,
|
||||
icon: option.icon,
|
||||
}))}
|
||||
defaultValue={varInput?.value as string | undefined}
|
||||
items={staticSelectItems}
|
||||
onSelect={item => handleValueChange(item.value as string)}
|
||||
placeholder={placeholder?.[language] || placeholder?.en_US}
|
||||
renderOption={options.some((opt: any) => opt.icon)
|
||||
renderOption={hasOptionIcon(visibleSelectOptions)
|
||||
? ({ item }) => (
|
||||
<div className="flex items-center">
|
||||
{item.icon && (
|
||||
@@ -394,74 +335,21 @@ const FormInputItem: FC<Props> = ({
|
||||
/>
|
||||
)}
|
||||
{isSelect && isConstant && isMultipleSelect && (
|
||||
<Listbox
|
||||
multiple
|
||||
value={varInput?.value || []}
|
||||
onChange={handleValueChange}
|
||||
<MultiSelectField
|
||||
disabled={readOnly}
|
||||
>
|
||||
<div className="group/simple-select relative h-8 grow">
|
||||
<ListboxButton className="flex h-full w-full cursor-pointer items-center rounded-lg border-0 bg-components-input-bg-normal pl-3 pr-10 focus-visible:bg-state-base-hover-alt focus-visible:outline-none group-hover/simple-select:bg-state-base-hover-alt sm:text-sm sm:leading-6">
|
||||
<span className={cn('system-sm-regular block truncate text-left', varInput?.value?.length > 0 ? 'text-components-input-text-filled' : 'text-components-input-text-placeholder')}>
|
||||
{getSelectedLabels(varInput?.value) || placeholder?.[language] || placeholder?.en_US || 'Select options'}
|
||||
</span>
|
||||
<span className="absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
<ChevronDownIcon
|
||||
className="h-4 w-4 text-text-quaternary group-hover/simple-select:text-text-secondary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</span>
|
||||
</ListboxButton>
|
||||
<ListboxOptions className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur px-1 py-1 text-base shadow-lg backdrop-blur-sm focus:outline-none sm:text-sm">
|
||||
{options.filter((option: { show_on: any[] }) => {
|
||||
if (option.show_on?.length)
|
||||
return option.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value)
|
||||
return true
|
||||
}).map((option: { value: any, label: { [x: string]: any, en_US: any }, icon?: string }) => (
|
||||
<ListboxOption
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className={({ focus }) =>
|
||||
cn('relative cursor-pointer select-none rounded-lg py-2 pl-3 pr-9 text-text-secondary hover:bg-state-base-hover', focus && 'bg-state-base-hover')}
|
||||
>
|
||||
{({ selected }) => (
|
||||
<>
|
||||
<div className="flex items-center">
|
||||
{option.icon && (
|
||||
<img src={option.icon} alt="" className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
<span className={cn('block truncate', selected && 'font-normal')}>
|
||||
{option.label[language] || option.label.en_US}
|
||||
</span>
|
||||
</div>
|
||||
{selected && (
|
||||
<span className="absolute inset-y-0 right-0 flex items-center pr-2 text-text-accent">
|
||||
<RiCheckLine className="h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</ListboxOption>
|
||||
))}
|
||||
</ListboxOptions>
|
||||
</div>
|
||||
</Listbox>
|
||||
value={(varInput?.value as string[] | undefined) || []}
|
||||
items={staticSelectItems}
|
||||
onChange={handleValueChange}
|
||||
placeholder={placeholder?.[language] || placeholder?.en_US}
|
||||
selectedLabel={selectedLabels}
|
||||
/>
|
||||
)}
|
||||
{isDynamicSelect && !isMultipleSelect && (
|
||||
<SimpleSelect
|
||||
wrapperClassName="h-8 grow"
|
||||
disabled={readOnly || isLoadingOptions}
|
||||
defaultValue={varInput?.value}
|
||||
items={(dynamicOptions || options || []).filter((option: { show_on?: any[] }) => {
|
||||
if (option.show_on?.length)
|
||||
return option.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value)
|
||||
|
||||
return true
|
||||
}).map((option: { value: any, label: { [x: string]: any, en_US: any }, icon?: string }) => ({
|
||||
value: option.value,
|
||||
name: option.label[language] || option.label.en_US,
|
||||
icon: option.icon,
|
||||
}))}
|
||||
defaultValue={varInput?.value as string | undefined}
|
||||
items={dynamicSelectItems}
|
||||
onSelect={item => handleValueChange(item.value as string)}
|
||||
placeholder={isLoadingOptions ? 'Loading...' : (placeholder?.[language] || placeholder?.en_US)}
|
||||
renderOption={({ item }) => (
|
||||
@@ -475,83 +363,22 @@ const FormInputItem: FC<Props> = ({
|
||||
/>
|
||||
)}
|
||||
{isDynamicSelect && isMultipleSelect && (
|
||||
<Listbox
|
||||
multiple
|
||||
value={varInput?.value || []}
|
||||
onChange={handleValueChange}
|
||||
<MultiSelectField
|
||||
disabled={readOnly || isLoadingOptions}
|
||||
>
|
||||
<div className="group/simple-select relative h-8 grow">
|
||||
<ListboxButton className="flex h-full w-full cursor-pointer items-center rounded-lg border-0 bg-components-input-bg-normal pl-3 pr-10 focus-visible:bg-state-base-hover-alt focus-visible:outline-none group-hover/simple-select:bg-state-base-hover-alt sm:text-sm sm:leading-6">
|
||||
<span className={cn('system-sm-regular block truncate text-left', isLoadingOptions
|
||||
? 'text-components-input-text-placeholder'
|
||||
: varInput?.value?.length > 0 ? 'text-components-input-text-filled' : 'text-components-input-text-placeholder')}
|
||||
>
|
||||
{isLoadingOptions
|
||||
? 'Loading...'
|
||||
: getSelectedLabels(varInput?.value) || placeholder?.[language] || placeholder?.en_US || 'Select options'}
|
||||
</span>
|
||||
<span className="absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
{isLoadingOptions
|
||||
? (
|
||||
<RiLoader4Line className="h-3.5 w-3.5 animate-spin text-text-secondary" />
|
||||
)
|
||||
: (
|
||||
<ChevronDownIcon
|
||||
className="h-4 w-4 text-text-quaternary group-hover/simple-select:text-text-secondary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</ListboxButton>
|
||||
<ListboxOptions className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur px-1 py-1 text-base shadow-lg backdrop-blur-sm focus:outline-none sm:text-sm">
|
||||
{(dynamicOptions || options || []).filter((option: { show_on?: any[] }) => {
|
||||
if (option.show_on?.length)
|
||||
return option.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value)
|
||||
return true
|
||||
}).map((option: { value: any, label: { [x: string]: any, en_US: any }, icon?: string }) => (
|
||||
<ListboxOption
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className={({ focus }) =>
|
||||
cn('relative cursor-pointer select-none rounded-lg py-2 pl-3 pr-9 text-text-secondary hover:bg-state-base-hover', focus && 'bg-state-base-hover')}
|
||||
>
|
||||
{({ selected }) => (
|
||||
<>
|
||||
<div className="flex items-center">
|
||||
{option.icon && (
|
||||
<img src={option.icon} alt="" className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
<span className={cn('block truncate', selected && 'font-normal')}>
|
||||
{option.label[language] || option.label.en_US}
|
||||
</span>
|
||||
</div>
|
||||
{selected && (
|
||||
<span className="absolute inset-y-0 right-0 flex items-center pr-2 text-text-accent">
|
||||
<RiCheckLine className="h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</ListboxOption>
|
||||
))}
|
||||
</ListboxOptions>
|
||||
</div>
|
||||
</Listbox>
|
||||
isLoading={isLoadingOptions}
|
||||
value={(varInput?.value as string[] | undefined) || []}
|
||||
items={dynamicSelectItems}
|
||||
onChange={handleValueChange}
|
||||
placeholder={placeholder?.[language] || placeholder?.en_US}
|
||||
selectedLabel={selectedLabels}
|
||||
/>
|
||||
)}
|
||||
{isShowJSONEditor && isConstant && (
|
||||
<div className="mt-1 w-full">
|
||||
<CodeEditor
|
||||
title="JSON"
|
||||
value={varInput?.value as any}
|
||||
isExpand
|
||||
isInNode
|
||||
language={CodeLanguage.json}
|
||||
onChange={handleValueChange}
|
||||
className="w-full"
|
||||
placeholder={<div className="whitespace-pre">{placeholder?.[language] || placeholder?.en_US}</div>}
|
||||
/>
|
||||
</div>
|
||||
<JsonEditorField
|
||||
value={(varInput?.value as string) || ''}
|
||||
onChange={handleValueChange}
|
||||
placeholder={<div className="whitespace-pre">{placeholder?.[language] || placeholder?.en_US}</div>}
|
||||
/>
|
||||
)}
|
||||
{isAppSelector && (
|
||||
<AppSelector
|
||||
@@ -581,9 +408,9 @@ const FormInputItem: FC<Props> = ({
|
||||
nodeId={nodeId}
|
||||
value={varInput?.value || []}
|
||||
onChange={value => handleVariableSelectorChange(value, variable)}
|
||||
filterVar={getFilterVar()}
|
||||
filterVar={getFilterVar(formState)}
|
||||
schema={schema}
|
||||
valueTypePlaceHolder={targetVarType()}
|
||||
valueTypePlaceHolder={getTargetVarType(formState)}
|
||||
currentTool={currentTool}
|
||||
currentProvider={currentProvider}
|
||||
isFilterFileVar={isBoolean}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import type { FC } from 'react'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
|
||||
export type InputNumberWithSliderProps = {
|
||||
value: number
|
||||
@@ -22,7 +22,7 @@ const InputNumberWithSlider: FC<InputNumberWithSliderProps> = ({
|
||||
onChange,
|
||||
}) => {
|
||||
const handleBlur = useCallback(() => {
|
||||
if (value === undefined || value === null) {
|
||||
if (value === undefined || value === null || Number.isNaN(value)) {
|
||||
onChange(defaultValue)
|
||||
return
|
||||
}
|
||||
@@ -57,8 +57,9 @@ const InputNumberWithSlider: FC<InputNumberWithSliderProps> = ({
|
||||
min={min}
|
||||
max={max}
|
||||
step={1}
|
||||
onChange={onChange}
|
||||
onValueChange={onChange}
|
||||
disabled={readonly}
|
||||
aria-label="Number input slider"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -6,8 +6,8 @@ import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Input from '@/app/components/base/input'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import Switch from '@/app/components/base/switch'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
import Field from '@/app/components/workflow/nodes/_base/components/field'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import { MemoryRole } from '../../../types'
|
||||
@@ -154,7 +154,7 @@ const MemoryConfig: FC<Props> = ({
|
||||
size="md"
|
||||
disabled={readonly}
|
||||
/>
|
||||
<div className="system-xs-medium-uppercase text-text-tertiary">{t(`${i18nPrefix}.windowSize`, { ns: 'workflow' })}</div>
|
||||
<div className="text-text-tertiary system-xs-medium-uppercase">{t(`${i18nPrefix}.windowSize`, { ns: 'workflow' })}</div>
|
||||
</div>
|
||||
<div className="flex h-8 items-center space-x-2">
|
||||
<Slider
|
||||
@@ -163,8 +163,9 @@ const MemoryConfig: FC<Props> = ({
|
||||
min={WINDOW_SIZE_MIN}
|
||||
max={WINDOW_SIZE_MAX}
|
||||
step={1}
|
||||
onChange={handleWindowSizeChange}
|
||||
onValueChange={handleWindowSizeChange}
|
||||
disabled={readonly || !payload.window?.enabled}
|
||||
aria-label={t(`${i18nPrefix}.windowSize`, { ns: 'workflow' })}
|
||||
/>
|
||||
<Input
|
||||
value={(payload.window?.size || WINDOW_SIZE_DEFAULT) as number}
|
||||
|
||||
@@ -3,8 +3,8 @@ import type {
|
||||
} from '@/app/components/workflow/types'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Input from '@/app/components/base/input'
|
||||
import Slider from '@/app/components/base/slider'
|
||||
import Switch from '@/app/components/base/switch'
|
||||
import { Slider } from '@/app/components/base/ui/slider'
|
||||
import Split from '@/app/components/workflow/nodes/_base/components/split'
|
||||
import { useRetryConfig } from './hooks'
|
||||
import s from './style.module.css'
|
||||
@@ -70,9 +70,10 @@ const RetryOnPanel = ({
|
||||
<Slider
|
||||
className="mr-3 w-[108px]"
|
||||
value={retry_config?.max_retries || 3}
|
||||
onChange={handleMaxRetriesChange}
|
||||
onValueChange={handleMaxRetriesChange}
|
||||
min={1}
|
||||
max={10}
|
||||
aria-label={t('nodes.common.retry.maxRetries', { ns: 'workflow' })}
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
@@ -91,9 +92,10 @@ const RetryOnPanel = ({
|
||||
<Slider
|
||||
className="mr-3 w-[108px]"
|
||||
value={retry_config?.retry_interval || 1000}
|
||||
onChange={handleRetryIntervalChange}
|
||||
onValueChange={handleRetryIntervalChange}
|
||||
min={100}
|
||||
max={5000}
|
||||
aria-label={t('nodes.common.retry.retryInterval', { ns: 'workflow' })}
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { FormOption } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { NodeOutPutVar } from '@/app/components/workflow/types'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { createNode, createStartNode, resetFixtureCounters } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
|
||||
import { VarType as VarKindType } from '../../../../tool/types'
|
||||
import VarReferencePicker from '../var-reference-picker'
|
||||
|
||||
const {
|
||||
mockFetchDynamicOptions,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFetchDynamicOptions: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-plugins', () => ({
|
||||
useFetchDynamicOptions: () => ({
|
||||
mutateAsync: mockFetchDynamicOptions,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('../var-reference-popup', () => ({
|
||||
default: ({
|
||||
onChange,
|
||||
}: {
|
||||
onChange: (value: string[], item: { variable: string, type: VarType }) => void
|
||||
}) => (
|
||||
<div>
|
||||
<button onClick={() => onChange(['node-a', 'answer'], { variable: 'answer', type: VarType.string })}>select-normal</button>
|
||||
<button onClick={() => onChange(['node-a', 'sys.query'], { variable: 'sys.query', type: VarType.string })}>select-system</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('VarReferencePicker branches', () => {
|
||||
const startNode = createStartNode({
|
||||
id: 'start-node',
|
||||
data: {
|
||||
title: 'Start',
|
||||
variables: [{
|
||||
variable: 'query',
|
||||
label: 'Query',
|
||||
type: InputVarType.textInput,
|
||||
required: false,
|
||||
}],
|
||||
},
|
||||
})
|
||||
const sourceNode = createNode({
|
||||
id: 'node-a',
|
||||
width: 120,
|
||||
height: 60,
|
||||
position: { x: 120, y: 80 },
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Source Node',
|
||||
outputs: {
|
||||
answer: { type: VarType.string },
|
||||
},
|
||||
},
|
||||
})
|
||||
const currentNode = createNode({
|
||||
id: 'node-current',
|
||||
data: { type: BlockEnum.Code, title: 'Current Node' },
|
||||
})
|
||||
|
||||
const availableVars: NodeOutPutVar[] = [{
|
||||
nodeId: 'node-a',
|
||||
title: 'Source Node',
|
||||
vars: [
|
||||
{ variable: 'answer', type: VarType.string },
|
||||
],
|
||||
}]
|
||||
|
||||
const renderPicker = (props: Partial<ComponentProps<typeof VarReferencePicker>> = {}) => {
|
||||
const onChange = vi.fn()
|
||||
const onOpen = vi.fn()
|
||||
|
||||
const result = renderWorkflowFlowComponent(
|
||||
<div id="workflow-container" style={{ width: 800, height: 600 }}>
|
||||
<VarReferencePicker
|
||||
nodeId="node-current"
|
||||
readonly={false}
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
onOpen={onOpen}
|
||||
availableNodes={[startNode, sourceNode, currentNode]}
|
||||
availableVars={availableVars}
|
||||
{...props}
|
||||
/>
|
||||
</div>,
|
||||
{
|
||||
nodes: [startNode, sourceNode, currentNode],
|
||||
edges: [],
|
||||
hooksStoreProps: {},
|
||||
},
|
||||
)
|
||||
|
||||
return { ...result, onChange, onOpen }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetFixtureCounters()
|
||||
vi.clearAllMocks()
|
||||
mockFetchDynamicOptions.mockResolvedValue({ options: [] as FormOption[] })
|
||||
})
|
||||
|
||||
it('should toggle a custom trigger and call onOpen when opening the popup', async () => {
|
||||
const { onOpen } = renderPicker({
|
||||
trigger: <button>custom-trigger</button>,
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('custom-trigger'))
|
||||
|
||||
expect(await screen.findByText('select-normal')).toBeInTheDocument()
|
||||
await waitFor(() => {
|
||||
expect(onOpen).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('should rewrite system selectors before forwarding the selection', async () => {
|
||||
const { onChange } = renderPicker()
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
fireEvent.click(await screen.findByText('select-system'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(
|
||||
['sys', 'query'],
|
||||
VarKindType.constant,
|
||||
expect.objectContaining({
|
||||
variable: 'sys.query',
|
||||
type: VarType.string,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should clear variable-mode values to an empty selector array', () => {
|
||||
const { onChange } = renderPicker({
|
||||
defaultVarKindType: VarKindType.variable,
|
||||
isSupportConstantValue: true,
|
||||
value: ['node-a', 'answer'],
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-clear'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith([], VarKindType.variable)
|
||||
})
|
||||
|
||||
it('should jump to the selected node when ctrl-clicking the node name', () => {
|
||||
const { onChange } = renderPicker({
|
||||
value: ['node-a', 'answer'],
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('Source Node'), { ctrlKey: true })
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should fetch dynamic options for supported constant fields', async () => {
|
||||
mockFetchDynamicOptions.mockResolvedValueOnce({
|
||||
options: [{
|
||||
value: 'dyn-1',
|
||||
label: { en_US: 'Dynamic 1', zh_Hans: '动态 1' },
|
||||
show_on: [],
|
||||
}],
|
||||
})
|
||||
|
||||
renderPicker({
|
||||
currentProvider: { plugin_id: 'provider-1', name: 'provider-1' } as never,
|
||||
currentTool: { name: 'tool-1' } as never,
|
||||
isSupportConstantValue: true,
|
||||
schema: {
|
||||
variable: 'field',
|
||||
type: 'dynamic-select',
|
||||
} as never,
|
||||
value: 'dyn-1',
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchDynamicOptions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('should focus the hidden control input for supported constant values', async () => {
|
||||
const { container } = renderPicker({
|
||||
isSupportConstantValue: true,
|
||||
schema: {
|
||||
type: 'text-input',
|
||||
} as never,
|
||||
value: 'constant-value',
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
|
||||
const hiddenInput = container.querySelector('input.sr-only') as HTMLInputElement
|
||||
await waitFor(() => {
|
||||
expect(document.activeElement).toBe(hiddenInput)
|
||||
})
|
||||
})
|
||||
|
||||
it('should render tooltip branches for partial paths and invalid variables without changing behavior', () => {
|
||||
const objectVars: NodeOutPutVar[] = [{
|
||||
nodeId: 'node-a',
|
||||
title: 'Source Node',
|
||||
vars: [{
|
||||
variable: 'payload',
|
||||
type: VarType.object,
|
||||
children: [{ variable: 'child', type: VarType.string }],
|
||||
}],
|
||||
}]
|
||||
|
||||
const { unmount } = renderPicker({
|
||||
availableVars: objectVars,
|
||||
value: ['node-a', 'payload', 'child'],
|
||||
})
|
||||
|
||||
expect(screen.getByText('child')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
renderPicker({
|
||||
value: ['missing-node', 'answer'],
|
||||
})
|
||||
|
||||
expect(screen.getByText('answer')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { CommonNodeType, Node, ValueSelector } from '@/app/components/workflow/types'
|
||||
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { createLoopNode, createNode, createStartNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import {
|
||||
getDynamicSelectSchema,
|
||||
getHasValue,
|
||||
getIsIterationVar,
|
||||
getIsLoopVar,
|
||||
getOutputVarNode,
|
||||
getOutputVarNodeId,
|
||||
getTooltipContent,
|
||||
getVarDisplayName,
|
||||
getVariableCategory,
|
||||
getVariableMeta,
|
||||
getWidthAllocations,
|
||||
isShowAPartSelector,
|
||||
} from '../var-reference-picker.helpers'
|
||||
|
||||
describe('var-reference-picker.helpers', () => {
|
||||
it('should detect whether the picker has a variable value', () => {
|
||||
expect(getHasValue(false, ['node-1', 'answer'])).toBe(true)
|
||||
expect(getHasValue(true, 'constant')).toBe(false)
|
||||
expect(getHasValue(false, [])).toBe(false)
|
||||
})
|
||||
|
||||
it('should detect iteration and loop variables by parent node id', () => {
|
||||
expect(getIsIterationVar(true, ['iter-parent', 'item'], 'iter-parent')).toBe(true)
|
||||
expect(getIsIterationVar(true, ['iter-parent', 'value'], 'iter-parent')).toBe(false)
|
||||
expect(getIsLoopVar(true, ['loop-parent', 'index'], 'loop-parent')).toBe(true)
|
||||
expect(getIsLoopVar(false, ['loop-parent', 'item'], 'loop-parent')).toBe(false)
|
||||
})
|
||||
|
||||
it('should resolve output variable nodes for normal, system, iteration, and loop variables', () => {
|
||||
const startNode = createStartNode({ id: 'start-1', data: { title: 'Start Node' } })
|
||||
const normalNode = createNode({ id: 'node-a', data: { type: BlockEnum.Code, title: 'Answer Node' } })
|
||||
const iterationNode = createNode({ id: 'iter-parent', data: { type: BlockEnum.Iteration, title: 'Iteration Parent' } }) as Node<CommonNodeType>
|
||||
const loopNode = createLoopNode({ id: 'loop-parent', data: { title: 'Loop Parent' } }) as Node<CommonNodeType>
|
||||
|
||||
expect(getOutputVarNode({
|
||||
availableNodes: [normalNode],
|
||||
hasValue: true,
|
||||
isConstant: false,
|
||||
isIterationVar: false,
|
||||
isLoopVar: false,
|
||||
iterationNode: null,
|
||||
loopNode: null,
|
||||
outputVarNodeId: 'node-a',
|
||||
startNode,
|
||||
value: ['node-a', 'answer'],
|
||||
})).toMatchObject({ id: 'node-a', title: 'Answer Node' })
|
||||
|
||||
expect(getOutputVarNode({
|
||||
availableNodes: [normalNode],
|
||||
hasValue: true,
|
||||
isConstant: false,
|
||||
isIterationVar: false,
|
||||
isLoopVar: false,
|
||||
iterationNode: null,
|
||||
loopNode: null,
|
||||
outputVarNodeId: 'sys',
|
||||
startNode,
|
||||
value: ['sys', 'files'],
|
||||
})).toEqual(startNode.data)
|
||||
|
||||
expect(getOutputVarNode({
|
||||
availableNodes: [normalNode],
|
||||
hasValue: true,
|
||||
isConstant: false,
|
||||
isIterationVar: true,
|
||||
isLoopVar: false,
|
||||
iterationNode,
|
||||
loopNode: null,
|
||||
outputVarNodeId: 'iter-parent',
|
||||
startNode,
|
||||
value: ['iter-parent', 'item'],
|
||||
})).toEqual(iterationNode.data)
|
||||
|
||||
expect(getOutputVarNode({
|
||||
availableNodes: [normalNode],
|
||||
hasValue: true,
|
||||
isConstant: false,
|
||||
isIterationVar: false,
|
||||
isLoopVar: true,
|
||||
iterationNode: null,
|
||||
loopNode,
|
||||
outputVarNodeId: 'loop-parent',
|
||||
startNode,
|
||||
value: ['loop-parent', 'item'],
|
||||
})).toEqual(loopNode.data)
|
||||
|
||||
expect(getOutputVarNode({
|
||||
availableNodes: [normalNode],
|
||||
hasValue: true,
|
||||
isConstant: false,
|
||||
isIterationVar: false,
|
||||
isLoopVar: false,
|
||||
iterationNode: null,
|
||||
loopNode: null,
|
||||
outputVarNodeId: 'missing-node',
|
||||
startNode,
|
||||
value: ['missing-node', 'answer'],
|
||||
})).toBeNull()
|
||||
})
|
||||
|
||||
it('should format display names and output node ids correctly', () => {
|
||||
expect(getOutputVarNodeId(true, ['node-a', 'answer'])).toBe('node-a')
|
||||
expect(getOutputVarNodeId(false, [])).toBe('')
|
||||
|
||||
expect(getVarDisplayName(true, ['sys', 'query'])).toBe('query')
|
||||
expect(getVarDisplayName(true, ['node-a', 'answer'])).toBe('answer')
|
||||
expect(getVarDisplayName(false, [])).toBe('')
|
||||
})
|
||||
|
||||
it('should derive variable meta and category from selectors', () => {
|
||||
const meta = getVariableMeta({ type: BlockEnum.Code }, ['env', 'API_KEY'], 'API_KEY')
|
||||
expect(meta).toMatchObject({
|
||||
isEnv: true,
|
||||
isValidVar: true,
|
||||
isException: true,
|
||||
})
|
||||
|
||||
expect(getVariableCategory({
|
||||
isChatVar: true,
|
||||
isEnv: false,
|
||||
isGlobal: false,
|
||||
isLoopVar: false,
|
||||
isRagVar: false,
|
||||
})).toBe('conversation')
|
||||
|
||||
expect(getVariableCategory({
|
||||
isChatVar: false,
|
||||
isEnv: false,
|
||||
isGlobal: true,
|
||||
isLoopVar: false,
|
||||
isRagVar: false,
|
||||
})).toBe('global')
|
||||
|
||||
expect(getVariableCategory({
|
||||
isChatVar: false,
|
||||
isEnv: false,
|
||||
isGlobal: false,
|
||||
isLoopVar: true,
|
||||
isRagVar: false,
|
||||
})).toBe('loop')
|
||||
|
||||
expect(getVariableCategory({
|
||||
isChatVar: false,
|
||||
isEnv: true,
|
||||
isGlobal: false,
|
||||
isLoopVar: false,
|
||||
isRagVar: false,
|
||||
})).toBe('environment')
|
||||
|
||||
expect(getVariableCategory({
|
||||
isChatVar: false,
|
||||
isEnv: false,
|
||||
isGlobal: false,
|
||||
isLoopVar: false,
|
||||
isRagVar: true,
|
||||
})).toBe('rag')
|
||||
})
|
||||
|
||||
it('should calculate width allocations and tooltip behavior', () => {
|
||||
expect(getWidthAllocations(240, 'Node', 'answer', 'string')).toEqual({
|
||||
maxNodeNameWidth: expect.any(Number),
|
||||
maxTypeWidth: expect.any(Number),
|
||||
maxVarNameWidth: expect.any(Number),
|
||||
})
|
||||
|
||||
expect(getTooltipContent(true, true, true)).toBe('full-path')
|
||||
expect(getTooltipContent(true, false, false)).toBe('invalid-variable')
|
||||
expect(getTooltipContent(false, false, true)).toBeNull()
|
||||
})
|
||||
|
||||
it('should produce dynamic select schemas and detect partial selectors', () => {
|
||||
const value = 'selected'
|
||||
const schema: Partial<CredentialFormSchema> = {
|
||||
type: 'dynamic-select',
|
||||
} as Partial<CredentialFormSchema>
|
||||
|
||||
expect(getDynamicSelectSchema({
|
||||
dynamicOptions: [{
|
||||
value: 'a',
|
||||
label: { en_US: 'A', zh_Hans: 'A' },
|
||||
show_on: [],
|
||||
}],
|
||||
isLoading: false,
|
||||
schema,
|
||||
value,
|
||||
})).toMatchObject({
|
||||
options: [{ value: 'a' }],
|
||||
})
|
||||
|
||||
expect(getDynamicSelectSchema({
|
||||
dynamicOptions: null,
|
||||
isLoading: true,
|
||||
schema,
|
||||
value,
|
||||
})).toMatchObject({
|
||||
options: [{ value: 'selected' }],
|
||||
})
|
||||
|
||||
expect(getDynamicSelectSchema({
|
||||
dynamicOptions: null,
|
||||
isLoading: false,
|
||||
schema,
|
||||
value,
|
||||
})).toMatchObject({ options: [] })
|
||||
|
||||
expect(isShowAPartSelector(['node-a', 'payload', 'child'] as ValueSelector)).toBe(true)
|
||||
expect(isShowAPartSelector(['rag', 'node-a', 'payload'] as ValueSelector)).toBe(false)
|
||||
})
|
||||
|
||||
it('should keep mapped variable names for known workflow aliases', () => {
|
||||
expect(getVarDisplayName(true, ['sys', 'files'])).toBe('files')
|
||||
expect(getVariableMeta({ type: VarType.string }, ['conversation', 'name'], 'name')).toMatchObject({
|
||||
isChatVar: true,
|
||||
isValidVar: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('should preserve non-dynamic schemas', () => {
|
||||
const schema: Partial<CredentialFormSchema> = {
|
||||
type: FormTypeEnum.textInput,
|
||||
}
|
||||
|
||||
expect(getDynamicSelectSchema({
|
||||
dynamicOptions: null,
|
||||
isLoading: false,
|
||||
schema,
|
||||
value: '',
|
||||
})).toEqual(schema)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { NodeOutPutVar } from '@/app/components/workflow/types'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { createNode, createStartNode, resetFixtureCounters } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
|
||||
import VarReferencePicker from '../var-reference-picker'
|
||||
|
||||
describe('VarReferencePicker', () => {
|
||||
const startNode = createStartNode({
|
||||
id: 'start-node',
|
||||
data: {
|
||||
title: 'Start',
|
||||
variables: [{
|
||||
variable: 'query',
|
||||
label: 'Query',
|
||||
type: InputVarType.textInput,
|
||||
required: false,
|
||||
}],
|
||||
},
|
||||
})
|
||||
const sourceNode = createNode({
|
||||
id: 'node-a',
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Source Node',
|
||||
outputs: {
|
||||
answer: { type: VarType.string },
|
||||
payload: { type: VarType.object },
|
||||
},
|
||||
},
|
||||
})
|
||||
const currentNode = createNode({
|
||||
id: 'node-current',
|
||||
data: { type: BlockEnum.Code, title: 'Current Node' },
|
||||
})
|
||||
|
||||
const availableVars: NodeOutPutVar[] = [{
|
||||
nodeId: 'node-a',
|
||||
title: 'Source Node',
|
||||
vars: [
|
||||
{ variable: 'answer', type: VarType.string },
|
||||
{
|
||||
variable: 'payload',
|
||||
type: VarType.object,
|
||||
children: [{ variable: 'child', type: VarType.string }],
|
||||
},
|
||||
],
|
||||
}]
|
||||
|
||||
const renderPicker = (props: Partial<ComponentProps<typeof VarReferencePicker>> = {}) => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
const result = renderWorkflowFlowComponent(
|
||||
<div id="workflow-container">
|
||||
<VarReferencePicker
|
||||
nodeId="node-current"
|
||||
readonly={false}
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
availableNodes={[startNode, sourceNode, currentNode]}
|
||||
availableVars={availableVars}
|
||||
{...props}
|
||||
/>
|
||||
</div>,
|
||||
{
|
||||
nodes: [startNode, sourceNode, currentNode],
|
||||
edges: [],
|
||||
hooksStoreProps: {},
|
||||
},
|
||||
)
|
||||
|
||||
return { ...result, onChange }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetFixtureCounters()
|
||||
})
|
||||
|
||||
it('should open the popup and select a variable from the available list', async () => {
|
||||
const { onChange } = renderPicker()
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
|
||||
fireEvent.click(await screen.findByText('answer'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(
|
||||
['node-a', 'answer'],
|
||||
'constant',
|
||||
expect.objectContaining({
|
||||
variable: 'answer',
|
||||
type: VarType.string,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should render the selected node and variable name, then clear it', async () => {
|
||||
const { onChange } = renderPicker({
|
||||
value: ['node-a', 'answer'],
|
||||
})
|
||||
|
||||
expect(screen.getByText('Source Node')).toBeInTheDocument()
|
||||
expect(screen.getByText('answer')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-clear'))
|
||||
expect(onChange).toHaveBeenCalledWith('', 'constant')
|
||||
})
|
||||
|
||||
it('should show object variables in the popup and select the root object path', async () => {
|
||||
const { onChange } = renderPicker()
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
fireEvent.click(await screen.findByText('payload'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(
|
||||
['node-a', 'payload'],
|
||||
'constant',
|
||||
expect.objectContaining({
|
||||
variable: 'payload',
|
||||
type: VarType.object,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should render a placeholder and respect readonly mode', async () => {
|
||||
const { onChange } = renderPicker({
|
||||
readonly: true,
|
||||
placeholder: 'Pick a variable',
|
||||
})
|
||||
|
||||
expect(screen.getByText('Pick a variable')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('answer')).not.toBeInTheDocument()
|
||||
})
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import { VarType as VarKindType } from '../../../../tool/types'
|
||||
import VarReferencePickerTrigger from '../var-reference-picker.trigger'
|
||||
|
||||
const createProps = (
|
||||
overrides: Partial<ComponentProps<typeof VarReferencePickerTrigger>> = {},
|
||||
): ComponentProps<typeof VarReferencePickerTrigger> => ({
|
||||
controlFocus: 0,
|
||||
handleClearVar: vi.fn(),
|
||||
handleVarKindTypeChange: vi.fn(),
|
||||
handleVariableJump: vi.fn(),
|
||||
hasValue: false,
|
||||
inputRef: { current: null },
|
||||
isConstant: false,
|
||||
isException: false,
|
||||
isFocus: false,
|
||||
isLoading: false,
|
||||
isShowAPart: false,
|
||||
isShowNodeName: true,
|
||||
maxNodeNameWidth: 80,
|
||||
maxTypeWidth: 60,
|
||||
maxVarNameWidth: 80,
|
||||
onChange: vi.fn(),
|
||||
open: false,
|
||||
outputVarNode: null,
|
||||
readonly: false,
|
||||
setControlFocus: vi.fn(),
|
||||
setOpen: vi.fn(),
|
||||
tooltipPopup: null,
|
||||
triggerRef: { current: null },
|
||||
value: [],
|
||||
varKindType: VarKindType.constant,
|
||||
varKindTypes: [
|
||||
{ label: 'Variable', value: VarKindType.variable },
|
||||
{ label: 'Constant', value: VarKindType.constant },
|
||||
],
|
||||
varName: '',
|
||||
variableCategory: 'system',
|
||||
WrapElem: 'div',
|
||||
VarPickerWrap: 'div',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('VarReferencePickerTrigger', () => {
|
||||
it('should show the placeholder state and open the picker for variable mode', () => {
|
||||
const setOpen = vi.fn()
|
||||
render(
|
||||
<VarReferencePickerTrigger
|
||||
{...createProps({
|
||||
placeholder: 'Pick variable',
|
||||
setOpen,
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Pick variable')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
expect(setOpen).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('should render the selected variable state and clear it', () => {
|
||||
const handleClearVar = vi.fn()
|
||||
const handleVariableJump = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferencePickerTrigger
|
||||
{...createProps({
|
||||
handleClearVar,
|
||||
handleVariableJump,
|
||||
hasValue: true,
|
||||
outputVarNode: { title: 'Source Node', desc: '', type: BlockEnum.Code },
|
||||
outputVarNodeId: 'node-a',
|
||||
type: VarType.string,
|
||||
value: ['node-a', 'answer'],
|
||||
varName: 'answer',
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Source Node')).toBeInTheDocument()
|
||||
expect(screen.getByText('answer')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByText('Source Node'), { ctrlKey: true })
|
||||
expect(handleVariableJump).toHaveBeenCalledWith('node-a')
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-clear'))
|
||||
expect(handleClearVar).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should render the support-constant trigger and focus constant input when clicked', () => {
|
||||
const setControlFocus = vi.fn()
|
||||
const setOpen = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferencePickerTrigger
|
||||
{...createProps({
|
||||
isConstant: true,
|
||||
isSupportConstantValue: true,
|
||||
schemaWithDynamicSelect: {
|
||||
type: 'text-input',
|
||||
} as never,
|
||||
setOpen,
|
||||
setControlFocus,
|
||||
value: 'constant-value',
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
expect(setControlFocus).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.click(screen.getByText('Constant'))
|
||||
expect(setOpen).toHaveBeenCalledWith(false)
|
||||
})
|
||||
|
||||
it('should render add button trigger in table mode', () => {
|
||||
render(
|
||||
<VarReferencePickerTrigger
|
||||
{...createProps({
|
||||
hasValue: true,
|
||||
isAddBtnTrigger: true,
|
||||
isInTable: true,
|
||||
value: ['node-a', 'answer'],
|
||||
varName: 'answer',
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(document.querySelector('button')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should stay inert in readonly mode and show value type placeholder badge', () => {
|
||||
const setOpen = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferencePickerTrigger
|
||||
{...createProps({
|
||||
placeholder: 'Readonly placeholder',
|
||||
readonly: true,
|
||||
setOpen,
|
||||
typePlaceHolder: 'string',
|
||||
valueTypePlaceHolder: 'text',
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByTestId('var-reference-picker-trigger'))
|
||||
expect(setOpen).not.toHaveBeenCalled()
|
||||
expect(screen.getByText('string')).toBeInTheDocument()
|
||||
expect(screen.getByText('text')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show loading placeholder and remove rows in table mode', () => {
|
||||
const onRemove = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferencePickerTrigger
|
||||
{...createProps({
|
||||
hasValue: false,
|
||||
isInTable: true,
|
||||
isLoading: true,
|
||||
onRemove,
|
||||
placeholder: 'Loading variable',
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Loading variable')).toBeInTheDocument()
|
||||
|
||||
const buttons = screen.getAllByRole('button')
|
||||
fireEvent.click(buttons[buttons.length - 1])
|
||||
expect(onRemove).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { NodeOutPutVar, Var } from '@/app/components/workflow/types'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import {
|
||||
filterReferenceVars,
|
||||
getValueSelector,
|
||||
getVariableCategory,
|
||||
getVariableDisplayName,
|
||||
} from '../var-reference-vars.helpers'
|
||||
|
||||
describe('var-reference-vars helpers', () => {
|
||||
it('should derive display names for flat and mapped variables', () => {
|
||||
expect(getVariableDisplayName('sys.files', false)).toBe('files')
|
||||
expect(getVariableDisplayName('current', true, true)).toBe('current_code')
|
||||
expect(getVariableDisplayName('foo', true, false)).toBe('foo')
|
||||
})
|
||||
|
||||
it('should resolve variable categories', () => {
|
||||
expect(getVariableCategory({ isEnv: true, isChatVar: false })).toBe('environment')
|
||||
expect(getVariableCategory({ isEnv: false, isChatVar: true })).toBe('conversation')
|
||||
expect(getVariableCategory({ isEnv: false, isChatVar: false, isLoopVar: true })).toBe('loop')
|
||||
expect(getVariableCategory({ isEnv: false, isChatVar: false, isRagVariable: true })).toBe('rag')
|
||||
})
|
||||
|
||||
it('should build selectors by variable scope and file support', () => {
|
||||
const itemData: Var = { variable: 'output', type: VarType.string }
|
||||
expect(getValueSelector({
|
||||
itemData,
|
||||
isFlat: true,
|
||||
isSupportFileVar: true,
|
||||
isFile: false,
|
||||
isSys: false,
|
||||
isEnv: false,
|
||||
isChatVar: false,
|
||||
nodeId: 'node-1',
|
||||
objPath: [],
|
||||
})).toEqual(['output'])
|
||||
|
||||
expect(getValueSelector({
|
||||
itemData: { variable: 'env.apiKey', type: VarType.string },
|
||||
isFlat: false,
|
||||
isSupportFileVar: true,
|
||||
isFile: false,
|
||||
isSys: false,
|
||||
isEnv: true,
|
||||
isChatVar: false,
|
||||
nodeId: 'node-1',
|
||||
objPath: ['parent'],
|
||||
})).toEqual(['parent', 'env', 'apiKey'])
|
||||
|
||||
expect(getValueSelector({
|
||||
itemData: { variable: 'file', type: VarType.file },
|
||||
isFlat: false,
|
||||
isSupportFileVar: false,
|
||||
isFile: true,
|
||||
isSys: false,
|
||||
isEnv: false,
|
||||
isChatVar: false,
|
||||
nodeId: 'node-1',
|
||||
objPath: [],
|
||||
})).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should filter out invalid vars and apply search text', () => {
|
||||
const vars = filterReferenceVars([
|
||||
{
|
||||
title: 'Node A',
|
||||
nodeId: 'node-a',
|
||||
vars: [
|
||||
{ variable: 'valid_name', type: VarType.string },
|
||||
{ variable: 'invalid-key', type: VarType.string },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Node B',
|
||||
nodeId: 'node-b',
|
||||
vars: [{ variable: 'another_value', type: VarType.string }],
|
||||
},
|
||||
] as NodeOutPutVar[], 'another')
|
||||
|
||||
expect(vars).toHaveLength(1)
|
||||
expect(vars[0].title).toBe('Node B')
|
||||
expect(vars[0].vars).toEqual([expect.objectContaining({ variable: 'another_value' })])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { NodeOutPutVar } from '@/app/components/workflow/types'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import VarReferenceVars from '../var-reference-vars'
|
||||
|
||||
vi.mock('../object-child-tree-panel/picker', () => ({
|
||||
default: ({
|
||||
onHovering,
|
||||
onSelect,
|
||||
}: {
|
||||
onHovering?: (value: boolean) => void
|
||||
onSelect?: (value: string[]) => void
|
||||
}) => (
|
||||
<div>
|
||||
<button onMouseEnter={() => onHovering?.(true)} onMouseLeave={() => onHovering?.(false)}>
|
||||
picker-panel
|
||||
</button>
|
||||
<button onClick={() => onSelect?.(['node-obj', 'payload', 'child'])}>pick-child</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('../manage-input-field', () => ({
|
||||
default: ({ onManage }: { onManage: () => void }) => <button onClick={onManage}>manage-input</button>,
|
||||
}))
|
||||
|
||||
describe('VarReferenceVars', () => {
|
||||
const createVars = (vars: NodeOutPutVar[]) => vars
|
||||
|
||||
const baseVars = createVars([{
|
||||
title: 'Node A',
|
||||
nodeId: 'node-a',
|
||||
vars: [{ variable: 'valid_name', type: VarType.string }],
|
||||
}])
|
||||
|
||||
it('should filter vars through the search box and call onClose on escape', () => {
|
||||
const onClose = vi.fn()
|
||||
render(
|
||||
<VarReferenceVars
|
||||
vars={baseVars}
|
||||
onChange={vi.fn()}
|
||||
onClose={onClose}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('workflow.common.searchVar'), {
|
||||
target: { value: 'valid' },
|
||||
})
|
||||
expect(screen.getByText('valid_name')).toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(screen.getByPlaceholderText('workflow.common.searchVar'), { key: 'Escape' })
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should call onChange when a variable item is chosen', () => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferenceVars
|
||||
vars={baseVars}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText('valid_name'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['node-a', 'valid_name'], expect.objectContaining({
|
||||
variable: 'valid_name',
|
||||
}))
|
||||
})
|
||||
|
||||
it('should render empty state and manage input action', () => {
|
||||
const onManageInputField = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferenceVars
|
||||
vars={[]}
|
||||
onChange={vi.fn()}
|
||||
showManageInputField
|
||||
onManageInputField={onManageInputField}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('workflow.common.noVar')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByText('manage-input'))
|
||||
expect(onManageInputField).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should render special variable labels and schema types', () => {
|
||||
render(
|
||||
<VarReferenceVars
|
||||
hideSearch
|
||||
preferSchemaType
|
||||
vars={createVars([
|
||||
{
|
||||
title: 'Specials',
|
||||
nodeId: 'node-special',
|
||||
vars: [
|
||||
{ variable: 'env.API_KEY', type: VarType.string, schemaType: 'secret' },
|
||||
{ variable: 'conversation.user_name', type: VarType.string, des: 'User name' },
|
||||
{ variable: 'retrieval.source.title', type: VarType.string, isRagVariable: true },
|
||||
],
|
||||
},
|
||||
])}
|
||||
onChange={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.queryByPlaceholderText('workflow.common.searchVar')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('API_KEY')).toBeInTheDocument()
|
||||
expect(screen.getByText('user_name')).toBeInTheDocument()
|
||||
expect(screen.getByText('secret')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render flat vars and the last output separator', () => {
|
||||
render(
|
||||
<VarReferenceVars
|
||||
hideSearch
|
||||
vars={createVars([
|
||||
{
|
||||
title: 'Flat',
|
||||
nodeId: 'node-flat',
|
||||
isFlat: true,
|
||||
vars: [{ variable: 'current', type: VarType.string }],
|
||||
},
|
||||
{
|
||||
title: 'Node B',
|
||||
nodeId: 'node-b',
|
||||
vars: [{ variable: 'payload', type: VarType.string }],
|
||||
},
|
||||
])}
|
||||
onChange={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('workflow.debug.lastOutput')).toBeInTheDocument()
|
||||
expect(screen.getByText('current_prompt')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should resolve selectors for special variables and file support', () => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferenceVars
|
||||
hideSearch
|
||||
isSupportFileVar
|
||||
vars={createVars([
|
||||
{
|
||||
title: 'Specials',
|
||||
nodeId: 'node-special',
|
||||
vars: [
|
||||
{ variable: 'env.API_KEY', type: VarType.string },
|
||||
{ variable: 'conversation.user_name', type: VarType.string, des: 'User name' },
|
||||
{ variable: 'current', type: VarType.string },
|
||||
{ variable: 'asset', type: VarType.file },
|
||||
],
|
||||
},
|
||||
])}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText('API_KEY'))
|
||||
fireEvent.click(screen.getByText('user_name'))
|
||||
fireEvent.click(screen.getByText('current'))
|
||||
fireEvent.click(screen.getByText('asset'))
|
||||
|
||||
expect(onChange).toHaveBeenNthCalledWith(1, ['env', 'API_KEY'], expect.objectContaining({ variable: 'env.API_KEY' }))
|
||||
expect(onChange).toHaveBeenNthCalledWith(2, ['conversation', 'user_name'], expect.objectContaining({ variable: 'conversation.user_name' }))
|
||||
expect(onChange).toHaveBeenNthCalledWith(3, ['node-special', 'current'], expect.objectContaining({ variable: 'current' }))
|
||||
expect(onChange).toHaveBeenNthCalledWith(4, ['node-special', 'asset'], expect.objectContaining({ variable: 'asset' }))
|
||||
})
|
||||
|
||||
it('should render object vars and select them by node path', () => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferenceVars
|
||||
hideSearch
|
||||
vars={createVars([
|
||||
{
|
||||
title: 'Object vars',
|
||||
nodeId: 'node-obj',
|
||||
vars: [{
|
||||
variable: 'payload',
|
||||
type: VarType.object,
|
||||
children: [{ variable: 'child', type: VarType.string }],
|
||||
}],
|
||||
},
|
||||
])}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText('payload'))
|
||||
expect(onChange).toHaveBeenCalledWith(['node-obj', 'payload'], expect.objectContaining({
|
||||
variable: 'payload',
|
||||
}))
|
||||
})
|
||||
|
||||
it('should ignore file vars when file support is disabled and forward blur events', () => {
|
||||
const onChange = vi.fn()
|
||||
const onBlur = vi.fn()
|
||||
|
||||
render(
|
||||
<VarReferenceVars
|
||||
vars={createVars([
|
||||
{
|
||||
title: 'Files',
|
||||
nodeId: 'node-files',
|
||||
vars: [{ variable: 'asset', type: VarType.file }],
|
||||
},
|
||||
])}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.blur(screen.getByPlaceholderText('workflow.common.searchVar'))
|
||||
expect(onBlur).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.click(screen.getByText('asset'))
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,221 @@
|
||||
'use client'
|
||||
|
||||
import type { VarType as VarKindType } from '../../../tool/types'
|
||||
import type { CredentialFormSchema, FormOption } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { CommonNodeType, Node, ValueSelector } from '@/app/components/workflow/types'
|
||||
import { VAR_SHOW_NAME_MAP } from '@/app/components/workflow/constants'
|
||||
import { getNodeInfoById, isConversationVar, isENV, isGlobalVar, isRagVariableVar, isSystemVar } from './utils'
|
||||
|
||||
type DynamicSchemaParams = {
|
||||
dynamicOptions: FormOption[] | null
|
||||
isLoading: boolean
|
||||
schema?: Partial<CredentialFormSchema>
|
||||
value: ValueSelector | string
|
||||
}
|
||||
|
||||
type VariableCategoryParams = {
|
||||
isChatVar: boolean
|
||||
isEnv: boolean
|
||||
isGlobal: boolean
|
||||
isLoopVar: boolean
|
||||
isRagVar: boolean
|
||||
}
|
||||
|
||||
type OutputVarNodeParams = {
|
||||
availableNodes: Node[]
|
||||
hasValue: boolean
|
||||
isConstant: boolean
|
||||
isIterationVar: boolean
|
||||
isLoopVar: boolean
|
||||
iterationNode: Node<CommonNodeType> | null
|
||||
loopNode: Node<CommonNodeType> | null
|
||||
outputVarNodeId: string
|
||||
startNode?: Node | null
|
||||
value: ValueSelector | string
|
||||
}
|
||||
|
||||
export const getVarKindOptions = (variableLabel = 'Variable', constantLabel = 'Constant') => ([
|
||||
{ label: variableLabel, value: 'variable' as VarKindType },
|
||||
{ label: constantLabel, value: 'constant' as VarKindType },
|
||||
])
|
||||
|
||||
export const getHasValue = (isConstant: boolean, value: ValueSelector | string) =>
|
||||
!isConstant && value.length > 0
|
||||
|
||||
export const getIsIterationVar = (
|
||||
isInIteration: boolean,
|
||||
value: ValueSelector | string,
|
||||
parentId?: string,
|
||||
) => {
|
||||
if (!isInIteration || !Array.isArray(value))
|
||||
return false
|
||||
return value[0] === parentId && ['item', 'index'].includes(value[1])
|
||||
}
|
||||
|
||||
export const getIsLoopVar = (
|
||||
isInLoop: boolean,
|
||||
value: ValueSelector | string,
|
||||
parentId?: string,
|
||||
) => {
|
||||
if (!isInLoop || !Array.isArray(value))
|
||||
return false
|
||||
return value[0] === parentId && ['item', 'index'].includes(value[1])
|
||||
}
|
||||
|
||||
export const getOutputVarNode = ({
|
||||
availableNodes,
|
||||
hasValue,
|
||||
isConstant,
|
||||
isIterationVar,
|
||||
isLoopVar,
|
||||
iterationNode,
|
||||
loopNode,
|
||||
outputVarNodeId,
|
||||
startNode,
|
||||
value,
|
||||
}: OutputVarNodeParams) => {
|
||||
if (!hasValue || isConstant)
|
||||
return null
|
||||
|
||||
if (isIterationVar)
|
||||
return iterationNode?.data ?? null
|
||||
|
||||
if (isLoopVar)
|
||||
return loopNode?.data ?? null
|
||||
|
||||
if (isSystemVar(value as ValueSelector))
|
||||
return startNode?.data ?? null
|
||||
|
||||
const node = getNodeInfoById(availableNodes, outputVarNodeId)?.data
|
||||
if (!node)
|
||||
return null
|
||||
|
||||
return {
|
||||
...node,
|
||||
id: outputVarNodeId,
|
||||
}
|
||||
}
|
||||
|
||||
export const getVarDisplayName = (
|
||||
hasValue: boolean,
|
||||
value: ValueSelector | string,
|
||||
) => {
|
||||
if (!hasValue || !Array.isArray(value))
|
||||
return ''
|
||||
|
||||
const showName = VAR_SHOW_NAME_MAP[value.join('.')]
|
||||
if (showName)
|
||||
return showName
|
||||
|
||||
const isSystem = isSystemVar(value)
|
||||
const varName = value[value.length - 1] ?? ''
|
||||
return `${isSystem ? 'sys.' : ''}${varName}`
|
||||
}
|
||||
|
||||
export const getVariableMeta = (
|
||||
outputVarNode: { type?: string } | null,
|
||||
value: ValueSelector | string,
|
||||
varName: string,
|
||||
) => {
|
||||
const selector = value as ValueSelector
|
||||
const isEnv = isENV(selector)
|
||||
const isChatVar = isConversationVar(selector)
|
||||
const isGlobal = isGlobalVar(selector)
|
||||
const isRagVar = isRagVariableVar(selector)
|
||||
const isValidVar = Boolean(outputVarNode) || isEnv || isChatVar || isGlobal || isRagVar
|
||||
return {
|
||||
isChatVar,
|
||||
isEnv,
|
||||
isGlobal,
|
||||
isRagVar,
|
||||
isValidVar,
|
||||
isException: Boolean(varName && outputVarNode?.type),
|
||||
}
|
||||
}
|
||||
|
||||
export const getVariableCategory = ({
|
||||
isChatVar,
|
||||
isEnv,
|
||||
isGlobal,
|
||||
isLoopVar,
|
||||
isRagVar,
|
||||
}: VariableCategoryParams) => {
|
||||
if (isEnv)
|
||||
return 'environment'
|
||||
if (isChatVar)
|
||||
return 'conversation'
|
||||
if (isGlobal)
|
||||
return 'global'
|
||||
if (isLoopVar)
|
||||
return 'loop'
|
||||
if (isRagVar)
|
||||
return 'rag'
|
||||
return 'system'
|
||||
}
|
||||
|
||||
export const getWidthAllocations = (
|
||||
triggerWidth: number,
|
||||
nodeTitle: string,
|
||||
varName: string,
|
||||
type: string,
|
||||
) => {
|
||||
const availableWidth = triggerWidth - 56
|
||||
const totalTextLength = (nodeTitle + varName + type).length || 1
|
||||
const priorityWidth = 15
|
||||
return {
|
||||
maxNodeNameWidth: priorityWidth + Math.floor(nodeTitle.length / totalTextLength * availableWidth),
|
||||
maxTypeWidth: Math.floor(type.length / totalTextLength * availableWidth),
|
||||
maxVarNameWidth: -priorityWidth + Math.floor(varName.length / totalTextLength * availableWidth),
|
||||
}
|
||||
}
|
||||
|
||||
export const getDynamicSelectSchema = ({
|
||||
dynamicOptions,
|
||||
isLoading,
|
||||
schema,
|
||||
value,
|
||||
}: DynamicSchemaParams) => {
|
||||
if (schema?.type !== 'dynamic-select')
|
||||
return schema
|
||||
|
||||
if (dynamicOptions) {
|
||||
return {
|
||||
...schema,
|
||||
options: dynamicOptions,
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading && value && typeof value === 'string') {
|
||||
return {
|
||||
...schema,
|
||||
options: [{
|
||||
value,
|
||||
label: { en_US: value, zh_Hans: value },
|
||||
show_on: [],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...schema,
|
||||
options: [],
|
||||
}
|
||||
}
|
||||
|
||||
export const getTooltipContent = (
|
||||
hasValue: boolean,
|
||||
isShowAPart: boolean,
|
||||
isValidVar: boolean,
|
||||
) => {
|
||||
if (isValidVar && isShowAPart)
|
||||
return 'full-path'
|
||||
if (!isValidVar && hasValue)
|
||||
return 'invalid-variable'
|
||||
return null
|
||||
}
|
||||
|
||||
export const getOutputVarNodeId = (hasValue: boolean, value: ValueSelector | string) =>
|
||||
hasValue && Array.isArray(value) ? value[0] : ''
|
||||
|
||||
export const isShowAPartSelector = (value: ValueSelector | string) =>
|
||||
Array.isArray(value) && value.length > 2 && !isRagVariableVar(value)
|
||||
@@ -0,0 +1,315 @@
|
||||
'use client'
|
||||
|
||||
import type { FC, ReactNode } from 'react'
|
||||
import type { VarType as VarKindType } from '../../../tool/types'
|
||||
import type { CredentialFormSchema, CredentialFormSchemaSelect } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import type { Tool } from '@/app/components/tools/types'
|
||||
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
|
||||
import type { Node, ToolWithProvider, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { RiArrowDownSLine, RiCloseLine, RiErrorWarningFill, RiLoader4Line, RiMoreLine } from '@remixicon/react'
|
||||
import Badge from '@/app/components/base/badge'
|
||||
import AddButton from '@/app/components/base/button/add-button'
|
||||
import { Line3 } from '@/app/components/base/icons/src/public/common'
|
||||
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'
|
||||
import TypeSelector from '@/app/components/workflow/nodes/_base/components/selector'
|
||||
import { VariableIconWithColor } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import RemoveButton from '../remove-button'
|
||||
import ConstantField from './constant-field'
|
||||
|
||||
type Props = {
|
||||
className?: string
|
||||
controlFocus: number
|
||||
currentProvider?: ToolWithProvider | TriggerWithProvider
|
||||
currentTool?: Tool
|
||||
handleClearVar: () => void
|
||||
handleVarKindTypeChange: (value: VarKindType) => void
|
||||
handleVariableJump: (nodeId: string) => void
|
||||
hasValue: boolean
|
||||
inputRef: React.RefObject<HTMLInputElement | null>
|
||||
inTable?: boolean
|
||||
isAddBtnTrigger?: boolean
|
||||
isConstant: boolean
|
||||
isException: boolean
|
||||
isFocus: boolean
|
||||
isInTable?: boolean
|
||||
isJustShowValue?: boolean
|
||||
isLoading: boolean
|
||||
isShowAPart: boolean
|
||||
isShowNodeName: boolean
|
||||
isSupportConstantValue?: boolean
|
||||
maxNodeNameWidth: number
|
||||
maxTypeWidth: number
|
||||
maxVarNameWidth: number
|
||||
onChange: (value: ValueSelector | string, varKindType: VarKindType, varInfo?: Var) => void
|
||||
onRemove?: () => void
|
||||
open: boolean
|
||||
outputVarNode?: Node['data'] | null
|
||||
outputVarNodeId?: string
|
||||
placeholder?: string
|
||||
readonly: boolean
|
||||
schemaWithDynamicSelect?: Partial<CredentialFormSchema>
|
||||
setControlFocus: (value: number) => void
|
||||
setOpen: (value: boolean) => void
|
||||
tooltipPopup: ReactNode
|
||||
triggerRef: React.RefObject<HTMLDivElement | null>
|
||||
type?: string
|
||||
typePlaceHolder?: string
|
||||
value: ValueSelector | string
|
||||
valueTypePlaceHolder?: string
|
||||
varKindType: VarKindType
|
||||
varKindTypes: Array<{ label: string, value: VarKindType }>
|
||||
varName: string
|
||||
variableCategory: string
|
||||
WrapElem: React.ElementType
|
||||
VarPickerWrap: React.ElementType
|
||||
}
|
||||
|
||||
const VarReferencePickerTrigger: FC<Props> = ({
|
||||
className,
|
||||
controlFocus,
|
||||
handleClearVar,
|
||||
handleVarKindTypeChange,
|
||||
handleVariableJump,
|
||||
hasValue,
|
||||
inputRef,
|
||||
isAddBtnTrigger,
|
||||
isConstant,
|
||||
isException,
|
||||
isFocus,
|
||||
isInTable,
|
||||
isJustShowValue,
|
||||
isLoading,
|
||||
isShowAPart,
|
||||
isShowNodeName,
|
||||
isSupportConstantValue,
|
||||
maxNodeNameWidth,
|
||||
maxTypeWidth,
|
||||
maxVarNameWidth,
|
||||
onChange,
|
||||
onRemove,
|
||||
open,
|
||||
outputVarNode,
|
||||
outputVarNodeId,
|
||||
placeholder,
|
||||
readonly,
|
||||
schemaWithDynamicSelect,
|
||||
setControlFocus,
|
||||
setOpen,
|
||||
tooltipPopup,
|
||||
triggerRef,
|
||||
type,
|
||||
typePlaceHolder,
|
||||
value,
|
||||
valueTypePlaceHolder,
|
||||
varKindType,
|
||||
varKindTypes,
|
||||
varName,
|
||||
variableCategory,
|
||||
VarPickerWrap,
|
||||
WrapElem,
|
||||
}) => {
|
||||
return (
|
||||
<WrapElem
|
||||
onClick={() => {
|
||||
if (readonly)
|
||||
return
|
||||
if (!isConstant)
|
||||
setOpen(!open)
|
||||
else
|
||||
setControlFocus(Date.now())
|
||||
}}
|
||||
className={cn(className, 'group/picker-trigger-wrap relative !flex', !readonly && 'cursor-pointer')}
|
||||
data-testid="var-reference-picker-trigger"
|
||||
>
|
||||
<>
|
||||
{isAddBtnTrigger
|
||||
? (
|
||||
<div>
|
||||
<AddButton onClick={() => {}}></AddButton>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<div ref={!isSupportConstantValue ? triggerRef : null} className={cn((open || isFocus) ? 'border-gray-300' : 'border-gray-100', 'group/wrap relative flex h-8 w-full items-center', !isSupportConstantValue && 'rounded-lg bg-components-input-bg-normal p-1', isInTable && 'border-none bg-transparent', readonly && 'bg-components-input-bg-disabled', isJustShowValue && 'h-6 bg-transparent p-0')}>
|
||||
{isSupportConstantValue
|
||||
? (
|
||||
<div
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setOpen(false)
|
||||
setControlFocus(Date.now())
|
||||
}}
|
||||
className="mr-1 flex h-full items-center space-x-1"
|
||||
>
|
||||
<TypeSelector
|
||||
noLeft
|
||||
trigger={(
|
||||
<div className="flex h-8 items-center bg-components-input-bg-normal px-2 radius-md">
|
||||
<div className="mr-1 text-components-input-text-filled system-sm-regular">{varKindTypes.find(item => item.value === varKindType)?.label}</div>
|
||||
<RiArrowDownSLine className="h-4 w-4 text-text-quaternary" />
|
||||
</div>
|
||||
)}
|
||||
popupClassName="top-8"
|
||||
readonly={readonly}
|
||||
value={varKindType}
|
||||
options={varKindTypes}
|
||||
onChange={handleVarKindTypeChange}
|
||||
showChecked
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
: (!hasValue && (
|
||||
<div className="ml-1.5 mr-1">
|
||||
<Variable02 className={`h-4 w-4 ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'}`} />
|
||||
</div>
|
||||
))}
|
||||
{isConstant
|
||||
? (
|
||||
<ConstantField
|
||||
value={value as string}
|
||||
onChange={onChange as ((value: string | number, varKindType: VarKindType, varInfo?: Var) => void)}
|
||||
schema={schemaWithDynamicSelect as CredentialFormSchemaSelect}
|
||||
readonly={readonly}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<VarPickerWrap
|
||||
onClick={() => {
|
||||
if (readonly)
|
||||
return
|
||||
if (!isConstant)
|
||||
setOpen(!open)
|
||||
else
|
||||
setControlFocus(Date.now())
|
||||
}}
|
||||
className="h-full grow"
|
||||
>
|
||||
<div ref={isSupportConstantValue ? triggerRef : null} className={cn('h-full', isSupportConstantValue && 'flex items-center rounded-lg bg-components-panel-bg py-1 pl-1')}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
disabled={!tooltipPopup}
|
||||
render={(
|
||||
<div className={cn('h-full items-center rounded-[5px] px-1.5', hasValue ? 'inline-flex bg-components-badge-white-to-dark' : 'flex')}>
|
||||
{hasValue
|
||||
? (
|
||||
<>
|
||||
{isShowNodeName && (
|
||||
<div
|
||||
className="flex items-center"
|
||||
onClick={(e) => {
|
||||
if (e.metaKey || e.ctrlKey)
|
||||
handleVariableJump(outputVarNodeId || '')
|
||||
}}
|
||||
>
|
||||
<div className="h-3 px-[1px]">
|
||||
{'type' in (outputVarNode || {}) && outputVarNode?.type && (
|
||||
<div className="h-3 w-3" />
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className="mx-0.5 truncate text-xs font-medium text-text-secondary"
|
||||
title={outputVarNode?.title as string | undefined}
|
||||
style={{ maxWidth: maxNodeNameWidth }}
|
||||
>
|
||||
{outputVarNode?.title as string | undefined}
|
||||
</div>
|
||||
<Line3 className="mr-0.5"></Line3>
|
||||
</div>
|
||||
)}
|
||||
{isShowAPart && (
|
||||
<div className="flex items-center">
|
||||
<RiMoreLine className="h-3 w-3 text-text-secondary" />
|
||||
<Line3 className="mr-0.5 text-divider-deep"></Line3>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center text-text-accent">
|
||||
{isLoading && <RiLoader4Line className="h-3.5 w-3.5 animate-spin text-text-secondary" />}
|
||||
<VariableIconWithColor
|
||||
variables={value as ValueSelector}
|
||||
variableCategory={variableCategory}
|
||||
isExceptionVariable={isException}
|
||||
/>
|
||||
<div
|
||||
className={cn('ml-0.5 truncate text-xs font-medium', isException && 'text-text-warning')}
|
||||
title={varName}
|
||||
style={{ maxWidth: maxVarNameWidth }}
|
||||
>
|
||||
{varName}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="ml-0.5 truncate text-center capitalize text-text-tertiary system-xs-regular"
|
||||
title={type}
|
||||
style={{ maxWidth: maxTypeWidth }}
|
||||
>
|
||||
{type}
|
||||
</div>
|
||||
{!('title' in (outputVarNode || {})) && <RiErrorWarningFill className="ml-0.5 h-3 w-3 text-text-destructive" />}
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<div className={`overflow-hidden ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'} text-ellipsis system-sm-regular`}>
|
||||
{isLoading
|
||||
? (
|
||||
<div className="flex items-center">
|
||||
<RiLoader4Line className="mr-1 h-3.5 w-3.5 animate-spin text-text-secondary" />
|
||||
<span>{placeholder}</span>
|
||||
</div>
|
||||
)
|
||||
: placeholder}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{tooltipPopup !== null && tooltipPopup !== undefined && (
|
||||
<TooltipContent variant="plain">
|
||||
{tooltipPopup}
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
</VarPickerWrap>
|
||||
)}
|
||||
{(hasValue && !readonly && !isInTable && !isJustShowValue) && (
|
||||
<div
|
||||
className="group invisible absolute right-1 top-[50%] h-5 translate-y-[-50%] cursor-pointer rounded-md p-1 hover:bg-state-base-hover group-hover/wrap:visible"
|
||||
onClick={handleClearVar}
|
||||
data-testid="var-reference-picker-clear"
|
||||
>
|
||||
<RiCloseLine className="h-3.5 w-3.5 text-text-tertiary group-hover:text-text-secondary" />
|
||||
</div>
|
||||
)}
|
||||
{!hasValue && valueTypePlaceHolder && (
|
||||
<Badge
|
||||
className="absolute right-1 top-[50%] translate-y-[-50%] capitalize"
|
||||
text={valueTypePlaceHolder}
|
||||
uppercase={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!readonly && isInTable && (
|
||||
<RemoveButton
|
||||
className="absolute right-1 top-0.5 hidden group-hover/picker-trigger-wrap:block"
|
||||
onClick={() => onRemove?.()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!hasValue && typePlaceHolder && (
|
||||
<Badge
|
||||
className="absolute right-2 top-1.5"
|
||||
text={typePlaceHolder}
|
||||
uppercase={false}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
<input ref={inputRef} className="sr-only" value={controlFocus} readOnly />
|
||||
</WrapElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default VarReferencePickerTrigger
|
||||
@@ -4,13 +4,6 @@ import type { CredentialFormSchema, CredentialFormSchemaSelect, FormOption } fro
|
||||
import type { Tool } from '@/app/components/tools/types'
|
||||
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
|
||||
import type { CommonNodeType, Node, NodeOutPutVar, ToolWithProvider, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import {
|
||||
RiArrowDownSLine,
|
||||
RiCloseLine,
|
||||
RiErrorWarningFill,
|
||||
RiLoader4Line,
|
||||
RiMoreLine,
|
||||
} from '@remixicon/react'
|
||||
import { noop } from 'es-toolkit/function'
|
||||
import { produce } from 'immer'
|
||||
import * as React from 'react'
|
||||
@@ -21,36 +14,41 @@ import {
|
||||
useReactFlow,
|
||||
useStoreApi,
|
||||
} from 'reactflow'
|
||||
import Badge from '@/app/components/base/badge'
|
||||
import AddButton from '@/app/components/base/button/add-button'
|
||||
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 Tooltip from '@/app/components/base/tooltip'
|
||||
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { VarBlockIcon } from '@/app/components/workflow/block-icon'
|
||||
import { VAR_SHOW_NAME_MAP } from '@/app/components/workflow/constants'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useWorkflowVariables,
|
||||
} from '@/app/components/workflow/hooks'
|
||||
// import type { BaseResource, BaseResourceProvider } from '@/app/components/workflow/nodes/_base/types'
|
||||
import TypeSelector from '@/app/components/workflow/nodes/_base/components/selector'
|
||||
import { VariableIconWithColor } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'
|
||||
import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { isExceptionVariable } from '@/app/components/workflow/utils'
|
||||
import { useFetchDynamicOptions } from '@/service/use-plugins'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import useAvailableVarList from '../../hooks/use-available-var-list'
|
||||
import RemoveButton from '../remove-button'
|
||||
import ConstantField from './constant-field'
|
||||
import { getNodeInfoById, isConversationVar, isENV, isGlobalVar, isRagVariableVar, isSystemVar, removeFileVars, varTypeToStructType } from './utils'
|
||||
import { removeFileVars, varTypeToStructType } from './utils'
|
||||
import VarFullPathPanel from './var-full-path-panel'
|
||||
import {
|
||||
getDynamicSelectSchema,
|
||||
getHasValue,
|
||||
getIsIterationVar,
|
||||
getIsLoopVar,
|
||||
getOutputVarNode,
|
||||
getOutputVarNodeId,
|
||||
getTooltipContent,
|
||||
getVarDisplayName,
|
||||
getVariableCategory,
|
||||
getVariableMeta,
|
||||
getVarKindOptions,
|
||||
getWidthAllocations,
|
||||
isShowAPartSelector,
|
||||
} from './var-reference-picker.helpers'
|
||||
import VarReferencePickerTrigger from './var-reference-picker.trigger'
|
||||
import VarReferencePopup from './var-reference-popup'
|
||||
|
||||
const TRIGGER_DEFAULT_WIDTH = 227
|
||||
@@ -141,17 +139,17 @@ const VarReferencePicker: FC<Props> = ({
|
||||
|
||||
const node = nodes.find(n => n.id === nodeId)
|
||||
const isInIteration = !!(node?.data as any)?.isInIteration
|
||||
const iterationNode = isInIteration ? nodes.find(n => n.id === node?.parentId) : null
|
||||
const iterationNode = isInIteration ? (nodes.find(n => n.id === node?.parentId) ?? null) : null
|
||||
|
||||
const isInLoop = !!(node?.data as any)?.isInLoop
|
||||
const loopNode = isInLoop ? nodes.find(n => n.id === node?.parentId) : null
|
||||
const loopNode = isInLoop ? (nodes.find(n => n.id === node?.parentId) ?? null) : null
|
||||
|
||||
const triggerRef = useRef<HTMLDivElement>(null)
|
||||
const [triggerWidth, setTriggerWidth] = useState(TRIGGER_DEFAULT_WIDTH)
|
||||
useEffect(() => {
|
||||
if (triggerRef.current)
|
||||
setTriggerWidth(triggerRef.current.clientWidth)
|
||||
}, [triggerRef.current])
|
||||
}, [])
|
||||
|
||||
const [varKindType, setVarKindType] = useState<VarKindType>(defaultVarKindType)
|
||||
const isConstant = isSupportConstantValue && varKindType === VarKindType.constant
|
||||
@@ -164,72 +162,41 @@ const VarReferencePicker: FC<Props> = ({
|
||||
const [open, setOpen] = useState(false)
|
||||
useEffect(() => {
|
||||
onOpen()
|
||||
}, [open])
|
||||
const hasValue = !isConstant && value.length > 0
|
||||
}, [open, onOpen])
|
||||
const hasValue = getHasValue(!!isConstant, value)
|
||||
|
||||
const isIterationVar = useMemo(() => {
|
||||
if (!isInIteration)
|
||||
return false
|
||||
if (value[0] === node?.parentId && ['item', 'index'].includes(value[1]))
|
||||
return true
|
||||
return false
|
||||
}, [isInIteration, value, node])
|
||||
const isIterationVar = useMemo(
|
||||
() => getIsIterationVar(isInIteration, value, node?.parentId),
|
||||
[isInIteration, node?.parentId, value],
|
||||
)
|
||||
|
||||
const isLoopVar = useMemo(() => {
|
||||
if (!isInLoop)
|
||||
return false
|
||||
if (value[0] === node?.parentId && ['item', 'index'].includes(value[1]))
|
||||
return true
|
||||
return false
|
||||
}, [isInLoop, value, node])
|
||||
const isLoopVar = useMemo(
|
||||
() => getIsLoopVar(isInLoop, value, node?.parentId),
|
||||
[isInLoop, node?.parentId, value],
|
||||
)
|
||||
|
||||
const outputVarNodeId = hasValue ? value[0] : ''
|
||||
const outputVarNode = useMemo(() => {
|
||||
if (!hasValue || isConstant)
|
||||
return null
|
||||
const outputVarNodeId = getOutputVarNodeId(hasValue, value)
|
||||
const outputVarNode = useMemo(() => getOutputVarNode({
|
||||
availableNodes,
|
||||
hasValue,
|
||||
isConstant: !!isConstant,
|
||||
isIterationVar,
|
||||
isLoopVar,
|
||||
iterationNode,
|
||||
loopNode,
|
||||
outputVarNodeId,
|
||||
startNode,
|
||||
value,
|
||||
}), [availableNodes, hasValue, isConstant, isIterationVar, isLoopVar, iterationNode, loopNode, outputVarNodeId, startNode, value])
|
||||
|
||||
if (isIterationVar)
|
||||
return iterationNode?.data
|
||||
const isShowAPart = isShowAPartSelector(value)
|
||||
|
||||
if (isLoopVar)
|
||||
return loopNode?.data
|
||||
const varName = useMemo(
|
||||
() => getVarDisplayName(hasValue, value),
|
||||
[hasValue, value],
|
||||
)
|
||||
|
||||
if (isSystemVar(value as ValueSelector))
|
||||
return startNode?.data
|
||||
|
||||
const node = getNodeInfoById(availableNodes, outputVarNodeId)?.data
|
||||
if (node) {
|
||||
return {
|
||||
...node,
|
||||
id: outputVarNodeId,
|
||||
}
|
||||
}
|
||||
}, [value, hasValue, isConstant, isIterationVar, iterationNode, availableNodes, outputVarNodeId, startNode, isLoopVar, loopNode])
|
||||
|
||||
const isShowAPart = (value as ValueSelector).length > 2 && !isRagVariableVar((value as ValueSelector))
|
||||
|
||||
const varName = useMemo(() => {
|
||||
if (!hasValue)
|
||||
return ''
|
||||
const showName = VAR_SHOW_NAME_MAP[(value as ValueSelector).join('.')]
|
||||
if (showName)
|
||||
return showName
|
||||
|
||||
const isSystem = isSystemVar(value as ValueSelector)
|
||||
const varName = Array.isArray(value) ? value[(value as ValueSelector).length - 1] : ''
|
||||
return `${isSystem ? 'sys.' : ''}${varName}`
|
||||
}, [hasValue, value])
|
||||
|
||||
const varKindTypes = [
|
||||
{
|
||||
label: 'Variable',
|
||||
value: VarKindType.variable,
|
||||
},
|
||||
{
|
||||
label: 'Constant',
|
||||
value: VarKindType.constant,
|
||||
},
|
||||
]
|
||||
const varKindTypes = getVarKindOptions()
|
||||
|
||||
const handleVarKindTypeChange = useCallback((value: VarKindType) => {
|
||||
setVarKindType(value)
|
||||
@@ -302,39 +269,28 @@ const VarReferencePicker: FC<Props> = ({
|
||||
preferSchemaType,
|
||||
})
|
||||
|
||||
const { isEnv, isChatVar, isGlobal, isRagVar, isValidVar, isException } = useMemo(() => {
|
||||
const isEnv = isENV(value as ValueSelector)
|
||||
const isChatVar = isConversationVar(value as ValueSelector)
|
||||
const isGlobal = isGlobalVar(value as ValueSelector)
|
||||
const isRagVar = isRagVariableVar(value as ValueSelector)
|
||||
const isValidVar = Boolean(outputVarNode) || isEnv || isChatVar || isGlobal || isRagVar
|
||||
const isException = isExceptionVariable(varName, outputVarNode?.type)
|
||||
return {
|
||||
isEnv,
|
||||
isChatVar,
|
||||
isGlobal,
|
||||
isRagVar,
|
||||
isValidVar,
|
||||
isException,
|
||||
}
|
||||
}, [value, outputVarNode, varName])
|
||||
const { isEnv, isChatVar, isGlobal, isRagVar, isValidVar } = useMemo(
|
||||
() => getVariableMeta(outputVarNode, value, varName),
|
||||
[outputVarNode, value, varName],
|
||||
)
|
||||
const isException = useMemo(
|
||||
() => isExceptionVariable(varName, outputVarNode?.type),
|
||||
[outputVarNode?.type, varName],
|
||||
)
|
||||
|
||||
// 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]
|
||||
})()
|
||||
const {
|
||||
maxNodeNameWidth,
|
||||
maxTypeWidth,
|
||||
maxVarNameWidth,
|
||||
} = getWidthAllocations(triggerWidth, outputVarNode?.title || '', varName || '', type || '')
|
||||
|
||||
const WrapElem = isSupportConstantValue ? 'div' : PortalToFollowElemTrigger
|
||||
const VarPickerWrap = !isSupportConstantValue ? 'div' : PortalToFollowElemTrigger
|
||||
|
||||
const tooltipPopup = useMemo(() => {
|
||||
if (isValidVar && isShowAPart) {
|
||||
const tooltipType = getTooltipContent(hasValue, isShowAPart, isValidVar)
|
||||
if (tooltipType === 'full-path') {
|
||||
return (
|
||||
<VarFullPathPanel
|
||||
nodeName={outputVarNode?.title}
|
||||
@@ -344,7 +300,7 @@ const VarReferencePicker: FC<Props> = ({
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (!isValidVar && hasValue)
|
||||
if (tooltipType === 'invalid-variable')
|
||||
return t('errorMsg.invalidVariable', { ns: 'workflow' })
|
||||
|
||||
return null
|
||||
@@ -359,7 +315,7 @@ const VarReferencePicker: FC<Props> = ({
|
||||
(schema as CredentialFormSchemaSelect)?.variable || '',
|
||||
'tool',
|
||||
)
|
||||
const handleFetchDynamicOptions = async () => {
|
||||
const handleFetchDynamicOptions = useCallback(async () => {
|
||||
if (schema?.type !== FormTypeEnum.dynamicSelect || !currentTool || !currentProvider)
|
||||
return
|
||||
setIsLoading(true)
|
||||
@@ -370,58 +326,25 @@ const VarReferencePicker: FC<Props> = ({
|
||||
finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
}, [currentProvider, currentTool, fetchDynamicOptions, schema?.type])
|
||||
useEffect(() => {
|
||||
handleFetchDynamicOptions()
|
||||
}, [currentTool, currentProvider, schema])
|
||||
}, [handleFetchDynamicOptions])
|
||||
|
||||
const schemaWithDynamicSelect = useMemo(() => {
|
||||
if (schema?.type !== FormTypeEnum.dynamicSelect)
|
||||
return schema
|
||||
// rewrite schema.options with dynamicOptions
|
||||
if (dynamicOptions) {
|
||||
return {
|
||||
...schema,
|
||||
options: dynamicOptions,
|
||||
}
|
||||
}
|
||||
const schemaWithDynamicSelect = useMemo(
|
||||
() => getDynamicSelectSchema({ dynamicOptions, isLoading, schema, value }),
|
||||
[dynamicOptions, isLoading, schema, value],
|
||||
)
|
||||
|
||||
// If we don't have dynamic options but we have a selected value, create a temporary option to preserve the selection during loading
|
||||
if (isLoading && value && typeof value === 'string') {
|
||||
const preservedOptions = [{
|
||||
value,
|
||||
label: { en_US: value, zh_Hans: value },
|
||||
show_on: [],
|
||||
}]
|
||||
return {
|
||||
...schema,
|
||||
options: preservedOptions,
|
||||
}
|
||||
}
|
||||
const variableCategory = useMemo(
|
||||
() => getVariableCategory({ isChatVar, isEnv, isGlobal, isLoopVar, isRagVar }),
|
||||
[isChatVar, isEnv, isGlobal, isLoopVar, isRagVar],
|
||||
)
|
||||
|
||||
// Default case: return schema with empty options
|
||||
return {
|
||||
...schema,
|
||||
options: [],
|
||||
}
|
||||
}, [schema, dynamicOptions, isLoading, value])
|
||||
|
||||
const variableCategory = useMemo(() => {
|
||||
if (isEnv)
|
||||
return 'environment'
|
||||
if (isChatVar)
|
||||
return 'conversation'
|
||||
if (isGlobal)
|
||||
return 'global'
|
||||
if (isLoopVar)
|
||||
return 'loop'
|
||||
if (isRagVar)
|
||||
return 'rag'
|
||||
return 'system'
|
||||
}, [isEnv, isChatVar, isGlobal, isLoopVar, isRagVar])
|
||||
const triggerPlaceholder = placeholder ?? t('common.setVarValuePlaceholder', { ns: 'workflow' })
|
||||
|
||||
return (
|
||||
<div className={cn(className, !readonly && 'cursor-pointer')}>
|
||||
<div className={cn(className)}>
|
||||
<PortalToFollowElem
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
@@ -429,204 +352,52 @@ const VarReferencePicker: FC<Props> = ({
|
||||
>
|
||||
{!!trigger && <PortalToFollowElemTrigger onClick={() => setOpen(!open)}>{trigger}</PortalToFollowElemTrigger>}
|
||||
{!trigger && (
|
||||
<WrapElem
|
||||
onClick={() => {
|
||||
if (readonly)
|
||||
return
|
||||
if (!isConstant)
|
||||
setOpen(!open)
|
||||
else
|
||||
setControlFocus(Date.now())
|
||||
}}
|
||||
className="group/picker-trigger-wrap relative !flex"
|
||||
>
|
||||
<>
|
||||
{isAddBtnTrigger
|
||||
? (
|
||||
<div>
|
||||
<AddButton onClick={noop}></AddButton>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<div ref={!isSupportConstantValue ? triggerRef : null} className={cn((open || isFocus) ? 'border-gray-300' : 'border-gray-100', 'group/wrap relative flex h-8 w-full items-center', !isSupportConstantValue && 'rounded-lg bg-components-input-bg-normal p-1', isInTable && 'border-none bg-transparent', readonly && 'bg-components-input-bg-disabled', isJustShowValue && 'h-6 bg-transparent p-0')}>
|
||||
{isSupportConstantValue
|
||||
? (
|
||||
<div
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setOpen(false)
|
||||
setControlFocus(Date.now())
|
||||
}}
|
||||
className="mr-1 flex h-full items-center space-x-1"
|
||||
>
|
||||
<TypeSelector
|
||||
noLeft
|
||||
trigger={(
|
||||
<div className="radius-md flex h-8 items-center bg-components-input-bg-normal px-2">
|
||||
<div className="system-sm-regular mr-1 text-components-input-text-filled">{varKindTypes.find(item => item.value === varKindType)?.label}</div>
|
||||
<RiArrowDownSLine className="h-4 w-4 text-text-quaternary" />
|
||||
</div>
|
||||
)}
|
||||
popupClassName="top-8"
|
||||
readonly={readonly}
|
||||
value={varKindType}
|
||||
options={varKindTypes}
|
||||
onChange={handleVarKindTypeChange}
|
||||
showChecked
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
: (!hasValue && (
|
||||
<div className="ml-1.5 mr-1">
|
||||
<Variable02 className={`h-4 w-4 ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'}`} />
|
||||
</div>
|
||||
))}
|
||||
{isConstant
|
||||
? (
|
||||
<ConstantField
|
||||
value={value as string}
|
||||
onChange={onChange as ((value: string | number, varKindType: VarKindType, varInfo?: Var) => void)}
|
||||
schema={schemaWithDynamicSelect as CredentialFormSchema}
|
||||
readonly={readonly}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<VarPickerWrap
|
||||
onClick={() => {
|
||||
if (readonly)
|
||||
return
|
||||
if (!isConstant)
|
||||
setOpen(!open)
|
||||
else
|
||||
setControlFocus(Date.now())
|
||||
}}
|
||||
className="h-full grow"
|
||||
>
|
||||
<div ref={isSupportConstantValue ? triggerRef : null} className={cn('h-full', isSupportConstantValue && 'flex items-center rounded-lg bg-components-panel-bg py-1 pl-1')}>
|
||||
<Tooltip noDecoration={isShowAPart} popupContent={tooltipPopup}>
|
||||
<div className={cn('h-full items-center rounded-[5px] px-1.5', hasValue ? 'inline-flex bg-components-badge-white-to-dark' : 'flex')}>
|
||||
{hasValue
|
||||
? (
|
||||
<>
|
||||
{isShowNodeName && !isEnv && !isChatVar && !isGlobal && !isRagVar && (
|
||||
<div
|
||||
className="flex items-center"
|
||||
onClick={(e) => {
|
||||
if (e.metaKey || e.ctrlKey) {
|
||||
e.stopPropagation()
|
||||
handleVariableJump(outputVarNode?.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="h-3 px-[1px]">
|
||||
{outputVarNode?.type && (
|
||||
<VarBlockIcon
|
||||
className="!text-text-primary"
|
||||
type={outputVarNode.type}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className="mx-0.5 truncate text-xs font-medium text-text-secondary"
|
||||
title={outputVarNode?.title}
|
||||
style={{
|
||||
maxWidth: maxNodeNameWidth,
|
||||
}}
|
||||
>
|
||||
{outputVarNode?.title}
|
||||
</div>
|
||||
<Line3 className="mr-0.5"></Line3>
|
||||
</div>
|
||||
)}
|
||||
{isShowAPart && (
|
||||
<div className="flex items-center">
|
||||
<RiMoreLine className="h-3 w-3 text-text-secondary" />
|
||||
<Line3 className="mr-0.5 text-divider-deep"></Line3>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center text-text-accent">
|
||||
{isLoading && <RiLoader4Line className="h-3.5 w-3.5 animate-spin text-text-secondary" />}
|
||||
<VariableIconWithColor
|
||||
variables={value as ValueSelector}
|
||||
variableCategory={variableCategory}
|
||||
isExceptionVariable={isException}
|
||||
/>
|
||||
<div
|
||||
className={cn('ml-0.5 truncate text-xs font-medium', isEnv && '!text-text-secondary', isChatVar && 'text-util-colors-teal-teal-700', isException && 'text-text-warning', isGlobal && 'text-util-colors-orange-orange-600')}
|
||||
title={varName}
|
||||
style={{
|
||||
maxWidth: maxVarNameWidth,
|
||||
}}
|
||||
>
|
||||
{varName}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="system-xs-regular ml-0.5 truncate text-center capitalize text-text-tertiary"
|
||||
title={type}
|
||||
style={{
|
||||
maxWidth: maxTypeWidth,
|
||||
}}
|
||||
>
|
||||
{type}
|
||||
</div>
|
||||
{!isValidVar && <RiErrorWarningFill className="ml-0.5 h-3 w-3 text-text-destructive" />}
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<div className={`overflow-hidden ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'} system-sm-regular text-ellipsis`}>
|
||||
{isLoading
|
||||
? (
|
||||
<div className="flex items-center">
|
||||
<RiLoader4Line className="mr-1 h-3.5 w-3.5 animate-spin text-text-secondary" />
|
||||
<span>{placeholder ?? t('common.setVarValuePlaceholder', { ns: 'workflow' })}</span>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
placeholder ?? t('common.setVarValuePlaceholder', { ns: 'workflow' })
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
</VarPickerWrap>
|
||||
)}
|
||||
{(hasValue && !readonly && !isInTable && !isJustShowValue) && (
|
||||
<div
|
||||
className="group invisible absolute right-1 top-[50%] h-5 translate-y-[-50%] cursor-pointer rounded-md p-1 hover:bg-state-base-hover group-hover/wrap:visible"
|
||||
onClick={handleClearVar}
|
||||
>
|
||||
<RiCloseLine className="h-3.5 w-3.5 text-text-tertiary group-hover:text-text-secondary" />
|
||||
</div>
|
||||
)}
|
||||
{!hasValue && valueTypePlaceHolder && (
|
||||
<Badge
|
||||
className=" absolute right-1 top-[50%] translate-y-[-50%] capitalize"
|
||||
text={valueTypePlaceHolder}
|
||||
uppercase={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!readonly && isInTable && (
|
||||
<RemoveButton
|
||||
className="absolute right-1 top-0.5 hidden group-hover/picker-trigger-wrap:block"
|
||||
onClick={() => onRemove?.()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!hasValue && typePlaceHolder && (
|
||||
<Badge
|
||||
className="absolute right-2 top-1.5"
|
||||
text={typePlaceHolder}
|
||||
uppercase={false}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</WrapElem>
|
||||
<VarReferencePickerTrigger
|
||||
className={className}
|
||||
controlFocus={controlFocus}
|
||||
currentProvider={currentProvider}
|
||||
currentTool={currentTool}
|
||||
handleClearVar={handleClearVar}
|
||||
handleVarKindTypeChange={handleVarKindTypeChange}
|
||||
handleVariableJump={handleVariableJump}
|
||||
hasValue={hasValue}
|
||||
inputRef={inputRef}
|
||||
isAddBtnTrigger={isAddBtnTrigger}
|
||||
isConstant={!!isConstant}
|
||||
isException={isException}
|
||||
isFocus={isFocus}
|
||||
isInTable={isInTable}
|
||||
isJustShowValue={isJustShowValue}
|
||||
isLoading={isLoading}
|
||||
isShowAPart={isShowAPart}
|
||||
isShowNodeName={isShowNodeName && !isEnv && !isChatVar && !isGlobal && !isRagVar}
|
||||
isSupportConstantValue={isSupportConstantValue}
|
||||
maxNodeNameWidth={maxNodeNameWidth}
|
||||
maxTypeWidth={maxTypeWidth}
|
||||
maxVarNameWidth={maxVarNameWidth}
|
||||
onChange={onChange}
|
||||
onRemove={onRemove}
|
||||
open={open}
|
||||
outputVarNode={outputVarNode as Node['data'] | null}
|
||||
outputVarNodeId={outputVarNodeId}
|
||||
placeholder={triggerPlaceholder}
|
||||
readonly={readonly}
|
||||
schemaWithDynamicSelect={schemaWithDynamicSelect}
|
||||
setControlFocus={setControlFocus}
|
||||
setOpen={setOpen}
|
||||
tooltipPopup={tooltipPopup}
|
||||
triggerRef={triggerRef}
|
||||
type={type}
|
||||
typePlaceHolder={typePlaceHolder}
|
||||
value={value}
|
||||
valueTypePlaceHolder={valueTypePlaceHolder}
|
||||
varKindType={varKindType}
|
||||
varKindTypes={varKindTypes}
|
||||
varName={varName}
|
||||
variableCategory={variableCategory}
|
||||
VarPickerWrap={VarPickerWrap}
|
||||
WrapElem={WrapElem}
|
||||
/>
|
||||
)}
|
||||
<PortalToFollowElemContent
|
||||
style={{
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { VAR_SHOW_NAME_MAP } from '@/app/components/workflow/constants'
|
||||
import { checkKeys } from '@/utils/var'
|
||||
import { isSpecialVar } from './utils'
|
||||
|
||||
export const getVariableDisplayName = (
|
||||
variable: string,
|
||||
isFlat: boolean,
|
||||
isInCodeGeneratorInstructionEditor?: boolean,
|
||||
) => {
|
||||
if (VAR_SHOW_NAME_MAP[variable])
|
||||
return VAR_SHOW_NAME_MAP[variable]
|
||||
if (!isFlat)
|
||||
return variable
|
||||
if (variable === 'current')
|
||||
return isInCodeGeneratorInstructionEditor ? 'current_code' : 'current_prompt'
|
||||
return variable
|
||||
}
|
||||
|
||||
export const getVariableCategory = ({
|
||||
isEnv,
|
||||
isChatVar,
|
||||
isLoopVar,
|
||||
isRagVariable,
|
||||
}: {
|
||||
isEnv: boolean
|
||||
isChatVar: boolean
|
||||
isLoopVar?: boolean
|
||||
isRagVariable?: boolean
|
||||
}) => {
|
||||
if (isEnv)
|
||||
return 'environment'
|
||||
if (isChatVar)
|
||||
return 'conversation'
|
||||
if (isLoopVar)
|
||||
return 'loop'
|
||||
if (isRagVariable)
|
||||
return 'rag'
|
||||
return 'system'
|
||||
}
|
||||
|
||||
export const getValueSelector = ({
|
||||
itemData,
|
||||
isFlat,
|
||||
isSupportFileVar,
|
||||
isFile,
|
||||
isSys,
|
||||
isEnv,
|
||||
isChatVar,
|
||||
isRagVariable,
|
||||
nodeId,
|
||||
objPath,
|
||||
}: {
|
||||
itemData: Var
|
||||
isFlat?: boolean
|
||||
isSupportFileVar?: boolean
|
||||
isFile: boolean
|
||||
isSys: boolean
|
||||
isEnv: boolean
|
||||
isChatVar: boolean
|
||||
isRagVariable?: boolean
|
||||
nodeId: string
|
||||
objPath: string[]
|
||||
}): ValueSelector | undefined => {
|
||||
if (!isSupportFileVar && isFile)
|
||||
return undefined
|
||||
|
||||
if (isFlat)
|
||||
return [itemData.variable]
|
||||
if (isSys || isEnv || isChatVar || isRagVariable)
|
||||
return [...objPath, ...itemData.variable.split('.')]
|
||||
return [nodeId, ...objPath, itemData.variable]
|
||||
}
|
||||
|
||||
const getVisibleChildren = (vars: Var[]) => {
|
||||
return vars.filter(variable => checkKeys([variable.variable], false).isValid || isSpecialVar(variable.variable.split('.')[0]))
|
||||
}
|
||||
|
||||
export const filterReferenceVars = (vars: NodeOutPutVar[], searchText: string) => {
|
||||
const searchTextLower = searchText.toLowerCase()
|
||||
|
||||
return vars
|
||||
.map(node => ({ ...node, vars: getVisibleChildren(node.vars) }))
|
||||
.filter(node => node.vars.length > 0)
|
||||
.filter((node) => {
|
||||
if (!searchText)
|
||||
return true
|
||||
return node.vars.some(variable => variable.variable.toLowerCase().includes(searchTextLower))
|
||||
|| node.title.toLowerCase().includes(searchTextLower)
|
||||
})
|
||||
.map((node) => {
|
||||
if (!searchText || node.title.toLowerCase().includes(searchTextLower))
|
||||
return node
|
||||
|
||||
return {
|
||||
...node,
|
||||
vars: node.vars.filter(variable => variable.variable.toLowerCase().includes(searchTextLower)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -17,15 +17,19 @@ import {
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import { VAR_SHOW_NAME_MAP } from '@/app/components/workflow/constants'
|
||||
import PickerStructurePanel from '@/app/components/workflow/nodes/_base/components/variable/object-child-tree-panel/picker'
|
||||
import { VariableIconWithColor } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import { checkKeys } from '@/utils/var'
|
||||
import { Type } from '../../../llm/types'
|
||||
import ManageInputField from './manage-input-field'
|
||||
import { isSpecialVar, varTypeToStructType } from './utils'
|
||||
import { varTypeToStructType } from './utils'
|
||||
import {
|
||||
filterReferenceVars,
|
||||
getValueSelector,
|
||||
getVariableCategory,
|
||||
getVariableDisplayName,
|
||||
} from './var-reference-vars.helpers'
|
||||
|
||||
type ItemProps = {
|
||||
nodeId: string
|
||||
@@ -84,17 +88,10 @@ const Item: FC<ItemProps> = ({
|
||||
}
|
||||
}, [isFlat, isInCodeGeneratorInstructionEditor, itemData.variable])
|
||||
|
||||
const varName = useMemo(() => {
|
||||
if (VAR_SHOW_NAME_MAP[itemData.variable])
|
||||
return VAR_SHOW_NAME_MAP[itemData.variable]
|
||||
|
||||
if (!isFlat)
|
||||
return itemData.variable
|
||||
if (itemData.variable === 'current')
|
||||
return isInCodeGeneratorInstructionEditor ? 'current_code' : 'current_prompt'
|
||||
|
||||
return itemData.variable
|
||||
}, [isFlat, isInCodeGeneratorInstructionEditor, itemData.variable])
|
||||
const varName = useMemo(
|
||||
() => getVariableDisplayName(itemData.variable, !!isFlat, isInCodeGeneratorInstructionEditor),
|
||||
[isFlat, isInCodeGeneratorInstructionEditor, itemData.variable],
|
||||
)
|
||||
|
||||
const objStructuredOutput: StructuredOutput | null = useMemo(() => {
|
||||
if (!isObj)
|
||||
@@ -150,30 +147,26 @@ const Item: FC<ItemProps> = ({
|
||||
const handleChosen = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
e.nativeEvent.stopImmediatePropagation()
|
||||
if (!isSupportFileVar && isFile)
|
||||
return
|
||||
const valueSelector = getValueSelector({
|
||||
itemData,
|
||||
isFlat,
|
||||
isSupportFileVar,
|
||||
isFile,
|
||||
isSys,
|
||||
isEnv,
|
||||
isChatVar,
|
||||
isRagVariable,
|
||||
nodeId,
|
||||
objPath,
|
||||
})
|
||||
|
||||
if (isFlat) {
|
||||
onChange([itemData.variable], itemData)
|
||||
}
|
||||
else if (isSys || isEnv || isChatVar || isRagVariable) { // system variable | environment variable | conversation variable
|
||||
onChange([...objPath, ...itemData.variable.split('.')], itemData)
|
||||
}
|
||||
else {
|
||||
onChange([nodeId, ...objPath, itemData.variable], itemData)
|
||||
}
|
||||
if (valueSelector)
|
||||
onChange(valueSelector, itemData)
|
||||
}
|
||||
const variableCategory = useMemo(() => {
|
||||
if (isEnv)
|
||||
return 'environment'
|
||||
if (isChatVar)
|
||||
return 'conversation'
|
||||
if (isLoopVar)
|
||||
return 'loop'
|
||||
if (isRagVariable)
|
||||
return 'rag'
|
||||
return 'system'
|
||||
}, [isEnv, isChatVar, isSys, isLoopVar, isRagVariable])
|
||||
const variableCategory = useMemo(
|
||||
() => getVariableCategory({ isEnv, isChatVar, isLoopVar, isRagVariable }),
|
||||
[isEnv, isChatVar, isLoopVar, isRagVariable],
|
||||
)
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
open={open}
|
||||
@@ -290,30 +283,7 @@ const VarReferenceVars: FC<Props> = ({
|
||||
}
|
||||
}
|
||||
|
||||
const filteredVars = vars.filter((v) => {
|
||||
const children = v.vars.filter(v => checkKeys([v.variable], false).isValid || isSpecialVar(v.variable.split('.')[0]))
|
||||
return children.length > 0
|
||||
}).filter((node) => {
|
||||
if (!searchText)
|
||||
return node
|
||||
const children = node.vars.filter((v) => {
|
||||
const searchTextLower = searchText.toLowerCase()
|
||||
return v.variable.toLowerCase().includes(searchTextLower) || node.title.toLowerCase().includes(searchTextLower)
|
||||
})
|
||||
return children.length > 0
|
||||
}).map((node) => {
|
||||
let vars = node.vars.filter(v => checkKeys([v.variable], false).isValid || isSpecialVar(v.variable.split('.')[0]))
|
||||
if (searchText) {
|
||||
const searchTextLower = searchText.toLowerCase()
|
||||
if (!node.title.toLowerCase().includes(searchTextLower))
|
||||
vars = vars.filter(v => v.variable.toLowerCase().includes(searchText.toLowerCase()))
|
||||
}
|
||||
|
||||
return {
|
||||
...node,
|
||||
vars,
|
||||
}
|
||||
})
|
||||
const filteredVars = useMemo(() => filterReferenceVars(vars, searchText), [vars, searchText])
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
|
||||
import type { CustomRunFormProps } from '@/app/components/workflow/nodes/data-source/types'
|
||||
import type { Node, ToolWithProvider } from '@/app/components/workflow/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import {
|
||||
clampNodePanelWidth,
|
||||
getCompressedNodePanelWidth,
|
||||
getCurrentDataSource,
|
||||
getCurrentToolCollection,
|
||||
getCurrentTriggerPlugin,
|
||||
getCustomRunForm,
|
||||
getMaxNodePanelWidth,
|
||||
} from '../helpers'
|
||||
|
||||
describe('workflow-panel helpers', () => {
|
||||
const asToolList = (tools: Array<Partial<ToolWithProvider>>) => tools as ToolWithProvider[]
|
||||
const asTriggerList = (triggers: Array<Partial<TriggerWithProvider>>) => triggers as TriggerWithProvider[]
|
||||
const asNodeData = (data: Partial<Node['data']>) => data as Node['data']
|
||||
const createCustomRunFormProps = (payload: Partial<CustomRunFormProps['payload']>): CustomRunFormProps => ({
|
||||
nodeId: 'node-1',
|
||||
flowId: 'flow-1',
|
||||
flowType: 'app' as CustomRunFormProps['flowType'],
|
||||
payload: payload as CustomRunFormProps['payload'],
|
||||
setRunResult: vi.fn(),
|
||||
setIsRunAfterSingleRun: vi.fn(),
|
||||
isPaused: false,
|
||||
isRunAfterSingleRun: false,
|
||||
onSuccess: vi.fn(),
|
||||
onCancel: vi.fn(),
|
||||
appendNodeInspectVars: vi.fn(),
|
||||
})
|
||||
|
||||
describe('panel width helpers', () => {
|
||||
it('should use the default max width when canvas width is unavailable', () => {
|
||||
expect(getMaxNodePanelWidth(undefined, 120)).toBe(720)
|
||||
})
|
||||
|
||||
it('should clamp width into the supported panel range', () => {
|
||||
expect(clampNodePanelWidth(320, 800)).toBe(400)
|
||||
expect(clampNodePanelWidth(960, 800)).toBe(800)
|
||||
expect(clampNodePanelWidth(640, 800)).toBe(640)
|
||||
})
|
||||
|
||||
it('should return a compressed width only when the canvas overflows', () => {
|
||||
expect(getCompressedNodePanelWidth(500, 1500, 300)).toBeUndefined()
|
||||
expect(getCompressedNodePanelWidth(900, 1200, 200)).toBe(600)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tool and provider lookup', () => {
|
||||
it('should prefer fresh built-in tool data when it is available', () => {
|
||||
const storeTools = [{ id: 'legacy/tool', allow_delete: false }]
|
||||
const queryTools = [{ id: 'provider/tool', allow_delete: true }]
|
||||
|
||||
expect(getCurrentToolCollection(asToolList(queryTools), asToolList(storeTools), 'provider/tool')).toEqual(queryTools[0])
|
||||
})
|
||||
|
||||
it('should fall back to store data when query data is unavailable', () => {
|
||||
const storeTools = [{ id: 'provider/tool', allow_delete: false }]
|
||||
|
||||
expect(getCurrentToolCollection(undefined, asToolList(storeTools), 'provider/tool')).toEqual(storeTools[0])
|
||||
})
|
||||
|
||||
it('should resolve the current trigger plugin and datasource only for matching node types', () => {
|
||||
const triggerData = asNodeData({ type: BlockEnum.TriggerPlugin, plugin_id: 'trigger-1' })
|
||||
const dataSourceData = asNodeData({ type: BlockEnum.DataSource, plugin_id: 'source-1', provider_type: 'remote' })
|
||||
const triggerPlugins = [{ plugin_id: 'trigger-1', id: '1' }]
|
||||
const dataSources = [{ plugin_id: 'source-1' }]
|
||||
|
||||
expect(getCurrentTriggerPlugin(triggerData, asTriggerList(triggerPlugins))).toEqual(triggerPlugins[0])
|
||||
expect(getCurrentDataSource(dataSourceData, dataSources)).toEqual(dataSources[0])
|
||||
expect(getCurrentTriggerPlugin(asNodeData({ type: BlockEnum.Tool }), asTriggerList(triggerPlugins))).toBeUndefined()
|
||||
expect(getCurrentDataSource(asNodeData({ type: BlockEnum.Tool }), dataSources)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('custom run form fallback', () => {
|
||||
it('should return a fallback message for unsupported custom run form nodes', () => {
|
||||
const form = getCustomRunForm({
|
||||
...createCustomRunFormProps({ type: BlockEnum.Tool }),
|
||||
})
|
||||
|
||||
expect(form).toMatchObject({
|
||||
props: {
|
||||
children: expect.arrayContaining(['Custom Run Form:', ' ', 'not found']),
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,146 +1,615 @@
|
||||
/**
|
||||
* Workflow Panel Width Persistence Tests
|
||||
* Tests for GitHub issue #22745: Panel width persistence bug fix
|
||||
*/
|
||||
import type { PropsWithChildren } from 'react'
|
||||
import type { ToolWithProvider } from '@/app/components/workflow/types'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import * as React from 'react'
|
||||
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import BasePanel from '../index'
|
||||
|
||||
export {}
|
||||
const mockHandleNodeSelect = vi.fn()
|
||||
const mockHandleNodeDataUpdate = vi.fn()
|
||||
const mockHandleNodeDataUpdateWithSyncDraft = vi.fn()
|
||||
const mockSaveStateToHistory = vi.fn()
|
||||
const mockSetDetail = vi.fn()
|
||||
const mockSetShowAccountSettingModal = vi.fn()
|
||||
const mockHandleSingleRun = vi.fn()
|
||||
const mockHandleStop = vi.fn()
|
||||
const mockHandleRunWithParams = vi.fn()
|
||||
let mockShowMessageLogModal = false
|
||||
let mockBuiltInTools = [{
|
||||
id: 'provider/tool',
|
||||
name: 'Tool',
|
||||
type: 'builtin',
|
||||
allow_delete: true,
|
||||
}]
|
||||
let mockTriggerPlugins: Array<Record<string, unknown>> = []
|
||||
|
||||
type PanelWidthSource = 'user' | 'system'
|
||||
|
||||
// Core panel width logic extracted from the component
|
||||
const createPanelWidthManager = (storageKey: string) => {
|
||||
return {
|
||||
updateWidth: (width: number, source: PanelWidthSource = 'user') => {
|
||||
const newValue = Math.max(400, Math.min(width, 800))
|
||||
if (source === 'user')
|
||||
localStorage.setItem(storageKey, `${newValue}`)
|
||||
|
||||
return newValue
|
||||
},
|
||||
getStoredWidth: () => {
|
||||
const stored = localStorage.getItem(storageKey)
|
||||
return stored ? Number.parseFloat(stored) : 400
|
||||
},
|
||||
}
|
||||
const mockLogsState = {
|
||||
showSpecialResultPanel: false,
|
||||
}
|
||||
|
||||
describe('Workflow Panel Width Persistence', () => {
|
||||
describe('Node Panel Width Management', () => {
|
||||
const storageKey = 'workflow-node-panel-width'
|
||||
const mockLastRunState = {
|
||||
isShowSingleRun: false,
|
||||
hideSingleRun: vi.fn(),
|
||||
runningStatus: NodeRunningStatus.Succeeded,
|
||||
runInputData: {},
|
||||
runInputDataRef: { current: {} },
|
||||
runResult: {},
|
||||
setRunResult: vi.fn(),
|
||||
getInputVars: vi.fn(),
|
||||
toVarInputs: vi.fn(),
|
||||
tabType: 'settings',
|
||||
isRunAfterSingleRun: false,
|
||||
setIsRunAfterSingleRun: vi.fn(),
|
||||
setTabType: vi.fn(),
|
||||
handleAfterCustomSingleRun: vi.fn(),
|
||||
singleRunParams: {
|
||||
forms: [],
|
||||
onStop: vi.fn(),
|
||||
runningStatus: NodeRunningStatus.Succeeded,
|
||||
existVarValuesInForms: [],
|
||||
filteredExistVarForms: [],
|
||||
},
|
||||
nodeInfo: { id: 'node-1' },
|
||||
setRunInputData: vi.fn(),
|
||||
handleStop: () => mockHandleStop(),
|
||||
handleSingleRun: () => mockHandleSingleRun(),
|
||||
handleRunWithParams: (...args: unknown[]) => mockHandleRunWithParams(...args),
|
||||
getExistVarValuesInForms: vi.fn(() => []),
|
||||
getFilteredExistVarForms: vi.fn(() => []),
|
||||
}
|
||||
|
||||
it('should save user resize to localStorage', () => {
|
||||
const manager = createPanelWidthManager(storageKey)
|
||||
const createDataSourceCollection = (overrides: Partial<ToolWithProvider> = {}): ToolWithProvider => ({
|
||||
id: 'source-1',
|
||||
name: 'Source',
|
||||
author: 'Author',
|
||||
description: { en_US: 'Source description', zh_Hans: 'Source description' },
|
||||
icon: 'source-icon',
|
||||
label: { en_US: 'Source', zh_Hans: 'Source' },
|
||||
type: 'datasource',
|
||||
team_credentials: {},
|
||||
is_team_authorization: false,
|
||||
allow_delete: false,
|
||||
labels: [],
|
||||
plugin_id: 'source-1',
|
||||
tools: [],
|
||||
meta: {} as ToolWithProvider['meta'],
|
||||
...overrides,
|
||||
}) as ToolWithProvider
|
||||
|
||||
const result = manager.updateWidth(500, 'user')
|
||||
vi.mock('@/app/components/app/store', () => ({
|
||||
useStore: (selector: (state: { showMessageLogModal: boolean, appDetail: { id: string } }) => unknown) => selector({
|
||||
showMessageLogModal: mockShowMessageLogModal,
|
||||
appDetail: { id: 'app-1' },
|
||||
}),
|
||||
}))
|
||||
|
||||
expect(result).toBe(500)
|
||||
expect(localStorage.setItem).toHaveBeenCalledWith(storageKey, '500')
|
||||
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
|
||||
useLanguage: () => 'en_US',
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/plugins/plugin-detail-panel/store', () => ({
|
||||
usePluginStore: () => ({
|
||||
setDetail: mockSetDetail,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks', () => ({
|
||||
useAvailableBlocks: () => ({ availableNextBlocks: [] }),
|
||||
useEdgesInteractions: () => ({
|
||||
handleEdgeDeleteByDeleteBranch: vi.fn(),
|
||||
}),
|
||||
useNodeDataUpdate: () => ({
|
||||
handleNodeDataUpdate: mockHandleNodeDataUpdate,
|
||||
handleNodeDataUpdateWithSyncDraft: mockHandleNodeDataUpdateWithSyncDraft,
|
||||
}),
|
||||
useNodesInteractions: () => ({
|
||||
handleNodeSelect: mockHandleNodeSelect,
|
||||
}),
|
||||
useNodesMetaData: () => ({
|
||||
nodesMap: {
|
||||
[BlockEnum.Tool]: { defaultRunInputData: {}, metaData: { helpLinkUri: '' } },
|
||||
[BlockEnum.DataSource]: { defaultRunInputData: {}, metaData: { helpLinkUri: '' } },
|
||||
},
|
||||
}),
|
||||
useNodesReadOnly: () => ({
|
||||
nodesReadOnly: false,
|
||||
}),
|
||||
useToolIcon: () => undefined,
|
||||
useWorkflowHistory: () => ({
|
||||
saveStateToHistory: mockSaveStateToHistory,
|
||||
}),
|
||||
WorkflowHistoryEvent: {
|
||||
NodeTitleChange: 'NodeTitleChange',
|
||||
NodeDescriptionChange: 'NodeDescriptionChange',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks-store', () => ({
|
||||
useHooksStore: (selector: (state: { configsMap: { flowId: string, flowType: string } }) => unknown) => selector({
|
||||
configsMap: {
|
||||
flowId: 'flow-1',
|
||||
flowType: 'app',
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud', () => ({
|
||||
default: () => ({
|
||||
appendNodeInspectVars: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/run/hooks', () => ({
|
||||
useLogs: () => mockLogsState,
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-tools', () => ({
|
||||
useAllBuiltInTools: () => ({
|
||||
data: mockBuiltInTools,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-triggers', () => ({
|
||||
useAllTriggerPlugins: () => ({
|
||||
data: mockTriggerPlugins,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/context/modal-context', () => ({
|
||||
useModalContext: () => ({
|
||||
setShowAccountSettingModal: mockSetShowAccountSettingModal,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/utils', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/app/components/workflow/utils')>()
|
||||
return {
|
||||
...actual,
|
||||
canRunBySingle: () => true,
|
||||
hasErrorHandleNode: () => false,
|
||||
hasRetryNode: () => false,
|
||||
isSupportCustomRunForm: (type: string) => type === BlockEnum.DataSource,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../hooks/use-resize-panel', () => ({
|
||||
useResizePanel: () => ({
|
||||
triggerRef: { current: null },
|
||||
containerRef: { current: null },
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('../last-run/use-last-run', () => ({
|
||||
default: () => mockLastRunState,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/plugins/plugin-auth', () => ({
|
||||
PluginAuth: ({ children }: PropsWithChildren) => <div>{children}</div>,
|
||||
AuthorizedInNode: ({ onAuthorizationItemClick }: { onAuthorizationItemClick?: (credentialId: string) => void }) => (
|
||||
<button onClick={() => onAuthorizationItemClick?.('credential-1')}>authorized-in-node</button>
|
||||
),
|
||||
PluginAuthInDataSourceNode: ({ children, onJumpToDataSourcePage }: PropsWithChildren<{ onJumpToDataSourcePage?: () => void }>) => (
|
||||
<div>
|
||||
<button onClick={onJumpToDataSourcePage}>jump-to-datasource</button>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
AuthorizedInDataSourceNode: ({ onJumpToDataSourcePage }: { onJumpToDataSourcePage?: () => void }) => (
|
||||
<button onClick={onJumpToDataSourcePage}>authorized-in-datasource-node</button>
|
||||
),
|
||||
AuthCategory: { tool: 'tool' },
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/plugins/readme-panel/entrance', () => ({
|
||||
ReadmeEntrance: () => <div>readme-entrance</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/block-icon', () => ({
|
||||
default: () => <div>block-icon</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/_base/components/split', () => ({
|
||||
default: () => <div>split</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/nodes/data-source/before-run-form', () => ({
|
||||
default: () => <div>data-source-before-run-form</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/run/special-result-panel', () => ({
|
||||
default: () => <div>special-result-panel</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../before-run-form', () => ({
|
||||
default: () => <div>before-run-form</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../before-run-form/panel-wrap', () => ({
|
||||
default: ({ children }: PropsWithChildren<{ nodeName: string, onHide: () => void }>) => <div>{children}</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../error-handle/error-handle-on-panel', () => ({
|
||||
default: () => <div>error-handle-panel</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../help-link', () => ({
|
||||
default: () => <div>help-link</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../next-step', () => ({
|
||||
default: () => <div>next-step</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../panel-operator', () => ({
|
||||
default: () => <div>panel-operator</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../retry/retry-on-panel', () => ({
|
||||
default: () => <div>retry-panel</div>,
|
||||
}))
|
||||
|
||||
vi.mock('../title-description-input', () => ({
|
||||
TitleInput: ({ value, onBlur }: { value: string, onBlur: (value: string) => void }) => (
|
||||
<input aria-label="title-input" defaultValue={value} onBlur={event => onBlur(event.target.value)} />
|
||||
),
|
||||
DescriptionInput: ({ value, onChange }: { value: string, onChange: (value: string) => void }) => (
|
||||
<textarea aria-label="description-input" defaultValue={value} onChange={event => onChange(event.target.value)} />
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('../last-run', () => ({
|
||||
default: ({
|
||||
isPaused,
|
||||
updateNodeRunningStatus,
|
||||
}: {
|
||||
isPaused?: boolean
|
||||
updateNodeRunningStatus?: (status: NodeRunningStatus) => void
|
||||
}) => (
|
||||
<div>
|
||||
<div>{isPaused ? 'paused' : 'active'}</div>
|
||||
<button onClick={() => updateNodeRunningStatus?.(NodeRunningStatus.Running)}>last-run-update-status</button>
|
||||
<div>last-run-panel</div>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('../tab', () => ({
|
||||
__esModule: true,
|
||||
TabType: { settings: 'settings', lastRun: 'lastRun' },
|
||||
default: ({ value, onChange }: { value: string, onChange: (value: string) => void }) => (
|
||||
<div>
|
||||
<button onClick={() => onChange('settings')}>settings-tab</button>
|
||||
<button onClick={() => onChange('lastRun')}>last-run-tab</button>
|
||||
<span>{value}</span>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('../trigger-subscription', () => ({
|
||||
TriggerSubscription: ({ children, onSubscriptionChange }: PropsWithChildren<{ onSubscriptionChange?: (value: { id: string }, callback?: () => void) => void }>) => (
|
||||
<div>
|
||||
<button onClick={() => onSubscriptionChange?.({ id: 'subscription-1' }, vi.fn())}>change-subscription</button>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
const createData = (overrides: Record<string, unknown> = {}) => ({
|
||||
title: 'Tool Node',
|
||||
desc: 'Node description',
|
||||
type: BlockEnum.Tool,
|
||||
provider_id: 'provider/tool',
|
||||
_singleRunningStatus: undefined,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('workflow-panel index', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockShowMessageLogModal = false
|
||||
mockBuiltInTools = [{
|
||||
id: 'provider/tool',
|
||||
name: 'Tool',
|
||||
type: 'builtin',
|
||||
allow_delete: true,
|
||||
}]
|
||||
mockTriggerPlugins = []
|
||||
mockLogsState.showSpecialResultPanel = false
|
||||
mockLastRunState.isShowSingleRun = false
|
||||
mockLastRunState.tabType = 'settings'
|
||||
})
|
||||
|
||||
it('should render the settings panel and wire title, description, run, and close actions', async () => {
|
||||
const { container } = renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData() as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
showSingleRunPanel: false,
|
||||
workflowCanvasWidth: 1200,
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
buildInTools: [],
|
||||
dataSourceList: [],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(screen.getByText('panel-child')).toBeInTheDocument()
|
||||
expect(screen.getByText('authorized-in-node')).toBeInTheDocument()
|
||||
|
||||
fireEvent.blur(screen.getByDisplayValue('Tool Node'), { target: { value: 'Updated title' } })
|
||||
fireEvent.change(screen.getByDisplayValue('Node description'), { target: { value: 'Updated description' } })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalled()
|
||||
})
|
||||
expect(mockSaveStateToHistory).toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByText('authorized-in-node'))
|
||||
|
||||
it('should not save system compression to localStorage', () => {
|
||||
const manager = createPanelWidthManager(storageKey)
|
||||
const clickableItems = container.querySelectorAll('.cursor-pointer')
|
||||
fireEvent.click(clickableItems[0] as HTMLElement)
|
||||
fireEvent.click(clickableItems[clickableItems.length - 1] as HTMLElement)
|
||||
|
||||
const result = manager.updateWidth(200, 'system')
|
||||
expect(mockHandleSingleRun).toHaveBeenCalledTimes(1)
|
||||
expect(mockHandleNodeSelect).toHaveBeenCalledWith('node-1', true)
|
||||
expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ credential_id: 'credential-1' }),
|
||||
}))
|
||||
})
|
||||
|
||||
expect(result).toBe(400) // Respects minimum width
|
||||
expect(localStorage.setItem).not.toHaveBeenCalled()
|
||||
})
|
||||
it('should render the special result panel when logs request it', () => {
|
||||
mockLogsState.showSpecialResultPanel = true
|
||||
|
||||
it('should enforce minimum width of 400px', () => {
|
||||
const manager = createPanelWidthManager(storageKey)
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData() as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
// User tries to set below minimum
|
||||
const userResult = manager.updateWidth(300, 'user')
|
||||
expect(userResult).toBe(400)
|
||||
expect(localStorage.setItem).toHaveBeenCalledWith(storageKey, '400')
|
||||
expect(screen.getByText('special-result-panel')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// System compression below minimum
|
||||
const systemResult = manager.updateWidth(150, 'system')
|
||||
expect(systemResult).toBe(400)
|
||||
expect(localStorage.setItem).toHaveBeenCalledTimes(1) // Only user call
|
||||
})
|
||||
it('should render last-run content when the tab switches', () => {
|
||||
mockLastRunState.tabType = 'lastRun'
|
||||
|
||||
it('should preserve user preferences during system compression', () => {
|
||||
localStorage.setItem(storageKey, '600')
|
||||
const manager = createPanelWidthManager(storageKey)
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData() as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
// System compresses panel
|
||||
manager.updateWidth(200, 'system')
|
||||
expect(screen.getByText('last-run-panel')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// User preference should remain unchanged
|
||||
expect(localStorage.getItem(storageKey)).toBe('600')
|
||||
it('should render the plain tab layout and allow last-run status updates', async () => {
|
||||
mockLastRunState.tabType = 'lastRun'
|
||||
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-plain" data={createData({ type: 'custom' }) as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(screen.queryByText('authorized-in-node')).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByText('last-run-update-status'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockHandleNodeDataUpdate).toHaveBeenCalledWith(expect.objectContaining({
|
||||
id: 'node-plain',
|
||||
data: expect.objectContaining({
|
||||
_singleRunningStatus: NodeRunningStatus.Running,
|
||||
}),
|
||||
}))
|
||||
})
|
||||
})
|
||||
|
||||
describe('Bug Scenario Reproduction', () => {
|
||||
it('should reproduce original bug behavior (for comparison)', () => {
|
||||
const storageKey = 'workflow-node-panel-width'
|
||||
it('should mark the last run as paused after a running single-run completes', async () => {
|
||||
mockLastRunState.tabType = 'lastRun'
|
||||
|
||||
// Original buggy behavior - always saves regardless of source
|
||||
const buggyUpdate = (width: number) => {
|
||||
localStorage.setItem(storageKey, `${width}`)
|
||||
return Math.max(400, width)
|
||||
}
|
||||
const { rerender } = renderWorkflowComponent(
|
||||
<BasePanel id="node-pause" data={createData({ _singleRunningStatus: NodeRunningStatus.Running }) as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
localStorage.setItem(storageKey, '500') // User preference
|
||||
buggyUpdate(200) // System compression pollutes localStorage
|
||||
expect(screen.getByText('active')).toBeInTheDocument()
|
||||
|
||||
expect(localStorage.getItem(storageKey)).toBe('200') // Bug: corrupted state
|
||||
})
|
||||
rerender(
|
||||
<BasePanel id="node-pause" data={createData({ _isSingleRun: true, _singleRunningStatus: undefined }) as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
)
|
||||
|
||||
it('should verify fix prevents localStorage pollution', () => {
|
||||
const storageKey = 'workflow-node-panel-width'
|
||||
const manager = createPanelWidthManager(storageKey)
|
||||
|
||||
localStorage.setItem(storageKey, '500') // User preference
|
||||
manager.updateWidth(200, 'system') // System compression
|
||||
|
||||
expect(localStorage.getItem(storageKey)).toBe('500') // Fix: preserved state
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('paused')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('should handle multiple rapid operations correctly', () => {
|
||||
const manager = createPanelWidthManager('workflow-node-panel-width')
|
||||
it('should render custom data source single run form for supported nodes', () => {
|
||||
mockLastRunState.isShowSingleRun = true
|
||||
|
||||
// Rapid system adjustments
|
||||
manager.updateWidth(300, 'system')
|
||||
manager.updateWidth(250, 'system')
|
||||
manager.updateWidth(180, 'system')
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData({ type: BlockEnum.DataSource }) as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
// Single user adjustment
|
||||
manager.updateWidth(550, 'user')
|
||||
|
||||
expect(localStorage.setItem).toHaveBeenCalledTimes(1)
|
||||
expect(localStorage.setItem).toHaveBeenCalledWith('workflow-node-panel-width', '550')
|
||||
})
|
||||
|
||||
it('should handle corrupted localStorage gracefully', () => {
|
||||
localStorage.setItem('workflow-node-panel-width', '150') // Below minimum
|
||||
const manager = createPanelWidthManager('workflow-node-panel-width')
|
||||
|
||||
const storedWidth = manager.getStoredWidth()
|
||||
expect(storedWidth).toBe(150) // Returns raw value
|
||||
|
||||
// User can correct the preference
|
||||
const correctedWidth = manager.updateWidth(500, 'user')
|
||||
expect(correctedWidth).toBe(500)
|
||||
expect(localStorage.getItem('workflow-node-panel-width')).toBe('500')
|
||||
})
|
||||
expect(screen.getByText('data-source-before-run-form')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
describe('TypeScript Type Safety', () => {
|
||||
it('should enforce source parameter type', () => {
|
||||
const manager = createPanelWidthManager('workflow-node-panel-width')
|
||||
it('should render data source authorization controls and jump to the settings modal', () => {
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData({ type: BlockEnum.DataSource, plugin_id: 'source-1', provider_type: 'remote' }) as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
dataSourceList: [createDataSourceCollection({ is_authorized: false })],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
// Valid source values
|
||||
manager.updateWidth(500, 'user')
|
||||
manager.updateWidth(500, 'system')
|
||||
fireEvent.click(screen.getByText('authorized-in-datasource-node'))
|
||||
|
||||
// Default to 'user'
|
||||
manager.updateWidth(500)
|
||||
expect(mockSetShowAccountSettingModal).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
expect(localStorage.setItem).toHaveBeenCalledTimes(2) // user + default
|
||||
it('should react to pending single run actions', () => {
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData() as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
pendingSingleRun: {
|
||||
nodeId: 'node-1',
|
||||
action: 'run',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(mockHandleSingleRun).toHaveBeenCalledTimes(1)
|
||||
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData() as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
pendingSingleRun: {
|
||||
nodeId: 'node-1',
|
||||
action: 'stop',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(mockHandleStop).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should load trigger plugin details when the selected node is a trigger plugin', async () => {
|
||||
mockTriggerPlugins = [{
|
||||
id: 'trigger-1',
|
||||
name: 'trigger-name',
|
||||
plugin_id: 'plugin-id',
|
||||
plugin_unique_identifier: 'plugin-uid',
|
||||
label: {
|
||||
en_US: 'Trigger Name',
|
||||
},
|
||||
declaration: {},
|
||||
subscription_schema: [],
|
||||
subscription_constructor: {},
|
||||
}]
|
||||
|
||||
renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData({ type: BlockEnum.TriggerPlugin, plugin_id: 'plugin-id' }) as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 200,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSetDetail).toHaveBeenCalledWith(expect.objectContaining({
|
||||
id: 'trigger-1',
|
||||
name: 'Trigger Name',
|
||||
}))
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('change-subscription'))
|
||||
expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(
|
||||
{ id: 'node-1', data: { subscription_id: 'subscription-1' } },
|
||||
expect.objectContaining({ sync: true }),
|
||||
)
|
||||
})
|
||||
|
||||
it('should stop a running node and offset when the log modal is visible', () => {
|
||||
mockShowMessageLogModal = true
|
||||
|
||||
const { container } = renderWorkflowComponent(
|
||||
<BasePanel id="node-1" data={createData({ _singleRunningStatus: NodeRunningStatus.Running }) as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
nodePanelWidth: 480,
|
||||
otherPanelWidth: 240,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const root = container.firstElementChild as HTMLElement
|
||||
expect(root.style.right).toBe('240px')
|
||||
expect(root.className).toContain('absolute')
|
||||
|
||||
const clickableItems = container.querySelectorAll('.cursor-pointer')
|
||||
fireEvent.click(clickableItems[0] as HTMLElement)
|
||||
|
||||
expect(mockHandleStop).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should persist user resize changes and compress oversized panel widths', async () => {
|
||||
const { container } = renderWorkflowComponent(
|
||||
<BasePanel id="node-resize" data={createData() as never}>
|
||||
<div>panel-child</div>
|
||||
</BasePanel>,
|
||||
{
|
||||
initialStoreState: {
|
||||
workflowCanvasWidth: 800,
|
||||
nodePanelWidth: 600,
|
||||
otherPanelWidth: 200,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
const panel = container.querySelector('[style*="width"]') as HTMLElement
|
||||
expect(panel.style.width).toBe('400px')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
|
||||
import type { CustomRunFormProps } from '@/app/components/workflow/nodes/data-source/types'
|
||||
import type { Node, ToolWithProvider } from '@/app/components/workflow/types'
|
||||
import DataSourceBeforeRunForm from '@/app/components/workflow/nodes/data-source/before-run-form'
|
||||
import { DataSourceClassification } from '@/app/components/workflow/nodes/data-source/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { canFindTool } from '@/utils'
|
||||
|
||||
const MIN_NODE_PANEL_WIDTH = 400
|
||||
const DEFAULT_MAX_NODE_PANEL_WIDTH = 720
|
||||
|
||||
export const getMaxNodePanelWidth = (workflowCanvasWidth?: number, otherPanelWidth?: number, reservedCanvasWidth = MIN_NODE_PANEL_WIDTH) => {
|
||||
if (!workflowCanvasWidth)
|
||||
return DEFAULT_MAX_NODE_PANEL_WIDTH
|
||||
|
||||
const available = workflowCanvasWidth - (otherPanelWidth || 0) - reservedCanvasWidth
|
||||
return Math.max(available, MIN_NODE_PANEL_WIDTH)
|
||||
}
|
||||
|
||||
export const clampNodePanelWidth = (width: number, maxNodePanelWidth: number) => {
|
||||
return Math.max(MIN_NODE_PANEL_WIDTH, Math.min(width, maxNodePanelWidth))
|
||||
}
|
||||
|
||||
export const getCompressedNodePanelWidth = (nodePanelWidth: number, workflowCanvasWidth?: number, otherPanelWidth?: number, reservedCanvasWidth = MIN_NODE_PANEL_WIDTH) => {
|
||||
if (!workflowCanvasWidth)
|
||||
return undefined
|
||||
|
||||
const total = nodePanelWidth + (otherPanelWidth || 0) + reservedCanvasWidth
|
||||
if (total <= workflowCanvasWidth)
|
||||
return undefined
|
||||
|
||||
return clampNodePanelWidth(workflowCanvasWidth - (otherPanelWidth || 0) - reservedCanvasWidth, getMaxNodePanelWidth(workflowCanvasWidth, otherPanelWidth, reservedCanvasWidth))
|
||||
}
|
||||
|
||||
export const getCustomRunForm = (params: CustomRunFormProps): ReactNode => {
|
||||
const nodeType = params.payload.type
|
||||
switch (nodeType) {
|
||||
case BlockEnum.DataSource:
|
||||
return <DataSourceBeforeRunForm {...params} />
|
||||
default:
|
||||
return (
|
||||
<div>
|
||||
Custom Run Form:
|
||||
{nodeType}
|
||||
{' '}
|
||||
not found
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const getCurrentToolCollection = (
|
||||
buildInTools: ToolWithProvider[] | undefined,
|
||||
storeBuildInTools: ToolWithProvider[] | undefined,
|
||||
providerId?: string,
|
||||
) => {
|
||||
const candidates = buildInTools ?? storeBuildInTools
|
||||
return candidates?.find(item => canFindTool(item.id, providerId))
|
||||
}
|
||||
|
||||
export const getCurrentDataSource = (
|
||||
data: Node['data'],
|
||||
dataSourceList: Array<{ plugin_id?: string, is_authorized?: boolean }> | undefined,
|
||||
) => {
|
||||
if (data.type !== BlockEnum.DataSource || data.provider_type === DataSourceClassification.localFile)
|
||||
return undefined
|
||||
|
||||
return dataSourceList?.find(item => item.plugin_id === data.plugin_id)
|
||||
}
|
||||
|
||||
export const getCurrentTriggerPlugin = (
|
||||
data: Node['data'],
|
||||
triggerPlugins: TriggerWithProvider[] | undefined,
|
||||
) => {
|
||||
if (data.type !== BlockEnum.TriggerPlugin || !data.plugin_id || !triggerPlugins?.length)
|
||||
return undefined
|
||||
|
||||
return triggerPlugins.find(plugin => plugin.plugin_id === data.plugin_id)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { FC, ReactNode } from 'react'
|
||||
import type { SimpleSubscription } from '@/app/components/plugins/plugin-detail-panel/subscription-list'
|
||||
import type { CustomRunFormProps } from '@/app/components/workflow/nodes/data-source/types'
|
||||
import type { Node } from '@/app/components/workflow/types'
|
||||
import {
|
||||
RiCloseLine,
|
||||
@@ -47,8 +46,6 @@ import {
|
||||
import { useHooksStore } from '@/app/components/workflow/hooks-store'
|
||||
import useInspectVarsCrud from '@/app/components/workflow/hooks/use-inspect-vars-crud'
|
||||
import Split from '@/app/components/workflow/nodes/_base/components/split'
|
||||
import DataSourceBeforeRunForm from '@/app/components/workflow/nodes/data-source/before-run-form'
|
||||
import { DataSourceClassification } from '@/app/components/workflow/nodes/data-source/types'
|
||||
import { useLogs } from '@/app/components/workflow/run/hooks'
|
||||
import SpecialResultPanel from '@/app/components/workflow/run/special-result-panel'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
@@ -63,7 +60,6 @@ import { useModalContext } from '@/context/modal-context'
|
||||
import { useAllBuiltInTools } from '@/service/use-tools'
|
||||
import { useAllTriggerPlugins } from '@/service/use-triggers'
|
||||
import { FlowType } from '@/types/common'
|
||||
import { canFindTool } from '@/utils'
|
||||
import { cn } from '@/utils/classnames'
|
||||
import { useResizePanel } from '../../hooks/use-resize-panel'
|
||||
import BeforeRunForm from '../before-run-form'
|
||||
@@ -74,28 +70,20 @@ import NextStep from '../next-step'
|
||||
import PanelOperator from '../panel-operator'
|
||||
import RetryOnPanel from '../retry/retry-on-panel'
|
||||
import { DescriptionInput, TitleInput } from '../title-description-input'
|
||||
import {
|
||||
clampNodePanelWidth,
|
||||
getCompressedNodePanelWidth,
|
||||
getCurrentDataSource,
|
||||
getCurrentToolCollection,
|
||||
getCurrentTriggerPlugin,
|
||||
getCustomRunForm,
|
||||
getMaxNodePanelWidth,
|
||||
} from './helpers'
|
||||
import LastRun from './last-run'
|
||||
import useLastRun from './last-run/use-last-run'
|
||||
import Tab, { TabType } from './tab'
|
||||
import { TriggerSubscription } from './trigger-subscription'
|
||||
|
||||
const getCustomRunForm = (params: CustomRunFormProps): React.JSX.Element => {
|
||||
const nodeType = params.payload.type
|
||||
switch (nodeType) {
|
||||
case BlockEnum.DataSource:
|
||||
return <DataSourceBeforeRunForm {...params} />
|
||||
default:
|
||||
return (
|
||||
<div>
|
||||
Custom Run Form:
|
||||
{nodeType}
|
||||
{' '}
|
||||
not found
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
type BasePanelProps = {
|
||||
children: ReactNode
|
||||
id: Node['id']
|
||||
@@ -124,17 +112,13 @@ const BasePanel: FC<BasePanelProps> = ({
|
||||
|
||||
const reservedCanvasWidth = 400 // Reserve the minimum visible width for the canvas
|
||||
|
||||
const maxNodePanelWidth = useMemo(() => {
|
||||
if (!workflowCanvasWidth)
|
||||
return 720
|
||||
|
||||
const available = workflowCanvasWidth - (otherPanelWidth || 0) - reservedCanvasWidth
|
||||
return Math.max(available, 400)
|
||||
}, [workflowCanvasWidth, otherPanelWidth])
|
||||
const maxNodePanelWidth = useMemo(
|
||||
() => getMaxNodePanelWidth(workflowCanvasWidth, otherPanelWidth, reservedCanvasWidth),
|
||||
[workflowCanvasWidth, otherPanelWidth],
|
||||
)
|
||||
|
||||
const updateNodePanelWidth = useCallback((width: number, source: 'user' | 'system' = 'user') => {
|
||||
// Ensure the width is within the min and max range
|
||||
const newValue = Math.max(400, Math.min(width, maxNodePanelWidth))
|
||||
const newValue = clampNodePanelWidth(width, maxNodePanelWidth)
|
||||
|
||||
if (source === 'user')
|
||||
localStorage.setItem('workflow-node-panel-width', `${newValue}`)
|
||||
@@ -162,15 +146,9 @@ const BasePanel: FC<BasePanelProps> = ({
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!workflowCanvasWidth)
|
||||
return
|
||||
|
||||
// If the total width of the three exceeds the canvas, shrink the node panel to the available range (at least 400px)
|
||||
const total = nodePanelWidth + otherPanelWidth + reservedCanvasWidth
|
||||
if (total > workflowCanvasWidth) {
|
||||
const target = Math.max(workflowCanvasWidth - otherPanelWidth - reservedCanvasWidth, 400)
|
||||
debounceUpdate(target)
|
||||
}
|
||||
const compressedWidth = getCompressedNodePanelWidth(nodePanelWidth, workflowCanvasWidth, otherPanelWidth, reservedCanvasWidth)
|
||||
if (compressedWidth !== undefined)
|
||||
debounceUpdate(compressedWidth)
|
||||
}, [nodePanelWidth, otherPanelWidth, workflowCanvasWidth, debounceUpdate])
|
||||
|
||||
const { handleNodeSelect } = useNodesInteractions()
|
||||
@@ -284,21 +262,17 @@ const BasePanel: FC<BasePanelProps> = ({
|
||||
|
||||
const storeBuildInTools = useStore(s => s.buildInTools)
|
||||
const { data: buildInTools } = useAllBuiltInTools()
|
||||
const currToolCollection = useMemo(() => {
|
||||
const candidates = buildInTools ?? storeBuildInTools
|
||||
return candidates?.find(item => canFindTool(item.id, data.provider_id))
|
||||
}, [buildInTools, storeBuildInTools, data.provider_id])
|
||||
const currToolCollection = useMemo(
|
||||
() => getCurrentToolCollection(buildInTools, storeBuildInTools, data.provider_id),
|
||||
[buildInTools, storeBuildInTools, data.provider_id],
|
||||
)
|
||||
const needsToolAuth = useMemo(() => {
|
||||
return data.type === BlockEnum.Tool && currToolCollection?.allow_delete
|
||||
}, [data.type, currToolCollection?.allow_delete])
|
||||
|
||||
// only fetch trigger plugins when the node is a trigger plugin
|
||||
const { data: triggerPlugins = [] } = useAllTriggerPlugins(data.type === BlockEnum.TriggerPlugin)
|
||||
const currentTriggerPlugin = useMemo(() => {
|
||||
if (data.type !== BlockEnum.TriggerPlugin || !data.plugin_id || !triggerPlugins?.length)
|
||||
return undefined
|
||||
return triggerPlugins?.find(p => p.plugin_id === data.plugin_id)
|
||||
}, [data.type, data.plugin_id, triggerPlugins])
|
||||
const currentTriggerPlugin = useMemo(() => getCurrentTriggerPlugin(data, triggerPlugins), [data, triggerPlugins])
|
||||
const { setDetail } = usePluginStore()
|
||||
|
||||
useEffect(() => {
|
||||
@@ -321,10 +295,7 @@ const BasePanel: FC<BasePanelProps> = ({
|
||||
|
||||
const dataSourceList = useStore(s => s.dataSourceList)
|
||||
|
||||
const currentDataSource = useMemo(() => {
|
||||
if (data.type === BlockEnum.DataSource && data.provider_type !== DataSourceClassification.localFile)
|
||||
return dataSourceList?.find(item => item.plugin_id === data.plugin_id)
|
||||
}, [data.type, data.provider_type, data.plugin_id, dataSourceList])
|
||||
const currentDataSource = useMemo(() => getCurrentDataSource(data, dataSourceList), [data, dataSourceList])
|
||||
|
||||
const handleAuthorizationItemClick = useCallback((credential_id: string) => {
|
||||
handleNodeDataUpdateWithSyncDraft({
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import { NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import LastRun from '../index'
|
||||
|
||||
const mockUseHooksStore = vi.hoisted(() => vi.fn())
|
||||
const mockUseLastRun = vi.hoisted(() => vi.fn())
|
||||
const mockResultPanel = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@remixicon/react', () => ({
|
||||
RiLoader2Line: () => <div data-testid="loading-icon" />,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks-store', () => ({
|
||||
useHooksStore: (selector: (state: {
|
||||
configsMap?: { flowType?: string, flowId?: string }
|
||||
}) => unknown) => mockUseHooksStore(selector),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/use-workflow', () => ({
|
||||
useLastRun: (...args: unknown[]) => mockUseLastRun(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/run/result-panel', () => ({
|
||||
__esModule: true,
|
||||
default: (props: Record<string, unknown>) => {
|
||||
mockResultPanel(props)
|
||||
return <div data-testid="result-panel">{String(props.status)}</div>
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../no-data', () => ({
|
||||
__esModule: true,
|
||||
default: ({ onSingleRun }: { onSingleRun: () => void }) => (
|
||||
<button type="button" onClick={onSingleRun}>
|
||||
no-data
|
||||
</button>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('LastRun', () => {
|
||||
const updateNodeRunningStatus = vi.fn()
|
||||
const onSingleRunClicked = vi.fn()
|
||||
let visibilityState = 'visible'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockUseHooksStore.mockImplementation((selector: (state: {
|
||||
configsMap?: { flowType?: string, flowId?: string }
|
||||
}) => unknown) => selector({
|
||||
configsMap: {
|
||||
flowType: 'appFlow',
|
||||
flowId: 'flow-1',
|
||||
},
|
||||
}))
|
||||
mockUseLastRun.mockReturnValue({
|
||||
data: undefined,
|
||||
isFetching: false,
|
||||
error: undefined,
|
||||
})
|
||||
visibilityState = 'visible'
|
||||
Object.defineProperty(document, 'visibilityState', {
|
||||
configurable: true,
|
||||
get: () => visibilityState,
|
||||
})
|
||||
})
|
||||
|
||||
it('should show a loader while fetching the last run before any single run starts', () => {
|
||||
mockUseLastRun.mockReturnValue({
|
||||
data: undefined,
|
||||
isFetching: true,
|
||||
error: undefined,
|
||||
})
|
||||
|
||||
render(
|
||||
<LastRun
|
||||
appId="app-1"
|
||||
nodeId="node-1"
|
||||
canSingleRun
|
||||
isRunAfterSingleRun={false}
|
||||
updateNodeRunningStatus={updateNodeRunningStatus}
|
||||
onSingleRunClicked={onSingleRunClicked}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('loading-icon')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('result-panel')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show a running result panel while a single run is still executing', () => {
|
||||
render(
|
||||
<LastRun
|
||||
appId="app-1"
|
||||
nodeId="node-1"
|
||||
canSingleRun
|
||||
isRunAfterSingleRun
|
||||
updateNodeRunningStatus={updateNodeRunningStatus}
|
||||
onSingleRunClicked={onSingleRunClicked}
|
||||
runningStatus={NodeRunningStatus.Running}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('result-panel')).toHaveTextContent('running')
|
||||
expect(mockResultPanel).toHaveBeenCalledWith(expect.objectContaining({
|
||||
status: 'running',
|
||||
showSteps: false,
|
||||
}))
|
||||
})
|
||||
|
||||
it('should render the no-data state for 404 last-run responses and forward single-run clicks', () => {
|
||||
mockUseLastRun.mockReturnValue({
|
||||
data: undefined,
|
||||
isFetching: false,
|
||||
error: { status: 404 },
|
||||
})
|
||||
|
||||
render(
|
||||
<LastRun
|
||||
appId="app-1"
|
||||
nodeId="node-1"
|
||||
canSingleRun
|
||||
isRunAfterSingleRun={false}
|
||||
updateNodeRunningStatus={updateNodeRunningStatus}
|
||||
onSingleRunClicked={onSingleRunClicked}
|
||||
/>,
|
||||
)
|
||||
|
||||
act(() => {
|
||||
screen.getByText('no-data').click()
|
||||
})
|
||||
|
||||
expect(onSingleRunClicked).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should render resolved result data and let paused state override the final status', () => {
|
||||
mockUseLastRun.mockReturnValue({
|
||||
data: {
|
||||
status: NodeRunningStatus.Succeeded,
|
||||
execution_metadata: { total_tokens: 9 },
|
||||
created_by_account: { created_by: 'Alice' },
|
||||
},
|
||||
isFetching: false,
|
||||
error: undefined,
|
||||
})
|
||||
|
||||
render(
|
||||
<LastRun
|
||||
appId="app-1"
|
||||
nodeId="node-1"
|
||||
canSingleRun
|
||||
isRunAfterSingleRun
|
||||
updateNodeRunningStatus={updateNodeRunningStatus}
|
||||
onSingleRunClicked={onSingleRunClicked}
|
||||
runningStatus={NodeRunningStatus.Succeeded}
|
||||
isPaused
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Stopped)
|
||||
expect(mockResultPanel).toHaveBeenCalledWith(expect.objectContaining({
|
||||
status: NodeRunningStatus.Stopped,
|
||||
total_tokens: 9,
|
||||
created_by: 'Alice',
|
||||
showSteps: false,
|
||||
}))
|
||||
})
|
||||
|
||||
it('should respect stopped and listening one-step statuses', () => {
|
||||
mockUseLastRun.mockReturnValue({
|
||||
data: {
|
||||
status: NodeRunningStatus.Succeeded,
|
||||
},
|
||||
isFetching: false,
|
||||
error: undefined,
|
||||
})
|
||||
|
||||
const { rerender } = render(
|
||||
<LastRun
|
||||
appId="app-1"
|
||||
nodeId="node-1"
|
||||
canSingleRun
|
||||
isRunAfterSingleRun
|
||||
updateNodeRunningStatus={updateNodeRunningStatus}
|
||||
onSingleRunClicked={onSingleRunClicked}
|
||||
runningStatus={NodeRunningStatus.Stopped}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Stopped)
|
||||
|
||||
rerender(
|
||||
<LastRun
|
||||
appId="app-1"
|
||||
nodeId="node-1"
|
||||
canSingleRun
|
||||
isRunAfterSingleRun
|
||||
updateNodeRunningStatus={updateNodeRunningStatus}
|
||||
onSingleRunClicked={onSingleRunClicked}
|
||||
runningStatus={NodeRunningStatus.Listening}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Listening)
|
||||
})
|
||||
|
||||
it('should react to page visibility changes while keeping the current result rendered', () => {
|
||||
mockUseLastRun.mockReturnValue({
|
||||
data: {
|
||||
status: NodeRunningStatus.Succeeded,
|
||||
},
|
||||
isFetching: false,
|
||||
error: undefined,
|
||||
})
|
||||
|
||||
render(
|
||||
<LastRun
|
||||
appId="app-1"
|
||||
nodeId="node-1"
|
||||
canSingleRun
|
||||
isRunAfterSingleRun
|
||||
updateNodeRunningStatus={updateNodeRunningStatus}
|
||||
onSingleRunClicked={onSingleRunClicked}
|
||||
runningStatus={NodeRunningStatus.Succeeded}
|
||||
/>,
|
||||
)
|
||||
|
||||
act(() => {
|
||||
visibilityState = 'hidden'
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
visibilityState = 'visible'
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
})
|
||||
|
||||
expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Succeeded)
|
||||
})
|
||||
})
|
||||
94
web/app/components/workflow/nodes/_base/node-sections.tsx
Normal file
94
web/app/components/workflow/nodes/_base/node-sections.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import type { TFunction } from 'i18next'
|
||||
import type { ReactElement } from 'react'
|
||||
import type { IterationNodeType } from '@/app/components/workflow/nodes/iteration/types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'
|
||||
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
|
||||
type HeaderMetaProps = {
|
||||
data: NodeProps['data']
|
||||
hasVarValue: boolean
|
||||
isLoading: boolean
|
||||
loopIndex: ReactElement | null
|
||||
t: TFunction
|
||||
}
|
||||
|
||||
export const NodeHeaderMeta = ({
|
||||
data,
|
||||
hasVarValue,
|
||||
isLoading,
|
||||
loopIndex,
|
||||
t,
|
||||
}: HeaderMetaProps) => {
|
||||
return (
|
||||
<>
|
||||
{data.type === BlockEnum.Iteration && (data as IterationNodeType).is_parallel && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<div className="ml-1 flex items-center justify-center rounded-[5px] border-[1px] border-text-warning px-[5px] py-[3px] text-text-warning system-2xs-medium-uppercase">
|
||||
{t('nodes.iteration.parallelModeUpper', { ns: 'workflow' })}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent popupClassName="w-[180px]">
|
||||
<div className="font-extrabold">
|
||||
{t('nodes.iteration.parallelModeEnableTitle', { ns: 'workflow' })}
|
||||
</div>
|
||||
{t('nodes.iteration.parallelModeEnableDesc', { ns: 'workflow' })}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{!!(data._iterationLength && data._iterationIndex && data._runningStatus === NodeRunningStatus.Running) && (
|
||||
<div className="mr-1.5 text-xs font-medium text-text-accent">
|
||||
{data._iterationIndex > data._iterationLength ? data._iterationLength : data._iterationIndex}
|
||||
/
|
||||
{data._iterationLength}
|
||||
</div>
|
||||
)}
|
||||
{!!(data.type === BlockEnum.Loop && data._loopIndex) && loopIndex}
|
||||
{isLoading && <span className="i-ri-loader-2-line h-3.5 w-3.5 animate-spin text-text-accent" />}
|
||||
{!isLoading && data._runningStatus === NodeRunningStatus.Failed && (
|
||||
<span className="i-ri-error-warning-fill h-3.5 w-3.5 text-text-destructive" />
|
||||
)}
|
||||
{!isLoading && data._runningStatus === NodeRunningStatus.Exception && (
|
||||
<span className="i-ri-alert-fill h-3.5 w-3.5 text-text-warning-secondary" />
|
||||
)}
|
||||
{!isLoading && (data._runningStatus === NodeRunningStatus.Succeeded || (!data._runningStatus && hasVarValue)) && (
|
||||
<span className="i-ri-checkbox-circle-fill h-3.5 w-3.5 text-text-success" />
|
||||
)}
|
||||
{!isLoading && data._runningStatus === NodeRunningStatus.Paused && (
|
||||
<span className="i-ri-pause-circle-fill h-3.5 w-3.5 text-text-warning-secondary" />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type NodeBodyProps = {
|
||||
data: NodeProps['data']
|
||||
child: ReactElement
|
||||
}
|
||||
|
||||
export const NodeBody = ({
|
||||
data,
|
||||
child,
|
||||
}: NodeBodyProps) => {
|
||||
if (data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) {
|
||||
return (
|
||||
<div className="grow pb-1 pl-1 pr-1">
|
||||
{child}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return child
|
||||
}
|
||||
|
||||
export const NodeDescription = ({ data }: { data: NodeProps['data'] }) => {
|
||||
if (!data.desc || data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop)
|
||||
return null
|
||||
|
||||
return (
|
||||
<div className="whitespace-pre-line break-words px-3 pb-2 pt-1 text-text-tertiary system-xs-regular">
|
||||
{data.desc}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
32
web/app/components/workflow/nodes/_base/node.helpers.tsx
Normal file
32
web/app/components/workflow/nodes/_base/node.helpers.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import { BlockEnum, isTriggerNode, NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
|
||||
export const getNodeStatusBorders = (
|
||||
runningStatus: NodeRunningStatus | undefined,
|
||||
hasVarValue: boolean,
|
||||
showSelectedBorder: boolean,
|
||||
) => {
|
||||
return {
|
||||
showRunningBorder: (runningStatus === NodeRunningStatus.Running || runningStatus === NodeRunningStatus.Paused) && !showSelectedBorder,
|
||||
showSuccessBorder: (runningStatus === NodeRunningStatus.Succeeded || (hasVarValue && !runningStatus)) && !showSelectedBorder,
|
||||
showFailedBorder: runningStatus === NodeRunningStatus.Failed && !showSelectedBorder,
|
||||
showExceptionBorder: runningStatus === NodeRunningStatus.Exception && !showSelectedBorder,
|
||||
}
|
||||
}
|
||||
|
||||
export const getLoopIndexTextKey = (runningStatus: NodeRunningStatus | undefined) => {
|
||||
if (runningStatus === NodeRunningStatus.Running)
|
||||
return 'nodes.loop.currentLoopCount'
|
||||
if (runningStatus === NodeRunningStatus.Succeeded || runningStatus === NodeRunningStatus.Failed)
|
||||
return 'nodes.loop.totalLoopCount'
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const isEntryWorkflowNode = (type: NodeProps['data']['type']) => {
|
||||
return isTriggerNode(type) || type === BlockEnum.Start
|
||||
}
|
||||
|
||||
export const isContainerNode = (type: NodeProps['data']['type']) => {
|
||||
return type === BlockEnum.Iteration || type === BlockEnum.Loop
|
||||
}
|
||||
@@ -2,17 +2,14 @@ import type {
|
||||
FC,
|
||||
ReactElement,
|
||||
} from 'react'
|
||||
import type { IterationNodeType } from '@/app/components/workflow/nodes/iteration/types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import {
|
||||
cloneElement,
|
||||
memo,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
import BlockIcon from '@/app/components/workflow/block-icon'
|
||||
import { ToolTypeEnum } from '@/app/components/workflow/block-selector/types'
|
||||
import { useNodesReadOnly, useToolIcon } from '@/app/components/workflow/hooks'
|
||||
@@ -23,7 +20,6 @@ import { useNodeLoopInteractions } from '@/app/components/workflow/nodes/loop/us
|
||||
import CopyID from '@/app/components/workflow/nodes/tool/components/copy-id'
|
||||
import {
|
||||
BlockEnum,
|
||||
isTriggerNode,
|
||||
NodeRunningStatus,
|
||||
} from '@/app/components/workflow/types'
|
||||
import { hasErrorHandleNode, hasRetryNode } from '@/app/components/workflow/utils'
|
||||
@@ -38,6 +34,18 @@ import {
|
||||
} from './components/node-handle'
|
||||
import NodeResizer from './components/node-resizer'
|
||||
import RetryOnNode from './components/retry/retry-on-node'
|
||||
import {
|
||||
NodeBody,
|
||||
NodeDescription,
|
||||
NodeHeaderMeta,
|
||||
} from './node-sections'
|
||||
import {
|
||||
getLoopIndexTextKey,
|
||||
getNodeStatusBorders,
|
||||
isContainerNode,
|
||||
isEntryWorkflowNode,
|
||||
} from './node.helpers'
|
||||
import useNodeResizeObserver from './use-node-resize-observer'
|
||||
|
||||
type NodeChildProps = {
|
||||
id: string
|
||||
@@ -65,59 +73,34 @@ const BaseNode: FC<BaseNodeProps> = ({
|
||||
const { shouldDim: pluginDimmed, isChecking: pluginIsChecking, isMissing: pluginIsMissing, canInstall: pluginCanInstall, uniqueIdentifier: pluginUniqueIdentifier } = useNodePluginInstallation(data)
|
||||
const pluginInstallLocked = !pluginIsChecking && pluginIsMissing && pluginCanInstall && Boolean(pluginUniqueIdentifier)
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef.current && data.selected && data.isInIteration) {
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
handleNodeIterationChildSizeChange(id)
|
||||
})
|
||||
useNodeResizeObserver({
|
||||
enabled: Boolean(data.selected && data.isInIteration),
|
||||
nodeRef,
|
||||
onResize: () => handleNodeIterationChildSizeChange(id),
|
||||
})
|
||||
|
||||
resizeObserver.observe(nodeRef.current)
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
}
|
||||
}
|
||||
}, [data.isInIteration, data.selected, id, handleNodeIterationChildSizeChange])
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef.current && data.selected && data.isInLoop) {
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
handleNodeLoopChildSizeChange(id)
|
||||
})
|
||||
|
||||
resizeObserver.observe(nodeRef.current)
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
}
|
||||
}
|
||||
}, [data.isInLoop, data.selected, id, handleNodeLoopChildSizeChange])
|
||||
useNodeResizeObserver({
|
||||
enabled: Boolean(data.selected && data.isInLoop),
|
||||
nodeRef,
|
||||
onResize: () => handleNodeLoopChildSizeChange(id),
|
||||
})
|
||||
|
||||
const { hasNodeInspectVars } = useInspectVarsCrud()
|
||||
const isLoading = data._runningStatus === NodeRunningStatus.Running || data._singleRunningStatus === NodeRunningStatus.Running
|
||||
const hasVarValue = hasNodeInspectVars(id)
|
||||
const showSelectedBorder = data.selected || data._isBundled || data._isEntering
|
||||
const showSelectedBorder = Boolean(data.selected || data._isBundled || data._isEntering)
|
||||
const {
|
||||
showRunningBorder,
|
||||
showSuccessBorder,
|
||||
showFailedBorder,
|
||||
showExceptionBorder,
|
||||
} = useMemo(() => {
|
||||
return {
|
||||
showRunningBorder: (data._runningStatus === NodeRunningStatus.Running || data._runningStatus === NodeRunningStatus.Paused) && !showSelectedBorder,
|
||||
showSuccessBorder: (data._runningStatus === NodeRunningStatus.Succeeded || (hasVarValue && !data._runningStatus)) && !showSelectedBorder,
|
||||
showFailedBorder: data._runningStatus === NodeRunningStatus.Failed && !showSelectedBorder,
|
||||
showExceptionBorder: data._runningStatus === NodeRunningStatus.Exception && !showSelectedBorder,
|
||||
}
|
||||
}, [data._runningStatus, hasVarValue, showSelectedBorder])
|
||||
} = useMemo(() => getNodeStatusBorders(data._runningStatus, hasVarValue, showSelectedBorder), [data._runningStatus, hasVarValue, showSelectedBorder])
|
||||
|
||||
const LoopIndex = useMemo(() => {
|
||||
let text = ''
|
||||
|
||||
if (data._runningStatus === NodeRunningStatus.Running)
|
||||
text = t('nodes.loop.currentLoopCount', { ns: 'workflow', count: data._loopIndex })
|
||||
if (data._runningStatus === NodeRunningStatus.Succeeded || data._runningStatus === NodeRunningStatus.Failed)
|
||||
text = t('nodes.loop.totalLoopCount', { ns: 'workflow', count: data._loopIndex })
|
||||
const translationKey = getLoopIndexTextKey(data._runningStatus)
|
||||
const text = translationKey
|
||||
? t(translationKey, { ns: 'workflow', count: data._loopIndex })
|
||||
: ''
|
||||
|
||||
if (text) {
|
||||
return (
|
||||
@@ -145,8 +128,8 @@ const BaseNode: FC<BaseNodeProps> = ({
|
||||
)}
|
||||
ref={nodeRef}
|
||||
style={{
|
||||
width: (data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) ? data.width : 'auto',
|
||||
height: (data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) ? data.height : 'auto',
|
||||
width: isContainerNode(data.type) ? data.width : 'auto',
|
||||
height: isContainerNode(data.type) ? data.height : 'auto',
|
||||
}}
|
||||
>
|
||||
{(data._dimmed || pluginDimmed || pluginInstallLocked) && (
|
||||
@@ -174,8 +157,8 @@ const BaseNode: FC<BaseNodeProps> = ({
|
||||
className={cn(
|
||||
'group relative pb-1 shadow-xs',
|
||||
'rounded-[15px] border border-transparent',
|
||||
(data.type !== BlockEnum.Iteration && data.type !== BlockEnum.Loop) && 'w-[240px] bg-workflow-block-bg',
|
||||
(data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) && 'flex h-full w-full flex-col border-workflow-block-border bg-workflow-block-bg-transparent',
|
||||
!isContainerNode(data.type) && 'w-[240px] bg-workflow-block-bg',
|
||||
isContainerNode(data.type) && 'flex h-full w-full flex-col border-workflow-block-border bg-workflow-block-bg-transparent',
|
||||
!data._runningStatus && 'hover:shadow-lg',
|
||||
showRunningBorder && '!border-state-accent-solid',
|
||||
showSuccessBorder && '!border-state-success-solid',
|
||||
@@ -239,7 +222,7 @@ const BaseNode: FC<BaseNodeProps> = ({
|
||||
}
|
||||
<div className={cn(
|
||||
'flex items-center rounded-t-2xl px-3 pb-2 pt-3',
|
||||
(data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) && 'bg-transparent',
|
||||
isContainerNode(data.type) && 'bg-transparent',
|
||||
)}
|
||||
>
|
||||
<BlockIcon
|
||||
@@ -255,72 +238,19 @@ const BaseNode: FC<BaseNodeProps> = ({
|
||||
<div>
|
||||
{data.title}
|
||||
</div>
|
||||
{
|
||||
data.type === BlockEnum.Iteration && (data as IterationNodeType).is_parallel && (
|
||||
<Tooltip popupContent={(
|
||||
<div className="w-[180px]">
|
||||
<div className="font-extrabold">
|
||||
{t('nodes.iteration.parallelModeEnableTitle', { ns: 'workflow' })}
|
||||
</div>
|
||||
{t('nodes.iteration.parallelModeEnableDesc', { ns: 'workflow' })}
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<div className="ml-1 flex items-center justify-center rounded-[5px] border-[1px] border-text-warning px-[5px] py-[3px] text-text-warning system-2xs-medium-uppercase">
|
||||
{t('nodes.iteration.parallelModeUpper', { ns: 'workflow' })}
|
||||
</div>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
{
|
||||
!!(data._iterationLength && data._iterationIndex && data._runningStatus === NodeRunningStatus.Running) && (
|
||||
<div className="mr-1.5 text-xs font-medium text-text-accent">
|
||||
{data._iterationIndex > data._iterationLength ? data._iterationLength : data._iterationIndex}
|
||||
/
|
||||
{data._iterationLength}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
!!(data.type === BlockEnum.Loop && data._loopIndex) && LoopIndex
|
||||
}
|
||||
{
|
||||
isLoading && <span className="i-ri-loader-2-line h-3.5 w-3.5 animate-spin text-text-accent" />
|
||||
}
|
||||
{
|
||||
!isLoading && data._runningStatus === NodeRunningStatus.Failed && (
|
||||
<span className="i-ri-error-warning-fill h-3.5 w-3.5 text-text-destructive" />
|
||||
)
|
||||
}
|
||||
{
|
||||
!isLoading && data._runningStatus === NodeRunningStatus.Exception && (
|
||||
<span className="i-ri-alert-fill h-3.5 w-3.5 text-text-warning-secondary" />
|
||||
)
|
||||
}
|
||||
{
|
||||
!isLoading && (data._runningStatus === NodeRunningStatus.Succeeded || (hasVarValue && !data._runningStatus)) && (
|
||||
<span className="i-ri-checkbox-circle-fill h-3.5 w-3.5 text-text-success" />
|
||||
)
|
||||
}
|
||||
{
|
||||
!isLoading && data._runningStatus === NodeRunningStatus.Paused && (
|
||||
<span className="i-ri-pause-circle-fill h-3.5 w-3.5 text-text-warning-secondary" />
|
||||
)
|
||||
}
|
||||
<NodeHeaderMeta
|
||||
data={data}
|
||||
hasVarValue={hasVarValue}
|
||||
isLoading={isLoading}
|
||||
loopIndex={LoopIndex}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
{
|
||||
data.type !== BlockEnum.Iteration && data.type !== BlockEnum.Loop && (
|
||||
cloneElement(children, { id, data } as any)
|
||||
)
|
||||
}
|
||||
{
|
||||
(data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) && (
|
||||
<div className="grow pb-1 pl-1 pr-1">
|
||||
{cloneElement(children, { id, data } as any)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<NodeBody
|
||||
data={data}
|
||||
child={cloneElement(children, { id, data } as any)}
|
||||
/>
|
||||
{
|
||||
hasRetryNode(data.type) && (
|
||||
<RetryOnNode
|
||||
@@ -337,13 +267,7 @@ const BaseNode: FC<BaseNodeProps> = ({
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
!!(data.desc && data.type !== BlockEnum.Iteration && data.type !== BlockEnum.Loop) && (
|
||||
<div className="whitespace-pre-line break-words px-3 pb-2 pt-1 text-text-tertiary system-xs-regular">
|
||||
{data.desc}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<NodeDescription data={data} />
|
||||
{data.type === BlockEnum.Tool && data.provider_type === ToolTypeEnum.MCP && (
|
||||
<div className="px-3 pb-2">
|
||||
<CopyID content={data.provider_id || ''} />
|
||||
@@ -354,7 +278,7 @@ const BaseNode: FC<BaseNodeProps> = ({
|
||||
)
|
||||
|
||||
const isStartNode = data.type === BlockEnum.Start
|
||||
const isEntryNode = isTriggerNode(data.type as any) || isStartNode
|
||||
const isEntryNode = isEntryWorkflowNode(data.type)
|
||||
|
||||
return isEntryNode
|
||||
? (
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useEffect } from 'react'
|
||||
|
||||
type ResizeObserverParams = {
|
||||
enabled: boolean
|
||||
nodeRef: React.RefObject<HTMLDivElement | null>
|
||||
onResize: () => void
|
||||
}
|
||||
|
||||
const useNodeResizeObserver = ({
|
||||
enabled,
|
||||
nodeRef,
|
||||
onResize,
|
||||
}: ResizeObserverParams) => {
|
||||
useEffect(() => {
|
||||
if (!enabled || !nodeRef.current)
|
||||
return
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
onResize()
|
||||
})
|
||||
|
||||
resizeObserver.observe(nodeRef.current)
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
}
|
||||
}, [enabled, nodeRef, onResize])
|
||||
}
|
||||
|
||||
export default useNodeResizeObserver
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { DataSourceNodeType } from '../../types'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { VarType as VarKindType } from '../../types'
|
||||
import { useConfig } from '../use-config'
|
||||
|
||||
const mockUseStoreApi = vi.hoisted(() => vi.fn())
|
||||
const mockUseNodeDataUpdate = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('reactflow', () => ({
|
||||
useStoreApi: () => mockUseStoreApi(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/hooks', () => ({
|
||||
useNodeDataUpdate: () => mockUseNodeDataUpdate(),
|
||||
}))
|
||||
|
||||
const createNode = (overrides: Partial<DataSourceNodeType> = {}): { id: string, data: DataSourceNodeType } => ({
|
||||
id: 'data-source-node',
|
||||
data: {
|
||||
title: 'Datasource',
|
||||
desc: '',
|
||||
type: 'data-source',
|
||||
plugin_id: 'plugin-1',
|
||||
provider_type: 'local_file',
|
||||
provider_name: 'provider',
|
||||
datasource_name: 'source-a',
|
||||
datasource_label: 'Source A',
|
||||
datasource_parameters: {},
|
||||
datasource_configurations: {},
|
||||
_dataSourceStartToAdd: true,
|
||||
...overrides,
|
||||
} as DataSourceNodeType,
|
||||
})
|
||||
|
||||
describe('data-source/hooks/use-config', () => {
|
||||
const mockHandleNodeDataUpdateWithSyncDraft = vi.fn()
|
||||
let currentNode = createNode()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
currentNode = createNode()
|
||||
|
||||
mockUseStoreApi.mockReturnValue({
|
||||
getState: () => ({
|
||||
getNodes: () => [currentNode],
|
||||
}),
|
||||
})
|
||||
mockUseNodeDataUpdate.mockReturnValue({
|
||||
handleNodeDataUpdateWithSyncDraft: mockHandleNodeDataUpdateWithSyncDraft,
|
||||
})
|
||||
})
|
||||
|
||||
it('should clear the local-file auto-add flag on mount and update datasource payloads', () => {
|
||||
const { result } = renderHook(() => useConfig('data-source-node'))
|
||||
|
||||
expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith({
|
||||
id: 'data-source-node',
|
||||
data: expect.objectContaining({
|
||||
_dataSourceStartToAdd: false,
|
||||
}),
|
||||
})
|
||||
|
||||
mockHandleNodeDataUpdateWithSyncDraft.mockClear()
|
||||
result.current.handleFileExtensionsChange(['pdf', 'csv'])
|
||||
result.current.handleParametersChange({
|
||||
dataset: {
|
||||
type: VarKindType.constant,
|
||||
value: 'docs',
|
||||
},
|
||||
})
|
||||
|
||||
expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenNthCalledWith(1, {
|
||||
id: 'data-source-node',
|
||||
data: expect.objectContaining({
|
||||
fileExtensions: ['pdf', 'csv'],
|
||||
}),
|
||||
})
|
||||
expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenNthCalledWith(2, {
|
||||
id: 'data-source-node',
|
||||
data: expect.objectContaining({
|
||||
datasource_parameters: {
|
||||
dataset: {
|
||||
type: VarKindType.constant,
|
||||
value: 'docs',
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
it('should derive output schema metadata and detect object outputs', () => {
|
||||
const dataSourceList = [{
|
||||
plugin_id: 'plugin-1',
|
||||
tools: [{
|
||||
name: 'source-a',
|
||||
output_schema: {
|
||||
properties: {
|
||||
items: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'List of items',
|
||||
},
|
||||
metadata: {
|
||||
type: 'object',
|
||||
description: 'Object field',
|
||||
},
|
||||
count: {
|
||||
type: 'number',
|
||||
description: 'Total count',
|
||||
},
|
||||
},
|
||||
},
|
||||
}],
|
||||
}]
|
||||
|
||||
const { result } = renderHook(() => useConfig('data-source-node', dataSourceList))
|
||||
|
||||
expect(result.current.outputSchema).toEqual([
|
||||
{
|
||||
name: 'items',
|
||||
type: 'Array[String]',
|
||||
description: 'List of items',
|
||||
},
|
||||
{
|
||||
name: 'metadata',
|
||||
value: {
|
||||
type: 'object',
|
||||
description: 'Object field',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'count',
|
||||
type: 'Number',
|
||||
description: 'Total count',
|
||||
},
|
||||
])
|
||||
expect(result.current.hasObjectOutput).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import * as React from 'react'
|
||||
import { UserActionButtonType } from '../../types'
|
||||
import ButtonStyleDropdown from '../button-style-dropdown'
|
||||
|
||||
const mockUseTranslation = vi.hoisted(() => vi.fn())
|
||||
const mockButton = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => mockUseTranslation(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/base/button', () => ({
|
||||
__esModule: true,
|
||||
default: (props: {
|
||||
variant?: string
|
||||
children?: React.ReactNode
|
||||
className?: string
|
||||
}) => {
|
||||
mockButton(props)
|
||||
return <div data-testid={`button-${props.variant ?? 'default'}`}>{props.children}</div>
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/base/portal-to-follow-elem', () => {
|
||||
const OpenContext = React.createContext(false)
|
||||
|
||||
return {
|
||||
PortalToFollowElem: ({
|
||||
open,
|
||||
children,
|
||||
}: {
|
||||
open: boolean
|
||||
children?: React.ReactNode
|
||||
}) => (
|
||||
<OpenContext value={open}>
|
||||
<div data-testid="portal" data-open={String(open)}>{children}</div>
|
||||
</OpenContext>
|
||||
),
|
||||
PortalToFollowElemTrigger: ({
|
||||
children,
|
||||
onClick,
|
||||
}: {
|
||||
children?: React.ReactNode
|
||||
onClick?: () => void
|
||||
}) => (
|
||||
<button type="button" data-testid="portal-trigger" onClick={onClick}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
PortalToFollowElemContent: ({
|
||||
children,
|
||||
}: {
|
||||
children?: React.ReactNode
|
||||
}) => {
|
||||
const open = React.use(OpenContext)
|
||||
return open ? <div data-testid="portal-content">{children}</div> : null
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe('ButtonStyleDropdown', () => {
|
||||
const onChange = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockUseTranslation.mockReturnValue({
|
||||
t: (key: string) => key,
|
||||
})
|
||||
})
|
||||
|
||||
it('should map the current style to the trigger button and update the selected style', () => {
|
||||
render(
|
||||
<ButtonStyleDropdown
|
||||
text="Approve"
|
||||
data={UserActionButtonType.Ghost}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(mockButton).toHaveBeenCalledWith(expect.objectContaining({
|
||||
variant: 'ghost',
|
||||
}))
|
||||
expect(screen.getByTestId('portal')).toHaveAttribute('data-open', 'false')
|
||||
|
||||
fireEvent.click(screen.getByTestId('portal-trigger'))
|
||||
expect(screen.getByTestId('portal')).toHaveAttribute('data-open', 'true')
|
||||
expect(screen.getByText('nodes.humanInput.userActions.chooseStyle')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByTestId('button-primary').parentElement as HTMLElement)
|
||||
fireEvent.click(screen.getByTestId('button-secondary').parentElement as HTMLElement)
|
||||
fireEvent.click(screen.getByTestId('button-secondary-accent').parentElement as HTMLElement)
|
||||
fireEvent.click(screen.getAllByTestId('button-ghost')[1].parentElement as HTMLElement)
|
||||
|
||||
expect(onChange).toHaveBeenNthCalledWith(1, UserActionButtonType.Primary)
|
||||
expect(onChange).toHaveBeenNthCalledWith(2, UserActionButtonType.Default)
|
||||
expect(onChange).toHaveBeenNthCalledWith(3, UserActionButtonType.Accent)
|
||||
expect(onChange).toHaveBeenNthCalledWith(4, UserActionButtonType.Ghost)
|
||||
})
|
||||
|
||||
it('should keep the dropdown closed in readonly mode', () => {
|
||||
render(
|
||||
<ButtonStyleDropdown
|
||||
text="Approve"
|
||||
data={UserActionButtonType.Default}
|
||||
onChange={onChange}
|
||||
readonly
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(mockButton).toHaveBeenCalledWith(expect.objectContaining({
|
||||
variant: 'secondary',
|
||||
}))
|
||||
|
||||
fireEvent.click(screen.getByTestId('portal-trigger'))
|
||||
|
||||
expect(screen.getByTestId('portal')).toHaveAttribute('data-open', 'false')
|
||||
expect(screen.queryByTestId('portal-content')).not.toBeInTheDocument()
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should map the accent style to the secondary-accent trigger button', () => {
|
||||
render(
|
||||
<ButtonStyleDropdown
|
||||
text="Approve"
|
||||
data={UserActionButtonType.Accent}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(mockButton).toHaveBeenCalledWith(expect.objectContaining({
|
||||
variant: 'secondary-accent',
|
||||
}))
|
||||
})
|
||||
|
||||
it('should map the primary style to the primary trigger button', () => {
|
||||
render(
|
||||
<ButtonStyleDropdown
|
||||
text="Approve"
|
||||
data={UserActionButtonType.Primary}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(mockButton).toHaveBeenCalledWith(expect.objectContaining({
|
||||
variant: 'primary',
|
||||
}))
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user