Compare commits

..
Author SHA1 Message Date
hj24 0b96062be0 fix: save and sync partner cookie failed 2026-04-01 23:47:02 +08:00
Tim RenGitHubClaude Opus 4.6autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
391007d02e refactor: migrate service_api and inner_api to sessionmaker pattern (#34379)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-01 14:53:41 +00:00
wangxiaoleiandGitHub e41965061c fix: sqlalchemy.exc.InvalidRequestError: Can't operate on closed tran… (#34407) 2026-04-01 13:15:36 +00:00
Stephen ZhouandGitHub 2b9eb06555 chore: move commit hook to root (#34404) 2026-04-01 11:02:53 +00:00
RenzoGitHubautofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>Asuka Minato
31f7752ba9 refactor: select in 10 service files (#34373)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Asuka Minato <i@asukaminato.eu.org>
2026-04-01 08:03:49 +00:00
173 changed files with 2655 additions and 8206 deletions
+1
View File
@@ -213,6 +213,7 @@ api/.vscode
# pnpm
/.pnpm-store
/node_modules
.vite-hooks/_
# plugin migrate
plugins.jsonl
+1 -1
View File
@@ -77,7 +77,7 @@ if $web_modified; then
fi
cd ./web || exit 1
lint-staged
vp staged
if $web_ts_modified; then
echo "Running TypeScript type-check:tsgo"
@@ -593,17 +593,15 @@ class PublishedRagPipelineApi(Resource):
# The role of the current user in the ta table must be admin, owner, or editor
current_user, _ = current_account_with_tenant()
rag_pipeline_service = RagPipelineService()
with sessionmaker(db.engine).begin() as session:
pipeline = session.merge(pipeline)
workflow = rag_pipeline_service.publish_workflow(
session=session,
pipeline=pipeline,
account=current_user,
)
pipeline.is_published = True
pipeline.workflow_id = workflow.id
session.add(pipeline)
workflow_created_at = TimestampField().format(workflow.created_at)
workflow = rag_pipeline_service.publish_workflow(
session=db.session, # type: ignore[reportArgumentType,arg-type]
pipeline=pipeline,
account=current_user,
)
pipeline.is_published = True
pipeline.workflow_id = workflow.id
db.session.commit()
workflow_created_at = TimestampField().format(workflow.created_at)
return {
"result": "success",
+3 -3
View File
@@ -6,7 +6,7 @@ from flask import current_app, request
from flask_login import user_logged_in
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker
from extensions.ext_database import db
from libs.login import current_user
@@ -33,7 +33,7 @@ def get_user(tenant_id: str, user_id: str | None) -> EndUser:
user_id = DefaultEndUserSessionID.DEFAULT_SESSION_ID
is_anonymous = user_id == DefaultEndUserSessionID.DEFAULT_SESSION_ID
try:
with Session(db.engine) as session:
with sessionmaker(db.engine, expire_on_commit=False).begin() as session:
user_model = None
if is_anonymous:
@@ -56,7 +56,7 @@ def get_user(tenant_id: str, user_id: str | None) -> EndUser:
session_id=user_id,
)
session.add(user_model)
session.commit()
session.flush()
session.refresh(user_model)
except Exception:
@@ -3,7 +3,7 @@ from typing import Any, Literal
from flask import request
from flask_restx import Resource
from pydantic import BaseModel, Field, TypeAdapter, field_validator, model_validator
from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker
from werkzeug.exceptions import BadRequest, NotFound
import services
@@ -116,7 +116,7 @@ class ConversationApi(Resource):
last_id = str(query_args.last_id) if query_args.last_id else None
try:
with Session(db.engine) as session:
with sessionmaker(db.engine).begin() as session:
pagination = ConversationService.pagination_by_last_id(
session=session,
app_model=app_model,
+2 -2
View File
@@ -8,7 +8,7 @@ from graphon.enums import WorkflowExecutionStatus
from graphon.graph_engine.manager import GraphEngineManager
from graphon.model_runtime.errors.invoke import InvokeError
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.orm import sessionmaker
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
from controllers.common.schema import register_schema_models
@@ -314,7 +314,7 @@ class WorkflowAppLogApi(Resource):
# get paginate workflow app logs
workflow_app_service = WorkflowAppService()
with Session(db.engine) as session:
with sessionmaker(db.engine).begin() as session:
workflow_app_log_pagination = workflow_app_service.get_paginate_workflow_app_logs(
session=session,
app_model=app_model,
+10 -14
View File
@@ -2,6 +2,7 @@ import threading
from typing import Any
import pytz
from sqlalchemy import select
import contexts
from core.app.app_config.easy_ui_based_app.agent.manager import AgentConfigManager
@@ -23,25 +24,25 @@ class AgentService:
contexts.plugin_tool_providers.set({})
contexts.plugin_tool_providers_lock.set(threading.Lock())
conversation: Conversation | None = (
db.session.query(Conversation)
conversation: Conversation | None = db.session.scalar(
select(Conversation)
.where(
Conversation.id == conversation_id,
Conversation.app_id == app_model.id,
)
.first()
.limit(1)
)
if not conversation:
raise ValueError(f"Conversation not found: {conversation_id}")
message: Message | None = (
db.session.query(Message)
message: Message | None = db.session.scalar(
select(Message)
.where(
Message.id == message_id,
Message.conversation_id == conversation_id,
)
.first()
.limit(1)
)
if not message:
@@ -51,16 +52,11 @@ class AgentService:
if conversation.from_end_user_id:
# only select name field
executor = (
db.session.query(EndUser, EndUser.name).where(EndUser.id == conversation.from_end_user_id).first()
)
executor_name = db.session.scalar(select(EndUser.name).where(EndUser.id == conversation.from_end_user_id))
else:
executor = db.session.query(Account, Account.name).where(Account.id == conversation.from_account_id).first()
executor_name = db.session.scalar(select(Account.name).where(Account.id == conversation.from_account_id))
if executor:
executor = executor.name
else:
executor = "Unknown"
executor = executor_name or "Unknown"
assert isinstance(current_user, Account)
assert current_user.timezone is not None
timezone = pytz.timezone(current_user.timezone)
+27 -21
View File
@@ -1,3 +1,5 @@
from sqlalchemy import select
from core.extension.api_based_extension_requestor import APIBasedExtensionRequestor
from core.helper.encrypter import decrypt_token, encrypt_token
from extensions.ext_database import db
@@ -7,11 +9,12 @@ from models.api_based_extension import APIBasedExtension, APIBasedExtensionPoint
class APIBasedExtensionService:
@staticmethod
def get_all_by_tenant_id(tenant_id: str) -> list[APIBasedExtension]:
extension_list = (
db.session.query(APIBasedExtension)
.filter_by(tenant_id=tenant_id)
.order_by(APIBasedExtension.created_at.desc())
.all()
extension_list = list(
db.session.scalars(
select(APIBasedExtension)
.where(APIBasedExtension.tenant_id == tenant_id)
.order_by(APIBasedExtension.created_at.desc())
).all()
)
for extension in extension_list:
@@ -36,11 +39,10 @@ class APIBasedExtensionService:
@staticmethod
def get_with_tenant_id(tenant_id: str, api_based_extension_id: str) -> APIBasedExtension:
extension = (
db.session.query(APIBasedExtension)
.filter_by(tenant_id=tenant_id)
.filter_by(id=api_based_extension_id)
.first()
extension = db.session.scalar(
select(APIBasedExtension)
.where(APIBasedExtension.tenant_id == tenant_id, APIBasedExtension.id == api_based_extension_id)
.limit(1)
)
if not extension:
@@ -58,23 +60,27 @@ class APIBasedExtensionService:
if not extension_data.id:
# case one: check new data, name must be unique
is_name_existed = (
db.session.query(APIBasedExtension)
.filter_by(tenant_id=extension_data.tenant_id)
.filter_by(name=extension_data.name)
.first()
is_name_existed = db.session.scalar(
select(APIBasedExtension)
.where(
APIBasedExtension.tenant_id == extension_data.tenant_id,
APIBasedExtension.name == extension_data.name,
)
.limit(1)
)
if is_name_existed:
raise ValueError("name must be unique, it is already existed")
else:
# case two: check existing data, name must be unique
is_name_existed = (
db.session.query(APIBasedExtension)
.filter_by(tenant_id=extension_data.tenant_id)
.filter_by(name=extension_data.name)
.where(APIBasedExtension.id != extension_data.id)
.first()
is_name_existed = db.session.scalar(
select(APIBasedExtension)
.where(
APIBasedExtension.tenant_id == extension_data.tenant_id,
APIBasedExtension.name == extension_data.name,
APIBasedExtension.id != extension_data.id,
)
.limit(1)
)
if is_name_existed:
+4 -5
View File
@@ -6,6 +6,7 @@ import sqlalchemy as sa
from flask_sqlalchemy.pagination import Pagination
from graphon.model_runtime.entities.model_entities import ModelPropertyKey, ModelType
from graphon.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
from sqlalchemy import select
from configs import dify_config
from constants.model_template import default_app_templates
@@ -433,9 +434,7 @@ class AppService:
meta["tool_icons"][tool_name] = url_prefix + provider_id + "/icon"
elif provider_type == "api":
try:
provider: ApiToolProvider | None = (
db.session.query(ApiToolProvider).where(ApiToolProvider.id == provider_id).first()
)
provider: ApiToolProvider | None = db.session.get(ApiToolProvider, provider_id)
if provider is None:
raise ValueError(f"provider not found for tool {tool_name}")
meta["tool_icons"][tool_name] = json.loads(provider.icon)
@@ -451,7 +450,7 @@ class AppService:
:param app_id: app id
:return: app code
"""
site = db.session.query(Site).where(Site.app_id == app_id).first()
site = db.session.scalar(select(Site).where(Site.app_id == app_id).limit(1))
if not site:
raise ValueError(f"App with id {app_id} not found")
return str(site.code)
@@ -463,7 +462,7 @@ class AppService:
:param app_code: app code
:return: app id
"""
site = db.session.query(Site).where(Site.code == app_code).first()
site = db.session.scalar(select(Site).where(Site.code == app_code).limit(1))
if not site:
raise ValueError(f"App with code {app_code} not found")
return str(site.app_id)
+11 -11
View File
@@ -4,7 +4,7 @@ import json
from datetime import datetime
from flask import Response
from sqlalchemy import or_
from sqlalchemy import or_, select
from extensions.ext_database import db
from models.enums import FeedbackRating
@@ -41,8 +41,8 @@ class FeedbackService:
raise ValueError(f"Unsupported format: {format_type}")
# Build base query
query = (
db.session.query(MessageFeedback, Message, Conversation, App, Account)
stmt = (
select(MessageFeedback, Message, Conversation, App, Account)
.join(Message, MessageFeedback.message_id == Message.id)
.join(Conversation, MessageFeedback.conversation_id == Conversation.id)
.join(App, MessageFeedback.app_id == App.id)
@@ -52,36 +52,36 @@ class FeedbackService:
# Apply filters
if from_source:
query = query.filter(MessageFeedback.from_source == from_source)
stmt = stmt.where(MessageFeedback.from_source == from_source)
if rating:
query = query.filter(MessageFeedback.rating == rating)
stmt = stmt.where(MessageFeedback.rating == rating)
if has_comment is not None:
if has_comment:
query = query.filter(MessageFeedback.content.isnot(None), MessageFeedback.content != "")
stmt = stmt.where(MessageFeedback.content.isnot(None), MessageFeedback.content != "")
else:
query = query.filter(or_(MessageFeedback.content.is_(None), MessageFeedback.content == ""))
stmt = stmt.where(or_(MessageFeedback.content.is_(None), MessageFeedback.content == ""))
if start_date:
try:
start_dt = datetime.strptime(start_date, "%Y-%m-%d")
query = query.filter(MessageFeedback.created_at >= start_dt)
stmt = stmt.where(MessageFeedback.created_at >= start_dt)
except ValueError:
raise ValueError(f"Invalid start_date format: {start_date}. Use YYYY-MM-DD")
if end_date:
try:
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
query = query.filter(MessageFeedback.created_at <= end_dt)
stmt = stmt.where(MessageFeedback.created_at <= end_dt)
except ValueError:
raise ValueError(f"Invalid end_date format: {end_date}. Use YYYY-MM-DD")
# Order by creation date (newest first)
query = query.order_by(MessageFeedback.created_at.desc())
stmt = stmt.order_by(MessageFeedback.created_at.desc())
# Execute query
results = query.all()
results = db.session.execute(stmt).all()
# Prepare data for export
export_data = []
@@ -6,6 +6,7 @@ from uuid import uuid4
import yaml
from flask_login import current_user
from sqlalchemy import select
from constants import DOCUMENT_EXTENSIONS
from core.plugin.impl.plugin import PluginInstaller
@@ -26,7 +27,7 @@ logger = logging.getLogger(__name__)
class RagPipelineTransformService:
def transform_dataset(self, dataset_id: str):
dataset = db.session.query(Dataset).where(Dataset.id == dataset_id).first()
dataset = db.session.get(Dataset, dataset_id)
if not dataset:
raise ValueError("Dataset not found")
if dataset.pipeline_id and dataset.runtime_mode == DatasetRuntimeMode.RAG_PIPELINE:
@@ -306,7 +307,7 @@ class RagPipelineTransformService:
jina_node_id = "1752491761974"
firecrawl_node_id = "1752565402678"
documents = db.session.query(Document).where(Document.dataset_id == dataset.id).all()
documents = db.session.scalars(select(Document).where(Document.dataset_id == dataset.id)).all()
for document in documents:
data_source_info_dict = document.data_source_info_dict
@@ -316,7 +317,7 @@ class RagPipelineTransformService:
document.data_source_type = DataSourceType.LOCAL_FILE
file_id = data_source_info_dict.get("upload_file_id")
if file_id:
file = db.session.query(UploadFile).where(UploadFile.id == file_id).first()
file = db.session.get(UploadFile, file_id)
if file:
data_source_info = json.dumps(
{
+7 -5
View File
@@ -1,3 +1,5 @@
from sqlalchemy import select
from configs import dify_config
from extensions.ext_database import db
from models.model import AccountTrialAppRecord, TrialApp
@@ -27,7 +29,7 @@ class RecommendedAppService:
apps = result["recommended_apps"]
for app in apps:
app_id = app["app_id"]
trial_app_model = db.session.query(TrialApp).where(TrialApp.app_id == app_id).first()
trial_app_model = db.session.scalar(select(TrialApp).where(TrialApp.app_id == app_id).limit(1))
if trial_app_model:
app["can_trial"] = True
else:
@@ -46,7 +48,7 @@ class RecommendedAppService:
result: dict = retrieval_instance.get_recommend_app_detail(app_id)
if FeatureService.get_system_features().enable_trial_app:
app_id = result["id"]
trial_app_model = db.session.query(TrialApp).where(TrialApp.app_id == app_id).first()
trial_app_model = db.session.scalar(select(TrialApp).where(TrialApp.app_id == app_id).limit(1))
if trial_app_model:
result["can_trial"] = True
else:
@@ -60,10 +62,10 @@ class RecommendedAppService:
:param app_id: app id
:return:
"""
account_trial_app_record = (
db.session.query(AccountTrialAppRecord)
account_trial_app_record = db.session.scalar(
select(AccountTrialAppRecord)
.where(AccountTrialAppRecord.app_id == app_id, AccountTrialAppRecord.account_id == account_id)
.first()
.limit(1)
)
if account_trial_app_record:
account_trial_app_record.count += 1
+11 -10
View File
@@ -1,5 +1,7 @@
from typing import Union
from sqlalchemy import select
from extensions.ext_database import db
from libs.infinite_scroll_pagination import InfiniteScrollPagination
from models import Account
@@ -16,16 +18,15 @@ class SavedMessageService:
) -> InfiniteScrollPagination:
if not user:
raise ValueError("User is required")
saved_messages = (
db.session.query(SavedMessage)
saved_messages = db.session.scalars(
select(SavedMessage)
.where(
SavedMessage.app_id == app_model.id,
SavedMessage.created_by_role == ("account" if isinstance(user, Account) else "end_user"),
SavedMessage.created_by == user.id,
)
.order_by(SavedMessage.created_at.desc())
.all()
)
).all()
message_ids = [sm.message_id for sm in saved_messages]
return MessageService.pagination_by_last_id(
@@ -36,15 +37,15 @@ class SavedMessageService:
def save(cls, app_model: App, user: Union[Account, EndUser] | None, message_id: str):
if not user:
return
saved_message = (
db.session.query(SavedMessage)
saved_message = db.session.scalar(
select(SavedMessage)
.where(
SavedMessage.app_id == app_model.id,
SavedMessage.message_id == message_id,
SavedMessage.created_by_role == ("account" if isinstance(user, Account) else "end_user"),
SavedMessage.created_by == user.id,
)
.first()
.limit(1)
)
if saved_message:
@@ -66,15 +67,15 @@ class SavedMessageService:
def delete(cls, app_model: App, user: Union[Account, EndUser] | None, message_id: str):
if not user:
return
saved_message = (
db.session.query(SavedMessage)
saved_message = db.session.scalar(
select(SavedMessage)
.where(
SavedMessage.app_id == app_model.id,
SavedMessage.message_id == message_id,
SavedMessage.created_by_role == ("account" if isinstance(user, Account) else "end_user"),
SavedMessage.created_by == user.id,
)
.first()
.limit(1)
)
if not saved_message:
@@ -332,12 +332,11 @@ class BuiltinToolManageService:
get builtin tool provider credentials
"""
with db.session.no_autoflush:
providers = (
db.session.query(BuiltinToolProvider)
.filter_by(tenant_id=tenant_id, provider=provider_name)
providers = db.session.scalars(
select(BuiltinToolProvider)
.where(BuiltinToolProvider.tenant_id == tenant_id, BuiltinToolProvider.provider == provider_name)
.order_by(BuiltinToolProvider.is_default.desc(), BuiltinToolProvider.created_at.asc())
.all()
)
).all()
if len(providers) == 0:
return []
+6 -9
View File
@@ -1,6 +1,7 @@
import logging
from graphon.model_runtime.entities.model_entities import ModelType
from sqlalchemy import delete, select
from core.model_manager import ModelInstance, ModelManager
from core.rag.datasource.keyword.keyword_factory import Keyword
@@ -29,7 +30,7 @@ class VectorService:
for segment in segments:
if doc_form == IndexStructureType.PARENT_CHILD_INDEX:
dataset_document = db.session.query(DatasetDocument).filter_by(id=segment.document_id).first()
dataset_document = db.session.get(DatasetDocument, segment.document_id)
if not dataset_document:
logger.warning(
"Expected DatasetDocument record to exist, but none was found, document_id=%s, segment_id=%s",
@@ -38,11 +39,7 @@ class VectorService:
)
continue
# get the process rule
processing_rule = (
db.session.query(DatasetProcessRule)
.where(DatasetProcessRule.id == dataset_document.dataset_process_rule_id)
.first()
)
processing_rule = db.session.get(DatasetProcessRule, dataset_document.dataset_process_rule_id)
if not processing_rule:
raise ValueError("No processing rule found.")
# get embedding model instance
@@ -271,8 +268,8 @@ class VectorService:
vector.delete_by_ids(old_attachment_ids)
# Delete existing segment attachment bindings in one operation
db.session.query(SegmentAttachmentBinding).where(SegmentAttachmentBinding.segment_id == segment.id).delete(
synchronize_session=False
db.session.execute(
delete(SegmentAttachmentBinding).where(SegmentAttachmentBinding.segment_id == segment.id)
)
if not attachment_ids:
@@ -280,7 +277,7 @@ class VectorService:
return
# Bulk fetch upload files - only fetch needed fields
upload_file_list = db.session.query(UploadFile).where(UploadFile.id.in_(attachment_ids)).all()
upload_file_list = db.session.scalars(select(UploadFile).where(UploadFile.id.in_(attachment_ids))).all()
if not upload_file_list:
db.session.commit()
+12 -12
View File
@@ -138,14 +138,14 @@ class WorkflowService:
if workflow_id:
return self.get_published_workflow_by_id(app_model, workflow_id)
# fetch draft workflow by app_model
workflow = (
db.session.query(Workflow)
workflow = db.session.scalar(
select(Workflow)
.where(
Workflow.tenant_id == app_model.tenant_id,
Workflow.app_id == app_model.id,
Workflow.version == Workflow.VERSION_DRAFT,
)
.first()
.limit(1)
)
# return draft workflow
@@ -155,14 +155,14 @@ class WorkflowService:
"""
fetch published workflow by workflow_id
"""
workflow = (
db.session.query(Workflow)
workflow = db.session.scalar(
select(Workflow)
.where(
Workflow.tenant_id == app_model.tenant_id,
Workflow.app_id == app_model.id,
Workflow.id == workflow_id,
)
.first()
.limit(1)
)
if not workflow:
return None
@@ -182,14 +182,14 @@ class WorkflowService:
return None
# fetch published workflow by workflow_id
workflow = (
db.session.query(Workflow)
workflow = db.session.scalar(
select(Workflow)
.where(
Workflow.tenant_id == app_model.tenant_id,
Workflow.app_id == app_model.id,
Workflow.id == app_model.workflow_id,
)
.first()
.limit(1)
)
return workflow
@@ -544,14 +544,14 @@ class WorkflowService:
# Use the same fallback logic as runtime: get the first available credential
# ordered by is_default DESC, created_at ASC (same as tool_manager.py)
default_provider = (
db.session.query(BuiltinToolProvider)
default_provider = db.session.scalar(
select(BuiltinToolProvider)
.where(
BuiltinToolProvider.tenant_id == tenant_id,
BuiltinToolProvider.provider == provider,
)
.order_by(BuiltinToolProvider.is_default.desc(), BuiltinToolProvider.created_at.asc())
.first()
.limit(1)
)
if not default_provider:
@@ -99,7 +99,7 @@ class TestFeedbackService:
)
]
mock_db_session.query.return_value = mock_query
mock_db_session.execute.return_value = mock_query
# Test CSV export
result = FeedbackService.export_feedbacks(app_id=sample_data["app"].id, format_type="csv")
@@ -138,7 +138,7 @@ class TestFeedbackService:
)
]
mock_db_session.query.return_value = mock_query
mock_db_session.execute.return_value = mock_query
# Test JSON export
result = FeedbackService.export_feedbacks(app_id=sample_data["app"].id, format_type="json")
@@ -175,7 +175,7 @@ class TestFeedbackService:
)
]
mock_db_session.query.return_value = mock_query
mock_db_session.execute.return_value = mock_query
# Test with filters
result = FeedbackService.export_feedbacks(
@@ -188,11 +188,8 @@ class TestFeedbackService:
format_type="csv",
)
# Verify filters were applied
assert mock_query.filter.called
filter_calls = mock_query.filter.call_args_list
# At least three filter invocations are expected (source, rating, comment)
assert len(filter_calls) >= 3
# Verify query was executed (filters are baked into the select statement)
assert mock_db_session.execute.called
def test_export_feedbacks_no_data(self, mock_db_session, sample_data):
"""Test exporting feedback when no data exists."""
@@ -206,7 +203,7 @@ class TestFeedbackService:
mock_query.order_by.return_value = mock_query
mock_query.all.return_value = []
mock_db_session.query.return_value = mock_query
mock_db_session.execute.return_value = mock_query
result = FeedbackService.export_feedbacks(app_id=sample_data["app"].id, format_type="csv")
@@ -271,7 +268,7 @@ class TestFeedbackService:
)
]
mock_db_session.query.return_value = mock_query
mock_db_session.execute.return_value = mock_query
# Test export
result = FeedbackService.export_feedbacks(app_id=sample_data["app"].id, format_type="json")
@@ -329,7 +326,7 @@ class TestFeedbackService:
)
]
mock_db_session.query.return_value = mock_query
mock_db_session.execute.return_value = mock_query
# Test export
result = FeedbackService.export_feedbacks(app_id=sample_data["app"].id, format_type="csv")
@@ -367,7 +364,7 @@ class TestFeedbackService:
),
]
mock_db_session.query.return_value = mock_query
mock_db_session.execute.return_value = mock_query
# Test export
result = FeedbackService.export_feedbacks(app_id=sample_data["app"].id, format_type="json")
@@ -41,15 +41,15 @@ class TestGetUser:
"""Test get_user function"""
@patch("controllers.inner_api.plugin.wraps.EndUser")
@patch("controllers.inner_api.plugin.wraps.Session")
@patch("controllers.inner_api.plugin.wraps.sessionmaker")
@patch("controllers.inner_api.plugin.wraps.db")
def test_should_return_existing_user_by_id(self, mock_db, mock_session_class, mock_enduser_class, app: Flask):
def test_should_return_existing_user_by_id(self, mock_db, mock_sessionmaker, mock_enduser_class, app: Flask):
"""Test returning existing user when found by ID"""
# Arrange
mock_user = MagicMock()
mock_user.id = "user123"
mock_session = MagicMock()
mock_session_class.return_value.__enter__.return_value = mock_session
mock_sessionmaker.return_value.begin.return_value.__enter__.return_value = mock_session
mock_session.get.return_value = mock_user
# Act
@@ -61,17 +61,17 @@ class TestGetUser:
mock_session.get.assert_called_once()
@patch("controllers.inner_api.plugin.wraps.EndUser")
@patch("controllers.inner_api.plugin.wraps.Session")
@patch("controllers.inner_api.plugin.wraps.sessionmaker")
@patch("controllers.inner_api.plugin.wraps.db")
def test_should_return_existing_anonymous_user_by_session_id(
self, mock_db, mock_session_class, mock_enduser_class, app: Flask
self, mock_db, mock_sessionmaker, mock_enduser_class, app: Flask
):
"""Test returning existing anonymous user by session_id"""
# Arrange
mock_user = MagicMock()
mock_user.session_id = "anonymous_session"
mock_session = MagicMock()
mock_session_class.return_value.__enter__.return_value = mock_session
mock_sessionmaker.return_value.begin.return_value.__enter__.return_value = mock_session
# non-anonymous path uses session.get(); anonymous uses session.scalar()
mock_session.get.return_value = mock_user
@@ -83,13 +83,13 @@ class TestGetUser:
assert result == mock_user
@patch("controllers.inner_api.plugin.wraps.EndUser")
@patch("controllers.inner_api.plugin.wraps.Session")
@patch("controllers.inner_api.plugin.wraps.sessionmaker")
@patch("controllers.inner_api.plugin.wraps.db")
def test_should_create_new_user_when_not_found(self, mock_db, mock_session_class, mock_enduser_class, app: Flask):
def test_should_create_new_user_when_not_found(self, mock_db, mock_sessionmaker, mock_enduser_class, app: Flask):
"""Test creating new user when not found in database"""
# Arrange
mock_session = MagicMock()
mock_session_class.return_value.__enter__.return_value = mock_session
mock_sessionmaker.return_value.begin.return_value.__enter__.return_value = mock_session
mock_session.get.return_value = None
mock_new_user = MagicMock()
mock_enduser_class.return_value = mock_new_user
@@ -101,21 +101,20 @@ class TestGetUser:
# Assert
assert result == mock_new_user
mock_session.add.assert_called_once()
mock_session.commit.assert_called_once()
mock_session.refresh.assert_called_once()
@patch("controllers.inner_api.plugin.wraps.select")
@patch("controllers.inner_api.plugin.wraps.EndUser")
@patch("controllers.inner_api.plugin.wraps.Session")
@patch("controllers.inner_api.plugin.wraps.sessionmaker")
@patch("controllers.inner_api.plugin.wraps.db")
def test_should_use_default_session_id_when_user_id_none(
self, mock_db, mock_session_class, mock_enduser_class, mock_select, app: Flask
self, mock_db, mock_sessionmaker, mock_enduser_class, mock_select, app: Flask
):
"""Test using default session ID when user_id is None"""
# Arrange
mock_user = MagicMock()
mock_session = MagicMock()
mock_session_class.return_value.__enter__.return_value = mock_session
mock_sessionmaker.return_value.begin.return_value.__enter__.return_value = mock_session
# When user_id is None, is_anonymous=True, so session.scalar() is used
mock_session.scalar.return_value = mock_user
@@ -127,15 +126,13 @@ class TestGetUser:
assert result == mock_user
@patch("controllers.inner_api.plugin.wraps.EndUser")
@patch("controllers.inner_api.plugin.wraps.Session")
@patch("controllers.inner_api.plugin.wraps.sessionmaker")
@patch("controllers.inner_api.plugin.wraps.db")
def test_should_raise_error_on_database_exception(
self, mock_db, mock_session_class, mock_enduser_class, app: Flask
):
def test_should_raise_error_on_database_exception(self, mock_db, mock_sessionmaker, mock_enduser_class, app: Flask):
"""Test raising ValueError when database operation fails"""
# Arrange
mock_session = MagicMock()
mock_session_class.return_value.__enter__.return_value = mock_session
mock_sessionmaker.return_value.begin.return_value.__enter__.return_value = mock_session
mock_session.get.side_effect = Exception("Database error")
# Act & Assert
@@ -433,13 +433,20 @@ class TestConversationApiController:
handler(api, app_model=app_model, end_user=end_user)
def test_list_last_not_found(self, app, monkeypatch: pytest.MonkeyPatch) -> None:
class _SessionStub:
class _BeginStub:
def __enter__(self):
return SimpleNamespace()
def __exit__(self, exc_type, exc, tb):
return False
class _SessionMakerStub:
def __init__(self, *args, **kwargs):
pass
def begin(self):
return _BeginStub()
monkeypatch.setattr(
ConversationService,
"pagination_by_last_id",
@@ -447,7 +454,7 @@ class TestConversationApiController:
)
conversation_module = sys.modules["controllers.service_api.app.conversation"]
monkeypatch.setattr(conversation_module, "db", SimpleNamespace(engine=object()))
monkeypatch.setattr(conversation_module, "Session", lambda *_args, **_kwargs: _SessionStub())
monkeypatch.setattr(conversation_module, "sessionmaker", _SessionMakerStub)
api = ConversationApi()
handler = _unwrap(api.get)
@@ -470,16 +470,23 @@ class TestWorkflowTaskStopApi:
class TestWorkflowAppLogApi:
def test_success(self, app, monkeypatch: pytest.MonkeyPatch) -> None:
class _SessionStub:
class _BeginStub:
def __enter__(self):
return SimpleNamespace()
def __exit__(self, exc_type, exc, tb):
return False
class _SessionMakerStub:
def __init__(self, *args, **kwargs):
pass
def begin(self):
return _BeginStub()
workflow_module = sys.modules["controllers.service_api.app.workflow"]
monkeypatch.setattr(workflow_module, "db", SimpleNamespace(engine=object()))
monkeypatch.setattr(workflow_module, "Session", lambda *_args, **_kwargs: _SessionStub())
monkeypatch.setattr(workflow_module, "sessionmaker", _SessionMakerStub)
monkeypatch.setattr(
WorkflowAppService,
"get_paginate_workflow_app_logs",
@@ -635,11 +642,14 @@ class TestWorkflowAppLogApiGet:
mock_svc_instance.get_paginate_workflow_app_logs.return_value = mock_pagination
mock_wf_svc_cls.return_value = mock_svc_instance
# Mock Session context manager
# Mock sessionmaker(...).begin() context manager
mock_session = Mock()
mock_db.engine = Mock()
mock_session.__enter__ = Mock(return_value=mock_session)
mock_session.__exit__ = Mock(return_value=False)
mock_begin = Mock()
mock_begin.__enter__ = Mock(return_value=mock_session)
mock_begin.__exit__ = Mock(return_value=False)
mock_session_factory = Mock()
mock_session_factory.begin.return_value = mock_begin
from controllers.service_api.app.workflow import WorkflowAppLogApi
@@ -647,7 +657,7 @@ class TestWorkflowAppLogApiGet:
"/workflows/logs?page=1&limit=20",
method="GET",
):
with patch("controllers.service_api.app.workflow.Session", return_value=mock_session):
with patch("controllers.service_api.app.workflow.sessionmaker", return_value=mock_session_factory):
api = WorkflowAppLogApi()
result = _unwrap(api.get)(api, app_model=mock_workflow_app)
@@ -77,22 +77,12 @@ def _make_segment(
def _mock_db_session_for_update_multimodel(*, upload_files: list[_UploadFileStub] | None) -> MagicMock:
session = MagicMock(name="session")
binding_query = MagicMock(name="binding_query")
binding_query.where.return_value = binding_query
binding_query.delete.return_value = 1
# db.session.execute() is used for delete(SegmentAttachmentBinding).where(...)
session.execute = MagicMock(name="execute")
upload_query = MagicMock(name="upload_query")
upload_query.where.return_value = upload_query
upload_query.all.return_value = upload_files or []
# db.session.scalars(select(UploadFile).where(...)).all() returns upload files
session.scalars.return_value.all.return_value = upload_files or []
def query_side_effect(model: object) -> MagicMock:
if model is vector_service_module.SegmentAttachmentBinding:
return binding_query
if model is vector_service_module.UploadFile:
return upload_query
return MagicMock(name=f"query({model})")
session.query.side_effect = query_side_effect
db_mock = MagicMock(name="db")
db_mock.session = session
return db_mock
@@ -165,22 +155,15 @@ def _mock_parent_child_queries(
) -> MagicMock:
session = MagicMock(name="session")
doc_query = MagicMock(name="doc_query")
doc_query.filter_by.return_value = doc_query
doc_query.first.return_value = dataset_document
get_dispatch: dict[object, object | None] = {
vector_service_module.DatasetDocument: dataset_document,
vector_service_module.DatasetProcessRule: processing_rule,
}
rule_query = MagicMock(name="rule_query")
rule_query.where.return_value = rule_query
rule_query.first.return_value = processing_rule
def get_side_effect(model: object, pk: object) -> object | None:
return get_dispatch.get(model)
def query_side_effect(model: object) -> MagicMock:
if model is vector_service_module.DatasetDocument:
return doc_query
if model is vector_service_module.DatasetProcessRule:
return rule_query
return MagicMock(name=f"query({model})")
session.query.side_effect = query_side_effect
session.get.side_effect = get_side_effect
db_mock = MagicMock(name="db")
db_mock.session = session
return db_mock
@@ -609,7 +592,7 @@ def test_update_multimodel_vector_deletes_bindings_and_commits_on_empty_new_ids(
vector_cls.assert_called_once_with(dataset=dataset)
vector_instance.delete_by_ids.assert_called_once_with(["old-1", "old-2"])
db_mock.session.query.assert_called_once_with(vector_service_module.SegmentAttachmentBinding)
db_mock.session.execute.assert_called_once()
db_mock.session.commit.assert_called_once()
db_mock.session.add_all.assert_not_called()
vector_instance.add_texts.assert_not_called()
@@ -644,6 +627,8 @@ def test_update_multimodel_vector_adds_bindings_and_vectors_and_skips_missing_up
binding_ctor = MagicMock(side_effect=lambda **kwargs: kwargs)
monkeypatch.setattr(vector_service_module, "SegmentAttachmentBinding", binding_ctor)
monkeypatch.setattr(vector_service_module, "delete", MagicMock())
monkeypatch.setattr(vector_service_module, "select", MagicMock())
logger_mock = MagicMock()
monkeypatch.setattr(vector_service_module, "logger", logger_mock)
@@ -677,6 +662,8 @@ def test_update_multimodel_vector_updates_bindings_without_multimodal_vector_ops
monkeypatch.setattr(
vector_service_module, "SegmentAttachmentBinding", MagicMock(side_effect=lambda **kwargs: kwargs)
)
monkeypatch.setattr(vector_service_module, "delete", MagicMock())
monkeypatch.setattr(vector_service_module, "select", MagicMock())
VectorService.update_multimodel_vector(segment=segment, attachment_ids=["file-1"], dataset=dataset)
@@ -698,6 +685,8 @@ def test_update_multimodel_vector_rolls_back_and_reraises_on_error(monkeypatch:
monkeypatch.setattr(
vector_service_module, "SegmentAttachmentBinding", MagicMock(side_effect=lambda **kwargs: kwargs)
)
monkeypatch.setattr(vector_service_module, "delete", MagicMock())
monkeypatch.setattr(vector_service_module, "select", MagicMock())
logger_mock = MagicMock()
monkeypatch.setattr(vector_service_module, "logger", logger_mock)
@@ -268,7 +268,7 @@ class TestWorkflowService:
Provides mock implementations of:
- session.add(): Adding new records
- session.commit(): Committing transactions
- session.query(): Querying database
- session.scalar(): Scalar queries
- session.execute(): Executing SQL statements
"""
with patch("services.workflow_service.db") as mock_db:
@@ -276,7 +276,7 @@ class TestWorkflowService:
mock_db.session = mock_session
mock_session.add = MagicMock()
mock_session.commit = MagicMock()
mock_session.query = MagicMock()
mock_session.scalar = MagicMock()
mock_session.execute = MagicMock()
yield mock_db
@@ -338,10 +338,8 @@ class TestWorkflowService:
app = TestWorkflowAssociatedDataFactory.create_app_mock()
mock_workflow = TestWorkflowAssociatedDataFactory.create_workflow_mock()
# Mock database query
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = mock_workflow
# Mock db.session.scalar() used by get_draft_workflow
mock_db_session.session.scalar.return_value = mock_workflow
result = workflow_service.get_draft_workflow(app)
@@ -351,10 +349,8 @@ class TestWorkflowService:
"""Test get_draft_workflow returns None when no draft exists."""
app = TestWorkflowAssociatedDataFactory.create_app_mock()
# Mock database query to return None
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = None
# Mock db.session.scalar() to return None
mock_db_session.session.scalar.return_value = None
result = workflow_service.get_draft_workflow(app)
@@ -366,10 +362,8 @@ class TestWorkflowService:
workflow_id = "workflow-123"
mock_workflow = TestWorkflowAssociatedDataFactory.create_workflow_mock(version="v1")
# Mock database query
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = mock_workflow
# Mock db.session.scalar() used by get_published_workflow_by_id
mock_db_session.session.scalar.return_value = mock_workflow
result = workflow_service.get_draft_workflow(app, workflow_id=workflow_id)
@@ -384,10 +378,8 @@ class TestWorkflowService:
workflow_id = "workflow-123"
mock_workflow = TestWorkflowAssociatedDataFactory.create_workflow_mock(workflow_id=workflow_id, version="v1")
# Mock database query
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = mock_workflow
# Mock db.session.scalar() used by get_published_workflow_by_id
mock_db_session.session.scalar.return_value = mock_workflow
result = workflow_service.get_published_workflow_by_id(app, workflow_id)
@@ -406,10 +398,8 @@ class TestWorkflowService:
workflow_id=workflow_id, version=Workflow.VERSION_DRAFT
)
# Mock database query
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = mock_workflow
# Mock db.session.scalar() used by get_published_workflow_by_id
mock_db_session.session.scalar.return_value = mock_workflow
with pytest.raises(IsDraftWorkflowError):
workflow_service.get_published_workflow_by_id(app, workflow_id)
@@ -419,10 +409,8 @@ class TestWorkflowService:
app = TestWorkflowAssociatedDataFactory.create_app_mock()
workflow_id = "nonexistent-workflow"
# Mock database query to return None
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = None
# Mock db.session.scalar() to return None
mock_db_session.session.scalar.return_value = None
result = workflow_service.get_published_workflow_by_id(app, workflow_id)
@@ -434,10 +422,8 @@ class TestWorkflowService:
app = TestWorkflowAssociatedDataFactory.create_app_mock(workflow_id=workflow_id)
mock_workflow = TestWorkflowAssociatedDataFactory.create_workflow_mock(workflow_id=workflow_id, version="v1")
# Mock database query
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = mock_workflow
# Mock db.session.scalar() used by get_published_workflow
mock_db_session.session.scalar.return_value = mock_workflow
result = workflow_service.get_published_workflow(app)
@@ -466,11 +452,9 @@ class TestWorkflowService:
graph = TestWorkflowAssociatedDataFactory.create_valid_workflow_graph()
features = {"file_upload": {"enabled": False}}
# Mock get_draft_workflow to return None (no existing draft)
# Mock db.session.scalar() to return None (no existing draft)
# This simulates the first time a workflow is created for an app
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = None
mock_db_session.session.scalar.return_value = None
with (
patch.object(workflow_service, "validate_features_structure"),
@@ -504,12 +488,10 @@ class TestWorkflowService:
features = {"file_upload": {"enabled": False}}
unique_hash = "test-hash-123"
# Mock existing draft workflow
# Mock existing draft workflow via db.session.scalar()
mock_workflow = TestWorkflowAssociatedDataFactory.create_workflow_mock(unique_hash=unique_hash)
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = mock_workflow
mock_db_session.session.scalar.return_value = mock_workflow
with (
patch.object(workflow_service, "validate_features_structure"),
@@ -545,12 +527,10 @@ class TestWorkflowService:
graph = TestWorkflowAssociatedDataFactory.create_valid_workflow_graph()
features = {}
# Mock existing draft workflow with different hash
# Mock existing draft workflow with different hash via db.session.scalar()
mock_workflow = TestWorkflowAssociatedDataFactory.create_workflow_mock(unique_hash="old-hash")
mock_query = MagicMock()
mock_db_session.session.query.return_value = mock_query
mock_query.where.return_value.first.return_value = mock_workflow
mock_db_session.session.scalar.return_value = mock_workflow
with pytest.raises(WorkflowHashNotEqualError):
workflow_service.sync_draft_workflow(
@@ -347,7 +347,7 @@ class TestGetBuiltinToolProviderCredentials:
def test_returns_empty_when_no_providers(self, mock_db):
mock_db.session.no_autoflush.__enter__ = MagicMock(return_value=None)
mock_db.session.no_autoflush.__exit__ = MagicMock(return_value=False)
mock_db.session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = []
mock_db.session.scalars.return_value.all.return_value = []
result = BuiltinToolManageService.get_builtin_tool_provider_credentials("t", "google")
@@ -362,7 +362,7 @@ class TestGetBuiltinToolProviderCredentials:
mock_db.session.no_autoflush.__exit__ = MagicMock(return_value=False)
provider = MagicMock(provider="google", is_default=False)
mock_db.session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = [provider]
mock_db.session.scalars.return_value.all.return_value = [provider]
mock_encrypter = MagicMock()
mock_encrypter.decrypt.return_value = {"key": "decrypted"}
+8 -4
View File
@@ -1,11 +1,15 @@
{
"name": "dify",
"private": true,
"scripts": {
"prepare": "vp config"
},
"devDependencies": {
"taze": "catalog:",
"vite-plus": "catalog:"
},
"engines": {
"node": "^22.22.1"
},
"packageManager": "pnpm@10.33.0",
"devDependencies": {
"taze": "catalog:"
}
"packageManager": "pnpm@10.33.0"
}
+3 -215
View File
@@ -345,9 +345,6 @@ catalogs:
html-to-image:
specifier: 1.11.13
version: 1.11.13
husky:
specifier: 9.1.7
version: 9.1.7
i18next:
specifier: 25.10.10
version: 25.10.10
@@ -390,9 +387,6 @@ catalogs:
lexical:
specifier: 0.42.0
version: 0.42.0
lint-staged:
specifier: 16.4.0
version: 16.4.0
mermaid:
specifier: 11.13.0
version: 11.13.0
@@ -402,9 +396,6 @@ catalogs:
mitt:
specifier: 3.0.1
version: 3.0.1
motion:
specifier: 12.38.0
version: 12.38.0
negotiator:
specifier: 1.0.0
version: 1.0.0
@@ -627,6 +618,9 @@ importers:
taze:
specifier: 'catalog:'
version: 19.10.0
vite-plus:
specifier: 'catalog:'
version: 0.1.14(@types/node@25.5.0)(esbuild@0.27.2)(happy-dom@20.8.9)(jiti@2.6.1)(sass@1.98.0)(terser@5.46.1)(tsx@4.21.0)(typescript@5.9.3)(vite@8.0.3(@emnapi/core@1.9.1)(@emnapi/runtime@1.9.1)(@types/node@25.5.0)(esbuild@0.27.2)(jiti@2.6.1)(sass@1.98.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.8.3))(yaml@2.8.3)
e2e:
devDependencies:
@@ -873,9 +867,6 @@ importers:
mitt:
specifier: 'catalog:'
version: 3.0.1
motion:
specifier: 'catalog:'
version: 12.38.0(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
negotiator:
specifier: 'catalog:'
version: 1.0.0
@@ -1171,18 +1162,12 @@ importers:
hono:
specifier: 'catalog:'
version: 4.12.9
husky:
specifier: 'catalog:'
version: 9.1.7
iconify-import-svg:
specifier: 'catalog:'
version: 0.1.2
knip:
specifier: 'catalog:'
version: 6.1.0(@emnapi/core@1.9.1)(@emnapi/runtime@1.9.1)
lint-staged:
specifier: 'catalog:'
version: 16.4.0
postcss:
specifier: 'catalog:'
version: 8.5.8
@@ -4757,10 +4742,6 @@ packages:
ajv@8.18.0:
resolution: {integrity: sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==}
ansi-escapes@7.3.0:
resolution: {integrity: sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==}
engines: {node: '>=18'}
ansi-regex@4.1.1:
resolution: {integrity: sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==}
engines: {node: '>=6'}
@@ -4781,10 +4762,6 @@ packages:
resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
engines: {node: '>=10'}
ansi-styles@6.2.3:
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'}
ansis@4.2.0:
resolution: {integrity: sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig==}
engines: {node: '>=14'}
@@ -5072,18 +5049,10 @@ packages:
resolution: {integrity: sha512-GfisEZEJvzKrmGWkvfhgzcz/BllN1USeqD2V6tg14OAOgaCD2Z/PUEuxnAZ/nPvmaHRG7a8y77p1T/IRQ4D1Hw==}
engines: {node: '>=4'}
cli-cursor@5.0.0:
resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==}
engines: {node: '>=18'}
cli-table3@0.6.5:
resolution: {integrity: sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==}
engines: {node: 10.* || >= 12.*}
cli-truncate@5.2.0:
resolution: {integrity: sha512-xRwvIOMGrfOAnM1JYtqQImuaNtDEv9v6oIYAs4LIHwTiKee8uwvIi363igssOC0O5U04i4AlENs79LQLu9tEMw==}
engines: {node: '>=20'}
client-only@0.0.1:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
@@ -5110,9 +5079,6 @@ packages:
color-name@1.1.4:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
colorette@2.0.20:
resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==}
comma-separated-tokens@1.0.8:
resolution: {integrity: sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==}
@@ -5578,10 +5544,6 @@ packages:
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
engines: {node: '>=0.12'}
environment@1.1.0:
resolution: {integrity: sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==}
engines: {node: '>=18'}
error-stack-parser-es@1.0.5:
resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==}
@@ -5971,9 +5933,6 @@ packages:
event-target-bus@1.0.0:
resolution: {integrity: sha512-uPcWKbj/BJU3Tbw9XqhHqET4/LBOhvv3/SJWr7NksxA6TC5YqBpaZgawE9R+WpYFCBFSAE4Vun+xQS6w4ABdlA==}
eventemitter3@5.0.4:
resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
events@3.3.0:
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
@@ -6097,20 +6056,6 @@ packages:
fraction.js@5.3.4:
resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==}
framer-motion@12.38.0:
resolution: {integrity: sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g==}
peerDependencies:
'@emotion/is-prop-valid': '*'
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@emotion/is-prop-valid':
optional: true
react:
optional: true
react-dom:
optional: true
fs-constants@1.0.0:
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
@@ -6309,11 +6254,6 @@ packages:
htmlparser2@10.1.0:
resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
husky@9.1.7:
resolution: {integrity: sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==}
engines: {node: '>=18'}
hasBin: true
i18next-resources-to-backend@1.2.1:
resolution: {integrity: sha512-okHbVA+HZ7n1/76MsfhPqDou0fptl2dAlhRDu2ideXloRRduzHsqDOznJBef+R3DFZnbvWoBW+KxJ7fnFjd6Yw==}
@@ -6439,10 +6379,6 @@ packages:
resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
engines: {node: '>=0.10.0'}
is-fullwidth-code-point@5.1.0:
resolution: {integrity: sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==}
engines: {node: '>=18'}
is-glob@4.0.3:
resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
engines: {node: '>=0.10.0'}
@@ -6750,15 +6686,6 @@ packages:
lines-and-columns@1.2.4:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
lint-staged@16.4.0:
resolution: {integrity: sha512-lBWt8hujh/Cjysw5GYVmZpFHXDCgZzhrOm8vbcUdobADZNOK/bRshr2kM3DfgrrtR1DQhfupW9gnIXOfiFi+bw==}
engines: {node: '>=20.17'}
hasBin: true
listr2@9.0.5:
resolution: {integrity: sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==}
engines: {node: '>=20.0.0'}
load-tsconfig@0.2.5:
resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
@@ -6790,10 +6717,6 @@ packages:
lodash@4.17.23:
resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==}
log-update@6.1.0:
resolution: {integrity: sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==}
engines: {node: '>=18'}
longest-streak@3.1.0:
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
@@ -7131,26 +7054,6 @@ packages:
moo-color@1.0.3:
resolution: {integrity: sha512-i/+ZKXMDf6aqYtBhuOcej71YSlbjT3wCO/4H1j8rPvxDJEifdwgg5MaFyu6iYAT8GBZJg2z0dkgK4YMzvURALQ==}
motion-dom@12.38.0:
resolution: {integrity: sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA==}
motion-utils@12.36.0:
resolution: {integrity: sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg==}
motion@12.38.0:
resolution: {integrity: sha512-uYfXzeHlgThchzwz5Te47dlv5JOUC7OB4rjJ/7XTUgtBZD8CchMN8qEJ4ZVsUmTyYA44zjV0fBwsiktRuFnn+w==}
peerDependencies:
'@emotion/is-prop-valid': '*'
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@emotion/is-prop-valid':
optional: true
react:
optional: true
react-dom:
optional: true
mrmime@2.0.1:
resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}
engines: {node: '>=10'}
@@ -7960,9 +7863,6 @@ packages:
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
rfdc@1.4.1:
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
robust-predicates@3.0.3:
resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==}
@@ -8083,14 +7983,6 @@ packages:
size-sensor@1.0.3:
resolution: {integrity: sha512-+k9mJ2/rQMiRmQUcjn+qznch260leIXY8r4FyYKKyRBO/s5UoeMAHGkCJyE1R/4wrIhTJONfyloY55SkE7ve3A==}
slice-ansi@7.1.2:
resolution: {integrity: sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==}
engines: {node: '>=18'}
slice-ansi@8.0.0:
resolution: {integrity: sha512-stxByr12oeeOyY2BlviTNQlYV5xOj47GirPr4yA1hE9JCtxfQN0+tVbkxwCtYDQWhEKWFHsEK48ORg5jrouCAg==}
engines: {node: '>=20'}
smol-toml@1.6.1:
resolution: {integrity: sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==}
engines: {node: '>= 18'}
@@ -8174,10 +8066,6 @@ packages:
resolution: {integrity: sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg==}
engines: {node: '>=0.6.19'}
string-argv@0.3.2:
resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
engines: {node: '>=0.6.19'}
string-ts@2.3.1:
resolution: {integrity: sha512-xSJq+BS52SaFFAVxuStmx6n5aYZU571uYUnUrPXkPFCfdHyZMMlbP2v2Wx5sNBnAVzq/2+0+mcBLBa3Xa5ubYw==}
@@ -8914,10 +8802,6 @@ packages:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
wrap-ansi@9.0.2:
resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}
engines: {node: '>=18'}
wrappy@1.0.2:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
@@ -12698,10 +12582,6 @@ snapshots:
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
ansi-escapes@7.3.0:
dependencies:
environment: 1.1.0
ansi-regex@4.1.1: {}
ansi-regex@5.0.1: {}
@@ -12714,8 +12594,6 @@ snapshots:
ansi-styles@5.2.0: {}
ansi-styles@6.2.3: {}
ansis@4.2.0: {}
any-promise@1.3.0: {}
@@ -12987,21 +12865,12 @@ snapshots:
dependencies:
escape-string-regexp: 1.0.5
cli-cursor@5.0.0:
dependencies:
restore-cursor: 5.1.0
cli-table3@0.6.5:
dependencies:
string-width: 8.2.0
optionalDependencies:
'@colors/colors': 1.5.0
cli-truncate@5.2.0:
dependencies:
slice-ansi: 8.0.0
string-width: 8.2.0
client-only@0.0.1: {}
clsx@2.1.1: {}
@@ -13038,8 +12907,6 @@ snapshots:
color-name@1.1.4: {}
colorette@2.0.20: {}
comma-separated-tokens@1.0.8: {}
comma-separated-tokens@2.0.3: {}
@@ -13483,8 +13350,6 @@ snapshots:
entities@7.0.1: {}
environment@1.1.0: {}
error-stack-parser-es@1.0.5: {}
error-stack-parser@2.1.4:
@@ -14146,8 +14011,6 @@ snapshots:
event-target-bus@1.0.0: {}
eventemitter3@5.0.4: {}
events@3.3.0: {}
expand-template@2.0.3:
@@ -14266,15 +14129,6 @@ snapshots:
fraction.js@5.3.4: {}
framer-motion@12.38.0(react-dom@19.2.4(react@19.2.4))(react@19.2.4):
dependencies:
motion-dom: 12.38.0
motion-utils: 12.36.0
tslib: 2.8.1
optionalDependencies:
react: 19.2.4
react-dom: 19.2.4(react@19.2.4)
fs-constants@1.0.0:
optional: true
@@ -14545,8 +14399,6 @@ snapshots:
domutils: 3.2.2
entities: 7.0.1
husky@9.1.7: {}
i18next-resources-to-backend@1.2.1:
dependencies:
'@babel/runtime': 7.29.2
@@ -14645,10 +14497,6 @@ snapshots:
is-extglob@2.1.1: {}
is-fullwidth-code-point@5.1.0:
dependencies:
get-east-asian-width: 1.5.0
is-glob@4.0.3:
dependencies:
is-extglob: 2.1.1
@@ -14902,24 +14750,6 @@ snapshots:
lines-and-columns@1.2.4: {}
lint-staged@16.4.0:
dependencies:
commander: 14.0.3
listr2: 9.0.5
picomatch: 4.0.4
string-argv: 0.3.2
tinyexec: 1.0.4
yaml: 2.8.3
listr2@9.0.5:
dependencies:
cli-truncate: 5.2.0
colorette: 2.0.20
eventemitter3: 5.0.4
log-update: 6.1.0
rfdc: 1.4.1
wrap-ansi: 9.0.2
load-tsconfig@0.2.5: {}
loader-runner@4.3.1: {}
@@ -14944,14 +14774,6 @@ snapshots:
lodash@4.17.23: {}
log-update@6.1.0:
dependencies:
ansi-escapes: 7.3.0
cli-cursor: 5.0.0
slice-ansi: 7.1.2
strip-ansi: 7.2.0
wrap-ansi: 9.0.2
longest-streak@3.1.0: {}
loose-envify@1.4.0:
@@ -15600,20 +15422,6 @@ snapshots:
dependencies:
color-name: 1.1.4
motion-dom@12.38.0:
dependencies:
motion-utils: 12.36.0
motion-utils@12.36.0: {}
motion@12.38.0(react-dom@19.2.4(react@19.2.4))(react@19.2.4):
dependencies:
framer-motion: 12.38.0(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
tslib: 2.8.1
optionalDependencies:
react: 19.2.4
react-dom: 19.2.4(react@19.2.4)
mrmime@2.0.1: {}
ms@2.1.3: {}
@@ -16602,8 +16410,6 @@ snapshots:
reusify@1.1.0: {}
rfdc@1.4.1: {}
robust-predicates@3.0.3: {}
rolldown@1.0.0-rc.12(@emnapi/core@1.9.1)(@emnapi/runtime@1.9.1):
@@ -16797,16 +16603,6 @@ snapshots:
size-sensor@1.0.3: {}
slice-ansi@7.1.2:
dependencies:
ansi-styles: 6.2.3
is-fullwidth-code-point: 5.1.0
slice-ansi@8.0.0:
dependencies:
ansi-styles: 6.2.3
is-fullwidth-code-point: 5.1.0
smol-toml@1.6.1: {}
solid-js@1.9.11:
@@ -16907,8 +16703,6 @@ snapshots:
string-argv@0.3.1: {}
string-argv@0.3.2: {}
string-ts@2.3.1: {}
string-width@8.2.0:
@@ -17753,12 +17547,6 @@ snapshots:
word-wrap@1.2.5: {}
wrap-ansi@9.0.2:
dependencies:
ansi-styles: 6.2.3
string-width: 8.2.0
strip-ansi: 7.2.0
wrappy@1.0.2: {}
ws@8.20.0: {}
+1 -4
View File
@@ -3,7 +3,7 @@ minimumReleaseAge: 1440
blockExoticSubdeps: true
strictDepBuilds: true
allowBuilds:
"@parcel/watcher": false
'@parcel/watcher': false
canvas: false
esbuild: false
sharp: false
@@ -183,7 +183,6 @@ catalog:
hono: 4.12.9
html-entities: 2.6.0
html-to-image: 1.11.13
husky: 9.1.7
i18next: 25.10.10
i18next-resources-to-backend: 1.2.1
iconify-import-svg: 0.1.2
@@ -198,11 +197,9 @@ catalog:
ky: 1.14.3
lamejs: 1.2.1
lexical: 0.42.0
lint-staged: 16.4.0
mermaid: 11.13.0
mime: 4.1.0
mitt: 3.0.1
motion: 12.38.0
negotiator: 1.0.0
next: 16.2.1
next-themes: 0.4.6
+5
View File
@@ -0,0 +1,5 @@
import { defineConfig } from 'vite-plus'
export default defineConfig({
staged: {},
})
+1 -1
View File
@@ -31,7 +31,7 @@ RUN corepack install
# Install only the web workspace to keep image builds from pulling in
# unrelated workspace dependencies such as e2e tooling.
RUN pnpm install --filter ./web... --frozen-lockfile
RUN VITE_GIT_HOOKS=0 pnpm install --filter ./web... --frozen-lockfile
# build resources
FROM base AS builder
-1
View File
@@ -22,7 +22,6 @@ web/node_modules
web/dist
web/build
web/coverage
web/.husky
web/.next
web/.pnpm-store
web/.vscode
@@ -75,10 +75,11 @@ vi.mock('@/app/components/plugins/card/base/description', () => ({
}))
vi.mock('@/app/components/plugins/card/base/org-info', () => ({
default: ({ orgName, downloadCount }: { orgName: string, downloadCount?: number }) => (
default: ({ orgName, packageName }: { orgName: string, packageName: string }) => (
<div data-testid="org-info">
{orgName}
{typeof downloadCount === 'number' ? ` · ${downloadCount}` : null}
/
{packageName}
</div>
),
}))
@@ -123,7 +124,7 @@ describe('Plugin Card Rendering Integration', () => {
expect(screen.getByTestId('card-icon')).toBeInTheDocument()
expect(screen.getByTestId('title')).toHaveTextContent('Google Search')
expect(screen.getByTestId('org-info')).toHaveTextContent('langgenius')
expect(screen.getByTestId('org-info')).toHaveTextContent('langgenius/google-search')
expect(screen.getByTestId('description')).toHaveTextContent('Search the web using Google')
})
+1 -1
View File
@@ -6,7 +6,7 @@ const PluginList = () => {
return (
<PluginPage
plugins={<PluginsPanel />}
marketplace={<Marketplace />}
marketplace={<Marketplace pluginTypeSwitchClassName="top-[60px]" />}
/>
)
}
+4 -10
View File
@@ -14,7 +14,6 @@ type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: 'horizontal' | 'vertical'
overlay?: React.ReactNode
}
type CarouselContextValue = {
@@ -50,7 +49,7 @@ type TCarousel = {
>
const Carousel: TCarousel = React.forwardRef(
({ orientation = 'horizontal', opts, plugins, overlay, className, children, ...props }, ref) => {
({ orientation = 'horizontal', opts, plugins, className, children, ...props }, ref) => {
const [carouselRef, api] = useEmblaCarousel(
{ ...opts, axis: orientation === 'horizontal' ? 'x' : 'y' },
plugins,
@@ -116,19 +115,14 @@ const Carousel: TCarousel = React.forwardRef(
}}
>
<div
ref={carouselRef}
// onKeyDownCapture={handleKeyDown}
className={cn('relative', className)}
className={cn('relative overflow-hidden', className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{overlay}
<div
ref={carouselRef}
className="overflow-hidden [border-radius:inherit]"
>
{children}
</div>
{children}
</div>
</CarouselContext.Provider>
)
@@ -1,24 +0,0 @@
<svg width="588" height="588" viewBox="0 0 588 588" fill="none" xmlns="http://www.w3.org/2000/svg">
<g opacity="0.2" clip-path="url(#clip0_20862_53031)">
<g filter="url(#filter0_d_20862_53031)">
<path d="M204.231 152.332L201.643 142.673C194.496 115.999 210.326 88.5823 236.999 81.4353C263.672 74.2882 291.089 90.1173 298.236 116.791L300.824 126.45L407.076 97.9798C417.745 95.1209 428.712 101.453 431.571 112.122L452.276 189.396C453.706 194.731 450.539 200.214 445.205 201.643C418.532 208.79 402.703 236.208 409.85 262.881C416.997 289.554 444.414 305.383 471.087 298.236C476.421 296.807 481.905 299.973 483.335 305.307L504.04 382.581C506.899 393.251 500.568 404.217 489.898 407.076L180.802 489.898C170.132 492.757 159.166 486.426 156.307 475.756L83.8375 205.297C80.9787 194.628 87.3104 183.661 97.9796 180.802L204.231 152.332Z" fill="#F2F4F7"/>
<path d="M237.257 82.4012C263.397 75.3971 290.266 90.9096 297.27 117.049L300.117 127.675L407.335 98.9457C417.471 96.2297 427.889 102.245 430.605 112.381L451.31 189.655C452.597 194.456 449.747 199.391 444.946 200.677C417.74 207.967 401.594 235.933 408.884 263.139C416.174 290.346 444.139 306.492 471.346 299.202C476.146 297.916 481.082 300.766 482.369 305.566L503.074 382.84C505.79 392.976 499.775 403.394 489.639 406.11L180.543 488.932C170.407 491.648 159.989 485.633 157.273 475.497L84.8034 205.038C82.0875 194.902 88.1027 184.484 98.2384 181.768L205.456 153.039L202.609 142.414C195.605 116.274 211.118 89.4053 237.257 82.4012Z" stroke="white" stroke-width="2"/>
</g>
</g>
<defs>
<filter id="filter0_d_20862_53031" x="31.151" y="59.719" width="525.576" height="514.866" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feMorphology radius="12" operator="erode" in="SourceAlpha" result="effect1_dropShadow_20862_53031"/>
<feOffset dy="32"/>
<feGaussianBlur stdDeviation="32"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0.0352941 0 0 0 0 0.0352941 0 0 0 0 0.0431373 0 0 0 0.14 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_20862_53031"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_20862_53031" result="shape"/>
</filter>
<clipPath id="clip0_20862_53031">
<rect width="480" height="480" fill="white" transform="translate(0 124.233) rotate(-15)"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

@@ -1,26 +0,0 @@
<svg width="588" height="588" viewBox="0 0 588 588" fill="none" xmlns="http://www.w3.org/2000/svg">
<g opacity="0.2" clip-path="url(#clip0_21509_19682)">
<g filter="url(#filter0_d_21509_19682)">
<path d="M346.36 300.589C389.034 289.159 432.902 314.489 444.34 357.157C455.774 399.831 430.445 443.698 387.771 455.137C345.095 466.572 301.227 441.245 289.792 398.568C278.362 355.895 303.687 312.023 346.36 300.589Z" fill="#F2F4F7"/>
<path d="M116.295 221.279C122.148 217.181 129.755 216.517 136.23 219.537L261.798 278.096C268.274 281.114 272.666 287.369 273.288 294.489C273.908 301.604 270.669 308.514 264.818 312.611L151.323 392.076C145.47 396.175 137.869 396.858 131.393 393.838C124.917 390.819 120.544 384.556 119.922 377.439L107.85 239.415C107.227 232.299 110.444 225.378 116.295 221.279Z" fill="#F2F4F7"/>
<path d="M283.278 160.623C283.279 127.486 310.148 100.606 343.285 100.606L383.281 100.606C416.416 100.607 443.279 127.482 443.279 160.618L443.279 200.613C443.28 233.747 416.42 260.604 383.286 260.607L343.272 260.612C310.138 260.609 283.28 233.752 283.278 200.619L283.278 160.623Z" fill="#F2F4F7"/>
<path d="M346.619 301.555C388.759 290.268 432.079 315.281 443.374 357.416C454.666 399.557 429.653 442.875 387.513 454.171C345.37 465.464 302.05 440.453 290.758 398.31C279.471 356.169 304.479 312.846 346.619 301.555ZM116.869 222.099C122.429 218.205 129.656 217.574 135.808 220.443L261.376 279.002C267.529 281.87 271.701 287.814 272.291 294.576C272.88 301.333 269.804 307.898 264.245 311.791L150.75 391.257C145.361 395.03 138.416 395.757 132.395 393.19L131.815 392.931C125.665 390.064 121.51 384.115 120.918 377.353L108.846 239.329C108.254 232.567 111.311 225.992 116.869 222.099ZM284.278 160.623C284.28 128.038 310.701 101.606 343.285 101.606L383.281 101.606C415.864 101.608 442.279 128.034 442.28 160.618L442.28 200.614C442.28 233.195 415.868 259.604 383.286 259.607L343.272 259.612C310.691 259.61 284.281 233.2 284.278 200.619L284.278 160.623Z" stroke="white" stroke-width="2"/>
</g>
</g>
<defs>
<filter id="filter0_d_21509_19682" x="55.7732" y="80.6057" width="443.312" height="461.277" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feMorphology radius="12" operator="erode" in="SourceAlpha" result="effect1_dropShadow_21509_19682"/>
<feOffset dy="32"/>
<feGaussianBlur stdDeviation="32"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0.0352941 0 0 0 0 0.0352941 0 0 0 0 0.0431373 0 0 0 0.14 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_21509_19682"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_21509_19682" result="shape"/>
</filter>
<clipPath id="clip0_21509_19682">
<rect width="480" height="480" fill="white" transform="translate(0 124.233) rotate(-15)"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 2.9 KiB

@@ -1,5 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11.6301 11.3333C11.6301 12.4379 10.7347 13.3333 9.63013 13.3333C8.52559 13.3333 7.63013 12.4379 7.63013 11.3333C7.63013 10.2287 8.52559 9.33325 9.63013 9.33325C10.7347 9.33325 11.6301 10.2287 11.6301 11.3333Z" stroke="white" stroke-width="1.5" stroke-linejoin="round"/>
<path d="M3.1353 4.75464L6.67352 7.72353L2.33325 9.30327L3.1353 4.75464Z" stroke="white" stroke-width="1.5" stroke-linejoin="round"/>
<path d="M9.79576 2.5L13.6595 3.53527L12.6242 7.399L8.7605 6.36371L9.79576 2.5Z" stroke="white" stroke-width="1.5" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 658 B

@@ -1,5 +0,0 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.5 6.66675H17.5V15.8334H2.5V6.66675Z" stroke="#354052" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.16675 6.66659V3.33325H8.33341V6.66659" stroke="#354052" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M11.6667 6.66659V3.33325H15.8334V6.66659" stroke="#354052" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 509 B

@@ -1,183 +0,0 @@
{
"icon": {
"type": "element",
"isRootNode": true,
"name": "svg",
"attributes": {
"width": "588",
"height": "588",
"viewBox": "0 0 588 588",
"fill": "none",
"xmlns": "http://www.w3.org/2000/svg"
},
"children": [
{
"type": "element",
"name": "g",
"attributes": {
"opacity": "0.2",
"clip-path": "url(#clip0_20862_53031)"
},
"children": [
{
"type": "element",
"name": "g",
"attributes": {
"filter": "url(#filter0_d_20862_53031)"
},
"children": [
{
"type": "element",
"name": "path",
"attributes": {
"d": "M204.231 152.332L201.643 142.673C194.496 115.999 210.326 88.5823 236.999 81.4353C263.672 74.2882 291.089 90.1173 298.236 116.791L300.824 126.45L407.076 97.9798C417.745 95.1209 428.712 101.453 431.571 112.122L452.276 189.396C453.706 194.731 450.539 200.214 445.205 201.643C418.532 208.79 402.703 236.208 409.85 262.881C416.997 289.554 444.414 305.383 471.087 298.236C476.421 296.807 481.905 299.973 483.335 305.307L504.04 382.581C506.899 393.251 500.568 404.217 489.898 407.076L180.802 489.898C170.132 492.757 159.166 486.426 156.307 475.756L83.8375 205.297C80.9787 194.628 87.3104 183.661 97.9796 180.802L204.231 152.332Z",
"fill": "#F2F4F7"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M237.257 82.4012C263.397 75.3971 290.266 90.9096 297.27 117.049L300.117 127.675L407.335 98.9457C417.471 96.2297 427.889 102.245 430.605 112.381L451.31 189.655C452.597 194.456 449.747 199.391 444.946 200.677C417.74 207.967 401.594 235.933 408.884 263.139C416.174 290.346 444.139 306.492 471.346 299.202C476.146 297.916 481.082 300.766 482.369 305.566L503.074 382.84C505.79 392.976 499.775 403.394 489.639 406.11L180.543 488.932C170.407 491.648 159.989 485.633 157.273 475.497L84.8034 205.038C82.0875 194.902 88.1027 184.484 98.2384 181.768L205.456 153.039L202.609 142.414C195.605 116.274 211.118 89.4053 237.257 82.4012Z",
"stroke": "white",
"stroke-width": "2"
},
"children": []
}
]
}
]
},
{
"type": "element",
"name": "defs",
"attributes": {},
"children": [
{
"type": "element",
"name": "filter",
"attributes": {
"id": "filter0_d_20862_53031",
"x": "31.151",
"y": "59.719",
"width": "525.576",
"height": "514.866",
"filterUnits": "userSpaceOnUse",
"color-interpolation-filters": "sRGB"
},
"children": [
{
"type": "element",
"name": "feFlood",
"attributes": {
"flood-opacity": "0",
"result": "BackgroundImageFix"
},
"children": []
},
{
"type": "element",
"name": "feColorMatrix",
"attributes": {
"in": "SourceAlpha",
"type": "matrix",
"values": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0",
"result": "hardAlpha"
},
"children": []
},
{
"type": "element",
"name": "feMorphology",
"attributes": {
"radius": "12",
"operator": "erode",
"in": "SourceAlpha",
"result": "effect1_dropShadow_20862_53031"
},
"children": []
},
{
"type": "element",
"name": "feOffset",
"attributes": {
"dy": "32"
},
"children": []
},
{
"type": "element",
"name": "feGaussianBlur",
"attributes": {
"stdDeviation": "32"
},
"children": []
},
{
"type": "element",
"name": "feComposite",
"attributes": {
"in2": "hardAlpha",
"operator": "out"
},
"children": []
},
{
"type": "element",
"name": "feColorMatrix",
"attributes": {
"type": "matrix",
"values": "0 0 0 0 0.0352941 0 0 0 0 0.0352941 0 0 0 0 0.0431373 0 0 0 0.14 0"
},
"children": []
},
{
"type": "element",
"name": "feBlend",
"attributes": {
"mode": "normal",
"in2": "BackgroundImageFix",
"result": "effect1_dropShadow_20862_53031"
},
"children": []
},
{
"type": "element",
"name": "feBlend",
"attributes": {
"mode": "normal",
"in": "SourceGraphic",
"in2": "effect1_dropShadow_20862_53031",
"result": "shape"
},
"children": []
}
]
},
{
"type": "element",
"name": "clipPath",
"attributes": {
"id": "clip0_20862_53031"
},
"children": [
{
"type": "element",
"name": "rect",
"attributes": {
"width": "480",
"height": "480",
"fill": "white",
"transform": "translate(0 124.233) rotate(-15)"
},
"children": []
}
]
}
]
}
]
},
"name": "PluginHeaderBg"
}
@@ -1,20 +0,0 @@
// GENERATE BY script
// DON NOT EDIT IT MANUALLY
import type { IconData } from '@/app/components/base/icons/IconBase'
import * as React from 'react'
import IconBase from '@/app/components/base/icons/IconBase'
import data from './PluginHeaderBg.json'
const Icon = (
{
ref,
...props
}: React.SVGProps<SVGSVGElement> & {
ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>
},
) => <IconBase {...props} ref={ref} data={data as IconData} />
Icon.displayName = 'PluginHeaderBg'
export default Icon
@@ -1,201 +0,0 @@
{
"icon": {
"type": "element",
"isRootNode": true,
"name": "svg",
"attributes": {
"width": "588",
"height": "588",
"viewBox": "0 0 588 588",
"fill": "none",
"xmlns": "http://www.w3.org/2000/svg"
},
"children": [
{
"type": "element",
"name": "g",
"attributes": {
"opacity": "0.2",
"clip-path": "url(#clip0_21509_19682)"
},
"children": [
{
"type": "element",
"name": "g",
"attributes": {
"filter": "url(#filter0_d_21509_19682)"
},
"children": [
{
"type": "element",
"name": "path",
"attributes": {
"d": "M346.36 300.589C389.034 289.159 432.902 314.489 444.34 357.157C455.774 399.831 430.445 443.698 387.771 455.137C345.095 466.572 301.227 441.245 289.792 398.568C278.362 355.895 303.687 312.023 346.36 300.589Z",
"fill": "#F2F4F7"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M116.295 221.279C122.148 217.181 129.755 216.517 136.23 219.537L261.798 278.096C268.274 281.114 272.666 287.369 273.288 294.489C273.908 301.604 270.669 308.514 264.818 312.611L151.323 392.076C145.47 396.175 137.869 396.858 131.393 393.838C124.917 390.819 120.544 384.556 119.922 377.439L107.85 239.415C107.227 232.299 110.444 225.378 116.295 221.279Z",
"fill": "#F2F4F7"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M283.278 160.623C283.279 127.486 310.148 100.606 343.285 100.606L383.281 100.606C416.416 100.607 443.279 127.482 443.279 160.618L443.279 200.613C443.28 233.747 416.42 260.604 383.286 260.607L343.272 260.612C310.138 260.609 283.28 233.752 283.278 200.619L283.278 160.623Z",
"fill": "#F2F4F7"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M346.619 301.555C388.759 290.268 432.079 315.281 443.374 357.416C454.666 399.557 429.653 442.875 387.513 454.171C345.37 465.464 302.05 440.453 290.758 398.31C279.471 356.169 304.479 312.846 346.619 301.555ZM116.869 222.099C122.429 218.205 129.656 217.574 135.808 220.443L261.376 279.002C267.529 281.87 271.701 287.814 272.291 294.576C272.88 301.333 269.804 307.898 264.245 311.791L150.75 391.257C145.361 395.03 138.416 395.757 132.395 393.19L131.815 392.931C125.665 390.064 121.51 384.115 120.918 377.353L108.846 239.329C108.254 232.567 111.311 225.992 116.869 222.099ZM284.278 160.623C284.28 128.038 310.701 101.606 343.285 101.606L383.281 101.606C415.864 101.608 442.279 128.034 442.28 160.618L442.28 200.614C442.28 233.195 415.868 259.604 383.286 259.607L343.272 259.612C310.691 259.61 284.281 233.2 284.278 200.619L284.278 160.623Z",
"stroke": "white",
"stroke-width": "2"
},
"children": []
}
]
}
]
},
{
"type": "element",
"name": "defs",
"attributes": {},
"children": [
{
"type": "element",
"name": "filter",
"attributes": {
"id": "filter0_d_21509_19682",
"x": "55.7732",
"y": "80.6057",
"width": "443.312",
"height": "461.277",
"filterUnits": "userSpaceOnUse",
"color-interpolation-filters": "sRGB"
},
"children": [
{
"type": "element",
"name": "feFlood",
"attributes": {
"flood-opacity": "0",
"result": "BackgroundImageFix"
},
"children": []
},
{
"type": "element",
"name": "feColorMatrix",
"attributes": {
"in": "SourceAlpha",
"type": "matrix",
"values": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0",
"result": "hardAlpha"
},
"children": []
},
{
"type": "element",
"name": "feMorphology",
"attributes": {
"radius": "12",
"operator": "erode",
"in": "SourceAlpha",
"result": "effect1_dropShadow_21509_19682"
},
"children": []
},
{
"type": "element",
"name": "feOffset",
"attributes": {
"dy": "32"
},
"children": []
},
{
"type": "element",
"name": "feGaussianBlur",
"attributes": {
"stdDeviation": "32"
},
"children": []
},
{
"type": "element",
"name": "feComposite",
"attributes": {
"in2": "hardAlpha",
"operator": "out"
},
"children": []
},
{
"type": "element",
"name": "feColorMatrix",
"attributes": {
"type": "matrix",
"values": "0 0 0 0 0.0352941 0 0 0 0 0.0352941 0 0 0 0 0.0431373 0 0 0 0.14 0"
},
"children": []
},
{
"type": "element",
"name": "feBlend",
"attributes": {
"mode": "normal",
"in2": "BackgroundImageFix",
"result": "effect1_dropShadow_21509_19682"
},
"children": []
},
{
"type": "element",
"name": "feBlend",
"attributes": {
"mode": "normal",
"in": "SourceGraphic",
"in2": "effect1_dropShadow_21509_19682",
"result": "shape"
},
"children": []
}
]
},
{
"type": "element",
"name": "clipPath",
"attributes": {
"id": "clip0_21509_19682"
},
"children": [
{
"type": "element",
"name": "rect",
"attributes": {
"width": "480",
"height": "480",
"fill": "white",
"transform": "translate(0 124.233) rotate(-15)"
},
"children": []
}
]
}
]
}
]
},
"name": "TemplateHeaderBg"
}
@@ -1,20 +0,0 @@
// GENERATE BY script
// DON NOT EDIT IT MANUALLY
import type { IconData } from '@/app/components/base/icons/IconBase'
import * as React from 'react'
import IconBase from '@/app/components/base/icons/IconBase'
import data from './TemplateHeaderBg.json'
const Icon = (
{
ref,
...props
}: React.SVGProps<SVGSVGElement> & {
ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>
},
) => <IconBase {...props} ref={ref} data={data as IconData} />
Icon.displayName = 'TemplateHeaderBg'
export default Icon
@@ -1,8 +1,6 @@
export { default as Google } from './Google'
export { default as PartnerDark } from './PartnerDark'
export { default as PartnerLight } from './PartnerLight'
export { default as PluginHeaderBg } from './PluginHeaderBg'
export { default as TemplateHeaderBg } from './TemplateHeaderBg'
export { default as VerifiedDark } from './VerifiedDark'
export { default as VerifiedLight } from './VerifiedLight'
export { default as WebReader } from './WebReader'
@@ -1,50 +0,0 @@
{
"icon": {
"type": "element",
"isRootNode": true,
"name": "svg",
"attributes": {
"width": "16",
"height": "16",
"viewBox": "0 0 16 16",
"fill": "none",
"xmlns": "http://www.w3.org/2000/svg"
},
"children": [
{
"type": "element",
"name": "path",
"attributes": {
"d": "M11.6301 11.3333C11.6301 12.4379 10.7347 13.3333 9.63013 13.3333C8.52559 13.3333 7.63013 12.4379 7.63013 11.3333C7.63013 10.2287 8.52559 9.33325 9.63013 9.33325C10.7347 9.33325 11.6301 10.2287 11.6301 11.3333Z",
"stroke": "currentColor",
"stroke-width": "1.5",
"stroke-linejoin": "round"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M3.1353 4.75464L6.67352 7.72353L2.33325 9.30327L3.1353 4.75464Z",
"stroke": "currentColor",
"stroke-width": "1.5",
"stroke-linejoin": "round"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M9.79576 2.5L13.6595 3.53527L12.6242 7.399L8.7605 6.36371L9.79576 2.5Z",
"stroke": "currentColor",
"stroke-width": "1.5",
"stroke-linejoin": "round"
},
"children": []
}
]
},
"name": "Playground"
}
@@ -1,20 +0,0 @@
// GENERATE BY script
// DON NOT EDIT IT MANUALLY
import type { IconData } from '@/app/components/base/icons/IconBase'
import * as React from 'react'
import IconBase from '@/app/components/base/icons/IconBase'
import data from './Playground.json'
const Icon = (
{
ref,
...props
}: React.SVGProps<SVGSVGElement> & {
ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>
},
) => <IconBase {...props} ref={ref} data={data as IconData} />
Icon.displayName = 'Playground'
export default Icon
@@ -1,53 +0,0 @@
{
"icon": {
"type": "element",
"isRootNode": true,
"name": "svg",
"attributes": {
"width": "20",
"height": "20",
"viewBox": "0 0 20 20",
"fill": "none",
"xmlns": "http://www.w3.org/2000/svg"
},
"children": [
{
"type": "element",
"name": "path",
"attributes": {
"d": "M2.5 6.66675H17.5V15.8334H2.5V6.66675Z",
"stroke": "currentColor",
"stroke-width": "1.5",
"stroke-linecap": "round",
"stroke-linejoin": "round"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M4.16675 6.66659V3.33325H8.33341V6.66659",
"stroke": "currentColor",
"stroke-width": "1.5",
"stroke-linecap": "round",
"stroke-linejoin": "round"
},
"children": []
},
{
"type": "element",
"name": "path",
"attributes": {
"d": "M11.6667 6.66659V3.33325H15.8334V6.66659",
"stroke": "currentColor",
"stroke-width": "1.5",
"stroke-linecap": "round",
"stroke-linejoin": "round"
},
"children": []
}
]
},
"name": "Plugin"
}
@@ -1,20 +0,0 @@
// GENERATE BY script
// DON NOT EDIT IT MANUALLY
import type { IconData } from '@/app/components/base/icons/IconBase'
import * as React from 'react'
import IconBase from '@/app/components/base/icons/IconBase'
import data from './Plugin.json'
const Icon = (
{
ref,
...props
}: React.SVGProps<SVGSVGElement> & {
ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>
},
) => <IconBase {...props} ref={ref} data={data as IconData} />
Icon.displayName = 'Plugin'
export default Icon
@@ -1,5 +1,3 @@
export { default as BoxSparkleFill } from './BoxSparkleFill'
export { default as LeftCorner } from './LeftCorner'
export { default as Playground } from './Playground'
export { default as Plugin } from './Plugin'
export { default as Trigger } from './Trigger'
@@ -11,7 +11,7 @@ const Icon = (
ref,
...props
}: React.SVGProps<SVGSVGElement> & {
ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>
ref?: React.RefObject<React.MutableRefObject<HTMLOrSVGElement>>
},
) => <IconBase {...props} ref={ref} data={data as IconData} />
@@ -41,13 +41,6 @@ export const preprocessThinkTag = (content: string) => {
])(content)
}
export const preprocessMarkdownContent = (content: string) => {
return flow([
preprocessThinkTag,
preprocessLaTeX,
])(content)
}
/**
* Transforms a URI for use in react-markdown, ensuring security and compatibility.
* This function is designed to work with react-markdown v9+ which has stricter
@@ -11,7 +11,7 @@ const PartnerStackCookieRecorder = () => {
if (!IS_CLOUD_EDITION)
return
saveOrUpdate()
}, [])
}, [saveOrUpdate])
return null
}
@@ -14,7 +14,7 @@ const PartnerStack: FC = () => {
saveOrUpdate()
// bind PartnerStack info after user logged in
bind()
}, [])
}, [saveOrUpdate, bind])
return null
}
@@ -64,8 +64,8 @@ const InstallFromMarketplace = ({
{
!isAllPluginsLoading && !collapse && (
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={allPlugins}
showInstallButton
cardContainerClassName="grid grid-cols-2 gap-2"
@@ -69,8 +69,8 @@ const InstallFromMarketplace = ({
{
!isAllPluginsLoading && !collapse && (
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={allPlugins}
showInstallButton
cardContainerClassName="grid grid-cols-2 gap-2"
@@ -0,0 +1,50 @@
import { render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import CardMoreInfo from '../card-more-info'
vi.mock('../base/download-count', () => ({
default: ({ downloadCount }: { downloadCount: number }) => (
<span data-testid="download-count">{downloadCount}</span>
),
}))
describe('CardMoreInfo', () => {
it('renders tags with # prefix', () => {
render(<CardMoreInfo tags={['search', 'agent']} />)
expect(screen.getByText('search')).toBeInTheDocument()
expect(screen.getByText('agent')).toBeInTheDocument()
// # prefixes
const hashmarks = screen.getAllByText('#')
expect(hashmarks).toHaveLength(2)
})
it('renders download count when provided', () => {
render(<CardMoreInfo downloadCount={1000} tags={[]} />)
expect(screen.getByTestId('download-count')).toHaveTextContent('1000')
})
it('does not render download count when undefined', () => {
render(<CardMoreInfo tags={['tag1']} />)
expect(screen.queryByTestId('download-count')).not.toBeInTheDocument()
})
it('renders separator between download count and tags', () => {
render(<CardMoreInfo downloadCount={500} tags={['test']} />)
expect(screen.getByText('·')).toBeInTheDocument()
})
it('does not render separator when no tags', () => {
render(<CardMoreInfo downloadCount={500} tags={[]} />)
expect(screen.queryByText('·')).not.toBeInTheDocument()
})
it('does not render separator when no download count', () => {
render(<CardMoreInfo tags={['tag1']} />)
expect(screen.queryByText('·')).not.toBeInTheDocument()
})
it('handles empty tags array', () => {
const { container } = render(<CardMoreInfo tags={[]} />)
expect(container.firstChild).toBeInTheDocument()
})
})
@@ -181,17 +181,7 @@ describe('Card', () => {
render(<Card payload={plugin} />)
expect(screen.getByText('my-org')).toBeInTheDocument()
expect(screen.queryByText('my-plugin')).not.toBeInTheDocument()
})
it('should render install count from the plugin payload', () => {
const plugin = createMockPlugin({
install_count: 1234,
})
render(<Card payload={plugin} />)
expect(screen.getByText(/1,234/)).toBeInTheDocument()
expect(screen.getByText('my-plugin')).toBeInTheDocument()
})
it('should render plugin icon', () => {
@@ -475,14 +465,6 @@ describe('Card', () => {
expect(screen.queryByTestId('partner-badge')).not.toBeInTheDocument()
})
it('should handle null badges from the marketplace API', () => {
const plugin = createMockPlugin({ badges: null })
render(<Card payload={plugin} />)
expect(screen.queryByTestId('partner-badge')).not.toBeInTheDocument()
})
})
// ================================
@@ -614,7 +596,7 @@ describe('Card', () => {
render(<Card payload={plugin} />)
expect(screen.getByText('org<script>alert(1)</script>')).toBeInTheDocument()
expect(screen.getByText('plugin-with-special-chars!@#$%')).toBeInTheDocument()
})
it('should handle very long title', () => {
@@ -2,12 +2,6 @@ import { render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import DownloadCount from '../download-count'
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: (key: string) => key === 'marketplace.installs' ? 'installs' : key,
}),
}))
vi.mock('@/utils/format', () => ({
formatNumber: (n: number) => {
if (n >= 1000)
@@ -19,16 +13,16 @@ vi.mock('@/utils/format', () => ({
describe('DownloadCount', () => {
it('renders formatted download count', () => {
render(<DownloadCount downloadCount={1500} />)
expect(screen.getByText('1.5k installs')).toBeInTheDocument()
expect(screen.getByText('1.5k')).toBeInTheDocument()
})
it('renders small numbers directly', () => {
render(<DownloadCount downloadCount={42} />)
expect(screen.getByText('42 installs')).toBeInTheDocument()
expect(screen.getByText('42')).toBeInTheDocument()
})
it('renders zero download count', () => {
render(<DownloadCount downloadCount={0} />)
expect(screen.getByText('0 installs')).toBeInTheDocument()
expect(screen.getByText('0')).toBeInTheDocument()
})
})
@@ -1,4 +1,4 @@
import { useTranslation } from '#i18n'
import { RiInstallLine } from '@remixicon/react'
import * as React from 'react'
import { formatNumber } from '@/utils/format'
@@ -9,13 +9,10 @@ type Props = {
const DownloadCountComponent = ({
downloadCount,
}: Props) => {
const { t } = useTranslation('plugin')
return (
<div className="system-xs-regular text-text-tertiary">
{formatNumber(downloadCount)}
{' '}
{t('marketplace.installs')}
<div className="flex items-center space-x-1 text-text-tertiary">
<RiInstallLine className="h-3 w-3 shrink-0" />
<div className="system-xs-regular">{formatNumber(downloadCount)}</div>
</div>
)
}
@@ -1,14 +1,10 @@
import Link from 'next/link'
import { cn } from '@/utils/classnames'
import DownloadCount from './download-count'
type Props = {
className?: string
orgName?: string
packageName?: string
packageName: string
packageNameClassName?: string
downloadCount?: number
linkToOrg?: boolean
}
const OrgInfo = ({
@@ -16,42 +12,7 @@ const OrgInfo = ({
orgName,
packageName,
packageNameClassName,
downloadCount,
linkToOrg = true,
}: Props) => {
// New format: "by {orgName} · {downloadCount} installs" (for marketplace cards)
if (downloadCount !== undefined) {
return (
<div className={cn('system-xs-regular flex h-4 items-center gap-2 text-text-tertiary', className)}>
{orgName && (
<span className="shrink-0">
<span className="mr-1 text-text-tertiary">by</span>
{linkToOrg
? (
<Link
href={`/creator/${orgName}`}
target="_blank"
rel="noopener noreferrer"
className="hover:text-text-secondary hover:underline"
onClick={e => e.stopPropagation()}
>
{orgName}
</Link>
)
: (
<span className="text-text-tertiary">
{orgName}
</span>
)}
</span>
)}
<span className="shrink-0">·</span>
<DownloadCount downloadCount={downloadCount} />
</div>
)
}
// Legacy format: "{orgName} / {packageName}" (for plugin detail panels)
return (
<div className={cn('flex h-4 items-center space-x-0.5', className)}>
{orgName && (
@@ -60,11 +21,9 @@ const OrgInfo = ({
<span className="system-xs-regular shrink-0 text-text-quaternary">/</span>
</>
)}
{packageName && (
<span className={cn('system-xs-regular w-0 shrink-0 grow truncate text-text-tertiary', packageNameClassName)}>
{packageName}
</span>
)}
<span className={cn('system-xs-regular w-0 shrink-0 grow truncate text-text-tertiary', packageNameClassName)}>
{packageName}
</span>
</div>
)
}
@@ -0,0 +1,40 @@
import * as React from 'react'
import DownloadCount from './base/download-count'
type Props = {
downloadCount?: number
tags: string[]
}
const CardMoreInfoComponent = ({
downloadCount,
tags,
}: Props) => {
return (
<div className="flex h-5 items-center">
{downloadCount !== undefined && <DownloadCount downloadCount={downloadCount} />}
{downloadCount !== undefined && tags && tags.length > 0 && <div className="system-xs-regular mx-2 text-text-quaternary">·</div>}
{tags && tags.length > 0 && (
<>
<div className="flex h-4 flex-wrap space-x-2 overflow-hidden">
{tags.map(tag => (
<div
key={tag}
className="system-xs-regular flex max-w-[120px] space-x-1 overflow-hidden"
title={`# ${tag}`}
>
<span className="text-text-quaternary">#</span>
<span className="truncate text-text-tertiary">{tag}</span>
</div>
))}
</div>
</>
)}
</div>
)
}
// Memoize to prevent unnecessary re-renders when tags array hasn't changed
const CardMoreInfo = React.memo(CardMoreInfoComponent)
export default CardMoreInfo
@@ -1,34 +0,0 @@
import { RiPriceTag3Line } from '@remixicon/react'
import * as React from 'react'
type Props = {
tags: string[]
}
const CardTagsComponent = ({
tags,
}: Props) => {
return (
<div className="mt-2 flex min-h-[20px] items-center gap-1">
{tags && tags.length > 0 && (
<div className="flex flex-wrap gap-1 overflow-hidden">
{tags.slice(0, 2).map(tag => (
<span
key={tag}
className="inline-flex max-w-[100px] items-center gap-0.5 truncate rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-[5px] py-[3px]"
title={tag}
>
<RiPriceTag3Line className="h-3 w-3 shrink-0 text-text-quaternary" />
<span className="system-2xs-medium-uppercase text-text-tertiary">{tag.toUpperCase()}</span>
</span>
))}
</div>
)}
</div>
)
}
// Memoize to prevent unnecessary re-renders when tags array hasn't changed
const CardTags = React.memo(CardTagsComponent)
export default CardTags
+2 -6
View File
@@ -34,7 +34,6 @@ export type Props = {
isLoading?: boolean
loadingFileName?: string
limitedInstall?: boolean
disableOrgLink?: boolean
}
const Card = ({
@@ -49,14 +48,12 @@ const Card = ({
isLoading = false,
loadingFileName,
limitedInstall = false,
disableOrgLink = false,
}: Props) => {
const locale = useGetLanguage()
const { t } = useTranslation()
const { categoriesMap } = useCategories(true)
const currentWorkspaceId = useSelector(s => s.currentWorkspace.id)
const { category, type, name, org, label, brief, icon, icon_dark, verified, from } = payload
const badges = payload.badges ?? []
const { category, type, name, org, label, brief, icon, icon_dark, verified, badges = [], from } = payload
const { theme } = useTheme()
const iconSrc = getPluginCardIconUrl(
{ from, name, org, type },
@@ -96,8 +93,7 @@ const Card = ({
<OrgInfo
className="mt-0.5"
orgName={org}
downloadCount={payload.install_count}
linkToOrg={!disableOrgLink}
packageName={name}
/>
</div>
</div>
@@ -4,32 +4,16 @@ import { Provider as JotaiProvider } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import {
useActivePluginCategory,
useActivePluginType,
useFilterPluginTags,
useMarketplaceMoreClick,
useMarketplacePluginSort,
useMarketplacePluginSortValue,
useMarketplaceSearchMode,
useSearchText,
useSetMarketplacePluginSort,
useMarketplaceSort,
useMarketplaceSortValue,
useSearchPluginText,
useSetMarketplaceSort,
} from '../atoms'
import { DEFAULT_PLUGIN_SORT } from '../constants'
const { mockRouterPush, mockNavigation } = vi.hoisted(() => ({
mockRouterPush: vi.fn(),
mockNavigation: {
pathname: '/plugins',
params: {} as Record<string, string | undefined>,
},
}))
vi.mock('next/navigation', () => ({
useRouter: () => ({
push: mockRouterPush,
}),
usePathname: () => mockNavigation.pathname,
useParams: () => mockNavigation.params,
}))
import { DEFAULT_SORT } from '../constants'
const createWrapper = (searchParams = '') => {
const { wrapper: NuqsWrapper } = createNuqsTestWrapper({ searchParams })
@@ -46,30 +30,28 @@ const createWrapper = (searchParams = '') => {
describe('Marketplace sort atoms', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
})
it('should return default sort value from useMarketplaceSort', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => useMarketplacePluginSort(), { wrapper })
const { result } = renderHook(() => useMarketplaceSort(), { wrapper })
expect(result.current[0]).toEqual(DEFAULT_PLUGIN_SORT)
expect(result.current[0]).toEqual(DEFAULT_SORT)
expect(typeof result.current[1]).toBe('function')
})
it('should return default sort value from useMarketplaceSortValue', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => useMarketplacePluginSortValue(), { wrapper })
const { result } = renderHook(() => useMarketplaceSortValue(), { wrapper })
expect(result.current).toEqual(DEFAULT_PLUGIN_SORT)
expect(result.current).toEqual(DEFAULT_SORT)
})
it('should return setter from useSetMarketplaceSort', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => ({
setSort: useSetMarketplacePluginSort(),
sortValue: useMarketplacePluginSortValue(),
setSort: useSetMarketplaceSort(),
sortValue: useMarketplaceSortValue(),
}), { wrapper })
act(() => {
@@ -81,7 +63,7 @@ describe('Marketplace sort atoms', () => {
it('should update sort value via useMarketplaceSort setter', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => useMarketplacePluginSort(), { wrapper })
const { result } = renderHook(() => useMarketplaceSort(), { wrapper })
act(() => {
result.current[1]({ sortBy: 'created_at', sortOrder: 'ASC' })
@@ -91,16 +73,14 @@ describe('Marketplace sort atoms', () => {
})
})
describe('useSearchText', () => {
describe('useSearchPluginText', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
})
it('should return empty string as default', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => useSearchText(), { wrapper })
const { result } = renderHook(() => useSearchPluginText(), { wrapper })
expect(result.current[0]).toBe('')
expect(typeof result.current[1]).toBe('function')
@@ -108,14 +88,14 @@ describe('useSearchText', () => {
it('should parse q from search params', () => {
const { wrapper } = createWrapper('?q=hello')
const { result } = renderHook(() => useSearchText(), { wrapper })
const { result } = renderHook(() => useSearchPluginText(), { wrapper })
expect(result.current[0]).toBe('hello')
})
it('should expose a setter function for search text', async () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => useSearchText(), { wrapper })
const { result } = renderHook(() => useSearchPluginText(), { wrapper })
await act(async () => {
result.current[1]('search term')
@@ -125,23 +105,21 @@ describe('useSearchText', () => {
})
})
describe('useActivePluginCategory', () => {
describe('useActivePluginType', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
})
it('should return "all" as default category', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => useActivePluginCategory(), { wrapper })
const { result } = renderHook(() => useActivePluginType(), { wrapper })
expect(result.current[0]).toBe('all')
})
it('should parse category from search params', () => {
const { wrapper } = createWrapper('?category=tool')
const { result } = renderHook(() => useActivePluginCategory(), { wrapper })
const { result } = renderHook(() => useActivePluginType(), { wrapper })
expect(result.current[0]).toBe('tool')
})
@@ -150,8 +128,6 @@ describe('useActivePluginCategory', () => {
describe('useFilterPluginTags', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
})
it('should return empty array as default', () => {
@@ -172,8 +148,6 @@ describe('useFilterPluginTags', () => {
describe('useMarketplaceSearchMode', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
})
it('should return false when no search text, no tags, and category has collections (all)', () => {
@@ -187,7 +161,7 @@ describe('useMarketplaceSearchMode', () => {
const { wrapper } = createWrapper('?q=test&category=all')
const { result } = renderHook(() => useMarketplaceSearchMode(), { wrapper })
expect(result.current).toBeTruthy()
expect(result.current).toBe(true)
})
it('should return true when tags are present', () => {
@@ -215,8 +189,6 @@ describe('useMarketplaceSearchMode', () => {
describe('useMarketplaceMoreClick', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
})
it('should return a callback function', () => {
@@ -230,8 +202,8 @@ describe('useMarketplaceMoreClick', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => ({
handleMoreClick: useMarketplaceMoreClick(),
sort: useMarketplacePluginSortValue(),
searchText: useSearchText()[0],
sort: useMarketplaceSortValue(),
searchText: useSearchPluginText()[0],
}), { wrapper })
const sortBefore = result.current.sort
@@ -250,7 +222,7 @@ describe('useMarketplaceMoreClick', () => {
const { result } = renderHook(() => ({
handleMoreClick: useMarketplaceMoreClick(),
sort: useMarketplacePluginSortValue(),
sort: useMarketplaceSortValue(),
}), { wrapper })
act(() => {
@@ -268,13 +240,13 @@ describe('useMarketplaceMoreClick', () => {
const { wrapper } = createWrapper()
const { result } = renderHook(() => ({
handleMoreClick: useMarketplaceMoreClick(),
sort: useMarketplacePluginSortValue(),
sort: useMarketplaceSortValue(),
}), { wrapper })
act(() => {
result.current.handleMoreClick({})
})
expect(result.current.sort).toEqual(DEFAULT_PLUGIN_SORT)
expect(result.current.sort).toEqual(DEFAULT_SORT)
})
})
@@ -42,10 +42,8 @@ const mockCollectionPlugins = vi.fn()
vi.mock('@/service/client', () => ({
marketplaceClient: {
plugins: {
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
},
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
},
}))
@@ -92,8 +90,8 @@ describe('useMarketplaceCollectionsAndPlugins (integration)', () => {
expect(result.current.isSuccess).toBe(true)
})
expect(result.current.pluginCollections).toBeDefined()
expect(result.current.pluginCollectionPluginsMap).toBeDefined()
expect(result.current.marketplaceCollections).toBeDefined()
expect(result.current.marketplaceCollectionPluginsMap).toBeDefined()
})
it('should handle query with empty params (truthy)', async () => {
@@ -118,10 +118,10 @@ describe('useMarketplaceCollectionsAndPlugins', () => {
expect(result.current.isLoading).toBe(false)
expect(result.current.isSuccess).toBe(false)
expect(typeof result.current.queryMarketplaceCollectionsAndPlugins).toBe('function')
expect(typeof result.current.setPluginCollections).toBe('function')
expect(typeof result.current.setPluginCollectionPluginsMap).toBe('function')
expect(result.current.pluginCollections).toBeUndefined()
expect(result.current.pluginCollectionPluginsMap).toBeUndefined()
expect(typeof result.current.setMarketplaceCollections).toBe('function')
expect(typeof result.current.setMarketplaceCollectionPluginsMap).toBe('function')
expect(result.current.marketplaceCollections).toBeUndefined()
expect(result.current.marketplaceCollectionPluginsMap).toBeUndefined()
})
})
@@ -427,8 +427,8 @@ describe('Hooks queryFn Coverage', () => {
await waitFor(() => {
expect(result.current.isSuccess).toBe(true)
})
expect(result.current.pluginCollections).toBeDefined()
expect(result.current.pluginCollectionPluginsMap).toBeDefined()
expect(result.current.marketplaceCollections).toBeDefined()
expect(result.current.marketplaceCollectionPluginsMap).toBeDefined()
})
it('should test getNextPageParam via fetchNextPage behavior', async () => {
@@ -2,12 +2,6 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('next/headers', () => ({
headers: async () => ({
get: (name: string) => name === 'sec-fetch-dest' ? 'document' : null,
}),
}))
vi.mock('@/config', () => ({
API_PREFIX: '/api',
APP_VERSION: '1.0.0',
@@ -21,24 +15,15 @@ vi.mock('@/utils/var', () => ({
const mockCollections = vi.fn()
const mockCollectionPlugins = vi.fn()
const mockSearchAdvanced = vi.fn()
vi.mock('@/service/client', () => ({
marketplaceClient: {
plugins: {
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
},
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
},
marketplaceQuery: {
plugins: {
collections: {
queryKey: (params: unknown) => ['marketplace', 'plugins', 'collections', params],
},
searchAdvanced: {
queryKey: (params: unknown) => ['marketplace', 'plugins', 'searchAdvanced', params],
},
collections: {
queryKey: (params: unknown) => ['marketplace', 'collections', params],
},
},
}))
@@ -61,9 +46,6 @@ describe('HydrateQueryClient', () => {
mockCollectionPlugins.mockResolvedValue({
data: { plugins: [] },
})
mockSearchAdvanced.mockResolvedValue({
data: { plugins: [], total: 0 },
})
})
it('should render children within HydrationBoundary', async () => {
@@ -99,7 +81,6 @@ describe('HydrateQueryClient', () => {
await HydrateQueryClient({
searchParams: Promise.resolve({ category: 'all' }),
isMarketplacePlatform: true,
children: <div>Child</div>,
})
@@ -111,36 +92,31 @@ describe('HydrateQueryClient', () => {
await HydrateQueryClient({
searchParams: Promise.resolve({ category: 'tool' }),
isMarketplacePlatform: true,
children: <div>Child</div>,
})
expect(mockCollections).toHaveBeenCalled()
})
it('should prefetch search results when category does not have collections (model)', async () => {
it('should not prefetch when category does not have collections (model)', async () => {
const { HydrateQueryClient } = await import('../hydration-server')
await HydrateQueryClient({
searchParams: Promise.resolve({ category: 'model' }),
isMarketplacePlatform: true,
children: <div>Child</div>,
})
expect(mockCollections).toHaveBeenCalled()
expect(mockSearchAdvanced).toHaveBeenCalled()
expect(mockCollections).not.toHaveBeenCalled()
})
it('should prefetch search results when category does not have collections (bundle)', async () => {
it('should not prefetch when category does not have collections (bundle)', async () => {
const { HydrateQueryClient } = await import('../hydration-server')
await HydrateQueryClient({
searchParams: Promise.resolve({ category: 'bundle' }),
isMarketplacePlatform: true,
children: <div>Child</div>,
})
expect(mockCollections).toHaveBeenCalled()
expect(mockSearchAdvanced).toHaveBeenCalled()
expect(mockCollections).not.toHaveBeenCalled()
})
})
@@ -8,44 +8,24 @@ vi.mock('@/context/query-client', () => ({
}))
vi.mock('../hydration-server', () => ({
HydrateQueryClient: ({
children,
isMarketplacePlatform,
}: {
children: React.ReactNode
isMarketplacePlatform?: boolean
}) => (
<div data-testid="hydrate-query-client" data-marketplace-platform={String(Boolean(isMarketplacePlatform))}>{children}</div>
HydrateQueryClient: ({ children }: { children: React.ReactNode }) => (
<div data-testid="hydration-client">{children}</div>
),
}))
vi.mock('../hydration-client', () => ({
HydrateClient: ({
children,
isMarketplacePlatform,
}: {
children: React.ReactNode
isMarketplacePlatform?: boolean
}) => (
<div data-testid="hydrate-client" data-marketplace-platform={String(Boolean(isMarketplacePlatform))}>{children}</div>
vi.mock('../description', () => ({
default: () => <div data-testid="description">Description</div>,
}))
vi.mock('../list/list-wrapper', () => ({
default: ({ showInstallButton }: { showInstallButton: boolean }) => (
<div data-testid="list-wrapper" data-show-install={showInstallButton}>ListWrapper</div>
),
}))
vi.mock('../marketplace-header', () => ({
default: ({
marketplaceNav,
}: {
marketplaceNav?: React.ReactNode
}) => (
<div data-testid="marketplace-header">
{marketplaceNav}
</div>
),
}))
vi.mock('../marketplace-content', () => ({
default: ({ showInstallButton }: { showInstallButton?: boolean }) => (
<div data-testid="marketplace-content" data-show-install={String(Boolean(showInstallButton))}>MarketplaceContent</div>
vi.mock('../sticky-search-and-switch-wrapper', () => ({
default: ({ pluginTypeSwitchClassName }: { pluginTypeSwitchClassName?: string }) => (
<div data-testid="sticky-wrapper" data-classname={pluginTypeSwitchClassName}>StickyWrapper</div>
),
}))
@@ -67,20 +47,20 @@ describe('Marketplace', () => {
const { getByTestId } = render(element as React.ReactElement)
expect(getByTestId('tanstack-initializer')).toBeInTheDocument()
expect(getByTestId('hydrate-query-client')).toBeInTheDocument()
expect(getByTestId('hydrate-client')).toBeInTheDocument()
expect(getByTestId('marketplace-header')).toBeInTheDocument()
expect(getByTestId('marketplace-content')).toBeInTheDocument()
expect(getByTestId('hydration-client')).toBeInTheDocument()
expect(getByTestId('description')).toBeInTheDocument()
expect(getByTestId('sticky-wrapper')).toBeInTheDocument()
expect(getByTestId('list-wrapper')).toBeInTheDocument()
})
it('should pass showInstallButton=true by default to MarketplaceContent', async () => {
it('should pass showInstallButton=true by default to ListWrapper', async () => {
const Marketplace = (await import('../index')).default
const element = await Marketplace({})
const { getByTestId } = render(element as React.ReactElement)
const marketplaceContent = getByTestId('marketplace-content')
expect(marketplaceContent.getAttribute('data-show-install')).toBe('true')
const listWrapper = getByTestId('list-wrapper')
expect(listWrapper.getAttribute('data-show-install')).toBe('true')
})
it('should pass showInstallButton=false when specified', async () => {
@@ -89,26 +69,27 @@ describe('Marketplace', () => {
const { getByTestId } = render(element as React.ReactElement)
const marketplaceContent = getByTestId('marketplace-content')
expect(marketplaceContent.getAttribute('data-show-install')).toBe('false')
const listWrapper = getByTestId('list-wrapper')
expect(listWrapper.getAttribute('data-show-install')).toBe('false')
})
it('should pass marketplaceNav to MarketplaceHeader', async () => {
it('should pass pluginTypeSwitchClassName to StickySearchAndSwitchWrapper', async () => {
const Marketplace = (await import('../index')).default
const element = await Marketplace({ marketplaceNav: <div data-testid="nav">Nav</div> })
const element = await Marketplace({ pluginTypeSwitchClassName: 'top-14' })
const { getByTestId } = render(element as React.ReactElement)
expect(getByTestId('nav')).toBeInTheDocument()
const stickyWrapper = getByTestId('sticky-wrapper')
expect(stickyWrapper.getAttribute('data-classname')).toBe('top-14')
})
it('should pass isMarketplacePlatform to hydrate wrappers', async () => {
it('should render without pluginTypeSwitchClassName', async () => {
const Marketplace = (await import('../index')).default
const element = await Marketplace({ isMarketplacePlatform: true })
const element = await Marketplace({})
const { getByTestId } = render(element as React.ReactElement)
expect(getByTestId('hydrate-query-client').getAttribute('data-marketplace-platform')).toBe('true')
expect(getByTestId('hydrate-client').getAttribute('data-marketplace-platform')).toBe('true')
const stickyWrapper = getByTestId('sticky-wrapper')
expect(stickyWrapper.getAttribute('data-classname')).toBeNull()
})
})
@@ -3,23 +3,7 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { Provider as JotaiProvider } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import { PluginCategorySwitch } from '../category-switch/plugin'
const { mockRouterPush, mockNavigation } = vi.hoisted(() => ({
mockRouterPush: vi.fn(),
mockNavigation: {
pathname: '/plugins',
params: {} as Record<string, string | undefined>,
},
}))
vi.mock('next/navigation', () => ({
useRouter: () => ({
push: mockRouterPush,
}),
usePathname: () => mockNavigation.pathname,
useParams: () => mockNavigation.params,
}))
import PluginTypeSwitch from '../plugin-type-switch'
vi.mock('#i18n', () => ({
useTranslation: () => ({
@@ -51,16 +35,14 @@ const createWrapper = (searchParams = '') => {
return { Wrapper }
}
describe('PluginCategorySwitch', () => {
describe('PluginTypeSwitch', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
})
it('should render all category options', () => {
const { Wrapper } = createWrapper()
render(<PluginCategorySwitch />, { wrapper: Wrapper })
render(<PluginTypeSwitch />, { wrapper: Wrapper })
expect(screen.getByText('All')).toBeInTheDocument()
expect(screen.getByText('Models')).toBeInTheDocument()
@@ -74,7 +56,7 @@ describe('PluginCategorySwitch', () => {
it('should apply active styling to current category', () => {
const { Wrapper } = createWrapper('?category=all')
render(<PluginCategorySwitch />, { wrapper: Wrapper })
render(<PluginTypeSwitch />, { wrapper: Wrapper })
const allButton = screen.getByText('All').closest('div')
expect(allButton?.className).toContain('!bg-components-main-nav-nav-button-bg-active')
@@ -82,7 +64,7 @@ describe('PluginCategorySwitch', () => {
it('should apply custom className', () => {
const { Wrapper } = createWrapper()
const { container } = render(<PluginCategorySwitch className="custom-class" />, { wrapper: Wrapper })
const { container } = render(<PluginTypeSwitch className="custom-class" />, { wrapper: Wrapper })
const outerDiv = container.firstChild as HTMLElement
expect(outerDiv.className).toContain('custom-class')
@@ -90,7 +72,7 @@ describe('PluginCategorySwitch', () => {
it('should update category when option is clicked', () => {
const { Wrapper } = createWrapper('?category=all')
render(<PluginCategorySwitch />, { wrapper: Wrapper })
render(<PluginTypeSwitch />, { wrapper: Wrapper })
fireEvent.click(screen.getByText('Models'))
@@ -100,7 +82,7 @@ describe('PluginCategorySwitch', () => {
it('should handle clicking on category with collections (Tools)', () => {
const { Wrapper } = createWrapper('?category=model')
render(<PluginCategorySwitch />, { wrapper: Wrapper })
render(<PluginTypeSwitch />, { wrapper: Wrapper })
fireEvent.click(screen.getByText('Tools'))
@@ -110,7 +92,7 @@ describe('PluginCategorySwitch', () => {
it('should handle clicking on category without collections (Models)', () => {
const { Wrapper } = createWrapper('?category=all')
render(<PluginCategorySwitch />, { wrapper: Wrapper })
render(<PluginTypeSwitch />, { wrapper: Wrapper })
fireEvent.click(screen.getByText('Models'))
@@ -120,7 +102,7 @@ describe('PluginCategorySwitch', () => {
it('should handle clicking on bundles', () => {
const { Wrapper } = createWrapper('?category=all')
render(<PluginCategorySwitch />, { wrapper: Wrapper })
render(<PluginTypeSwitch />, { wrapper: Wrapper })
fireEvent.click(screen.getByText('Bundles'))
@@ -130,7 +112,7 @@ describe('PluginCategorySwitch', () => {
it('should handle clicking on each category', () => {
const { Wrapper } = createWrapper('?category=all')
render(<PluginCategorySwitch />, { wrapper: Wrapper })
render(<PluginTypeSwitch />, { wrapper: Wrapper })
const categories = ['All', 'Models', 'Tools', 'Data Sources', 'Triggers', 'Agents', 'Extensions', 'Bundles']
categories.forEach((category) => {
@@ -143,7 +125,7 @@ describe('PluginCategorySwitch', () => {
it('should render icons for categories that have them', () => {
const { Wrapper } = createWrapper()
const { container } = render(<PluginCategorySwitch />, { wrapper: Wrapper })
const { container } = render(<PluginTypeSwitch />, { wrapper: Wrapper })
// "All" has no icon (icon: null), others should have SVG icons
const svgs = container.querySelectorAll('svg')
@@ -20,20 +20,16 @@ const mockSearchAdvanced = vi.fn()
vi.mock('@/service/client', () => ({
marketplaceClient: {
plugins: {
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
},
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
},
marketplaceQuery: {
plugins: {
collections: {
queryKey: (params: unknown) => ['marketplace', 'plugins', 'collections', params],
},
searchAdvanced: {
queryKey: (params: unknown) => ['marketplace', 'plugins', 'searchAdvanced', params],
},
collections: {
queryKey: (params: unknown) => ['marketplace', 'collections', params],
},
searchAdvanced: {
queryKey: (params: unknown) => ['marketplace', 'searchAdvanced', params],
},
},
}))
@@ -5,10 +5,6 @@ import { Provider as JotaiProvider } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
vi.mock('ahooks', () => ({
useDebounce: <T,>(value: T) => value,
}))
vi.mock('@/config', () => ({
API_PREFIX: '/api',
APP_VERSION: '1.0.0',
@@ -23,38 +19,19 @@ vi.mock('@/utils/var', () => ({
const mockCollections = vi.fn()
const mockCollectionPlugins = vi.fn()
const mockSearchAdvanced = vi.fn()
const { mockRouterPush, mockNavigation } = vi.hoisted(() => ({
mockRouterPush: vi.fn(),
mockNavigation: {
pathname: '/plugins',
params: {} as Record<string, string | undefined>,
},
}))
vi.mock('next/navigation', () => ({
useRouter: () => ({
push: mockRouterPush,
}),
usePathname: () => mockNavigation.pathname,
useParams: () => mockNavigation.params,
}))
vi.mock('@/service/client', () => ({
marketplaceClient: {
plugins: {
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
},
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
},
marketplaceQuery: {
plugins: {
collections: {
queryKey: (params: unknown) => ['marketplace', 'plugins', 'collections', params],
},
searchAdvanced: {
queryKey: (params: unknown) => ['marketplace', 'plugins', 'searchAdvanced', params],
},
collections: {
queryKey: (params: unknown) => ['marketplace', 'collections', params],
},
searchAdvanced: {
queryKey: (params: unknown) => ['marketplace', 'searchAdvanced', params],
},
},
}))
@@ -78,11 +55,9 @@ const createWrapper = (searchParams = '') => {
return { Wrapper, queryClient }
}
describe('usePluginsMarketplaceData', () => {
describe('useMarketplaceData', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNavigation.pathname = '/plugins'
mockNavigation.params = {}
mockCollections.mockResolvedValue({
data: {
@@ -105,7 +80,7 @@ describe('usePluginsMarketplaceData', () => {
})
it('should return initial state with loading and collections data', async () => {
const { usePluginsMarketplaceData } = await import('../state')
const { useMarketplaceData } = await import('../state')
const { Wrapper } = createWrapper('?category=all')
// Create a mock container for scroll
@@ -113,14 +88,14 @@ describe('usePluginsMarketplaceData', () => {
container.id = 'marketplace-container'
document.body.appendChild(container)
const { result } = renderHook(() => usePluginsMarketplaceData(), { wrapper: Wrapper })
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
})
expect(result.current.pluginCollections).toBeDefined()
expect(result.current.pluginCollectionPluginsMap).toBeDefined()
expect(result.current.marketplaceCollections).toBeDefined()
expect(result.current.marketplaceCollectionPluginsMap).toBeDefined()
expect(result.current.page).toBeDefined()
expect(result.current.isFetchingNextPage).toBe(false)
@@ -128,14 +103,14 @@ describe('usePluginsMarketplaceData', () => {
})
it('should return search mode data when search text is present', async () => {
const { usePluginsMarketplaceData } = await import('../state')
const { useMarketplaceData } = await import('../state')
const { Wrapper } = createWrapper('?category=all&q=test')
const container = document.createElement('div')
container.id = 'marketplace-container'
document.body.appendChild(container)
const { result } = renderHook(() => usePluginsMarketplaceData(), { wrapper: Wrapper })
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
@@ -148,7 +123,7 @@ describe('usePluginsMarketplaceData', () => {
})
it('should return plugins undefined in collection mode (not search mode)', async () => {
const { usePluginsMarketplaceData } = await import('../state')
const { useMarketplaceData } = await import('../state')
// "all" category with no search → collection mode
const { Wrapper } = createWrapper('?category=all')
@@ -156,7 +131,7 @@ describe('usePluginsMarketplaceData', () => {
container.id = 'marketplace-container'
document.body.appendChild(container)
const { result } = renderHook(() => usePluginsMarketplaceData(), { wrapper: Wrapper })
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
@@ -169,14 +144,14 @@ describe('usePluginsMarketplaceData', () => {
})
it('should enable search for category without collections (e.g. model)', async () => {
const { usePluginsMarketplaceData } = await import('../state')
const { useMarketplaceData } = await import('../state')
const { Wrapper } = createWrapper('?category=model')
const container = document.createElement('div')
container.id = 'marketplace-container'
document.body.appendChild(container)
const { result } = renderHook(() => usePluginsMarketplaceData(), { wrapper: Wrapper })
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
@@ -202,7 +177,7 @@ describe('usePluginsMarketplaceData', () => {
},
})
const { usePluginsMarketplaceData } = await import('../state')
const { useMarketplaceData } = await import('../state')
// Use "model" to force search mode
const { Wrapper } = createWrapper('?category=model')
@@ -214,7 +189,7 @@ describe('usePluginsMarketplaceData', () => {
Object.defineProperty(container, 'scrollHeight', { value: 1000, writable: true, configurable: true })
Object.defineProperty(container, 'clientHeight', { value: 200, writable: true, configurable: true })
const { result } = renderHook(() => usePluginsMarketplaceData(), { wrapper: Wrapper })
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
// Wait for data to fully load (isFetching becomes false, plugins become available)
await waitFor(() => {
@@ -231,7 +206,7 @@ describe('usePluginsMarketplaceData', () => {
})
it('should handle tags filter in search mode', async () => {
const { usePluginsMarketplaceData } = await import('../state')
const { useMarketplaceData } = await import('../state')
// tags in URL triggers search mode
const { Wrapper } = createWrapper('?category=all&tags=search')
@@ -239,7 +214,7 @@ describe('usePluginsMarketplaceData', () => {
container.id = 'marketplace-container'
document.body.appendChild(container)
const { result } = renderHook(() => usePluginsMarketplaceData(), { wrapper: Wrapper })
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
@@ -263,7 +238,7 @@ describe('usePluginsMarketplaceData', () => {
},
})
const { usePluginsMarketplaceData } = await import('../state')
const { useMarketplaceData } = await import('../state')
const { Wrapper } = createWrapper('?category=model')
const container = document.createElement('div')
@@ -274,7 +249,7 @@ describe('usePluginsMarketplaceData', () => {
Object.defineProperty(container, 'scrollHeight', { value: 1000, writable: true, configurable: true })
Object.defineProperty(container, 'clientHeight', { value: 200, writable: true, configurable: true })
const { result } = renderHook(() => usePluginsMarketplaceData(), { wrapper: Wrapper })
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
await waitFor(() => {
expect(result.current.plugins).toBeDefined()
@@ -0,0 +1,87 @@
import type { ReactNode } from 'react'
import { render } from '@testing-library/react'
import { Provider as JotaiProvider } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import StickySearchAndSwitchWrapper from '../sticky-search-and-switch-wrapper'
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: (key: string) => key,
}),
}))
// Mock child components to isolate wrapper logic
vi.mock('../plugin-type-switch', () => ({
default: () => <div data-testid="plugin-type-switch">PluginTypeSwitch</div>,
}))
vi.mock('../search-box/search-box-wrapper', () => ({
default: () => <div data-testid="search-box-wrapper">SearchBoxWrapper</div>,
}))
const createWrapper = () => {
const { wrapper: NuqsWrapper } = createNuqsTestWrapper()
const Wrapper = ({ children }: { children: ReactNode }) => (
<JotaiProvider>
<NuqsWrapper>
{children}
</NuqsWrapper>
</JotaiProvider>
)
return { Wrapper }
}
describe('StickySearchAndSwitchWrapper', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should render SearchBoxWrapper and PluginTypeSwitch', () => {
const { Wrapper } = createWrapper()
const { getByTestId } = render(
<StickySearchAndSwitchWrapper />,
{ wrapper: Wrapper },
)
expect(getByTestId('search-box-wrapper')).toBeInTheDocument()
expect(getByTestId('plugin-type-switch')).toBeInTheDocument()
})
it('should not apply sticky class when no pluginTypeSwitchClassName', () => {
const { Wrapper } = createWrapper()
const { container } = render(
<StickySearchAndSwitchWrapper />,
{ wrapper: Wrapper },
)
const outerDiv = container.firstChild as HTMLElement
expect(outerDiv.className).toContain('mt-4')
expect(outerDiv.className).not.toContain('sticky')
})
it('should apply sticky class when pluginTypeSwitchClassName contains top-', () => {
const { Wrapper } = createWrapper()
const { container } = render(
<StickySearchAndSwitchWrapper pluginTypeSwitchClassName="top-10" />,
{ wrapper: Wrapper },
)
const outerDiv = container.firstChild as HTMLElement
expect(outerDiv.className).toContain('sticky')
expect(outerDiv.className).toContain('z-10')
expect(outerDiv.className).toContain('top-10')
})
it('should not apply sticky class when pluginTypeSwitchClassName does not contain top-', () => {
const { Wrapper } = createWrapper()
const { container } = render(
<StickySearchAndSwitchWrapper pluginTypeSwitchClassName="custom-class" />,
{ wrapper: Wrapper },
)
const outerDiv = container.firstChild as HTMLElement
expect(outerDiv.className).not.toContain('sticky')
expect(outerDiv.className).toContain('custom-class')
})
})
@@ -23,11 +23,9 @@ const mockSearchAdvanced = vi.fn()
vi.mock('@/service/client', () => ({
marketplaceClient: {
plugins: {
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
},
collections: (...args: unknown[]) => mockCollections(...args),
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
},
}))
@@ -109,7 +107,7 @@ describe('getPluginLinkInMarketplace', () => {
const { getPluginLinkInMarketplace } = await import('../utils')
const plugin = createMockPlugin({ org: 'test-org', name: 'test-plugin', type: 'plugin' })
const link = getPluginLinkInMarketplace(plugin)
expect(link).toBe('https://marketplace.dify.ai/plugin/test-org/test-plugin')
expect(link).toBe('https://marketplace.dify.ai/plugins/test-org/test-plugin')
})
it('should return correct link for bundle', async () => {
@@ -125,7 +123,7 @@ describe('getPluginDetailLinkInMarketplace', () => {
const { getPluginDetailLinkInMarketplace } = await import('../utils')
const plugin = createMockPlugin({ org: 'test-org', name: 'test-plugin', type: 'plugin' })
const link = getPluginDetailLinkInMarketplace(plugin)
expect(link).toBe('/plugin/test-org/test-plugin')
expect(link).toBe('/plugins/test-org/test-plugin')
})
it('should return correct detail link for bundle', async () => {
@@ -136,69 +134,69 @@ describe('getPluginDetailLinkInMarketplace', () => {
})
})
describe('getPluginCondition', () => {
describe('getMarketplaceListCondition', () => {
it('should return category condition for tool', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition(PluginCategoryEnum.tool)).toBe('category=tool')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition(PluginCategoryEnum.tool)).toBe('category=tool')
})
it('should return category condition for model', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition(PluginCategoryEnum.model)).toBe('category=model')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition(PluginCategoryEnum.model)).toBe('category=model')
})
it('should return category condition for agent', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition(PluginCategoryEnum.agent)).toBe('category=agent-strategy')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition(PluginCategoryEnum.agent)).toBe('category=agent-strategy')
})
it('should return category condition for datasource', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition(PluginCategoryEnum.datasource)).toBe('category=datasource')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition(PluginCategoryEnum.datasource)).toBe('category=datasource')
})
it('should return category condition for trigger', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition(PluginCategoryEnum.trigger)).toBe('category=trigger')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition(PluginCategoryEnum.trigger)).toBe('category=trigger')
})
it('should return endpoint category for extension', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition(PluginCategoryEnum.extension)).toBe('category=endpoint')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition(PluginCategoryEnum.extension)).toBe('category=endpoint')
})
it('should return type condition for bundle', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition('bundle')).toBe('type=bundle')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition('bundle')).toBe('type=bundle')
})
it('should return empty string for all', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition('all')).toBe('')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition('all')).toBe('')
})
it('should return empty string for unknown type', async () => {
const { getPluginCondition } = await import('../utils')
expect(getPluginCondition('unknown')).toBe('')
const { getMarketplaceListCondition } = await import('../utils')
expect(getMarketplaceListCondition('unknown')).toBe('')
})
})
describe('getPluginFilterType', () => {
describe('getMarketplaceListFilterType', () => {
it('should return undefined for all', async () => {
const { getPluginFilterType } = await import('../utils')
expect(getPluginFilterType(PLUGIN_TYPE_SEARCH_MAP.all)).toBeUndefined()
const { getMarketplaceListFilterType } = await import('../utils')
expect(getMarketplaceListFilterType(PLUGIN_TYPE_SEARCH_MAP.all)).toBeUndefined()
})
it('should return bundle for bundle', async () => {
const { getPluginFilterType } = await import('../utils')
expect(getPluginFilterType(PLUGIN_TYPE_SEARCH_MAP.bundle)).toBe('bundle')
const { getMarketplaceListFilterType } = await import('../utils')
expect(getMarketplaceListFilterType(PLUGIN_TYPE_SEARCH_MAP.bundle)).toBe('bundle')
})
it('should return plugin for other categories', async () => {
const { getPluginFilterType } = await import('../utils')
expect(getPluginFilterType(PLUGIN_TYPE_SEARCH_MAP.tool)).toBe('plugin')
expect(getPluginFilterType(PLUGIN_TYPE_SEARCH_MAP.model)).toBe('plugin')
expect(getPluginFilterType(PLUGIN_TYPE_SEARCH_MAP.agent)).toBe('plugin')
const { getMarketplaceListFilterType } = await import('../utils')
expect(getMarketplaceListFilterType(PLUGIN_TYPE_SEARCH_MAP.tool)).toBe('plugin')
expect(getMarketplaceListFilterType(PLUGIN_TYPE_SEARCH_MAP.model)).toBe('plugin')
expect(getMarketplaceListFilterType(PLUGIN_TYPE_SEARCH_MAP.agent)).toBe('plugin')
})
})
+26 -198
View File
@@ -1,159 +1,31 @@
import type { SearchTab } from './search-params'
import type { PluginsSort, SearchParamsFromCollection } from './types'
import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai'
import { useParams, usePathname, useRouter } from 'next/navigation'
import { useQueryState } from 'nuqs'
import { useCallback, useMemo } from 'react'
import { CATEGORY_ALL, DEFAULT_PLUGIN_SORT, DEFAULT_TEMPLATE_SORT, getValidatedPluginCategory, getValidatedTemplateCategory, PLUGIN_CATEGORY_WITH_COLLECTIONS } from './constants'
import { CREATION_TYPE, marketplaceSearchParamsParsers } from './search-params'
import { useCallback } from 'react'
import { DEFAULT_SORT, PLUGIN_CATEGORY_WITH_COLLECTIONS } from './constants'
import { marketplaceSearchParamsParsers } from './search-params'
export const isMarketplacePlatformAtom = atom<boolean>(false)
const marketplacePluginSortAtom = atom<PluginsSort>(DEFAULT_PLUGIN_SORT)
export function useMarketplacePluginSort() {
return useAtom(marketplacePluginSortAtom)
const marketplaceSortAtom = atom<PluginsSort>(DEFAULT_SORT)
export function useMarketplaceSort() {
return useAtom(marketplaceSortAtom)
}
export function useMarketplacePluginSortValue() {
return useAtomValue(marketplacePluginSortAtom)
export function useMarketplaceSortValue() {
return useAtomValue(marketplaceSortAtom)
}
export function useSetMarketplacePluginSort() {
return useSetAtom(marketplacePluginSortAtom)
export function useSetMarketplaceSort() {
return useSetAtom(marketplaceSortAtom)
}
const marketplaceTemplateSortAtom = atom<PluginsSort>(DEFAULT_TEMPLATE_SORT)
export function useMarketplaceTemplateSort() {
return useAtom(marketplaceTemplateSortAtom)
}
export function useMarketplaceTemplateSortValue() {
return useAtomValue(marketplaceTemplateSortAtom)
}
export function useSetMarketplaceTemplateSort() {
return useSetAtom(marketplaceTemplateSortAtom)
}
export function useSearchText() {
export function useSearchPluginText() {
return useQueryState('q', marketplaceSearchParamsParsers.q)
}
export function useActivePluginCategory() {
const isAtMarketplace = useAtomValue(isMarketplacePlatformAtom)
const [category, setCategory] = useQueryState('category', marketplaceSearchParamsParsers.category)
const router = useRouter()
const pathname = usePathname()
const segments = pathname.split('/').filter(Boolean)
const categoryFromPath = segments[1] || CATEGORY_ALL
const validatedCategory = getValidatedPluginCategory(categoryFromPath)
const handleChange = useCallback(
(newCategory: string) => {
// Preserve the current query string (e.g. ?languages=en) so manual
// filters survive a category change.
const search = typeof window !== 'undefined' ? window.location.search : ''
router.push(`/plugins/${newCategory}${search}`)
},
[router],
)
if (isAtMarketplace) {
return [validatedCategory, handleChange] as const
}
return [getValidatedPluginCategory(category), setCategory] as const
}
export function useActiveTemplateCategory() {
const isAtMarketplace = useAtomValue(isMarketplacePlatformAtom)
const [category, setCategory] = useQueryState('category', marketplaceSearchParamsParsers.category)
const router = useRouter()
const pathname = usePathname()
const segments = pathname.split('/').filter(Boolean)
const categoryFromPath = segments[1] || CATEGORY_ALL
const validatedCategory = getValidatedTemplateCategory(categoryFromPath)
const handleChange = useCallback(
(newCategory: string) => {
// Preserve the current query string (e.g. ?languages=en) so manual
// filters survive a category change.
const search = typeof window !== 'undefined' ? window.location.search : ''
router.push(`/${CREATION_TYPE.templates}/${newCategory}${search}`)
},
[router],
)
if (isAtMarketplace) {
return [validatedCategory, handleChange] as const
}
return [getValidatedTemplateCategory(category), setCategory] as const
export function useActivePluginType() {
return useQueryState('category', marketplaceSearchParamsParsers.category)
}
export function useFilterPluginTags() {
return useQueryState('tags', marketplaceSearchParamsParsers.tags)
}
export function useFilterTemplateLanguages() {
return useQueryState('languages', marketplaceSearchParamsParsers.languages)
}
export function useSearchTab() {
const isAtMarketplace = useAtomValue(isMarketplacePlatformAtom)
const state = useQueryState('searchTab', marketplaceSearchParamsParsers.searchTab)
const router = useRouter()
// /search/[searchTab]
const { searchTab } = useParams()
const handleChange = useCallback(
(newTab: string) => {
const location = new URL(window.location.href)
const isAlreadyOnSearch = location.pathname.startsWith('/search/')
location.pathname = `/search/${newTab}`
if (isAlreadyOnSearch)
router.replace(location.href)
else
router.push(location.href)
},
[router],
)
if (isAtMarketplace) {
return [searchTab, handleChange] as const
}
return state
}
export function useCreationType() {
const isAtMarketplace = useAtomValue(isMarketplacePlatformAtom)
const [creationType] = useQueryState('creationType', marketplaceSearchParamsParsers.creationType)
const pathname = usePathname()
const segments = pathname.split('/').filter(Boolean)
if (isAtMarketplace) {
if (segments[0] === CREATION_TYPE.templates || segments[0] === 'template')
return CREATION_TYPE.templates
return CREATION_TYPE.plugins
}
return creationType
}
// Search-page-specific filter hooks (separate from list-page category/tags)
export function useSearchFilterCategories() {
return useQueryState('searchCategories', marketplaceSearchParamsParsers.searchCategories)
}
export function useSearchFilterLanguages() {
return useQueryState('searchLanguages', marketplaceSearchParamsParsers.searchLanguages)
}
export function useSearchFilterType() {
const [type, setType] = useQueryState('searchType', marketplaceSearchParamsParsers.searchType)
return [getValidatedPluginCategory(type), setType] as const
}
export function useSearchFilterTags() {
return useQueryState('searchTags', marketplaceSearchParamsParsers.searchTags)
}
/**
* Not all categories have collections, so we need to
* force the search mode for those categories.
@@ -161,74 +33,30 @@ export function useSearchFilterTags() {
export const searchModeAtom = atom<true | null>(null)
export function useMarketplaceSearchMode() {
const creationType = useCreationType()
const [searchText] = useSearchText()
const [searchTab] = useSearchTab()
const [searchPluginText] = useSearchPluginText()
const [filterPluginTags] = useFilterPluginTags()
const [filterTemplateLanguages] = useFilterTemplateLanguages()
const [activePluginCategory] = useActivePluginCategory()
const [activeTemplateCategory] = useActiveTemplateCategory()
const isPluginsView = creationType === CREATION_TYPE.plugins
const [activePluginType] = useActivePluginType()
const searchMode = useAtomValue(searchModeAtom)
const isSearchMode = searchTab || searchText
|| (isPluginsView && filterPluginTags.length > 0)
|| (searchMode ?? (isPluginsView && !PLUGIN_CATEGORY_WITH_COLLECTIONS.has(activePluginCategory)))
|| (!isPluginsView && activeTemplateCategory !== CATEGORY_ALL)
|| (!isPluginsView && filterTemplateLanguages.length > 0)
const isSearchMode = !!searchPluginText
|| filterPluginTags.length > 0
|| (searchMode ?? (!PLUGIN_CATEGORY_WITH_COLLECTIONS.has(activePluginType)))
return isSearchMode
}
/**
* Returns the active sort state based on the current creationType.
* Plugins use `marketplacePluginSortAtom`, templates use `marketplaceTemplateSortAtom`.
*/
export function useActiveSort(): [PluginsSort, (sort: PluginsSort) => void] {
const creationType = useCreationType()
const [pluginSort, setPluginSort] = useAtom(marketplacePluginSortAtom)
const [templateSort, setTemplateSort] = useAtom(marketplaceTemplateSortAtom)
const isTemplates = creationType === CREATION_TYPE.templates
const sort = isTemplates ? templateSort : pluginSort
const setSort = useMemo(
() => isTemplates ? setTemplateSort : setPluginSort,
[isTemplates, setTemplateSort, setPluginSort],
)
return [sort, setSort]
}
export function useActiveSortValue(): PluginsSort {
const creationType = useCreationType()
const pluginSort = useAtomValue(marketplacePluginSortAtom)
const templateSort = useAtomValue(marketplaceTemplateSortAtom)
return creationType === CREATION_TYPE.templates ? templateSort : pluginSort
}
export function useMarketplaceMoreClick() {
const [, setQ] = useSearchText()
const [, setSearchTab] = useSearchTab()
const setPluginSort = useSetAtom(marketplacePluginSortAtom)
const setTemplateSort = useSetAtom(marketplaceTemplateSortAtom)
const [,setQ] = useSearchPluginText()
const setSort = useSetAtom(marketplaceSortAtom)
const setSearchMode = useSetAtom(searchModeAtom)
return useCallback((searchParams?: SearchParamsFromCollection, searchTab?: SearchTab) => {
return useCallback((searchParams?: SearchParamsFromCollection) => {
if (!searchParams)
return
setQ(searchParams?.query || '')
if (searchTab === 'templates') {
setTemplateSort({
sortBy: searchParams?.sort_by || DEFAULT_TEMPLATE_SORT.sortBy,
sortOrder: searchParams?.sort_order || DEFAULT_TEMPLATE_SORT.sortOrder,
})
}
else {
setPluginSort({
sortBy: searchParams?.sort_by || DEFAULT_PLUGIN_SORT.sortBy,
sortOrder: searchParams?.sort_order || DEFAULT_PLUGIN_SORT.sortOrder,
})
}
setSort({
sortBy: searchParams?.sort_by || DEFAULT_SORT.sortBy,
sortOrder: searchParams?.sort_order || DEFAULT_SORT.sortOrder,
})
setSearchMode(true)
if (searchTab)
setSearchTab(searchTab)
}, [setQ, setSearchTab, setPluginSort, setTemplateSort, setSearchMode])
}, [setQ, setSort, setSearchMode])
}
@@ -1,69 +0,0 @@
'use client'
import type { ActivePluginType, ActiveTemplateCategory } from '../constants'
import { useTranslation } from '#i18n'
import { PLUGIN_TYPE_SEARCH_MAP, TEMPLATE_CATEGORY_MAP } from '../constants'
/**
* Returns a getter that translates a plugin category value to its display text.
* Pass `allAsAllTypes = true` to use "All types" instead of "All" for the `all` category
* (e.g. hero variant in category switch).
*/
export function usePluginCategoryText() {
const { t } = useTranslation()
return (category: ActivePluginType, allAsAllTypes = false): string => {
switch (category) {
case PLUGIN_TYPE_SEARCH_MAP.model:
return t('category.models', { ns: 'plugin' })
case PLUGIN_TYPE_SEARCH_MAP.tool:
return t('category.tools', { ns: 'plugin' })
case PLUGIN_TYPE_SEARCH_MAP.datasource:
return t('category.datasources', { ns: 'plugin' })
case PLUGIN_TYPE_SEARCH_MAP.trigger:
return t('category.triggers', { ns: 'plugin' })
case PLUGIN_TYPE_SEARCH_MAP.agent:
return t('category.agents', { ns: 'plugin' })
case PLUGIN_TYPE_SEARCH_MAP.extension:
return t('category.extensions', { ns: 'plugin' })
case PLUGIN_TYPE_SEARCH_MAP.bundle:
return t('category.bundles', { ns: 'plugin' })
case PLUGIN_TYPE_SEARCH_MAP.all:
default:
return allAsAllTypes
? t('category.allTypes', { ns: 'plugin' })
: t('category.all', { ns: 'plugin' })
}
}
}
/**
* Returns a getter that translates a template category value to its display text.
*/
export function useTemplateCategoryText() {
const { t } = useTranslation()
return (category: ActiveTemplateCategory): string => {
switch (category) {
case TEMPLATE_CATEGORY_MAP.marketing:
return t('marketplace.templateCategory.marketing', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.sales:
return t('marketplace.templateCategory.sales', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.support:
return t('marketplace.templateCategory.support', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.operations:
return t('marketplace.templateCategory.operations', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.it:
return t('marketplace.templateCategory.it', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.knowledge:
return t('marketplace.templateCategory.knowledge', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.design:
return t('marketplace.templateCategory.design', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.others:
return t('marketplace.templateCategory.others', { ns: 'plugin' })
case TEMPLATE_CATEGORY_MAP.all:
default:
return t('marketplace.templateCategory.all', { ns: 'plugin' })
}
}
}
@@ -1,64 +0,0 @@
'use client'
import { cn } from '@/utils/classnames'
export type CategoryOption = {
value: string
text: string
icon: React.ReactNode | null
}
type CategorySwitchProps = {
className?: string
variant?: 'default' | 'hero'
options: CategoryOption[]
activeValue: string
onChange: (value: string) => void
}
export const CommonCategorySwitch = ({
className,
variant = 'default',
options,
activeValue,
onChange,
}: CategorySwitchProps) => {
const isHeroVariant = variant === 'hero'
const getItemClassName = (isActive: boolean) => {
if (isHeroVariant) {
return cn(
'system-md-medium flex h-8 cursor-pointer items-center rounded-lg px-3 text-text-primary-on-surface transition-all',
isActive
? 'bg-components-button-secondary-bg text-saas-dify-blue-inverted'
: 'hover:bg-state-base-hover',
)
}
return cn(
'system-md-medium flex h-8 cursor-pointer items-center rounded-xl border border-transparent px-3 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary',
isActive && 'border-components-main-nav-nav-button-border !bg-components-main-nav-nav-button-bg-active !text-components-main-nav-nav-button-text-active shadow-xs',
)
}
return (
<div className={cn(
'flex shrink-0 items-center space-x-2',
!isHeroVariant && 'justify-center bg-background-body py-3',
className,
)}
>
{
options.map(option => (
<div
key={option.value}
className={getItemClassName(activeValue === option.value)}
onClick={() => onChange(option.value)}
>
{option.icon}
{option.text}
</div>
))
}
</div>
)
}
@@ -1,152 +0,0 @@
'use client'
import { useTranslation } from '#i18n'
import { RiArrowDownSLine, RiCloseCircleFill, RiGlobalLine } from '@remixicon/react'
import * as React from 'react'
import { useMemo, useState } from 'react'
import Checkbox from '@/app/components/base/checkbox'
import Input from '@/app/components/base/input'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import { cn } from '@/utils/classnames'
import { LANGUAGE_OPTIONS } from '../search-page/constants'
type HeroLanguagesFilterProps = {
languages: string[]
onLanguagesChange: (languages: string[]) => void
}
const LANGUAGE_LABEL_MAP: Record<string, string> = LANGUAGE_OPTIONS.reduce((acc, option) => {
acc[option.value] = option.nativeLabel
return acc
}, {} as Record<string, string>)
const HeroLanguagesFilter = ({
languages,
onLanguagesChange,
}: HeroLanguagesFilterProps) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const [searchText, setSearchText] = useState('')
const selectedLanguagesLength = languages.length
const hasSelected = selectedLanguagesLength > 0
const filteredOptions = useMemo(() => {
if (!searchText)
return LANGUAGE_OPTIONS
const normalizedSearchText = searchText.toLowerCase()
return LANGUAGE_OPTIONS.filter(option =>
option.nativeLabel.toLowerCase().includes(normalizedSearchText)
|| option.label.toLowerCase().includes(normalizedSearchText),
)
}, [searchText])
const handleCheck = (value: string) => {
if (languages.includes(value))
onLanguagesChange(languages.filter(language => language !== value))
else
onLanguagesChange([...languages, value])
}
return (
<PortalToFollowElem
placement="bottom-start"
offset={{
mainAxis: 4,
crossAxis: -6,
}}
open={open}
onOpenChange={setOpen}
>
<PortalToFollowElemTrigger
className="shrink-0"
onClick={() => setOpen(v => !v)}
>
<div
className={cn(
'flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-lg px-2.5 py-1.5',
!hasSelected && 'border border-white/30 text-text-primary-on-surface',
!hasSelected && open && 'bg-state-base-hover',
!hasSelected && !open && 'hover:bg-state-base-hover',
hasSelected && 'border-effect-highlight border bg-components-button-secondary-bg-hover shadow-md backdrop-blur-[5px]',
)}
>
<RiGlobalLine
className={cn(
'size-4 shrink-0',
hasSelected ? 'text-saas-dify-blue-inverted' : 'text-text-primary-on-surface',
)}
/>
<div className="system-md-medium flex items-center gap-0.5">
{!hasSelected && (
<span>{t('marketplace.languages', { ns: 'plugin' })}</span>
)}
{hasSelected && (
<span className="text-saas-dify-blue-inverted">
{languages
.map(language => LANGUAGE_LABEL_MAP[language])
.filter(Boolean)
.slice(0, 2)
.join(', ')}
</span>
)}
{selectedLanguagesLength > 2 && (
<div className="flex min-w-4 items-center justify-center rounded-[5px] border border-saas-dify-blue-inverted px-1 py-0.5">
<span className="system-2xs-medium-uppercase text-saas-dify-blue-inverted">
+
{selectedLanguagesLength - 2}
</span>
</div>
)}
</div>
{hasSelected && (
<RiCloseCircleFill
className="size-4 shrink-0 text-saas-dify-blue-inverted"
onClick={(e) => {
e.stopPropagation()
onLanguagesChange([])
}}
/>
)}
{!hasSelected && (
<RiArrowDownSLine className="size-4 shrink-0 text-text-primary-on-surface" />
)}
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className="z-[1000]">
<div className="w-[240px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
<div className="p-2 pb-1">
<Input
showLeftIcon
value={searchText}
onChange={e => setSearchText(e.target.value)}
placeholder={t('marketplace.searchFilterLanguage', { ns: 'plugin' })}
/>
</div>
<div className="max-h-[448px] overflow-y-auto p-1">
{filteredOptions.map(option => (
<div
key={option.value}
className="flex h-7 cursor-pointer select-none items-center rounded-lg px-2 py-1.5 hover:bg-state-base-hover"
onClick={() => handleCheck(option.value)}
>
<Checkbox
className="mr-1"
checked={languages.includes(option.value)}
/>
<div className="system-sm-medium px-1 text-text-secondary">
{option.nativeLabel}
</div>
</div>
))}
</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default React.memo(HeroLanguagesFilter)
@@ -1,94 +0,0 @@
'use client'
import { useTranslation } from '#i18n'
import { useState } from 'react'
import Checkbox from '@/app/components/base/checkbox'
import Input from '@/app/components/base/input'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import { useTags } from '@/app/components/plugins/hooks'
import HeroTagsTrigger from './hero-tags-trigger'
type HeroTagsFilterProps = {
tags: string[]
onTagsChange: (tags: string[]) => void
}
const HeroTagsFilter = ({
tags,
onTagsChange,
}: HeroTagsFilterProps) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const [searchText, setSearchText] = useState('')
const { tags: options, tagsMap } = useTags()
const filteredOptions = options.filter(option => option.label.toLowerCase().includes(searchText.toLowerCase()))
const handleCheck = (id: string) => {
if (tags.includes(id))
onTagsChange(tags.filter((tag: string) => tag !== id))
else
onTagsChange([...tags, id])
}
const selectedTagsLength = tags.length
return (
<PortalToFollowElem
placement="bottom-start"
offset={{
mainAxis: 4,
crossAxis: -6,
}}
open={open}
onOpenChange={setOpen}
>
<PortalToFollowElemTrigger
className="shrink-0"
onClick={() => setOpen(v => !v)}
>
<HeroTagsTrigger
selectedTagsLength={selectedTagsLength}
open={open}
tags={tags}
tagsMap={tagsMap}
onTagsChange={onTagsChange}
/>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className="z-[1000]">
<div className="w-[240px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
<div className="p-2 pb-1">
<Input
showLeftIcon
value={searchText}
onChange={e => setSearchText(e.target.value)}
placeholder={t('searchTags', { ns: 'pluginTags' }) || ''}
/>
</div>
<div className="max-h-[448px] overflow-y-auto p-1">
{
filteredOptions.map(option => (
<div
key={option.name}
className="flex h-7 cursor-pointer select-none items-center rounded-lg px-2 py-1.5 hover:bg-state-base-hover"
onClick={() => handleCheck(option.name)}
>
<Checkbox
className="mr-1"
checked={tags.includes(option.name)}
/>
<div className="system-sm-medium px-1 text-text-secondary">
{option.label}
</div>
</div>
))
}
</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default HeroTagsFilter
@@ -1,86 +0,0 @@
'use client'
import type { Tag } from '../../hooks'
import { useTranslation } from '#i18n'
import { RiArrowDownSLine, RiCloseCircleFill, RiPriceTag3Line } from '@remixicon/react'
import * as React from 'react'
import { cn } from '@/utils/classnames'
type HeroTagsTriggerProps = {
selectedTagsLength: number
open: boolean
tags: string[]
tagsMap: Record<string, Tag>
onTagsChange: (tags: string[]) => void
}
const HeroTagsTrigger = ({
selectedTagsLength,
open,
tags,
tagsMap,
onTagsChange,
}: HeroTagsTriggerProps) => {
const { t } = useTranslation()
const hasSelected = !!selectedTagsLength
return (
<div
className={cn(
'flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-lg px-2.5 py-1.5',
!hasSelected && 'border border-white/30 text-text-primary-on-surface',
!hasSelected && open && 'bg-state-base-hover',
!hasSelected && !open && 'hover:bg-state-base-hover',
hasSelected && 'border-effect-highlight border bg-components-button-secondary-bg-hover shadow-md backdrop-blur-[5px]',
)}
>
<RiPriceTag3Line className={cn(
'size-4 shrink-0',
hasSelected ? 'text-saas-dify-blue-inverted' : 'text-text-primary-on-surface',
)}
/>
<div className="system-md-medium flex items-center gap-0.5">
{
!hasSelected && (
<span>{t('allTags', { ns: 'pluginTags' })}</span>
)
}
{
hasSelected && (
<span className="text-saas-dify-blue-inverted">
{tags.map(tag => tagsMap[tag]?.label).filter(Boolean).slice(0, 2).join(', ')}
</span>
)
}
{
selectedTagsLength > 2 && (
<div className="flex min-w-4 items-center justify-center rounded-[5px] border border-saas-dify-blue-inverted px-1 py-0.5">
<span className="system-2xs-medium-uppercase text-saas-dify-blue-inverted">
+
{selectedTagsLength - 2}
</span>
</div>
)
}
</div>
{
hasSelected && (
<RiCloseCircleFill
className="size-4 shrink-0 text-saas-dify-blue-inverted"
onClick={(e) => {
e.stopPropagation()
onTagsChange([])
}}
/>
)
}
{
!hasSelected && (
<RiArrowDownSLine className="size-4 shrink-0 text-text-primary-on-surface" />
)
}
</div>
)
}
export default React.memo(HeroTagsTrigger)
@@ -1,4 +0,0 @@
'use client'
export { PluginCategorySwitch } from './plugin'
export { TemplateCategorySwitch } from './template'
@@ -1,94 +0,0 @@
'use client'
import type { ActivePluginType } from '../constants'
import type { PluginCategoryEnum } from '@/app/components/plugins/types'
import { RiArchive2Line } from '@remixicon/react'
import { useSetAtom } from 'jotai'
import { Plugin } from '@/app/components/base/icons/src/vender/plugin'
import { searchModeAtom, useActivePluginCategory, useFilterPluginTags } from '../atoms'
import { PLUGIN_CATEGORY_WITH_COLLECTIONS, PLUGIN_TYPE_SEARCH_MAP } from '../constants'
import { MARKETPLACE_TYPE_ICON_COMPONENTS } from '../plugin-type-icons'
import { usePluginCategoryText } from './category-text'
import { CommonCategorySwitch } from './common'
import HeroTagsFilter from './hero-tags-filter'
type PluginTypeSwitchProps = {
className?: string
variant?: 'default' | 'hero'
}
const categoryValues = [
PLUGIN_TYPE_SEARCH_MAP.all,
PLUGIN_TYPE_SEARCH_MAP.model,
PLUGIN_TYPE_SEARCH_MAP.tool,
PLUGIN_TYPE_SEARCH_MAP.datasource,
PLUGIN_TYPE_SEARCH_MAP.trigger,
PLUGIN_TYPE_SEARCH_MAP.agent,
PLUGIN_TYPE_SEARCH_MAP.extension,
PLUGIN_TYPE_SEARCH_MAP.bundle,
] as const
const getTypeIcon = (value: ActivePluginType, isHeroVariant?: boolean) => {
if (value === PLUGIN_TYPE_SEARCH_MAP.all)
return isHeroVariant ? <Plugin className="mr-1.5 h-4 w-4" /> : null
if (value === PLUGIN_TYPE_SEARCH_MAP.bundle)
return <RiArchive2Line className="mr-1.5 h-4 w-4" />
const Icon = MARKETPLACE_TYPE_ICON_COMPONENTS[value as PluginCategoryEnum]
return Icon ? <Icon className="mr-1.5 h-4 w-4" /> : null
}
export const PluginCategorySwitch = ({
className,
variant = 'default',
}: PluginTypeSwitchProps) => {
const [activePluginCategory, handleActivePluginCategoryChange] = useActivePluginCategory()
const [filterPluginTags, setFilterPluginTags] = useFilterPluginTags()
const setSearchMode = useSetAtom(searchModeAtom)
const getPluginCategoryText = usePluginCategoryText()
const isHeroVariant = variant === 'hero'
const options = categoryValues.map(value => ({
value,
text: getPluginCategoryText(value, isHeroVariant),
icon: getTypeIcon(value, isHeroVariant),
}))
const handleChange = (value: string) => {
handleActivePluginCategoryChange(value)
if (PLUGIN_CATEGORY_WITH_COLLECTIONS.has(value as ActivePluginType)) {
setSearchMode(null)
}
}
if (!isHeroVariant) {
return (
<CommonCategorySwitch
className={className}
variant={variant}
options={options}
activeValue={activePluginCategory}
onChange={handleChange}
/>
)
}
return (
<div className="flex shrink-0 items-center gap-2">
<HeroTagsFilter
tags={filterPluginTags}
onTagsChange={tags => setFilterPluginTags(tags.length ? tags : null)}
/>
<div className="text-text-primary-on-surface">
·
</div>
<CommonCategorySwitch
className={className}
variant={variant}
options={options}
activeValue={activePluginCategory}
onChange={handleChange}
/>
</div>
)
}
@@ -1,70 +0,0 @@
'use client'
import { Playground } from '@/app/components/base/icons/src/vender/plugin'
import { useActiveTemplateCategory, useFilterTemplateLanguages } from '../atoms'
import { CATEGORY_ALL, TEMPLATE_CATEGORY_MAP } from '../constants'
import { useTemplateCategoryText } from './category-text'
import { CommonCategorySwitch } from './common'
import HeroLanguagesFilter from './hero-languages-filter'
type TemplateCategorySwitchProps = {
className?: string
variant?: 'default' | 'hero'
}
const categoryValues = [
CATEGORY_ALL,
TEMPLATE_CATEGORY_MAP.marketing,
TEMPLATE_CATEGORY_MAP.sales,
TEMPLATE_CATEGORY_MAP.support,
TEMPLATE_CATEGORY_MAP.operations,
TEMPLATE_CATEGORY_MAP.it,
TEMPLATE_CATEGORY_MAP.knowledge,
TEMPLATE_CATEGORY_MAP.design,
TEMPLATE_CATEGORY_MAP.others,
] as const
export const TemplateCategorySwitch = ({
className,
variant = 'default',
}: TemplateCategorySwitchProps) => {
const [activeTemplateCategory, handleActiveTemplateCategoryChange] = useActiveTemplateCategory()
const [filterTemplateLanguages, setFilterTemplateLanguages] = useFilterTemplateLanguages()
const getTemplateCategoryText = useTemplateCategoryText()
const isHeroVariant = variant === 'hero'
const options = categoryValues.map(value => ({
value,
text: getTemplateCategoryText(value),
icon: value === CATEGORY_ALL && isHeroVariant ? <Playground className="mr-1.5 h-4 w-4" /> : null,
}))
if (!isHeroVariant) {
return (
<CommonCategorySwitch
className={className}
variant={variant}
options={options}
activeValue={activeTemplateCategory}
onChange={handleActiveTemplateCategoryChange}
/>
)
}
return (
<div className="flex shrink-0 items-center justify-between gap-2">
<CommonCategorySwitch
className={className}
variant={variant}
options={options}
activeValue={activeTemplateCategory}
onChange={handleActiveTemplateCategoryChange}
/>
<HeroLanguagesFilter
languages={filterTemplateLanguages}
onLanguagesChange={languages => setFilterTemplateLanguages(languages.length ? languages : null)}
/>
</div>
)
}
@@ -1,19 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getValidatedPluginCategory } from './constants'
describe('getValidatedPluginCategory', () => {
it('returns agent-strategy when query value is agent-strategy', () => {
expect(getValidatedPluginCategory('agent-strategy')).toBe('agent-strategy')
})
it('returns valid category values unchanged', () => {
expect(getValidatedPluginCategory('model')).toBe('model')
expect(getValidatedPluginCategory('tool')).toBe('tool')
expect(getValidatedPluginCategory('bundle')).toBe('bundle')
})
it('falls back to all for invalid category values', () => {
expect(getValidatedPluginCategory('agent')).toBe('all')
expect(getValidatedPluginCategory('invalid-category')).toBe('all')
})
})
@@ -1,21 +1,14 @@
import { PluginCategoryEnum } from '../types'
export const DEFAULT_PLUGIN_SORT = {
export const DEFAULT_SORT = {
sortBy: 'install_count',
sortOrder: 'DESC',
}
export const DEFAULT_TEMPLATE_SORT = {
sortBy: 'usage_count',
sortOrder: 'DESC',
}
export const SCROLL_BOTTOM_THRESHOLD = 100
export const CATEGORY_ALL = 'all'
export const PLUGIN_TYPE_SEARCH_MAP = {
[CATEGORY_ALL]: CATEGORY_ALL,
all: 'all',
model: PluginCategoryEnum.model,
tool: PluginCategoryEnum.tool,
agent: PluginCategoryEnum.agent,
@@ -28,7 +21,6 @@ export const PLUGIN_TYPE_SEARCH_MAP = {
type ValueOf<T> = T[keyof T]
export type ActivePluginType = ValueOf<typeof PLUGIN_TYPE_SEARCH_MAP>
const VALID_PLUGIN_CATEGORIES = new Set<ActivePluginType>(Object.values(PLUGIN_TYPE_SEARCH_MAP))
export const PLUGIN_CATEGORY_WITH_COLLECTIONS = new Set<ActivePluginType>(
[
@@ -36,29 +28,3 @@ export const PLUGIN_CATEGORY_WITH_COLLECTIONS = new Set<ActivePluginType>(
PLUGIN_TYPE_SEARCH_MAP.tool,
],
)
export const TEMPLATE_CATEGORY_MAP = {
[CATEGORY_ALL]: CATEGORY_ALL,
marketing: 'marketing',
sales: 'sales',
support: 'support',
operations: 'operations',
it: 'it',
knowledge: 'knowledge',
design: 'design',
others: 'others',
} as const
export type ActiveTemplateCategory = typeof TEMPLATE_CATEGORY_MAP[keyof typeof TEMPLATE_CATEGORY_MAP]
export function getValidatedPluginCategory(category: string): ActivePluginType {
if (VALID_PLUGIN_CATEGORIES.has(category as ActivePluginType))
return category as ActivePluginType
return CATEGORY_ALL
}
export function getValidatedTemplateCategory(category: string): ActiveTemplateCategory {
const key = (category in TEMPLATE_CATEGORY_MAP ? category : CATEGORY_ALL) as keyof typeof TEMPLATE_CATEGORY_MAP
return TEMPLATE_CATEGORY_MAP[key]
}
@@ -1,101 +1,649 @@
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Description } from '../index'
import Description from '../index'
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: (key: string) => {
const translations: Record<string, string> = {
'marketplace.pluginsHeroTitle': 'Build with plugins',
'marketplace.pluginsHeroSubtitle': 'Discover and install marketplace plugins.',
'marketplace.templatesHeroTitle': 'Build with templates',
'marketplace.templatesHeroSubtitle': 'Explore reusable templates.',
}
return translations[key] || key
},
}),
}))
// ================================
// Mock external dependencies
// ================================
let mockCreationType = 'plugins'
// Track mock locale for testing
let mockDefaultLocale = 'en-US'
vi.mock('../../atoms', () => ({
useCreationType: () => mockCreationType,
}))
vi.mock('../../search-params', () => ({
CREATION_TYPE: {
plugins: 'plugins',
templates: 'templates',
},
}))
vi.mock('../../category-switch', () => ({
PluginCategorySwitch: ({ variant }: { variant?: string }) => <div data-testid="plugin-category-switch">{variant}</div>,
TemplateCategorySwitch: ({ variant }: { variant?: string }) => <div data-testid="template-category-switch">{variant}</div>,
}))
vi.mock('motion/react', () => ({
motion: {
div: ({ children, ...props }: React.HTMLAttributes<HTMLDivElement>) => <div {...props}>{children}</div>,
},
useMotionValue: (value: number) => ({ set: vi.fn(), get: () => value }),
useSpring: (value: unknown) => value,
useTransform: (...args: unknown[]) => {
const values = args[0]
if (Array.isArray(values))
return 0
return values
},
}))
class ResizeObserverMock {
observe() {}
disconnect() {}
// Mock translations with realistic values
const pluginTranslations: Record<string, string> = {
'marketplace.empower': 'Empower your AI development',
'marketplace.discover': 'Discover',
'marketplace.difyMarketplace': 'Dify Marketplace',
'marketplace.and': 'and',
'category.models': 'Models',
'category.tools': 'Tools',
'category.datasources': 'Data Sources',
'category.triggers': 'Triggers',
'category.agents': 'Agent Strategies',
'category.extensions': 'Extensions',
'category.bundles': 'Bundles',
}
const commonTranslations: Record<string, string> = {
'operation.in': 'in',
}
// Mock i18n hooks
vi.mock('#i18n', () => ({
useLocale: vi.fn(() => mockDefaultLocale),
useTranslation: vi.fn((ns: string) => ({
t: (key: string) => {
if (ns === 'plugin')
return pluginTranslations[key] || key
if (ns === 'common')
return commonTranslations[key] || key
return key
},
})),
}))
// ================================
// Description Component Tests
// ================================
describe('Description', () => {
beforeEach(() => {
vi.clearAllMocks()
mockCreationType = 'plugins'
vi.stubGlobal('ResizeObserver', ResizeObserverMock)
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
cb(0)
return 1
})
vi.stubGlobal('cancelAnimationFrame', vi.fn())
mockDefaultLocale = 'en-US'
})
// ================================
// Rendering Tests
// ================================
describe('Rendering', () => {
it('should render plugin hero content by default', () => {
render(<Description />)
it('should render without crashing', () => {
const { container } = render(<Description />)
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Build with plugins')
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('Discover and install marketplace plugins.')
expect(screen.getByTestId('plugin-category-switch')).toHaveTextContent('hero')
expect(container.firstChild).toBeInTheDocument()
})
it('should render template hero content when creationType is templates', () => {
mockCreationType = 'templates'
it('should render h1 heading with empower text', () => {
render(<Description />)
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Build with templates')
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('Explore reusable templates.')
expect(screen.getByTestId('template-category-switch')).toHaveTextContent('hero')
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
expect(heading).toHaveTextContent('Empower your AI development')
})
it('should render h2 subheading', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading).toBeInTheDocument()
})
it('should apply correct CSS classes to h1', () => {
render(<Description />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toHaveClass('title-4xl-semi-bold')
expect(heading).toHaveClass('mb-2')
expect(heading).toHaveClass('text-center')
expect(heading).toHaveClass('text-text-primary')
})
it('should apply correct CSS classes to h2', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading).toHaveClass('body-md-regular')
expect(subheading).toHaveClass('text-center')
expect(subheading).toHaveClass('text-text-tertiary')
})
})
describe('Props', () => {
it('should render marketplace nav content when provided', () => {
render(<Description marketplaceNav={<div data-testid="marketplace-nav">Nav</div>} />)
expect(screen.getByTestId('marketplace-nav')).toBeInTheDocument()
// ================================
// Non-Chinese Locale Rendering Tests
// ================================
describe('Non-Chinese Locale Rendering', () => {
beforeEach(() => {
mockDefaultLocale = 'en-US'
})
it('should apply custom className to the sticky wrapper', () => {
const { container } = render(<Description className="custom-hero-class" />)
it('should render discover text for en-US locale', () => {
render(<Description />)
expect(container.querySelector('.custom-hero-class')).toBeInTheDocument()
expect(screen.getByText(/Discover/)).toBeInTheDocument()
})
it('should render all category names', () => {
render(<Description />)
expect(screen.getByText('Models')).toBeInTheDocument()
expect(screen.getByText('Tools')).toBeInTheDocument()
expect(screen.getByText('Data Sources')).toBeInTheDocument()
expect(screen.getByText('Triggers')).toBeInTheDocument()
expect(screen.getByText('Agent Strategies')).toBeInTheDocument()
expect(screen.getByText('Extensions')).toBeInTheDocument()
expect(screen.getByText('Bundles')).toBeInTheDocument()
})
it('should render "and" conjunction text', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading.textContent).toContain('and')
})
it('should render "in" preposition at the end for non-Chinese locales', () => {
render(<Description />)
expect(screen.getByText('in')).toBeInTheDocument()
})
it('should render Dify Marketplace text at the end for non-Chinese locales', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading.textContent).toContain('Dify Marketplace')
})
it('should render category spans with styled underline effect', () => {
const { container } = render(<Description />)
const styledSpans = container.querySelectorAll('.body-md-medium.relative.z-\\[1\\]')
// 7 category spans (models, tools, datasources, triggers, agents, extensions, bundles)
expect(styledSpans.length).toBe(7)
})
it('should apply text-text-secondary class to category spans', () => {
const { container } = render(<Description />)
const styledSpans = container.querySelectorAll('.text-text-secondary')
expect(styledSpans.length).toBeGreaterThanOrEqual(7)
})
})
// ================================
// Chinese (zh-Hans) Locale Rendering Tests
// ================================
describe('Chinese (zh-Hans) Locale Rendering', () => {
beforeEach(() => {
mockDefaultLocale = 'zh-Hans'
})
it('should render "in" text at the beginning for zh-Hans locale', () => {
render(<Description />)
// In zh-Hans mode, "in" appears at the beginning
const inElements = screen.getAllByText('in')
expect(inElements.length).toBeGreaterThanOrEqual(1)
})
it('should render Dify Marketplace text for zh-Hans locale', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading.textContent).toContain('Dify Marketplace')
})
it('should render discover text for zh-Hans locale', () => {
render(<Description />)
expect(screen.getByText(/Discover/)).toBeInTheDocument()
})
it('should render all categories for zh-Hans locale', () => {
render(<Description />)
expect(screen.getByText('Models')).toBeInTheDocument()
expect(screen.getByText('Tools')).toBeInTheDocument()
expect(screen.getByText('Data Sources')).toBeInTheDocument()
expect(screen.getByText('Triggers')).toBeInTheDocument()
expect(screen.getByText('Agent Strategies')).toBeInTheDocument()
expect(screen.getByText('Extensions')).toBeInTheDocument()
expect(screen.getByText('Bundles')).toBeInTheDocument()
})
it('should render both zh-Hans specific elements and shared elements', () => {
render(<Description />)
// zh-Hans has specific element order: "in" -> Dify Marketplace -> Discover
// then the same category list with "and" -> Bundles
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading.textContent).toContain('and')
})
})
// ================================
// Locale Variations Tests
// ================================
describe('Locale Variations', () => {
it('should use en-US locale by default', () => {
mockDefaultLocale = 'en-US'
render(<Description />)
expect(screen.getByText('Empower your AI development')).toBeInTheDocument()
})
it('should handle ja-JP locale as non-Chinese', () => {
mockDefaultLocale = 'ja-JP'
render(<Description />)
// Should render in non-Chinese format (discover first, then "in Dify Marketplace" at end)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading.textContent).toContain('Dify Marketplace')
})
it('should handle ko-KR locale as non-Chinese', () => {
mockDefaultLocale = 'ko-KR'
render(<Description />)
// Should render in non-Chinese format
expect(screen.getByText('Empower your AI development')).toBeInTheDocument()
})
it('should handle de-DE locale as non-Chinese', () => {
mockDefaultLocale = 'de-DE'
render(<Description />)
expect(screen.getByText('Empower your AI development')).toBeInTheDocument()
})
it('should handle fr-FR locale as non-Chinese', () => {
mockDefaultLocale = 'fr-FR'
render(<Description />)
expect(screen.getByText('Empower your AI development')).toBeInTheDocument()
})
it('should handle pt-BR locale as non-Chinese', () => {
mockDefaultLocale = 'pt-BR'
render(<Description />)
expect(screen.getByText('Empower your AI development')).toBeInTheDocument()
})
it('should handle es-ES locale as non-Chinese', () => {
mockDefaultLocale = 'es-ES'
render(<Description />)
expect(screen.getByText('Empower your AI development')).toBeInTheDocument()
})
})
// ================================
// Conditional Rendering Tests
// ================================
describe('Conditional Rendering', () => {
it('should render zh-Hans specific content when locale is zh-Hans', () => {
mockDefaultLocale = 'zh-Hans'
const { container } = render(<Description />)
// zh-Hans has additional span with mr-1 before "in" text at the start
const mrSpan = container.querySelector('span.mr-1')
expect(mrSpan).toBeInTheDocument()
})
it('should render non-Chinese specific content when locale is not zh-Hans', () => {
mockDefaultLocale = 'en-US'
render(<Description />)
// Non-Chinese has "in" and "Dify Marketplace" at the end
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading.textContent).toContain('Dify Marketplace')
})
it('should not render zh-Hans intro content for non-Chinese locales', () => {
mockDefaultLocale = 'en-US'
render(<Description />)
// For en-US, the order should be Discover ... in Dify Marketplace
// The "in" text should only appear once at the end
const subheading = screen.getByRole('heading', { level: 2 })
const content = subheading.textContent || ''
// "in" should appear after "Bundles" and before "Dify Marketplace"
const bundlesIndex = content.indexOf('Bundles')
const inIndex = content.indexOf('in')
const marketplaceIndex = content.indexOf('Dify Marketplace')
expect(bundlesIndex).toBeLessThan(inIndex)
expect(inIndex).toBeLessThan(marketplaceIndex)
})
it('should render zh-Hans with proper word order', () => {
mockDefaultLocale = 'zh-Hans'
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
const content = subheading.textContent || ''
// zh-Hans order: in -> Dify Marketplace -> Discover -> categories
const inIndex = content.indexOf('in')
const marketplaceIndex = content.indexOf('Dify Marketplace')
const discoverIndex = content.indexOf('Discover')
expect(inIndex).toBeLessThan(marketplaceIndex)
expect(marketplaceIndex).toBeLessThan(discoverIndex)
})
})
// ================================
// Category Styling Tests
// ================================
describe('Category Styling', () => {
it('should apply underline effect with after pseudo-element styling', () => {
const { container } = render(<Description />)
const categorySpan = container.querySelector('.after\\:absolute')
expect(categorySpan).toBeInTheDocument()
})
it('should apply correct after pseudo-element classes', () => {
const { container } = render(<Description />)
// Check for the specific after pseudo-element classes
const categorySpans = container.querySelectorAll('.after\\:bottom-\\[1\\.5px\\]')
expect(categorySpans.length).toBe(7)
})
it('should apply full width to after element', () => {
const { container } = render(<Description />)
const categorySpans = container.querySelectorAll('.after\\:w-full')
expect(categorySpans.length).toBe(7)
})
it('should apply correct height to after element', () => {
const { container } = render(<Description />)
const categorySpans = container.querySelectorAll('.after\\:h-2')
expect(categorySpans.length).toBe(7)
})
it('should apply bg-text-text-selected to after element', () => {
const { container } = render(<Description />)
const categorySpans = container.querySelectorAll('.after\\:bg-text-text-selected')
expect(categorySpans.length).toBe(7)
})
it('should have z-index 1 on category spans', () => {
const { container } = render(<Description />)
const categorySpans = container.querySelectorAll('.z-\\[1\\]')
expect(categorySpans.length).toBe(7)
})
it('should apply left margin to category spans', () => {
const { container } = render(<Description />)
const categorySpans = container.querySelectorAll('.ml-1')
expect(categorySpans.length).toBeGreaterThanOrEqual(7)
})
it('should apply both left and right margin to specific spans', () => {
const { container } = render(<Description />)
// Extensions and Bundles spans have both ml-1 and mr-1
const extensionsBundlesSpans = container.querySelectorAll('.ml-1.mr-1')
expect(extensionsBundlesSpans.length).toBe(2)
})
})
// ================================
// Edge Cases Tests
// ================================
describe('Edge Cases', () => {
it('should render fragment as root element', () => {
const { container } = render(<Description />)
// Fragment renders h1 and h2 as direct children
expect(container.querySelector('h1')).toBeInTheDocument()
expect(container.querySelector('h2')).toBeInTheDocument()
})
it('should handle zh-Hant as non-Chinese simplified', () => {
mockDefaultLocale = 'zh-Hant'
render(<Description />)
// zh-Hant is different from zh-Hans, should use non-Chinese format
const subheading = screen.getByRole('heading', { level: 2 })
const content = subheading.textContent || ''
// Check that "Dify Marketplace" appears at the end (non-Chinese format)
const discoverIndex = content.indexOf('Discover')
const marketplaceIndex = content.indexOf('Dify Marketplace')
// For non-Chinese locales, Discover should come before Dify Marketplace
expect(discoverIndex).toBeLessThan(marketplaceIndex)
})
})
// ================================
// Content Structure Tests
// ================================
describe('Content Structure', () => {
it('should have comma separators between categories', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
const content = subheading.textContent || ''
// Commas should exist between categories
expect(content).toMatch(/Models[^\n\r,\u2028\u2029]*,.*Tools[^\n\r,\u2028\u2029]*,.*Data Sources[^\n\r,\u2028\u2029]*,.*Triggers[^\n\r,\u2028\u2029]*,.*Agent Strategies[^\n\r,\u2028\u2029]*,.*Extensions/)
})
it('should have "and" before last category (Bundles)', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
const content = subheading.textContent || ''
// "and" should appear before Bundles
const andIndex = content.indexOf('and')
const bundlesIndex = content.indexOf('Bundles')
expect(andIndex).toBeLessThan(bundlesIndex)
})
it('should render all text elements in correct order for en-US', () => {
mockDefaultLocale = 'en-US'
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
const content = subheading.textContent || ''
const expectedOrder = [
'Discover',
'Models',
'Tools',
'Data Sources',
'Triggers',
'Agent Strategies',
'Extensions',
'and',
'Bundles',
'in',
'Dify Marketplace',
]
let lastIndex = -1
for (const text of expectedOrder) {
const currentIndex = content.indexOf(text)
expect(currentIndex).toBeGreaterThan(lastIndex)
lastIndex = currentIndex
}
})
it('should render all text elements in correct order for zh-Hans', () => {
mockDefaultLocale = 'zh-Hans'
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
const content = subheading.textContent || ''
// zh-Hans order: in -> Dify Marketplace -> Discover -> categories -> and -> Bundles
const inIndex = content.indexOf('in')
const marketplaceIndex = content.indexOf('Dify Marketplace')
const discoverIndex = content.indexOf('Discover')
const modelsIndex = content.indexOf('Models')
expect(inIndex).toBeLessThan(marketplaceIndex)
expect(marketplaceIndex).toBeLessThan(discoverIndex)
expect(discoverIndex).toBeLessThan(modelsIndex)
})
})
// ================================
// Layout Tests
// ================================
describe('Layout', () => {
it('should have shrink-0 on h1 heading', () => {
render(<Description />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toHaveClass('shrink-0')
})
it('should have shrink-0 on h2 subheading', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading).toHaveClass('shrink-0')
})
it('should have flex layout on h2', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading).toHaveClass('flex')
})
it('should have items-center on h2', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading).toHaveClass('items-center')
})
it('should have justify-center on h2', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading).toHaveClass('justify-center')
})
})
// ================================
// Accessibility Tests
// ================================
describe('Accessibility', () => {
it('should have proper heading hierarchy', () => {
render(<Description />)
const h1 = screen.getByRole('heading', { level: 1 })
const h2 = screen.getByRole('heading', { level: 2 })
expect(h1).toBeInTheDocument()
expect(h2).toBeInTheDocument()
})
it('should have readable text content', () => {
render(<Description />)
const h1 = screen.getByRole('heading', { level: 1 })
expect(h1.textContent).not.toBe('')
})
it('should have visible h1 heading', () => {
render(<Description />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeVisible()
})
it('should have visible h2 heading', () => {
render(<Description />)
const subheading = screen.getByRole('heading', { level: 2 })
expect(subheading).toBeVisible()
})
})
})
// ================================
// Integration Tests
// ================================
describe('Description Integration', () => {
beforeEach(() => {
vi.clearAllMocks()
mockDefaultLocale = 'en-US'
})
it('should render complete component structure', () => {
const { container } = render(<Description />)
// Main headings
expect(container.querySelector('h1')).toBeInTheDocument()
expect(container.querySelector('h2')).toBeInTheDocument()
// All category spans
const categorySpans = container.querySelectorAll('.body-md-medium')
expect(categorySpans.length).toBe(7)
})
it('should render complete zh-Hans structure', () => {
mockDefaultLocale = 'zh-Hans'
const { container } = render(<Description />)
// Main headings
expect(container.querySelector('h1')).toBeInTheDocument()
expect(container.querySelector('h2')).toBeInTheDocument()
// All category spans
const categorySpans = container.querySelectorAll('.body-md-medium')
expect(categorySpans.length).toBe(7)
})
it('should correctly differentiate between zh-Hans and en-US layouts', () => {
// Render en-US
mockDefaultLocale = 'en-US'
const { container: enContainer, unmount: unmountEn } = render(<Description />)
const enContent = enContainer.querySelector('h2')?.textContent || ''
unmountEn()
// Render zh-Hans
mockDefaultLocale = 'zh-Hans'
const { container: zhContainer } = render(<Description />)
const zhContent = zhContainer.querySelector('h2')?.textContent || ''
// Both should have all categories
expect(enContent).toContain('Models')
expect(zhContent).toContain('Models')
// But order should differ
const enMarketplaceIndex = enContent.indexOf('Dify Marketplace')
const enDiscoverIndex = enContent.indexOf('Discover')
const zhMarketplaceIndex = zhContent.indexOf('Dify Marketplace')
const zhDiscoverIndex = zhContent.indexOf('Discover')
// en-US: Discover comes before Dify Marketplace
expect(enDiscoverIndex).toBeLessThan(enMarketplaceIndex)
// zh-Hans: Dify Marketplace comes before Discover
expect(zhMarketplaceIndex).toBeLessThan(zhDiscoverIndex)
})
it('should maintain consistent styling across locales', () => {
// Render en-US
mockDefaultLocale = 'en-US'
const { container: enContainer, unmount: unmountEn } = render(<Description />)
const enCategoryCount = enContainer.querySelectorAll('.body-md-medium').length
unmountEn()
// Render zh-Hans
mockDefaultLocale = 'zh-Hans'
const { container: zhContainer } = render(<Description />)
const zhCategoryCount = zhContainer.querySelectorAll('.body-md-medium').length
// Both should have same number of styled category spans
expect(enCategoryCount).toBe(zhCategoryCount)
expect(enCategoryCount).toBe(7)
})
})
@@ -1,236 +1,72 @@
'use client'
import { useLocale, useTranslation } from '#i18n'
import type { MotionValue } from 'motion/react'
import { useTranslation } from '#i18n'
import { motion, useMotionValue, useSpring, useTransform } from 'motion/react'
import { useEffect, useLayoutEffect, useRef } from 'react'
import marketPlaceBg from '@/public/marketplace/hero-bg.jpg'
import marketplaceGradientNoise from '@/public/marketplace/hero-gradient-noise.svg'
import { cn } from '@/utils/classnames'
import { useCreationType } from '../atoms'
import { PluginCategorySwitch, TemplateCategorySwitch } from '../category-switch/index'
import { CREATION_TYPE } from '../search-params'
type DescriptionProps = {
className?: string
scrollContainerId?: string
marketplaceNav?: React.ReactNode
}
// Constants for collapse animation
const MAX_SCROLL = 120 // pixels to fully collapse
const EXPANDED_PADDING_TOP = 32 // pt-8
const COLLAPSED_PADDING_TOP = 12 // pt-3
const EXPANDED_PADDING_BOTTOM = 24 // pb-6
const COLLAPSED_PADDING_BOTTOM = 12 // pb-3
export const Description = ({
className,
scrollContainerId = 'marketplace-container',
marketplaceNav,
}: DescriptionProps) => {
const Description = () => {
const { t } = useTranslation('plugin')
const creationType = useCreationType()
const isTemplatesView = creationType === CREATION_TYPE.templates
const heroTitleKey = isTemplatesView ? 'marketplace.templatesHeroTitle' : 'marketplace.pluginsHeroTitle'
const heroSubtitleKey = isTemplatesView ? 'marketplace.templatesHeroSubtitle' : 'marketplace.pluginsHeroSubtitle'
const rafRef = useRef<number | null>(null)
const lastProgressRef = useRef(0)
const headerRef = useRef<HTMLDivElement | null>(null)
const titleContentRef = useRef<HTMLDivElement | null>(null)
const progress = useMotionValue(0)
const titleHeight = useMotionValue(72)
const smoothProgress = useSpring(progress, { stiffness: 260, damping: 34 })
const { t: tCommon } = useTranslation('common')
const locale = useLocale()
useLayoutEffect(() => {
const node = titleContentRef.current
if (!node)
return
const updateHeight = () => {
titleHeight.set(node.scrollHeight)
}
updateHeight()
if (typeof ResizeObserver === 'undefined')
return
const observer = new ResizeObserver(updateHeight)
observer.observe(node)
return () => observer.disconnect()
}, [titleHeight])
useEffect(() => {
const container = document.getElementById(scrollContainerId)
if (!container)
return
const handleScroll = () => {
// Cancel any pending animation frame
if (rafRef.current)
cancelAnimationFrame(rafRef.current)
// Use requestAnimationFrame for smooth updates
rafRef.current = requestAnimationFrame(() => {
const scrollTop = Math.round(container.scrollTop)
const heightDelta = container.scrollHeight - container.clientHeight
const effectiveMaxScroll = Math.max(1, Math.min(MAX_SCROLL, heightDelta))
const rawProgress = Math.min(Math.max(scrollTop / effectiveMaxScroll, 0), 1)
const snappedProgress = rawProgress >= 0.95
? 1
: rawProgress <= 0.05
? 0
: Math.round(rawProgress * 100) / 100
if (snappedProgress !== lastProgressRef.current) {
lastProgressRef.current = snappedProgress
progress.set(snappedProgress)
}
})
}
container.addEventListener('scroll', handleScroll, { passive: true })
// Initial check
handleScroll()
return () => {
container.removeEventListener('scroll', handleScroll)
if (rafRef.current)
cancelAnimationFrame(rafRef.current)
}
}, [progress, scrollContainerId])
// Calculate interpolated values
const contentOpacity = useTransform(smoothProgress, [0, 1], [1, 0])
const contentScale = useTransform(smoothProgress, [0, 1], [1, 0.9])
const titleMaxHeight: MotionValue<number> = useTransform(
[smoothProgress, titleHeight],
(values: number[]) => values[1] * (1 - values[0]),
)
const tabsMarginTop = useTransform(smoothProgress, [0, 1], [48, marketplaceNav ? 16 : 0])
const titleMarginTop = useTransform(smoothProgress, [0, 1], [marketplaceNav ? 80 : 0, 0])
const paddingTop = useTransform(smoothProgress, [0, 1], [marketplaceNav ? COLLAPSED_PADDING_TOP : EXPANDED_PADDING_TOP, COLLAPSED_PADDING_TOP])
const paddingBottom = useTransform(smoothProgress, [0, 1], [EXPANDED_PADDING_BOTTOM, COLLAPSED_PADDING_BOTTOM])
useEffect(() => {
const container = document.getElementById(scrollContainerId)
const header = headerRef.current
if (!container || !header)
return
let maxHeaderHeight = 0
let lastAppliedOffset = 0
const updateOffset = () => {
const currentHeaderHeight = Math.round(header.getBoundingClientRect().height)
maxHeaderHeight = Math.max(maxHeaderHeight, currentHeaderHeight)
const collapsedHeight = Math.max(0, maxHeaderHeight - currentHeaderHeight)
const currentScrollableTop = container.scrollHeight - container.clientHeight
const baseScrollableTop = Math.max(0, currentScrollableTop - lastAppliedOffset)
const shouldCompensate = baseScrollableTop <= maxHeaderHeight
const nextOffset = shouldCompensate ? collapsedHeight : 0
const offsetDelta = nextOffset - lastAppliedOffset
if (nextOffset > 0) {
// Only compensate when content is short enough that header collapse can clamp scrollTop.
container.style.setProperty('--marketplace-header-collapse-offset', `${nextOffset}px`)
if (offsetDelta !== 0 && container.scrollTop > 0)
container.scrollTop = Math.max(0, container.scrollTop + offsetDelta)
}
else {
container.style.removeProperty('--marketplace-header-collapse-offset')
}
lastAppliedOffset = nextOffset
}
updateOffset()
if (typeof ResizeObserver === 'undefined') {
return () => {
container.style.removeProperty('--marketplace-header-collapse-offset')
}
}
const observer = new ResizeObserver(updateOffset)
observer.observe(header)
observer.observe(container)
return () => {
observer.disconnect()
container.style.removeProperty('--marketplace-header-collapse-offset')
}
}, [scrollContainerId])
const isZhHans = locale === 'zh-Hans'
return (
<motion.div
ref={headerRef}
className={cn(
'sticky top-[60px] z-20 mx-4 mt-4 shrink-0 overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border px-6',
className,
)}
style={{
paddingTop,
paddingBottom,
}}
>
{/* Blue base background */}
<div className="absolute inset-0 bg-[rgba(0,51,255,0.9)]" />
{/* Decorative image with blend mode - showing top 1/3 of the image */}
<div
className="absolute inset-0 bg-no-repeat opacity-80 mix-blend-lighten"
style={{
backgroundImage: `url(${marketPlaceBg.src})`,
backgroundSize: '110% auto',
backgroundPosition: 'center top',
}}
/>
{/* Gradient & Noise overlay */}
<div
className="pointer-events-none absolute inset-0 bg-cover bg-center bg-no-repeat"
style={{ backgroundImage: `url(${marketplaceGradientNoise.src})` }}
/>
{marketplaceNav}
{/* Content */}
<div className="relative z-10">
{/* Title and subtitle - fade out and scale down */}
<motion.div
style={{
opacity: contentOpacity,
scale: contentScale,
transformOrigin: 'left top',
maxHeight: titleMaxHeight,
overflow: 'hidden',
willChange: 'opacity, transform',
marginTop: titleMarginTop,
}}
>
<div ref={titleContentRef}>
<h1 className="title-4xl-semi-bold mb-2 shrink-0 text-text-primary-on-surface">
{t(heroTitleKey)}
</h1>
<h2 className="body-md-regular shrink-0 text-text-secondary-on-surface">
{t(heroSubtitleKey)}
</h2>
</div>
</motion.div>
{/* Category switch tabs - Plugin or Template based on creationType */}
<motion.div style={{ marginTop: tabsMarginTop }}>
{isTemplatesView
? (
<TemplateCategorySwitch variant="hero" />
)
: (
<PluginCategorySwitch variant="hero" />
)}
</motion.div>
</div>
</motion.div>
<>
<h1 className="title-4xl-semi-bold mb-2 shrink-0 text-center text-text-primary">
{t('marketplace.empower')}
</h1>
<h2 className="body-md-regular flex shrink-0 items-center justify-center text-center text-text-tertiary">
{
isZhHans && (
<>
<span className="mr-1">{tCommon('operation.in')}</span>
{t('marketplace.difyMarketplace')}
{t('marketplace.discover')}
</>
)
}
{
!isZhHans && (
<>
{t('marketplace.discover')}
</>
)
}
<span className="body-md-medium relative z-[1] ml-1 text-text-secondary after:absolute after:bottom-[1.5px] after:left-0 after:h-2 after:w-full after:bg-text-text-selected after:content-['']">
{t('category.models')}
</span>
,
<span className="body-md-medium relative z-[1] ml-1 text-text-secondary after:absolute after:bottom-[1.5px] after:left-0 after:h-2 after:w-full after:bg-text-text-selected after:content-['']">
{t('category.tools')}
</span>
,
<span className="body-md-medium relative z-[1] ml-1 text-text-secondary after:absolute after:bottom-[1.5px] after:left-0 after:h-2 after:w-full after:bg-text-text-selected after:content-['']">
{t('category.datasources')}
</span>
,
<span className="body-md-medium relative z-[1] ml-1 text-text-secondary after:absolute after:bottom-[1.5px] after:left-0 after:h-2 after:w-full after:bg-text-text-selected after:content-['']">
{t('category.triggers')}
</span>
,
<span className="body-md-medium relative z-[1] ml-1 text-text-secondary after:absolute after:bottom-[1.5px] after:left-0 after:h-2 after:w-full after:bg-text-text-selected after:content-['']">
{t('category.agents')}
</span>
,
<span className="body-md-medium relative z-[1] ml-1 mr-1 text-text-secondary after:absolute after:bottom-[1.5px] after:left-0 after:h-2 after:w-full after:bg-text-text-selected after:content-['']">
{t('category.extensions')}
</span>
{t('marketplace.and')}
<span className="body-md-medium relative z-[1] ml-1 mr-1 text-text-secondary after:absolute after:bottom-[1.5px] after:left-0 after:h-2 after:w-full after:bg-text-text-selected after:content-['']">
{t('category.bundles')}
</span>
{
!isZhHans && (
<>
<span className="mr-1">{tCommon('operation.in')}</span>
{t('marketplace.difyMarketplace')}
</>
)
}
</h2>
</>
)
}
export default Description
@@ -3,7 +3,7 @@ import type {
} from '../types'
import type {
CollectionsAndPluginsSearchParams,
PluginCollection,
MarketplaceCollection,
PluginsSearchParams,
} from './types'
import type { PluginsFromMarketplaceResponse } from '@/app/components/plugins/types'
@@ -31,8 +31,8 @@ import {
*/
export const useMarketplaceCollectionsAndPlugins = () => {
const [queryParams, setQueryParams] = useState<CollectionsAndPluginsSearchParams>()
const [pluginCollectionsOverride, setPluginCollections] = useState<PluginCollection[]>()
const [pluginCollectionPluginsMapOverride, setPluginCollectionPluginsMap] = useState<Record<string, Plugin[]>>()
const [marketplaceCollectionsOverride, setMarketplaceCollections] = useState<MarketplaceCollection[]>()
const [marketplaceCollectionPluginsMapOverride, setMarketplaceCollectionPluginsMap] = useState<Record<string, Plugin[]>>()
const {
data,
@@ -54,10 +54,10 @@ export const useMarketplaceCollectionsAndPlugins = () => {
const isLoading = !!queryParams && (isFetching || isPending)
return {
pluginCollections: pluginCollectionsOverride ?? data?.marketplaceCollections,
setPluginCollections,
pluginCollectionPluginsMap: pluginCollectionPluginsMapOverride ?? data?.marketplaceCollectionPluginsMap,
setPluginCollectionPluginsMap,
marketplaceCollections: marketplaceCollectionsOverride ?? data?.marketplaceCollections,
setMarketplaceCollections,
marketplaceCollectionPluginsMap: marketplaceCollectionPluginsMapOverride ?? data?.marketplaceCollectionPluginsMap,
setMarketplaceCollectionPluginsMap,
queryMarketplaceCollectionsAndPlugins,
isLoading,
isSuccess,
@@ -1,17 +0,0 @@
'use client'
import { useHydrateAtoms } from 'jotai/utils'
import { isMarketplacePlatformAtom } from './atoms'
export function HydrateClient({
isMarketplacePlatform = false,
children,
}: {
isMarketplacePlatform?: boolean
children: React.ReactNode
}) {
useHydrateAtoms([
[isMarketplacePlatformAtom, isMarketplacePlatform],
])
return <>{children}</>
}
@@ -1,270 +1,43 @@
import type { SearchParams } from 'nuqs/server'
import type { CreatorSearchParams, PluginsSearchParams, TemplateSearchParams } from './types'
import type { MarketplaceSearchParams } from './search-params'
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { headers } from 'next/headers'
import { createLoader } from 'nuqs/server'
import { getQueryClientServer } from '@/context/query-client-server'
import { marketplaceQuery } from '@/service/client'
import {
CATEGORY_ALL,
DEFAULT_PLUGIN_SORT,
DEFAULT_TEMPLATE_SORT,
getValidatedPluginCategory,
getValidatedTemplateCategory,
PLUGIN_CATEGORY_WITH_COLLECTIONS,
PLUGIN_TYPE_SEARCH_MAP,
} from './constants'
import { CREATION_TYPE, marketplaceSearchParamsParsers, SEARCH_TABS } from './search-params'
import {
getCollectionsParams,
getMarketplaceCollectionsAndPlugins,
getMarketplaceCreators,
getMarketplacePlugins,
getMarketplaceTemplateCollectionsAndTemplates,
getMarketplaceTemplates,
getPluginFilterType,
} from './utils'
import { PLUGIN_CATEGORY_WITH_COLLECTIONS } from './constants'
import { marketplaceSearchParamsParsers } from './search-params'
import { getCollectionsParams, getMarketplaceCollectionsAndPlugins } from './utils'
export type Awaitable<T> = T | PromiseLike<T>
// The server side logic should move to marketplace's codebase so that we can get rid of Next.js
const ZERO_WIDTH_SPACE = '\u200B'
const SEARCH_PREVIEW_SIZE = 8
const SEARCH_PAGE_SIZE = 40
const loadSearchParams = createLoader(marketplaceSearchParamsParsers)
function pickFirstParam(value: string | string[] | undefined) {
if (Array.isArray(value))
return value[0]
return value
}
function getNextPageParam(lastPage: { page: number, page_size: number, total: number }) {
const nextPage = lastPage.page + 1
const loaded = lastPage.page * lastPage.page_size
return loaded < (lastPage.total || 0) ? nextPage : undefined
}
type RouteParams = { category?: string, creationType?: string, searchTab?: string } | undefined
async function shouldSkipServerPrefetch() {
const requestHeaders = await headers()
return requestHeaders.get('sec-fetch-dest') !== 'document'
}
async function getDehydratedState(
params?: Awaitable<RouteParams>,
searchParams?: Awaitable<SearchParams>,
) {
if (await shouldSkipServerPrefetch())
async function getDehydratedState(searchParams?: Promise<SearchParams>) {
if (!searchParams) {
return
const rawParams = params ? await params : undefined
const rawSearchParams = searchParams ? await searchParams : undefined
const parsedSearchParams = await loadSearchParams(Promise.resolve(rawSearchParams ?? {}))
const routeState = rawSearchParams as SearchParams & {
category?: string | string[]
creationType?: string | string[]
searchTab?: string | string[]
}
const loadSearchParams = createLoader(marketplaceSearchParamsParsers)
const params: MarketplaceSearchParams = await loadSearchParams(searchParams)
const creationTypeFromSearch = pickFirstParam(routeState?.creationType)
const categoryFromSearch = pickFirstParam(routeState?.category)
const searchTabFromSearch = pickFirstParam(routeState?.searchTab)
const creationType = rawParams?.creationType === CREATION_TYPE.templates || creationTypeFromSearch === CREATION_TYPE.templates
? CREATION_TYPE.templates
: CREATION_TYPE.plugins
const category = creationType === CREATION_TYPE.templates
? getValidatedTemplateCategory(rawParams?.category ?? categoryFromSearch ?? CATEGORY_ALL)
: getValidatedPluginCategory(rawParams?.category ?? categoryFromSearch ?? CATEGORY_ALL)
const searchTabRaw = rawParams?.searchTab ?? searchTabFromSearch ?? ''
const searchTab = SEARCH_TABS.includes(searchTabRaw as (typeof SEARCH_TABS)[number])
? searchTabRaw as (typeof SEARCH_TABS)[number]
: ''
if (!PLUGIN_CATEGORY_WITH_COLLECTIONS.has(params.category)) {
return
}
const queryClient = getQueryClientServer()
const prefetches: Promise<void>[] = []
if (searchTab) {
const searchText = parsedSearchParams.q
const query = searchText === ZERO_WIDTH_SPACE ? '' : searchText.trim()
const hasQuery = !!searchText && (!!query || searchText === ZERO_WIDTH_SPACE)
if (!hasQuery)
return
const pageSize = searchTab === 'all' ? SEARCH_PREVIEW_SIZE : SEARCH_PAGE_SIZE
const searchFilterType = getValidatedPluginCategory(parsedSearchParams.searchType)
const fetchPlugins = searchTab === 'all' || searchTab === 'plugins'
const fetchTemplates = searchTab === 'all' || searchTab === 'templates'
const fetchCreators = searchTab === 'all' || searchTab === 'creators'
if (fetchPlugins) {
const pluginCategory = searchTab === 'plugins' && searchFilterType !== CATEGORY_ALL
? searchFilterType
: undefined
const searchFilterTags = searchTab === 'plugins' && parsedSearchParams.searchTags.length > 0
? parsedSearchParams.searchTags
: undefined
const pluginsParams: PluginsSearchParams = {
query,
page_size: pageSize,
sort_by: DEFAULT_PLUGIN_SORT.sortBy,
sort_order: DEFAULT_PLUGIN_SORT.sortOrder,
category: pluginCategory,
tags: searchFilterTags,
type: getPluginFilterType(pluginCategory || PLUGIN_TYPE_SEARCH_MAP.all),
}
prefetches.push(queryClient.prefetchInfiniteQuery({
queryKey: marketplaceQuery.plugins.searchAdvanced.queryKey({
input: {
body: pluginsParams,
params: { kind: pluginsParams.type === 'bundle' ? 'bundles' : 'plugins' },
},
}),
queryFn: ({ pageParam = 1, signal }) => getMarketplacePlugins(pluginsParams, pageParam, signal),
getNextPageParam,
initialPageParam: 1,
}))
}
if (fetchTemplates) {
const templateCategories = searchTab === 'templates' && parsedSearchParams.searchCategories.length > 0
? parsedSearchParams.searchCategories
: undefined
const templateLanguages = searchTab === 'templates' && parsedSearchParams.searchLanguages.length > 0
? parsedSearchParams.searchLanguages
: undefined
const templatesParams: TemplateSearchParams = {
query,
page_size: pageSize,
sort_by: DEFAULT_TEMPLATE_SORT.sortBy,
sort_order: DEFAULT_TEMPLATE_SORT.sortOrder,
categories: templateCategories,
languages: templateLanguages,
}
prefetches.push(queryClient.prefetchInfiniteQuery({
queryKey: marketplaceQuery.templates.searchAdvanced.queryKey({
input: {
body: templatesParams,
},
}),
queryFn: ({ pageParam = 1, signal }) => getMarketplaceTemplates(templatesParams, pageParam, signal),
getNextPageParam,
initialPageParam: 1,
}))
}
if (fetchCreators) {
const creatorsParams: CreatorSearchParams = {
query,
page_size: pageSize,
}
prefetches.push(queryClient.prefetchInfiniteQuery({
queryKey: marketplaceQuery.creators.searchAdvanced.queryKey({
input: {
body: creatorsParams,
},
}),
queryFn: ({ pageParam = 1, signal }) => getMarketplaceCreators(creatorsParams, pageParam, signal),
getNextPageParam,
initialPageParam: 1,
}))
}
}
else if (creationType === CREATION_TYPE.templates) {
prefetches.push(queryClient.prefetchQuery({
queryKey: marketplaceQuery.templateCollections.list.queryKey({ input: { query: undefined } }),
queryFn: () => getMarketplaceTemplateCollectionsAndTemplates(),
}))
const isSearchMode = !!parsedSearchParams.q
|| category !== CATEGORY_ALL
|| parsedSearchParams.languages.length > 0
if (isSearchMode) {
const templatesParams: TemplateSearchParams = {
query: parsedSearchParams.q,
categories: category === CATEGORY_ALL ? undefined : [category],
sort_by: DEFAULT_TEMPLATE_SORT.sortBy,
sort_order: DEFAULT_TEMPLATE_SORT.sortOrder,
...(parsedSearchParams.languages.length > 0 ? { languages: parsedSearchParams.languages } : {}),
}
prefetches.push(queryClient.prefetchInfiniteQuery({
queryKey: marketplaceQuery.templates.searchAdvanced.queryKey({
input: {
body: templatesParams,
},
}),
queryFn: ({ pageParam = 1, signal }) => getMarketplaceTemplates(templatesParams, pageParam, signal),
getNextPageParam,
initialPageParam: 1,
}))
}
}
else {
const pluginCategory = getValidatedPluginCategory(category)
const collectionsParams = getCollectionsParams(pluginCategory)
prefetches.push(queryClient.prefetchQuery({
queryKey: marketplaceQuery.plugins.collections.queryKey({ input: { query: collectionsParams } }),
queryFn: () => getMarketplaceCollectionsAndPlugins(collectionsParams),
}))
const isSearchMode = !!parsedSearchParams.q
|| parsedSearchParams.tags.length > 0
|| !PLUGIN_CATEGORY_WITH_COLLECTIONS.has(pluginCategory)
if (isSearchMode) {
const pluginsParams: PluginsSearchParams = {
query: parsedSearchParams.q,
category: pluginCategory === CATEGORY_ALL ? undefined : pluginCategory,
tags: parsedSearchParams.tags,
sort_by: DEFAULT_PLUGIN_SORT.sortBy,
sort_order: DEFAULT_PLUGIN_SORT.sortOrder,
type: getPluginFilterType(pluginCategory),
}
prefetches.push(queryClient.prefetchInfiniteQuery({
queryKey: marketplaceQuery.plugins.searchAdvanced.queryKey({
input: {
body: pluginsParams,
params: { kind: pluginsParams.type === 'bundle' ? 'bundles' : 'plugins' },
},
}),
queryFn: ({ pageParam = 1, signal }) => getMarketplacePlugins(pluginsParams, pageParam, signal),
getNextPageParam,
initialPageParam: 1,
}))
}
}
if (!prefetches.length)
return
await Promise.all(prefetches)
await queryClient.prefetchQuery({
queryKey: marketplaceQuery.collections.queryKey({ input: { query: getCollectionsParams(params.category) } }),
queryFn: () => getMarketplaceCollectionsAndPlugins(getCollectionsParams(params.category)),
})
return dehydrate(queryClient)
}
export async function HydrateQueryClient({
params,
searchParams,
isMarketplacePlatform = false,
children,
}: {
params?: Awaitable<{ category?: string, creationType?: string, searchTab?: string } | undefined>
searchParams?: Awaitable<SearchParams>
isMarketplacePlatform?: boolean
searchParams: Promise<SearchParams> | undefined
children: React.ReactNode
}) {
const dehydratedState = isMarketplacePlatform ? await getDehydratedState(params, searchParams) : null
const dehydratedState = await getDehydratedState(searchParams)
return (
<HydrationBoundary state={dehydratedState}>
{children}
@@ -1,48 +1,34 @@
import type { SearchParams } from 'nuqs'
import type { Awaitable } from './hydration-server'
import { TanstackQueryInitializer } from '@/context/query-client'
import { cn } from '@/utils/classnames'
import { HydrateClient } from './hydration-client'
import Description from './description'
import { HydrateQueryClient } from './hydration-server'
import MarketplaceContent from './marketplace-content'
import MarketplaceHeader from './marketplace-header'
import ListWrapper from './list/list-wrapper'
import StickySearchAndSwitchWrapper from './sticky-search-and-switch-wrapper'
type MarketplaceProps = {
showInstallButton?: boolean
pluginTypeSwitchClassName?: string
/**
* Pass the search params & params from the request to prefetch data on the server.
* Pass the search params from the request to prefetch data on the server.
*/
params?: Awaitable<{ category?: string, creationType?: string, searchTab?: string } | undefined>
searchParams?: Awaitable<SearchParams>
/**
* Whether the marketplace is the platform marketplace.
*/
isMarketplacePlatform?: boolean
marketplaceNav?: React.ReactNode
searchParams?: Promise<SearchParams>
}
const Marketplace = ({
const Marketplace = async ({
showInstallButton = true,
params,
pluginTypeSwitchClassName,
searchParams,
isMarketplacePlatform = false,
marketplaceNav,
}: MarketplaceProps) => {
return (
<TanstackQueryInitializer>
<HydrateQueryClient
isMarketplacePlatform={isMarketplacePlatform}
searchParams={searchParams}
params={params}
>
<HydrateClient
isMarketplacePlatform={isMarketplacePlatform}
>
<MarketplaceHeader descriptionClassName={cn('mx-12 mt-1', isMarketplacePlatform && 'top-0 mx-0 mt-0 rounded-none')} marketplaceNav={marketplaceNav} />
<MarketplaceContent
showInstallButton={showInstallButton}
/>
</HydrateClient>
<HydrateQueryClient searchParams={searchParams}>
<Description />
<StickySearchAndSwitchWrapper
pluginTypeSwitchClassName={pluginTypeSwitchClassName}
/>
<ListWrapper
showInstallButton={showInstallButton}
/>
</HydrateQueryClient>
</TanstackQueryInitializer>
)
@@ -1,4 +1,4 @@
import type { PluginCollection, SearchParamsFromCollection } from '../../types'
import type { MarketplaceCollection, SearchParamsFromCollection } from '../../types'
import type { Plugin } from '@/app/components/plugins/types'
import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -20,7 +20,6 @@ vi.mock('#i18n', () => ({
'plugin.marketplace.viewMore': 'View More',
'plugin.marketplace.pluginsResult': `${options?.num || 0} plugins found`,
'plugin.marketplace.noPluginFound': 'No plugins found',
'plugin.marketplace.noTemplateFound': 'No template found',
'plugin.detailPanel.operation.install': 'Install',
'plugin.detailPanel.operation.detail': 'Detail',
}
@@ -35,28 +34,21 @@ const { mockMarketplaceData, mockMoreClick } = vi.hoisted(() => {
mockMarketplaceData: {
plugins: undefined as Plugin[] | undefined,
pluginsTotal: 0,
pluginCollections: undefined as PluginCollection[] | undefined,
pluginCollectionPluginsMap: undefined as Record<string, Plugin[]> | undefined,
marketplaceCollections: undefined as MarketplaceCollection[] | undefined,
marketplaceCollectionPluginsMap: undefined as Record<string, Plugin[]> | undefined,
isLoading: false,
page: 1,
},
mockMoreClick: vi.fn(),
}
})
let mockSearchMode = false
vi.mock('../../state', () => ({
useMarketplaceData: () => mockMarketplaceData,
isPluginsData: (data: Record<string, unknown>) => 'pluginCollections' in data,
}))
vi.mock('../../atoms', () => ({
useMarketplaceMoreClick: () => mockMoreClick,
useMarketplaceSearchMode: () => mockSearchMode,
useCreationType: () => 'plugins',
useFilterPluginTags: () => [[]],
useActivePluginCategory: () => ['all'],
useActiveTemplateCategory: () => ['all'],
}))
vi.mock('@/context/i18n', () => ({
@@ -107,17 +99,12 @@ vi.mock('@/i18n-config/language', () => ({
getLanguage: (locale: string) => locale || 'en-US',
}))
// Mock marketplace utils
vi.mock('../../utils', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../utils')>()
return {
...actual,
getPluginLinkInMarketplace: (plugin: Plugin, _params?: Record<string, string | undefined>) =>
`/plugin/${plugin.org}/${plugin.name}`,
getPluginDetailLinkInMarketplace: (plugin: Plugin) =>
`/plugin/${plugin.org}/${plugin.name}`,
}
})
vi.mock('../../utils', () => ({
getPluginLinkInMarketplace: (plugin: Plugin, _params?: Record<string, string | undefined>) =>
`/plugins/${plugin.org}/${plugin.name}`,
getPluginDetailLinkInMarketplace: (plugin: Plugin) =>
`/plugins/${plugin.org}/${plugin.name}`,
}))
vi.mock('@/app/components/plugins/card', () => ({
default: ({ payload, footer }: { payload: Plugin, footer?: React.ReactNode }) => (
@@ -129,10 +116,10 @@ vi.mock('@/app/components/plugins/card', () => ({
),
}))
// Mock CardTags component
vi.mock('@/app/components/plugins/card/card-tags', () => ({
default: ({ tags }: { tags: string[] }) => (
<div data-testid="card-tags">
vi.mock('@/app/components/plugins/card/card-more-info', () => ({
default: ({ downloadCount, tags }: { downloadCount: number, tags: string[] }) => (
<div data-testid="card-more-info">
<span data-testid="download-count">{downloadCount}</span>
<span data-testid="tags">{tags.join(',')}</span>
</div>
),
@@ -152,11 +139,10 @@ vi.mock('../../sort-dropdown', () => ({
),
}))
// Mock Empty component
vi.mock('../../empty', () => ({
default: ({ className, text }: { className?: string, text?: string }) => (
default: ({ className }: { className?: string }) => (
<div data-testid="empty-component" className={className}>
{text || 'No plugins found'}
No plugins found
</div>
),
}))
@@ -202,7 +188,7 @@ const createMockPluginList = (count: number): Plugin[] =>
label: { 'en-US': `Plugin ${i}` },
}))
const createMockCollection = (overrides?: Partial<PluginCollection>): PluginCollection => ({
const createMockCollection = (overrides?: Partial<MarketplaceCollection>): MarketplaceCollection => ({
name: `collection-${Math.random().toString(36).substring(7)}`,
label: { 'en-US': 'Test Collection' },
description: { 'en-US': 'Test collection description' },
@@ -214,7 +200,7 @@ const createMockCollection = (overrides?: Partial<PluginCollection>): PluginColl
...overrides,
})
const createMockCollectionList = (count: number): PluginCollection[] =>
const createMockCollectionList = (count: number): MarketplaceCollection[] =>
Array.from({ length: count }, (_, i) =>
createMockCollection({
name: `collection-${i}`,
@@ -227,8 +213,8 @@ const createMockCollectionList = (count: number): PluginCollection[] =>
// ================================
describe('List', () => {
const defaultProps = {
pluginCollections: [] as PluginCollection[],
pluginCollectionPluginsMap: {} as Record<string, Plugin[]>,
marketplaceCollections: [] as MarketplaceCollection[],
marketplaceCollectionPluginsMap: {} as Record<string, Plugin[]>,
plugins: undefined,
showInstallButton: false,
cardContainerClassName: '',
@@ -239,7 +225,6 @@ describe('List', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSearchMode = false
})
// ================================
@@ -263,8 +248,8 @@ describe('List', () => {
render(
<List
{...defaultProps}
pluginCollections={collections}
pluginCollectionPluginsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -309,8 +294,8 @@ describe('List', () => {
render(
<List
{...defaultProps}
pluginCollections={collections}
pluginCollectionPluginsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
plugins={[]}
/>,
)
@@ -421,12 +406,12 @@ describe('List', () => {
// Edge Cases Tests
// ================================
describe('Edge Cases', () => {
it('should handle empty pluginCollections', () => {
it('should handle empty marketplaceCollections', () => {
render(
<List
{...defaultProps}
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
/>,
)
@@ -443,8 +428,8 @@ describe('List', () => {
render(
<List
{...defaultProps}
pluginCollections={collections}
pluginCollectionPluginsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
plugins={undefined}
/>,
)
@@ -491,12 +476,12 @@ describe('List', () => {
// ================================
describe('ListWithCollection', () => {
const defaultProps = {
variant: 'plugins' as const,
collections: [] as PluginCollection[],
collectionItemsMap: {} as Record<string, Plugin[]>,
marketplaceCollections: [] as MarketplaceCollection[],
marketplaceCollectionPluginsMap: {} as Record<string, Plugin[]>,
showInstallButton: false,
cardContainerClassName: '',
cardRender: undefined,
onMoreClick: undefined,
}
beforeEach(() => {
@@ -523,8 +508,8 @@ describe('ListWithCollection', () => {
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -543,8 +528,8 @@ describe('ListWithCollection', () => {
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -563,8 +548,8 @@ describe('ListWithCollection', () => {
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -577,21 +562,21 @@ describe('ListWithCollection', () => {
// View More Button Tests
// ================================
describe('View More Button', () => {
it('should render View More button when collection is searchable and exceeds display limit', () => {
it('should render View More button when collection is searchable', () => {
const collections = [createMockCollection({
name: 'searchable-collection',
name: 'collection-0',
searchable: true,
search_params: { query: 'test' },
})]
const pluginsMap: Record<string, Plugin[]> = {
'searchable-collection': createMockPluginList(5),
'collection-0': createMockPluginList(1),
}
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -602,38 +587,16 @@ describe('ListWithCollection', () => {
const collections = [createMockCollection({
name: 'collection-0',
searchable: false,
search_params: undefined,
})]
const pluginsMap: Record<string, Plugin[]> = {
'collection-0': createMockPluginList(5),
'collection-0': createMockPluginList(1),
}
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
/>,
)
expect(screen.queryByText('View More')).not.toBeInTheDocument()
})
it('should not render View More button when items do not exceed display limit', () => {
const collections = [createMockCollection({
name: 'small-collection',
searchable: true,
search_params: { query: 'test' },
})]
const pluginsMap: Record<string, Plugin[]> = {
'small-collection': createMockPluginList(4),
}
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -643,106 +606,26 @@ describe('ListWithCollection', () => {
it('should call moreClick hook with search_params when View More is clicked', () => {
const searchParams: SearchParamsFromCollection = { query: 'test-query', sort_by: 'install_count' }
const collections = [createMockCollection({
name: 'clickable-collection',
name: 'collection-0',
searchable: true,
search_params: searchParams,
})]
const pluginsMap: Record<string, Plugin[]> = {
'clickable-collection': createMockPluginList(5),
'collection-0': createMockPluginList(1),
}
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
fireEvent.click(screen.getByText('View More'))
expect(mockMoreClick).toHaveBeenCalledTimes(1)
expect(mockMoreClick).toHaveBeenCalledWith(searchParams, undefined)
})
})
// ================================
// Grid Display Limit Tests
// ================================
describe('Grid Display Limit', () => {
it('should render at most 4 cards for searchable collections', () => {
const collections = createMockCollectionList(1)
const pluginsMap: Record<string, Plugin[]> = {
'collection-0': createMockPluginList(8),
}
const { container } = render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
/>,
)
const cards = container.querySelectorAll('[data-testid^="card-plugin-"]')
expect(cards.length).toBe(4)
})
it('should render all cards for non-searchable collections in carousel mode', () => {
const collections = [createMockCollection({
name: 'carousel-collection',
searchable: false,
})]
const pluginsMap: Record<string, Plugin[]> = {
'carousel-collection': createMockPluginList(8),
}
const { container } = render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
/>,
)
const cards = container.querySelectorAll('[data-testid^="card-plugin-"]')
expect(cards.length).toBe(8)
})
it('should render all cards when count is within the display limit', () => {
const collections = createMockCollectionList(1)
const pluginsMap: Record<string, Plugin[]> = {
'collection-0': createMockPluginList(3),
}
const { container } = render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
/>,
)
const cards = container.querySelectorAll('[data-testid^="card-plugin-"]')
expect(cards.length).toBe(3)
})
it('should render exactly 4 cards when collection has exactly 4 items', () => {
const collections = createMockCollectionList(1)
const pluginsMap: Record<string, Plugin[]> = {
'collection-0': createMockPluginList(4),
}
const { container } = render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
/>,
)
const cards = container.querySelectorAll('[data-testid^="card-plugin-"]')
expect(cards.length).toBe(4)
expect(mockMoreClick).toHaveBeenCalledWith(searchParams)
})
})
@@ -766,8 +649,8 @@ describe('ListWithCollection', () => {
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
cardRender={customCardRender}
/>,
)
@@ -790,8 +673,8 @@ describe('ListWithCollection', () => {
const { container } = render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
cardContainerClassName="custom-container"
/>,
)
@@ -808,8 +691,8 @@ describe('ListWithCollection', () => {
const { container } = render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
showInstallButton={true}
/>,
)
@@ -827,8 +710,8 @@ describe('ListWithCollection', () => {
render(
<ListWithCollection
{...defaultProps}
collections={[]}
collectionItemsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
/>,
)
@@ -843,8 +726,8 @@ describe('ListWithCollection', () => {
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -861,8 +744,8 @@ describe('ListWithCollection', () => {
render(
<ListWithCollection
{...defaultProps}
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -878,12 +761,11 @@ describe('ListWithCollection', () => {
describe('ListWrapper', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSearchMode = false
// Reset mock data
mockMarketplaceData.plugins = undefined
mockMarketplaceData.pluginsTotal = 0
mockMarketplaceData.pluginCollections = undefined
mockMarketplaceData.pluginCollectionPluginsMap = undefined
mockMarketplaceData.marketplaceCollections = undefined
mockMarketplaceData.marketplaceCollectionPluginsMap = undefined
mockMarketplaceData.isLoading = false
mockMarketplaceData.page = 1
})
@@ -922,52 +804,22 @@ describe('ListWrapper', () => {
expect(screen.queryByTestId('loading-component')).not.toBeInTheDocument()
})
it('should render template empty state with flex content wrapper when templates are empty', () => {
mockSearchMode = true
delete (mockMarketplaceData as Record<string, unknown>).pluginCollections
delete (mockMarketplaceData as Record<string, unknown>).pluginCollectionPluginsMap
;(mockMarketplaceData as Record<string, unknown>).templateCollections = []
;(mockMarketplaceData as Record<string, unknown>).templateCollectionTemplatesMap = {}
;(mockMarketplaceData as Record<string, unknown>).templates = []
const { container } = render(<ListWrapper />)
expect(screen.getByTestId('empty-component')).toBeInTheDocument()
expect(screen.getByText('No template found')).toBeInTheDocument()
expect(container.querySelector('.relative.flex.grow.flex-col')).toBeInTheDocument()
})
it('should keep plugin empty text when plugins are empty', () => {
mockSearchMode = true
mockMarketplaceData.plugins = []
mockMarketplaceData.pluginsTotal = 0
mockMarketplaceData.pluginCollections = []
mockMarketplaceData.pluginCollectionPluginsMap = {}
render(<ListWrapper />)
expect(screen.getByTestId('empty-component')).toBeInTheDocument()
expect(screen.getByText('No plugins found')).toBeInTheDocument()
})
})
// ================================
// Plugins Header Tests
// ================================
describe('Plugins Header', () => {
it('should render list top info when search mode is enabled', () => {
mockSearchMode = true
it('should render plugins result count when plugins are present', () => {
mockMarketplaceData.plugins = createMockPluginList(5)
mockMarketplaceData.pluginsTotal = 5
render(<ListWrapper />)
expect(screen.getByTestId('sort-dropdown')).toBeInTheDocument()
expect(screen.getByText('5 plugins found')).toBeInTheDocument()
})
it('should render SortDropdown when plugins are present', () => {
mockSearchMode = true
mockMarketplaceData.plugins = createMockPluginList(1)
render(<ListWrapper />)
@@ -990,8 +842,8 @@ describe('ListWrapper', () => {
describe('List Rendering Logic', () => {
it('should render collections when not loading', () => {
mockMarketplaceData.isLoading = false
mockMarketplaceData.pluginCollections = createMockCollectionList(1)
mockMarketplaceData.pluginCollectionPluginsMap = {
mockMarketplaceData.marketplaceCollections = createMockCollectionList(1)
mockMarketplaceData.marketplaceCollectionPluginsMap = {
'collection-0': createMockPluginList(1),
}
@@ -1003,8 +855,8 @@ describe('ListWrapper', () => {
it('should render List when loading but page > 1', () => {
mockMarketplaceData.isLoading = true
mockMarketplaceData.page = 2
mockMarketplaceData.pluginCollections = createMockCollectionList(1)
mockMarketplaceData.pluginCollectionPluginsMap = {
mockMarketplaceData.marketplaceCollections = createMockCollectionList(1)
mockMarketplaceData.marketplaceCollectionPluginsMap = {
'collection-0': createMockPluginList(1),
}
@@ -1028,13 +880,13 @@ describe('ListWrapper', () => {
})
it('should show View More button and call moreClick hook', () => {
mockMarketplaceData.pluginCollections = [createMockCollection({
name: 'wrapper-collection',
mockMarketplaceData.marketplaceCollections = [createMockCollection({
name: 'collection-0',
searchable: true,
search_params: { query: 'test' },
})]
mockMarketplaceData.pluginCollectionPluginsMap = {
'wrapper-collection': createMockPluginList(5),
mockMarketplaceData.marketplaceCollectionPluginsMap = {
'collection-0': createMockPluginList(1),
}
render(<ListWrapper />)
@@ -1050,28 +902,25 @@ describe('ListWrapper', () => {
// ================================
describe('Edge Cases', () => {
it('should handle empty plugins array', () => {
mockSearchMode = true
mockMarketplaceData.plugins = []
mockMarketplaceData.pluginsTotal = 0
render(<ListWrapper />)
expect(screen.getByText('0 plugins found')).toBeInTheDocument()
expect(screen.getByTestId('empty-component')).toBeInTheDocument()
})
it('should handle many plugin results', () => {
mockSearchMode = true
it('should handle large pluginsTotal', () => {
mockMarketplaceData.plugins = createMockPluginList(10)
mockMarketplaceData.pluginsTotal = 10000
render(<ListWrapper />)
expect(screen.getByTestId('card-plugin-0')).toBeInTheDocument()
expect(screen.getByTestId('card-plugin-9')).toBeInTheDocument()
expect(screen.getByText('10000 plugins found')).toBeInTheDocument()
})
it('should handle both loading and has plugins', () => {
mockSearchMode = true
mockMarketplaceData.isLoading = true
mockMarketplaceData.page = 2
mockMarketplaceData.plugins = createMockPluginList(5)
@@ -1079,7 +928,9 @@ describe('ListWrapper', () => {
render(<ListWrapper />)
expect(screen.getByTestId('card-plugin-0')).toBeInTheDocument()
// Should show plugins header and list
expect(screen.getByText('50 plugins found')).toBeInTheDocument()
// Should not show loading because page > 1
expect(screen.queryByTestId('loading-component')).not.toBeInTheDocument()
})
})
@@ -1103,8 +954,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
/>,
)
@@ -1112,7 +963,7 @@ describe('CardWrapper (via List integration)', () => {
expect(screen.getByTestId('card-test-plugin')).toBeInTheDocument()
})
it('should render CardTags with tags', () => {
it('should render CardMoreInfo with download count and tags', () => {
const plugin = createMockPlugin({
name: 'test-plugin',
install_count: 5000,
@@ -1121,13 +972,14 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
/>,
)
expect(screen.getByTestId('card-tags')).toBeInTheDocument()
expect(screen.getByTestId('card-more-info')).toBeInTheDocument()
expect(screen.getByTestId('download-count')).toHaveTextContent('5000')
})
})
@@ -1140,8 +992,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={plugins}
/>,
)
@@ -1160,8 +1012,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
/>,
@@ -1180,8 +1032,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
/>,
@@ -1201,15 +1053,15 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
/>,
)
const detailLink = screen.getByText('Detail').closest('a')
expect(detailLink).toHaveAttribute('href', '/plugin/test-org/link-test-plugin')
expect(detailLink).toHaveAttribute('href', '/plugins/test-org/link-test-plugin')
expect(detailLink).toHaveAttribute('target', '_blank')
})
@@ -1219,8 +1071,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
/>,
@@ -1235,8 +1087,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
/>,
@@ -1251,8 +1103,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
/>,
@@ -1277,8 +1129,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={false}
/>,
@@ -1297,8 +1149,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={false}
/>,
@@ -1312,8 +1164,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
/>,
)
@@ -1335,8 +1187,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
/>,
)
@@ -1352,8 +1204,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
/>,
)
@@ -1369,8 +1221,8 @@ describe('CardWrapper (via List integration)', () => {
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
/>,
)
@@ -1391,8 +1243,8 @@ describe('Combined Workflows', () => {
mockMarketplaceData.pluginsTotal = 0
mockMarketplaceData.isLoading = false
mockMarketplaceData.page = 1
mockMarketplaceData.pluginCollections = undefined
mockMarketplaceData.pluginCollectionPluginsMap = undefined
mockMarketplaceData.marketplaceCollections = undefined
mockMarketplaceData.marketplaceCollectionPluginsMap = undefined
})
it('should transition from loading to showing collections', async () => {
@@ -1405,8 +1257,8 @@ describe('Combined Workflows', () => {
// Simulate loading complete
mockMarketplaceData.isLoading = false
mockMarketplaceData.pluginCollections = createMockCollectionList(1)
mockMarketplaceData.pluginCollectionPluginsMap = {
mockMarketplaceData.marketplaceCollections = createMockCollectionList(1)
mockMarketplaceData.marketplaceCollectionPluginsMap = {
'collection-0': createMockPluginList(1),
}
@@ -1417,9 +1269,8 @@ describe('Combined Workflows', () => {
})
it('should transition from collections to search results', async () => {
mockSearchMode = true
mockMarketplaceData.pluginCollections = createMockCollectionList(1)
mockMarketplaceData.pluginCollectionPluginsMap = {
mockMarketplaceData.marketplaceCollections = createMockCollectionList(1)
mockMarketplaceData.marketplaceCollectionPluginsMap = {
'collection-0': createMockPluginList(1),
}
@@ -1434,21 +1285,20 @@ describe('Combined Workflows', () => {
rerender(<ListWrapper />)
expect(screen.queryByText('Collection 0')).not.toBeInTheDocument()
expect(screen.getByTestId('card-plugin-0')).toBeInTheDocument()
expect(screen.getByText('5 plugins found')).toBeInTheDocument()
})
it('should handle empty search results', () => {
mockSearchMode = true
mockMarketplaceData.plugins = []
mockMarketplaceData.pluginsTotal = 0
render(<ListWrapper />)
expect(screen.getByTestId('empty-component')).toBeInTheDocument()
expect(screen.getByText('0 plugins found')).toBeInTheDocument()
})
it('should support pagination (page > 1)', () => {
mockSearchMode = true
mockMarketplaceData.plugins = createMockPluginList(40)
mockMarketplaceData.pluginsTotal = 80
mockMarketplaceData.isLoading = true
@@ -1456,7 +1306,9 @@ describe('Combined Workflows', () => {
render(<ListWrapper />)
expect(screen.getByTestId('card-plugin-0')).toBeInTheDocument()
// Should show existing results while loading more
expect(screen.getByText('80 plugins found')).toBeInTheDocument()
// Should not show loading spinner for pagination
expect(screen.queryByTestId('loading-component')).not.toBeInTheDocument()
})
})
@@ -1480,9 +1332,8 @@ describe('Accessibility', () => {
const { container } = render(
<ListWithCollection
variant="plugins"
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -1493,19 +1344,17 @@ describe('Accessibility', () => {
it('should have clickable View More button', () => {
const collections = [createMockCollection({
name: 'accessible-collection',
name: 'collection-0',
searchable: true,
search_params: { query: 'test' },
})]
const pluginsMap: Record<string, Plugin[]> = {
'accessible-collection': createMockPluginList(5),
'collection-0': createMockPluginList(1),
}
render(
<ListWithCollection
variant="plugins"
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
@@ -1519,13 +1368,13 @@ describe('Accessibility', () => {
const { container } = render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={plugins}
/>,
)
const grid = container.querySelector('.grid')
const grid = container.querySelector('.grid-cols-4')
expect(grid).toBeInTheDocument()
})
})
@@ -1544,8 +1393,8 @@ describe('Performance', () => {
const startTime = performance.now()
render(
<List
pluginCollections={[]}
pluginCollectionPluginsMap={{}}
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={plugins}
/>,
)
@@ -1565,9 +1414,8 @@ describe('Performance', () => {
const startTime = performance.now()
render(
<ListWithCollection
variant="plugins"
collections={collections}
collectionItemsMap={pluginsMap}
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
/>,
)
const endTime = performance.now()
@@ -8,7 +8,7 @@ import * as React from 'react'
import { useMemo } from 'react'
import Button from '@/app/components/base/button'
import Card from '@/app/components/plugins/card'
import CardTags from '@/app/components/plugins/card/card-tags'
import CardMoreInfo from '@/app/components/plugins/card/card-more-info'
import { useTags } from '@/app/components/plugins/hooks'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
import { getPluginDetailLinkInMarketplace, getPluginLinkInMarketplace } from '../utils'
@@ -43,13 +43,14 @@ const CardWrapperComponent = ({
if (showInstallButton) {
return (
<div
className="group relative cursor-pointer rounded-xl hover:bg-components-panel-on-panel-item-bg-hover"
className="group relative cursor-pointer rounded-xl hover:bg-components-panel-on-panel-item-bg-hover"
>
<Card
key={plugin.name}
payload={plugin}
footer={(
<CardTags
<CardMoreInfo
downloadCount={plugin.install_count}
tags={tagLabels}
/>
)}
@@ -87,15 +88,15 @@ const CardWrapperComponent = ({
return (
<a
className="group relative block cursor-pointer rounded-xl"
className="group relative inline-block cursor-pointer rounded-xl"
href={getPluginDetailLinkInMarketplace(plugin)}
>
<Card
key={plugin.name}
payload={plugin}
disableOrgLink
footer={(
<CardTags
<CardMoreInfo
downloadCount={plugin.install_count}
tags={tagLabels}
/>
)}
@@ -1,128 +0,0 @@
'use client'
import type { RemixiconComponentType } from '@remixicon/react'
import { RiArrowLeftSLine, RiArrowRightSLine } from '@remixicon/react'
import { useMemo } from 'react'
import { Carousel as BaseCarousel, useCarousel } from '@/app/components/base/carousel'
import { cn } from '@/utils/classnames'
type CarouselProps = {
children: React.ReactNode
className?: string
gap?: number
showNavigation?: boolean
showPagination?: boolean
autoPlay?: boolean
autoPlayInterval?: number
}
type NavButtonProps = {
direction: 'left' | 'right'
disabled: boolean
onClick: () => void
Icon: RemixiconComponentType
}
const NavButton = ({ direction, disabled, onClick, Icon }: NavButtonProps) => (
<button
className={cn(
'flex items-center justify-center rounded-full border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg p-2 shadow-xs backdrop-blur-[5px] transition-all',
disabled
? 'cursor-not-allowed opacity-50'
: 'cursor-pointer hover:bg-components-button-secondary-bg-hover',
)}
onClick={onClick}
disabled={disabled}
aria-label={`Scroll ${direction}`}
>
<Icon className="h-4 w-4 text-components-button-secondary-text" />
</button>
)
type CarouselControlsProps = {
showPagination: boolean
}
const CarouselControls = ({ showPagination }: CarouselControlsProps) => {
const { api, selectedIndex, scrollPrev, scrollNext } = useCarousel()
const scrollSnaps = api?.scrollSnapList() ?? []
const totalPages = scrollSnaps.length
if (totalPages <= 1)
return null
return (
<div className="absolute -top-10 right-0 flex items-center gap-3">
{showPagination && (
<div className="flex items-center gap-1">
{scrollSnaps.map((snap, index) => (
<button
key={snap}
className={cn(
'h-[5px] w-[5px] rounded-full transition-all',
selectedIndex === index
? 'w-4 bg-components-button-primary-bg'
: 'bg-components-button-secondary-border hover:bg-components-button-secondary-border-hover',
)}
onClick={() => api?.scrollTo(index)}
aria-label={`Go to page ${index + 1}`}
/>
))}
</div>
)}
<div className="flex items-center gap-1">
<NavButton
direction="left"
disabled={totalPages <= 1}
onClick={scrollPrev}
Icon={RiArrowLeftSLine}
/>
<NavButton
direction="right"
disabled={totalPages <= 1}
onClick={scrollNext}
Icon={RiArrowRightSLine}
/>
</div>
</div>
)
}
const Carousel = ({
children,
className,
gap = 12,
showNavigation = true,
showPagination = true,
autoPlay = false,
autoPlayInterval = 5000,
}: CarouselProps) => {
const plugins = useMemo(() => {
if (!autoPlay)
return []
return [
BaseCarousel.Plugin.Autoplay({
delay: autoPlayInterval,
stopOnInteraction: false,
stopOnMouseEnter: true,
}),
]
}, [autoPlay, autoPlayInterval])
return (
<BaseCarousel
opts={{ align: 'start', containScroll: 'trimSnaps', loop: true }}
plugins={plugins}
className={className}
overlay={showNavigation ? <CarouselControls showPagination={showPagination} /> : null}
>
<BaseCarousel.Content style={{ columnGap: `${gap}px` }}>
{children}
</BaseCarousel.Content>
</BaseCarousel>
)
}
export default Carousel
@@ -1,34 +0,0 @@
export const GRID_CLASS = 'grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
export const GRID_DISPLAY_LIMIT = 4
export const CAROUSEL_PAGE_CLASS = 'w-full shrink-0'
export const CAROUSEL_PAGE_GRID_CLASS = 'grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
export const CAROUSEL_PAGE_SIZE = {
base: 2,
sm: 4,
lg: 6,
xl: 8,
} as const
export const CAROUSEL_BREAKPOINTS = {
sm: 640,
lg: 1024,
xl: 1280,
} as const
/** Collection name key that triggers carousel display (plugins: partners, templates: featured) */
export const CAROUSEL_COLLECTION_NAMES = {
partners: 'partners',
featured: 'featured',
} as const
export type BaseCollection = {
name: string
label: Record<string, string>
description: Record<string, string>
searchable?: boolean
search_params?: { query?: string, sort_by?: string, sort_order?: string }
}
@@ -1,246 +0,0 @@
'use client'
import type { SearchTab } from '../search-params'
import type { SearchParamsFromCollection } from '../types'
import type { BaseCollection } from './collection-constants'
import type { Locale } from '@/i18n-config/language'
import { useLocale, useTranslation } from '#i18n'
import { RiArrowRightSLine, RiArrowRightUpLine } from '@remixicon/react'
import { useEffect, useMemo, useState } from 'react'
import { renderI18nObject } from '@/i18n-config'
import { getLanguage } from '@/i18n-config/language'
import { cn } from '@/utils/classnames'
import { useMarketplaceMoreClick } from '../atoms'
import Empty from '../empty'
import { buildCarouselPages, getItemKeyByField } from '../utils'
import Carousel from './carousel'
import {
CAROUSEL_BREAKPOINTS,
CAROUSEL_PAGE_CLASS,
CAROUSEL_PAGE_GRID_CLASS,
CAROUSEL_PAGE_SIZE,
GRID_CLASS,
GRID_DISPLAY_LIMIT,
} from './collection-constants'
const getViewportWidth = () => typeof window === 'undefined' ? CAROUSEL_BREAKPOINTS.xl : window.innerWidth
const getCarouselItemsPerPage = (viewportWidth: number) => {
if (viewportWidth >= CAROUSEL_BREAKPOINTS.xl)
return CAROUSEL_PAGE_SIZE.xl
if (viewportWidth >= CAROUSEL_BREAKPOINTS.lg)
return CAROUSEL_PAGE_SIZE.lg
if (viewportWidth >= CAROUSEL_BREAKPOINTS.sm)
return CAROUSEL_PAGE_SIZE.sm
return CAROUSEL_PAGE_SIZE.base
}
type ViewMoreButtonProps = {
searchParams?: SearchParamsFromCollection
searchTab?: SearchTab
}
export function ViewMoreButton({ searchParams, searchTab }: ViewMoreButtonProps) {
const { t } = useTranslation()
const onMoreClick = useMarketplaceMoreClick()
return (
<div
className="flex cursor-pointer items-center text-text-accent system-xs-medium"
onClick={() => onMoreClick(searchParams, searchTab)}
>
{t('marketplace.viewMore', { ns: 'plugin' })}
<RiArrowRightSLine className="h-4 w-4" />
</div>
)
}
type CollectionHeaderProps<TCollection extends BaseCollection> = {
collection: TCollection
itemsLength: number
locale: Locale
viewMore: React.ReactNode
}
export function CollectionHeader<TCollection extends BaseCollection>({
collection,
itemsLength,
locale,
viewMore,
}: CollectionHeaderProps<TCollection>) {
const showViewMore = collection.searchable
&& !!collection.search_params
&& itemsLength > GRID_DISPLAY_LIMIT
// The API only ships translations for a subset of locales (e.g. en_US and
// zh_Hans). For any other locale (e.g. ja_JP, pt_BR, zh_Hant before fix)
// the keyed lookup returns undefined and the title/description render as
// empty divs. `renderI18nObject` from `@/i18n-config` handles the fallback
// chain (locale → en_US → first available value) consistently across the
// codebase.
const lang = getLanguage(locale)
const label = renderI18nObject(collection.label, lang)
const description = renderI18nObject(collection.description, lang)
// Plugin marketplace uses `partners`, Template marketplace uses `Partner Template`.
const isPartnersCollection = collection.name === 'partners' || collection.name === 'partner-template' || collection.name === 'Partner Template'
return (
<div className="mb-2 flex items-end justify-between">
<div>
<div className="text-text-primary title-xl-semi-bold">
{label}
</div>
<div className="text-text-tertiary system-xs-regular flex items-center gap-x-2">
<span>{description}</span>
{isPartnersCollection && (
<>
<span className="text-divider-regular">|</span>
<a
href="https://share-na2.hsforms.com/1NiS4r9lsSqGcuNBB77DeEQ40s9fk"
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-x-0.5 text-text-accent hover:underline"
>
<span>Become a Partner</span>
<RiArrowRightUpLine className="h-3.5 w-3.5" />
</a>
</>
)}
</div>
</div>
{showViewMore && viewMore}
</div>
)
}
type CarouselCollectionProps<TItem> = {
items: TItem[]
getItemKey: (item: TItem) => string
renderCard: (item: TItem) => React.ReactNode
cardContainerClassName?: string
}
export function CarouselCollection<TItem>({
items,
getItemKey,
renderCard,
cardContainerClassName,
}: CarouselCollectionProps<TItem>) {
const [viewportWidth, setViewportWidth] = useState(getViewportWidth)
useEffect(() => {
const handleResize = () => setViewportWidth(window.innerWidth)
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
const itemsPerPage = useMemo(() => getCarouselItemsPerPage(viewportWidth), [viewportWidth])
const pages = useMemo(() => buildCarouselPages(items, itemsPerPage), [items, itemsPerPage])
const hasMultiplePages = pages.length > 1
return (
<Carousel
showNavigation={hasMultiplePages}
showPagination={hasMultiplePages}
autoPlay={hasMultiplePages}
autoPlayInterval={5000}
>
{pages.map((pageItems, idx) => (
<div
key={pageItems[0] ? getItemKey(pageItems[0]) : idx}
className={CAROUSEL_PAGE_CLASS}
style={{ scrollSnapAlign: 'start' }}
>
<div className={cn(CAROUSEL_PAGE_GRID_CLASS, cardContainerClassName)}>
{pageItems.map(item => (
<div key={getItemKey(item)}>{renderCard(item)}</div>
))}
</div>
</div>
))}
</Carousel>
)
}
type CollectionListProps<TItem, TCollection extends BaseCollection> = {
collections: TCollection[]
collectionItemsMap: Record<string, TItem[]>
/** Field name to use as item key (e.g. 'plugin_id', 'id'). */
itemKeyField: keyof TItem
renderCard: (item: TItem) => React.ReactNode
/** Search tab for ViewMoreButton (e.g. 'templates' for template collections). */
viewMoreSearchTab?: SearchTab
gridClassName?: string
cardContainerClassName?: string
emptyClassName?: string
emptyText?: string
}
function CollectionList<TItem, TCollection extends BaseCollection>({
collections,
collectionItemsMap,
itemKeyField,
renderCard,
viewMoreSearchTab,
gridClassName = GRID_CLASS,
cardContainerClassName,
emptyClassName,
emptyText,
}: CollectionListProps<TItem, TCollection>) {
const locale = useLocale()
const collectionsWithItems = collections.filter((collection) => {
return collectionItemsMap[collection.name]?.length
})
if (collectionsWithItems.length === 0) {
return <Empty className={emptyClassName} text={emptyText} />
}
return (
<>
{
collectionsWithItems.map((collection) => {
const items = collectionItemsMap[collection.name]
return (
<div
key={collection.name}
className="py-3"
>
<CollectionHeader
collection={collection}
itemsLength={items.length}
locale={locale}
viewMore={<ViewMoreButton searchParams={collection.search_params} searchTab={viewMoreSearchTab} />}
/>
{!collection.searchable
? (
<CarouselCollection
items={items}
getItemKey={item => getItemKeyByField(item, itemKeyField)}
renderCard={renderCard}
cardContainerClassName={cardContainerClassName}
/>
)
: (
<div className={cn(gridClassName, cardContainerClassName)}>
{items.slice(0, GRID_DISPLAY_LIMIT).map(item => (
<div key={getItemKeyByField(item, itemKeyField)}>
{renderCard(item)}
</div>
))}
</div>
)}
</div>
)
})
}
</>
)
}
export default CollectionList
@@ -1,61 +0,0 @@
'use client'
import type { Template } from '../types'
import type { Plugin } from '@/app/components/plugins/types'
import { useTranslation } from '#i18n'
import Empty from '../empty'
import CardWrapper from './card-wrapper'
import { GRID_CLASS } from './collection-constants'
import TemplateCard from './template-card'
type PluginsVariant = {
variant: 'plugins'
items: Plugin[]
showInstallButton?: boolean
}
type TemplatesVariant = {
variant: 'templates'
items: Template[]
}
type FlatListProps = PluginsVariant | TemplatesVariant
const FlatList = (props: FlatListProps) => {
const { items, variant } = props
const { t } = useTranslation()
if (!items.length) {
if (variant === 'templates')
return <Empty text={t('marketplace.noTemplateFound', { ns: 'plugin' })} />
return <Empty />
}
if (variant === 'plugins') {
const { showInstallButton } = props
return (
<div className={GRID_CLASS}>
{items.map(plugin => (
<CardWrapper
key={`${plugin.org}/${plugin.name}`}
plugin={plugin}
showInstallButton={showInstallButton}
/>
))}
</div>
)
}
return (
<div className={GRID_CLASS}>
{items.map(template => (
<TemplateCard
key={template.id}
template={template}
/>
))}
</div>
)
}
export default FlatList
@@ -1,16 +1,14 @@
'use client'
import type { Plugin } from '../../types'
import type { PluginCollection } from '../types'
import type { MarketplaceCollection } from '../types'
import { cn } from '@/utils/classnames'
import Empty from '../empty'
import CardWrapper from './card-wrapper'
import { GRID_CLASS } from './collection-constants'
import ListWithCollection from './list-with-collection'
type ListProps = {
pluginCollections: PluginCollection[]
pluginCollectionPluginsMap: Record<string, Plugin[]>
marketplaceCollections: MarketplaceCollection[]
marketplaceCollectionPluginsMap: Record<string, Plugin[]>
plugins?: Plugin[]
showInstallButton?: boolean
cardContainerClassName?: string
@@ -18,8 +16,8 @@ type ListProps = {
emptyClassName?: string
}
const List = ({
pluginCollections,
pluginCollectionPluginsMap,
marketplaceCollections,
marketplaceCollectionPluginsMap,
plugins,
showInstallButton,
cardContainerClassName,
@@ -31,9 +29,8 @@ const List = ({
{
!plugins && (
<ListWithCollection
variant="plugins"
collections={pluginCollections}
collectionItemsMap={pluginCollectionPluginsMap}
marketplaceCollections={marketplaceCollections}
marketplaceCollectionPluginsMap={marketplaceCollectionPluginsMap}
showInstallButton={showInstallButton}
cardContainerClassName={cardContainerClassName}
cardRender={cardRender}
@@ -42,7 +39,11 @@ const List = ({
}
{
plugins && !!plugins.length && (
<div className={cn(GRID_CLASS, cardContainerClassName)}>
<div className={cn(
'grid grid-cols-4 gap-3',
cardContainerClassName,
)}
>
{
plugins.map((plugin) => {
if (cardRender)
@@ -1,71 +0,0 @@
'use client'
import { useTranslation } from '#i18n'
import {
useActivePluginCategory,
useActiveTemplateCategory,
useCreationType,
useFilterPluginTags,
} from '../atoms'
import { usePluginCategoryText, useTemplateCategoryText } from '../category-switch/category-text'
import {
CATEGORY_ALL,
} from '../constants'
import { CREATION_TYPE } from '../search-params'
import SortDropdown from '../sort-dropdown'
const ListTopInfo = () => {
const creationType = useCreationType()
const { t } = useTranslation()
const [filterPluginTags] = useFilterPluginTags()
const [activePluginCategory] = useActivePluginCategory()
const [activeTemplateCategory] = useActiveTemplateCategory()
const getPluginCategoryText = usePluginCategoryText()
const getTemplateCategoryText = useTemplateCategoryText()
const isPluginsView = creationType === CREATION_TYPE.plugins
const hasTags = isPluginsView && filterPluginTags.length > 0
if (hasTags) {
return (
<div className="mb-4 flex items-center justify-between pt-3">
<p className="title-xl-semi-bold text-text-primary">
{t('marketplace.listTopInfo.tagsTitle', { ns: 'plugin' })}
</p>
<SortDropdown />
</div>
)
}
const isAllCategory = isPluginsView
? activePluginCategory === CATEGORY_ALL
: activeTemplateCategory === CATEGORY_ALL
const categoryText = isPluginsView
? getPluginCategoryText(activePluginCategory)
: getTemplateCategoryText(activeTemplateCategory)
const title = t(
`marketplace.listTopInfo.${creationType}${isAllCategory ? 'TitleAll' : 'TitleByCategory'}`,
isAllCategory
? { ns: 'plugin' }
: { ns: 'plugin', category: categoryText },
)
return (
<div className="mb-4 flex items-center justify-between pt-3">
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="title-xl-semi-bold truncate text-text-primary">
{title}
</p>
<p className="system-xs-regular truncate text-text-tertiary">
{t(`marketplace.listTopInfo.${creationType}Subtitle`, { ns: 'plugin' })}
</p>
</div>
<SortDropdown />
</div>
)
}
export default ListTopInfo
@@ -1,83 +1,83 @@
'use client'
import type { PluginCollection, Template, TemplateCollection } from '../types'
import type { MarketplaceCollection } from '../types'
import type { Plugin } from '@/app/components/plugins/types'
import { useTranslation } from '#i18n'
import { useLocale, useTranslation } from '#i18n'
import { RiArrowRightSLine } from '@remixicon/react'
import { getLanguage } from '@/i18n-config/language'
import { cn } from '@/utils/classnames'
import { useMarketplaceMoreClick } from '../atoms'
import CardWrapper from './card-wrapper'
import CollectionList from './collection-list'
import TemplateCard from './template-card'
type BaseProps = {
cardContainerClassName?: string
}
type PluginsVariant = BaseProps & {
variant: 'plugins'
collections: PluginCollection[]
collectionItemsMap: Record<string, Plugin[]>
type ListWithCollectionProps = {
marketplaceCollections: MarketplaceCollection[]
marketplaceCollectionPluginsMap: Record<string, Plugin[]>
showInstallButton?: boolean
cardContainerClassName?: string
cardRender?: (plugin: Plugin) => React.JSX.Element | null
}
type TemplatesVariant = BaseProps & {
variant: 'templates'
collections: TemplateCollection[]
collectionItemsMap: Record<string, Template[]>
}
type ListWithCollectionProps = PluginsVariant | TemplatesVariant
const ListWithCollection = (props: ListWithCollectionProps) => {
const { variant, cardContainerClassName } = props
const ListWithCollection = ({
marketplaceCollections,
marketplaceCollectionPluginsMap,
showInstallButton,
cardContainerClassName,
cardRender,
}: ListWithCollectionProps) => {
const { t } = useTranslation()
if (variant === 'plugins') {
const {
collections,
collectionItemsMap,
showInstallButton,
cardRender,
} = props
const renderPluginCard = (plugin: Plugin) => {
if (cardRender)
return cardRender(plugin)
return (
<CardWrapper
plugin={plugin}
showInstallButton={showInstallButton}
/>
)
}
return (
<CollectionList
collections={collections}
collectionItemsMap={collectionItemsMap}
itemKeyField="plugin_id"
renderCard={renderPluginCard}
cardContainerClassName={cardContainerClassName}
/>
)
}
const { collections, collectionItemsMap } = props
const renderTemplateCard = (template: Template) => (
<TemplateCard template={template} />
)
const locale = useLocale()
const onMoreClick = useMarketplaceMoreClick()
return (
<CollectionList
collections={collections}
collectionItemsMap={collectionItemsMap}
itemKeyField="id"
renderCard={renderTemplateCard}
viewMoreSearchTab="templates"
cardContainerClassName={cardContainerClassName}
emptyText={t('marketplace.noTemplateFound', { ns: 'plugin' })}
/>
<>
{
marketplaceCollections.filter((collection) => {
return marketplaceCollectionPluginsMap[collection.name]?.length
}).map(collection => (
<div
key={collection.name}
className="py-3"
>
<div className="flex items-end justify-between">
<div>
<div className="title-xl-semi-bold text-text-primary">{collection.label[getLanguage(locale)]}</div>
<div className="system-xs-regular text-text-tertiary">{collection.description[getLanguage(locale)]}</div>
</div>
{
collection.searchable && (
<div
className="system-xs-medium flex cursor-pointer items-center text-text-accent "
onClick={() => onMoreClick(collection.search_params)}
>
{t('marketplace.viewMore', { ns: 'plugin' })}
<RiArrowRightSLine className="h-4 w-4" />
</div>
)
}
</div>
<div className={cn(
'mt-2 grid grid-cols-4 gap-3',
cardContainerClassName,
)}
>
{
marketplaceCollectionPluginsMap[collection.name].map((plugin) => {
if (cardRender)
return cardRender(plugin)
return (
<CardWrapper
key={plugin.plugin_id}
plugin={plugin}
showInstallButton={showInstallButton}
/>
)
})
}
</div>
</div>
))
}
</>
)
}
@@ -1,89 +0,0 @@
import type { Template } from '../types'
import type { Plugin } from '@/app/components/plugins/types'
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import ListWrapper from './list-wrapper'
const { mockMarketplaceData } = vi.hoisted(() => ({
mockMarketplaceData: {
creationType: 'plugins' as 'plugins' | 'templates',
isLoading: false,
page: 1,
isFetchingNextPage: false,
pluginCollections: [],
pluginCollectionPluginsMap: {},
plugins: undefined as Plugin[] | undefined,
templateCollections: [],
templateCollectionTemplatesMap: {},
templates: undefined as Template[] | undefined,
},
}))
vi.mock('../state', () => ({
useMarketplaceData: () => mockMarketplaceData,
isPluginsData: (data: typeof mockMarketplaceData) => data.creationType === 'plugins',
}))
vi.mock('../atoms', () => ({
useMarketplaceSearchMode: () => false,
}))
vi.mock('@/app/components/base/loading', () => ({
default: () => <div data-testid="loading-component">Loading</div>,
}))
vi.mock('./flat-list', () => ({
default: ({ variant, items }: { variant: 'plugins' | 'templates', items: unknown[] }) => (
<div data-testid={`flat-list-${variant}`}>
{items.length}
</div>
),
}))
vi.mock('./list-with-collection', () => ({
default: ({ variant }: { variant: 'plugins' | 'templates' }) => (
<div data-testid={`collection-list-${variant}`}>collection</div>
),
}))
describe('ListWrapper flat rendering', () => {
beforeEach(() => {
vi.clearAllMocks()
mockMarketplaceData.creationType = 'plugins'
mockMarketplaceData.isLoading = false
mockMarketplaceData.page = 1
mockMarketplaceData.isFetchingNextPage = false
mockMarketplaceData.plugins = undefined
mockMarketplaceData.templates = undefined
})
it('renders plugin flat list when plugin items exist', () => {
mockMarketplaceData.creationType = 'plugins'
mockMarketplaceData.plugins = [{ org: 'o', name: 'p' } as Plugin]
render(<ListWrapper />)
expect(screen.getByTestId('flat-list-plugins')).toBeInTheDocument()
expect(screen.queryByTestId('collection-list-plugins')).not.toBeInTheDocument()
})
it('renders template flat list when template items exist', () => {
mockMarketplaceData.creationType = 'templates'
mockMarketplaceData.templates = [{ id: 't1' } as Template]
render(<ListWrapper />)
expect(screen.getByTestId('flat-list-templates')).toBeInTheDocument()
expect(screen.queryByTestId('collection-list-templates')).not.toBeInTheDocument()
})
it('renders template collection list when templates are undefined', () => {
mockMarketplaceData.creationType = 'templates'
mockMarketplaceData.templates = undefined
render(<ListWrapper />)
expect(screen.getByTestId('collection-list-templates')).toBeInTheDocument()
expect(screen.queryByTestId('flat-list-templates')).not.toBeInTheDocument()
})
})
@@ -1,70 +1,64 @@
'use client'
import { useTranslation } from '#i18n'
import Loading from '@/app/components/base/loading'
import { useMarketplaceSearchMode } from '../atoms'
import { isPluginsData, useMarketplaceData } from '../state'
import FlatList from './flat-list'
import ListTopInfo from './list-top-info'
import ListWithCollection from './list-with-collection'
import SortDropdown from '../sort-dropdown'
import { useMarketplaceData } from '../state'
import List from './index'
type ListWrapperProps = {
showInstallButton?: boolean
}
const ListWrapper = ({
showInstallButton,
}: ListWrapperProps) => {
const { t } = useTranslation()
const ListWrapper = ({ showInstallButton }: ListWrapperProps) => {
const marketplaceData = useMarketplaceData()
const { isLoading, page, isFetchingNextPage } = marketplaceData
const isSearchMode = useMarketplaceSearchMode()
const renderContent = () => {
if (isPluginsData(marketplaceData)) {
const { pluginCollections, pluginCollectionPluginsMap, plugins } = marketplaceData
return plugins !== undefined
? (
<FlatList variant="plugins" items={plugins} showInstallButton={showInstallButton} />
)
: (
<ListWithCollection
variant="plugins"
collections={pluginCollections || []}
collectionItemsMap={pluginCollectionPluginsMap || {}}
showInstallButton={showInstallButton}
/>
)
}
const { templateCollections, templateCollectionTemplatesMap, templates } = marketplaceData
return templates !== undefined
? (
<FlatList variant="templates" items={templates} />
)
: (
<ListWithCollection
variant="templates"
collections={templateCollections || []}
collectionItemsMap={templateCollectionTemplatesMap || {}}
/>
)
}
const {
plugins,
pluginsTotal,
marketplaceCollections,
marketplaceCollectionPluginsMap,
isLoading,
isFetchingNextPage,
page,
} = useMarketplaceData()
return (
<div
style={{
scrollbarGutter: 'stable',
paddingBottom: 'calc(0.5rem + var(--marketplace-header-collapse-offset, 0px))',
}}
className="relative flex grow flex-col bg-background-default-subtle px-12 pt-2"
style={{ scrollbarGutter: 'stable' }}
className="relative flex grow flex-col bg-background-default-subtle px-12 py-2"
>
{isSearchMode && <ListTopInfo />}
<div className="relative flex grow flex-col">
{isLoading && page === 1 && (
{
plugins && (
<div className="mb-4 flex items-center pt-3">
<div className="title-xl-semi-bold text-text-primary">{t('marketplace.pluginsResult', { ns: 'plugin', num: pluginsTotal })}</div>
<div className="mx-3 h-3.5 w-[1px] bg-divider-regular"></div>
<SortDropdown />
</div>
)
}
{
isLoading && page === 1 && (
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
<Loading />
</div>
)}
{(!isLoading || page > 1) && renderContent()}
</div>
{isFetchingNextPage && <Loading className="my-3" />}
)
}
{
(!isLoading || page > 1) && (
<List
marketplaceCollections={marketplaceCollections || []}
marketplaceCollectionPluginsMap={marketplaceCollectionPluginsMap || {}}
plugins={plugins}
showInstallButton={showInstallButton}
/>
)
}
{
isFetchingNextPage && (
<Loading className="my-3" />
)
}
</div>
)
}
@@ -1,259 +0,0 @@
import type { Template } from '../types'
import { render } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import TemplateCard from './template-card'
// Mock AppIcon component to capture props for assertion
vi.mock('@/app/components/base/app-icon', () => ({
default: ({ size, iconType, icon, imageUrl, background }: {
size?: string
iconType?: string
icon?: string
imageUrl?: string | null
background?: string | null
}) => (
<span
data-testid="app-icon"
data-size={size}
data-icon-type={iconType}
data-icon={icon}
data-image-url={imageUrl || ''}
data-background={background || ''}
/>
),
}))
// Mock i18n
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) => {
if (key === 'marketplace.templateCard.by')
return `by ${options?.author || ''}`
if (key === 'usedCount')
return `${options?.num || 0} used`
return key
},
}),
useLocale: () => 'en-US',
}))
// Mock next/link
vi.mock('next/link', () => ({
default: ({ children, href, ...props }: { children: React.ReactNode, href: string }) => (
<a href={href} {...props}>{children}</a>
),
}))
vi.mock('@/hooks/use-theme', () => ({
default: () => ({ theme: 'light' }),
}))
// Mock marketplace utils
vi.mock('@/utils/get-icon', () => ({
getIconFromMarketPlace: (id: string) => `https://marketplace.dify.ai/api/v1/plugins/${id}/icon`,
}))
vi.mock('@/utils/template', () => ({
formatUsedCount: (count: number) => String(count),
}))
vi.mock('@/utils/var', () => ({
getMarketplaceUrl: (path: string) => `https://marketplace.dify.ai${path}`,
}))
vi.mock('@/app/components/plugins/card/base/corner-mark', () => ({
default: ({ text }: { text: string }) => <span data-testid="corner-mark">{text}</span>,
}))
// Mock marketplace utils (getTemplateIconUrl) while keeping other exports intact.
vi.mock('../utils', async () => {
const actual = await vi.importActual<typeof import('../utils')>('../utils')
return {
...actual,
getTemplateIconUrl: (template: { id: string, icon?: string, icon_file_key?: string }): string => {
if (template.icon?.startsWith('http'))
return template.icon
if (template.icon_file_key)
return `https://marketplace.dify.ai/api/v1/templates/${template.id}/icon`
return ''
},
}
})
// ================================
// Test Data Factories
// ================================
const createMockTemplate = (overrides?: Partial<Template>): Template => ({
id: 'test-template-id',
index_id: 'test-template-id',
template_name: 'test-template',
icon: '📄',
icon_background: '',
icon_file_key: '',
categories: ['Agent'],
overview: 'A test template',
readme: 'readme content',
partner_link: '',
deps_plugins: [],
preferred_languages: ['en'],
publisher_handle: 'test-publisher',
publisher_type: 'individual',
kind: 'classic',
status: 'published',
usage_count: 100,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
...overrides,
})
// ================================
// Tests
// ================================
describe('TemplateCard', () => {
describe('Icon Rendering via AppIcon', () => {
it('should pass emoji id to AppIcon when icon is an emoji id like sweat_smile', () => {
const template = createMockTemplate({ icon: 'sweat_smile' })
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
expect(appIcon).toBeInTheDocument()
expect(appIcon?.getAttribute('data-icon-type')).toBe('emoji')
expect(appIcon?.getAttribute('data-icon')).toBe('sweat_smile')
expect(appIcon?.getAttribute('data-size')).toBe('large')
})
it('should pass unicode emoji to AppIcon when icon is a unicode character', () => {
const template = createMockTemplate({ icon: '😅' })
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
expect(appIcon).toBeInTheDocument()
expect(appIcon?.getAttribute('data-icon-type')).toBe('emoji')
expect(appIcon?.getAttribute('data-icon')).toBe('😅')
})
it('should pass default fallback icon to AppIcon when icon and icon_file_key are both empty', () => {
const template = createMockTemplate({ icon: '', icon_file_key: '' })
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
expect(appIcon).toBeInTheDocument()
expect(appIcon?.getAttribute('data-icon-type')).toBe('emoji')
expect(appIcon?.getAttribute('data-icon')).toBe('📄')
})
it('should pass image URL to AppIcon when icon is a URL', () => {
const template = createMockTemplate({ icon: 'https://example.com/icon.png' })
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
expect(appIcon).toBeInTheDocument()
expect(appIcon?.getAttribute('data-icon-type')).toBe('image')
expect(appIcon?.getAttribute('data-image-url')).toBe('https://example.com/icon.png')
// icon prop should not be set for URL icons
expect(appIcon?.hasAttribute('data-icon')).toBe(false)
})
it('should resolve image URL from icon_file_key when icon is empty but icon_file_key is set', () => {
const template = createMockTemplate({
id: 'tpl-123',
icon: '',
icon_file_key: 'fa3b0f86-bc64-47ec-ad83-8e3cfc6739ae.jpg',
})
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
expect(appIcon).toBeInTheDocument()
expect(appIcon?.getAttribute('data-icon-type')).toBe('image')
expect(appIcon?.getAttribute('data-image-url')).toBe('https://marketplace.dify.ai/api/v1/templates/tpl-123/icon')
// icon prop should not be set when rendering as image
expect(appIcon?.hasAttribute('data-icon')).toBe(false)
})
it('should prefer icon URL over icon_file_key when both are present', () => {
const template = createMockTemplate({
icon: 'https://example.com/custom-icon.png',
icon_file_key: 'fa3b0f86-bc64-47ec-ad83-8e3cfc6739ae.jpg',
})
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
expect(appIcon?.getAttribute('data-icon-type')).toBe('image')
expect(appIcon?.getAttribute('data-image-url')).toBe('https://example.com/custom-icon.png')
})
})
describe('Avatar Background', () => {
it('should pass icon_background to AppIcon when provided', () => {
const template = createMockTemplate({ icon: 'sweat_smile', icon_background: '#FFEAD5' })
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
expect(appIcon?.getAttribute('data-background')).toBe('#FFEAD5')
})
it('should not pass background to AppIcon when icon_background is empty', () => {
const template = createMockTemplate({ icon: 'sweat_smile', icon_background: '' })
const { container } = render(<TemplateCard template={template} />)
const appIcon = container.querySelector('[data-testid="app-icon"]')
// Empty string means no background was passed (undefined becomes '')
expect(appIcon?.getAttribute('data-background')).toBe('')
})
})
describe('Sandbox', () => {
it('should render CornerMark when kind is sandboxed', () => {
const template = createMockTemplate({ kind: 'sandboxed' })
const { container } = render(<TemplateCard template={template} />)
const cornerMark = container.querySelector('[data-testid="corner-mark"]')
expect(cornerMark).toBeInTheDocument()
expect(cornerMark?.textContent).toBe('Sandbox')
})
it('should not render CornerMark when kind is classic', () => {
const template = createMockTemplate({ kind: 'classic' })
const { container } = render(<TemplateCard template={template} />)
const cornerMark = container.querySelector('[data-testid="corner-mark"]')
expect(cornerMark).not.toBeInTheDocument()
})
})
describe('Creator Link', () => {
it('should append publisher_type query to creator link', () => {
const template = createMockTemplate({ publisher_type: 'organization' })
const { getByText } = render(<TemplateCard template={template} />)
const creatorLink = getByText('test-publisher').closest('a')
expect(creatorLink).toHaveAttribute('href', '/creator/test-publisher?publisher_type=organization')
})
})
describe('Deps Plugins', () => {
it('should render dep plugin icons', () => {
const template = createMockTemplate({
deps_plugins: ['langgenius/google-search', 'langgenius/dalle'],
})
const { container } = render(<TemplateCard template={template} />)
const pluginIcons = container.querySelectorAll('.h-6.w-6 img')
expect(pluginIcons.length).toBe(2)
})
it('should show +N when deps_plugins exceed MAX_VISIBLE_DEPS_PLUGINS', () => {
const deps = Array.from({ length: 10 }, (_, i) => `org/plugin-${i}`)
const template = createMockTemplate({ deps_plugins: deps })
const { container } = render(<TemplateCard template={template} />)
// Should show 7 visible + "+3"
const pluginIcons = container.querySelectorAll('.h-6.w-6 img')
expect(pluginIcons.length).toBe(7)
expect(container.textContent).toContain('+3')
})
})
})
@@ -1,153 +0,0 @@
'use client'
import type { Template } from '../types'
import { useLocale, useTranslation } from '#i18n'
import Link from 'next/link'
import * as React from 'react'
import { useMemo } from 'react'
import AppIcon from '@/app/components/base/app-icon'
import { MARKETPLACE_URL_PREFIX } from '@/config'
import useTheme from '@/hooks/use-theme'
import { cn } from '@/utils/classnames'
import { getIconFromMarketPlace } from '@/utils/get-icon'
import { formatUsedCount } from '@/utils/template'
import { getMarketplaceUrl } from '@/utils/var'
import Partner from '../../base/badges/partner'
import { buildSearchParamsString, getTemplateIconUrl } from '../utils'
type TemplateCardProps = {
template: Template
className?: string
includeSource?: boolean
}
// Number of tag icons to show before showing "+X"
const MAX_VISIBLE_DEPS_PLUGINS = 7
const TemplateCardComponent = ({
template,
className,
includeSource = false,
}: TemplateCardProps) => {
const locale = useLocale()
const { t } = useTranslation()
const { theme } = useTheme()
const { id, template_name, overview, icon, publisher_handle, publisher_type, usage_count, icon_background, deps_plugins, badges = [] } = template
// const isSandbox = kind === 'sandboxed'
const iconUrl = getTemplateIconUrl(template)
const isPartner = badges.includes('partner')
const href = useMemo(() => {
const queryParams = {
theme,
language: locale,
templateId: id,
creationType: 'templates',
}
const encodedPublisherHandle = encodeURIComponent(publisher_handle)
const encodedTemplateName = encodeURIComponent(template_name)
return includeSource
? getMarketplaceUrl(`/template/${encodedPublisherHandle}/${encodedTemplateName}`, queryParams)
: `${MARKETPLACE_URL_PREFIX}/template/${encodedPublisherHandle}/${encodedTemplateName}?${buildSearchParamsString(queryParams)}`
}, [publisher_handle, template_name, theme, locale, id, includeSource])
const visibleDepsPlugins = deps_plugins?.slice(0, MAX_VISIBLE_DEPS_PLUGINS) || []
const remainingDepsPluginsCount = deps_plugins ? Math.max(0, deps_plugins.length - MAX_VISIBLE_DEPS_PLUGINS) : 0
const formattedUsedCount = formatUsedCount(usage_count, { precision: 0, rounding: 'floor' })
return (
<div
className={cn(
'hover-bg-components-panel-on-panel-item-bg relative flex h-full cursor-pointer flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg pb-3 shadow-xs',
className,
)}
>
{/* {isSandbox && <CornerMark text="Sandbox" />} */}
{/* Header */}
<div className="flex shrink-0 items-center gap-3 px-4 pb-2 pt-4">
{/* Avatar */}
<AppIcon
size="large"
iconType={iconUrl ? 'image' : 'emoji'}
icon={iconUrl ? undefined : (icon || '📄')}
imageUrl={iconUrl || undefined}
background={icon_background || undefined}
/>
{/* Title */}
<div className="flex min-w-0 flex-1 flex-col justify-center gap-0.5">
<div className="flex items-center">
<a
href={href}
className="truncate text-text-primary system-md-medium after:absolute after:inset-0"
>
{template_name}
</a>
{isPartner && <Partner className="relative z-[1] ml-0.5 h-4 w-4 shrink-0" text={t('marketplace.partnerTip', { ns: 'plugin' })} />}
</div>
<div className="flex items-center gap-2 text-text-tertiary system-xs-regular">
<span className="relative z-[1] flex shrink-0 items-center gap-1">
<span className="shrink-0">{t('marketplace.templateCard.by', { ns: 'plugin' })}</span>
<Link
href={`/creator/${publisher_handle}?publisher_type=${encodeURIComponent(publisher_type || 'individual')}`}
target="_blank"
rel="noopener noreferrer"
className="truncate hover:text-text-secondary hover:underline"
>
{publisher_handle}
</Link>
</span>
<span className="shrink-0">·</span>
<span className="shrink-0">
{t('usedCount', { ns: 'plugin', num: formattedUsedCount || 0 })}
</span>
</div>
</div>
</div>
{/* Description */}
<div className="shrink-0 px-4 pb-2 pt-1">
<p
className="line-clamp-2 min-h-[32px] text-text-secondary system-xs-regular"
title={overview}
>
{overview}
</p>
</div>
{/* Bottom Info Bar - Tags as icons */}
<div className="mt-auto flex min-h-7 shrink-0 items-center gap-1 px-4 py-1">
{deps_plugins && deps_plugins.length > 0 && (
<>
{visibleDepsPlugins.map((depsPlugin, index) => (
<div
key={`${id}-depsPlugin-${index}`}
className="flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded-md border-[0.5px] border-effects-icon-border bg-background-default-dodge"
title={depsPlugin}
>
<img
className="h-full w-full object-cover"
src={getIconFromMarketPlace(depsPlugin)}
alt={depsPlugin}
/>
</div>
))}
{remainingDepsPluginsCount > 0 && (
<div className="flex items-center justify-center p-0.5">
<span className="text-text-tertiary system-xs-regular">
+
{remainingDepsPluginsCount}
</span>
</div>
)}
</>
)}
</div>
</div>
)
}
const TemplateCard = React.memo(TemplateCardComponent)
export default TemplateCard

Some files were not shown because too many files have changed in this diff Show More