mirror of
https://github.com/formbricks/formbricks.git
synced 2026-03-27 18:00:55 -05:00
Compare commits
16 Commits
empty_list
...
cursor/fix
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
882ad99ed7 | ||
|
|
ce47b4c2d8 | ||
|
|
ce8f9de8ec | ||
|
|
ed3c2d2b58 | ||
|
|
9ae226329b | ||
|
|
12c3899b85 | ||
|
|
ccb1353eb5 | ||
|
|
22eb0b79ee | ||
|
|
5eb7a496da | ||
|
|
7ea55e199f | ||
|
|
83eb472acd | ||
|
|
d9fe6ee4f4 | ||
|
|
51b58be079 | ||
|
|
397643330a | ||
|
|
e5fa4328e1 | ||
|
|
4b777f1907 |
216
.cursor/rules/component-migration.mdc
Normal file
216
.cursor/rules/component-migration.mdc
Normal file
@@ -0,0 +1,216 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
# Component Migration Automation Rule
|
||||
|
||||
## Overview
|
||||
This rule automates the migration of deprecated components to new component systems in React/TypeScript codebases.
|
||||
|
||||
## Trigger
|
||||
When the user requests component migration (e.g., "migrate [DeprecatedComponent] to [NewComponent]" or "component migration").
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Discovery and Planning
|
||||
1. **Identify migration parameters:**
|
||||
- Ask user for deprecated component name (e.g., "Modal")
|
||||
- Ask user for new component name(s) (e.g., "Dialog")
|
||||
- Ask for any components to exclude (e.g., "ModalWithTabs")
|
||||
- Ask for specific import paths if needed
|
||||
|
||||
2. **Scan codebase** for deprecated components:
|
||||
- Search for `import.*[DeprecatedComponent]` patterns
|
||||
- Exclude specified components that should not be migrated
|
||||
- List all found components with file paths
|
||||
- Present numbered list to user for confirmation
|
||||
|
||||
### Step 2: Component-by-Component Migration
|
||||
For each component, follow this exact sequence:
|
||||
|
||||
#### 2.1 Component Migration
|
||||
- **Import changes:**
|
||||
- Ask user to provide the new import structure
|
||||
- Example transformation pattern:
|
||||
```typescript
|
||||
// FROM:
|
||||
import { [DeprecatedComponent] } from "@/components/ui/[DeprecatedComponent]"
|
||||
|
||||
// TO:
|
||||
import {
|
||||
[NewComponent],
|
||||
[NewComponentPart1],
|
||||
[NewComponentPart2],
|
||||
// ... other parts
|
||||
} from "@/components/ui/[NewComponent]"
|
||||
```
|
||||
|
||||
- **Props transformation:**
|
||||
- Ask user for prop mapping rules (e.g., `open` → `open`, `setOpen` → `onOpenChange`)
|
||||
- Ask for props to remove (e.g., `noPadding`, `closeOnOutsideClick`, `size`)
|
||||
- Apply transformations based on user specifications
|
||||
|
||||
- **Structure transformation:**
|
||||
- Ask user for the new component structure pattern
|
||||
- Apply the transformation maintaining all functionality
|
||||
- Preserve all existing logic, state management, and event handlers
|
||||
|
||||
#### 2.2 Wait for User Approval
|
||||
- Present the migration changes
|
||||
- Wait for explicit user approval before proceeding
|
||||
- If rejected, ask for specific feedback and iterate
|
||||
#### 2.3 Re-read and Apply Additional Changes
|
||||
- Re-read the component file to capture any user modifications
|
||||
- Apply any additional improvements the user made
|
||||
- Ensure all changes are incorporated
|
||||
|
||||
#### 2.4 Test File Updates
|
||||
- **Find corresponding test file** (same name with `.test.tsx` or `.test.ts`)
|
||||
- **Update test mocks:**
|
||||
- Ask user for new component mock structure
|
||||
- Replace old component mocks with new ones
|
||||
- Example pattern:
|
||||
```typescript
|
||||
// Add to test setup:
|
||||
jest.mock("@/components/ui/[NewComponent]", () => ({
|
||||
[NewComponent]: ({ children, [props] }: any) => ([mock implementation]),
|
||||
[NewComponentPart1]: ({ children }: any) => <div data-testid="[new-component-part1]">{children}</div>,
|
||||
[NewComponentPart2]: ({ children }: any) => <div data-testid="[new-component-part2]">{children}</div>,
|
||||
// ... other parts
|
||||
}));
|
||||
```
|
||||
- **Update test expectations:**
|
||||
- Change test IDs from old component to new component
|
||||
- Update any component-specific assertions
|
||||
- Ensure all new component parts used in the component are mocked
|
||||
|
||||
#### 2.5 Run Tests and Optimize
|
||||
- Execute `Node package manager test -- ComponentName.test.tsx`
|
||||
- Fix any failing tests
|
||||
- Optimize code quality (imports, formatting, etc.)
|
||||
- Re-run tests until all pass
|
||||
- **Maximum 3 iterations** - if still failing, ask user for guidance
|
||||
|
||||
#### 2.6 Wait for Final Approval
|
||||
- Present test results and any optimizations made
|
||||
- Wait for user approval of the complete migration
|
||||
- If rejected, iterate based on feedback
|
||||
|
||||
#### 2.7 Git Commit
|
||||
- Run: `git add .`
|
||||
- Run: `git commit -m "migrate [ComponentName] from [DeprecatedComponent] to [NewComponent]"`
|
||||
- Confirm commit was successful
|
||||
|
||||
### Step 3: Final Report Generation
|
||||
After all components are migrated, generate a comprehensive GitHub PR report:
|
||||
|
||||
#### PR Title
|
||||
```
|
||||
feat: migrate [DeprecatedComponent] components to [NewComponent] system
|
||||
```
|
||||
|
||||
#### PR Description Template
|
||||
```markdown
|
||||
## 🔄 [DeprecatedComponent] to [NewComponent] Migration
|
||||
|
||||
### Overview
|
||||
Migrated [X] [DeprecatedComponent] components to the new [NewComponent] component system to modernize the UI architecture and improve consistency.
|
||||
|
||||
### Components Migrated
|
||||
[List each component with file path]
|
||||
|
||||
### Technical Changes
|
||||
- **Imports:** Replaced `[DeprecatedComponent]` with `[NewComponent], [NewComponentParts...]`
|
||||
- **Props:** [List prop transformations]
|
||||
- **Structure:** Implemented proper [NewComponent] component hierarchy
|
||||
- **Styling:** [Describe styling changes]
|
||||
- **Tests:** Updated all test mocks and expectations
|
||||
|
||||
### Migration Pattern
|
||||
```typescript
|
||||
// Before
|
||||
<[DeprecatedComponent] [oldProps]>
|
||||
[oldStructure]
|
||||
</[DeprecatedComponent]>
|
||||
|
||||
// After
|
||||
<[NewComponent] [newProps]>
|
||||
[newStructure]
|
||||
</[NewComponent]>
|
||||
```
|
||||
|
||||
### Testing
|
||||
- ✅ All existing tests updated and passing
|
||||
- ✅ Component functionality preserved
|
||||
- ✅ UI/UX behavior maintained
|
||||
|
||||
### How to Test This PR
|
||||
1. **Functional Testing:**
|
||||
- Navigate to each migrated component's usage
|
||||
- Verify [component] opens and closes correctly
|
||||
- Test all interactive elements within [components]
|
||||
- Confirm styling and layout are preserved
|
||||
|
||||
2. **Automated Testing:**
|
||||
```bash
|
||||
Node package manager test
|
||||
```
|
||||
|
||||
3. **Visual Testing:**
|
||||
- Check that all [components] maintain proper styling
|
||||
- Verify responsive behavior
|
||||
- Test keyboard navigation and accessibility
|
||||
|
||||
### Breaking Changes
|
||||
[List any breaking changes or state "None - this is a drop-in replacement maintaining all existing functionality."]
|
||||
|
||||
### Notes
|
||||
- [Any excluded components] were preserved as they already use [NewComponent] internally
|
||||
- All form validation and complex state management preserved
|
||||
- Enhanced code quality with better imports and formatting
|
||||
```
|
||||
|
||||
## Special Considerations
|
||||
|
||||
### Excluded Components
|
||||
- **DO NOT MIGRATE** components specified by user as exclusions
|
||||
- They may already use the new component internally or have other reasons
|
||||
- Inform user these are skipped and why
|
||||
|
||||
### Complex Components
|
||||
- Preserve all existing functionality (forms, validation, state management)
|
||||
- Maintain prop interfaces
|
||||
- Keep all event handlers and callbacks
|
||||
- Preserve accessibility features
|
||||
|
||||
### Test Coverage
|
||||
- Ensure all new component parts are mocked when used
|
||||
- Mock all new component parts that appear in the component
|
||||
- Update test IDs from old component to new component
|
||||
- Maintain all existing test scenarios
|
||||
|
||||
### Error Handling
|
||||
- If tests fail after 3 iterations, stop and ask user for guidance
|
||||
- If component is too complex, ask user for specific guidance
|
||||
- If unsure about functionality preservation, ask for clarification
|
||||
|
||||
### Migration Patterns
|
||||
- Always ask user for specific migration patterns before starting
|
||||
- Confirm import structures, prop mappings, and component hierarchies
|
||||
- Adapt to different component architectures (simple replacements, complex restructuring, etc.)
|
||||
|
||||
## Success Criteria
|
||||
- All deprecated components successfully migrated to new components
|
||||
- All tests passing
|
||||
- No functionality lost
|
||||
- Code quality maintained or improved
|
||||
- User approval on each component
|
||||
- Successful git commits for each migration
|
||||
- Comprehensive PR report generated
|
||||
|
||||
## Usage Examples
|
||||
- "migrate Modal to Dialog"
|
||||
- "migrate Button to NewButton"
|
||||
- "migrate Card to ModernCard"
|
||||
- "component migration" (will prompt for details)
|
||||
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -1,6 +1,7 @@
|
||||
name: Feature request
|
||||
description: "Suggest an idea for this project \U0001F680"
|
||||
type: feature
|
||||
projects: "formbricks/21"
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem-description
|
||||
|
||||
11
.github/ISSUE_TEMPLATE/task.yml
vendored
11
.github/ISSUE_TEMPLATE/task.yml
vendored
@@ -1,11 +0,0 @@
|
||||
name: Task (internal)
|
||||
description: "Template for creating a task. Used by the Formbricks Team only \U0001f4e5"
|
||||
type: task
|
||||
body:
|
||||
- type: textarea
|
||||
id: task-summary
|
||||
attributes:
|
||||
label: Task description
|
||||
description: A clear detailed-rich description of the task.
|
||||
validations:
|
||||
required: true
|
||||
@@ -106,8 +106,7 @@ export const ShareEmbedSurvey = ({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogTitle className="sr-only" />
|
||||
<DialogContent className="w-full max-w-xl bg-white p-0 md:max-w-3xl lg:h-[700px] lg:max-w-5xl">
|
||||
<DialogContent className="w-full bg-white p-0 lg:h-[700px]" width="wide">
|
||||
{showView === "start" ? (
|
||||
<div className="h-full max-w-full overflow-hidden">
|
||||
<div className="flex h-[200px] w-full flex-col items-center justify-center space-y-6 p-8 text-center lg:h-2/5">
|
||||
|
||||
@@ -274,7 +274,7 @@ describe("getEnvironmentState", () => {
|
||||
|
||||
expect(withCache).toHaveBeenCalledWith(expect.any(Function), {
|
||||
key: `fb:env:${environmentId}:state`,
|
||||
ttl: 60 * 30 * 1000, // 30 minutes in milliseconds
|
||||
ttl: 5 * 60 * 1000, // 5 minutes in milliseconds
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -83,9 +83,8 @@ export const getEnvironmentState = async (
|
||||
{
|
||||
// Use enterprise-grade cache key pattern
|
||||
key: createCacheKey.environment.state(environmentId),
|
||||
// 30 minutes TTL ensures fresh data for hourly SDK checks
|
||||
// Balances performance with freshness requirements
|
||||
ttl: 60 * 30 * 1000, // 30 minutes in milliseconds
|
||||
// This is a temporary fix for the invalidation issues, will be changed later with a proper solution
|
||||
ttl: 5 * 60 * 1000, // 5 minutes in milliseconds
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -52,14 +52,6 @@ export const POST = withApiLogging(
|
||||
}
|
||||
|
||||
const inputValidation = ZActionClassInput.safeParse(actionClassInput);
|
||||
const environmentId = actionClassInput.environmentId;
|
||||
|
||||
if (!hasPermission(authentication.environmentPermissions, environmentId, "POST")) {
|
||||
return {
|
||||
response: responses.unauthorizedResponse(),
|
||||
};
|
||||
}
|
||||
|
||||
if (!inputValidation.success) {
|
||||
return {
|
||||
response: responses.badRequestResponse(
|
||||
@@ -70,6 +62,14 @@ export const POST = withApiLogging(
|
||||
};
|
||||
}
|
||||
|
||||
const environmentId = inputValidation.data.environmentId;
|
||||
|
||||
if (!hasPermission(authentication.environmentPermissions, environmentId, "POST")) {
|
||||
return {
|
||||
response: responses.unauthorizedResponse(),
|
||||
};
|
||||
}
|
||||
|
||||
const actionClass: TActionClass = await createActionClass(environmentId, inputValidation.data);
|
||||
auditLog.targetId = actionClass.id;
|
||||
auditLog.newObject = actionClass;
|
||||
|
||||
@@ -309,7 +309,6 @@
|
||||
"project_not_found": "Projekt nicht gefunden",
|
||||
"project_permission_not_found": "Projekt-Berechtigung nicht gefunden",
|
||||
"projects": "Projekte",
|
||||
"projects_limit_reached": "Projektlimit erreicht",
|
||||
"question": "Frage",
|
||||
"question_id": "Frage-ID",
|
||||
"questions": "Fragen",
|
||||
|
||||
@@ -309,7 +309,6 @@
|
||||
"project_not_found": "Project not found",
|
||||
"project_permission_not_found": "Project permission not found",
|
||||
"projects": "Projects",
|
||||
"projects_limit_reached": "Projects limit reached",
|
||||
"question": "Question",
|
||||
"question_id": "Question ID",
|
||||
"questions": "Questions",
|
||||
|
||||
@@ -309,7 +309,6 @@
|
||||
"project_not_found": "Projet non trouvé",
|
||||
"project_permission_not_found": "Autorisation de projet non trouvée",
|
||||
"projects": "Projets",
|
||||
"projects_limit_reached": "Limite de projets atteinte",
|
||||
"question": "Question",
|
||||
"question_id": "ID de la question",
|
||||
"questions": "Questions",
|
||||
|
||||
@@ -309,7 +309,6 @@
|
||||
"project_not_found": "Projeto não encontrado",
|
||||
"project_permission_not_found": "Permissão do projeto não encontrada",
|
||||
"projects": "Projetos",
|
||||
"projects_limit_reached": "Limites de projetos atingidos",
|
||||
"question": "Pergunta",
|
||||
"question_id": "ID da Pergunta",
|
||||
"questions": "Perguntas",
|
||||
@@ -357,7 +356,7 @@
|
||||
"start_free_trial": "Iniciar Teste Grátis",
|
||||
"status": "status",
|
||||
"step_by_step_manual": "Manual passo a passo",
|
||||
"styling": "estilização",
|
||||
"styling": "Estilização",
|
||||
"submit": "Enviar",
|
||||
"summary": "Resumo",
|
||||
"survey": "Pesquisa",
|
||||
@@ -369,7 +368,7 @@
|
||||
"survey_paused": "Pesquisa pausada.",
|
||||
"survey_scheduled": "Pesquisa agendada.",
|
||||
"survey_type": "Tipo de Pesquisa",
|
||||
"surveys": "pesquisas",
|
||||
"surveys": "Pesquisas",
|
||||
"switch_organization": "Mudar organização",
|
||||
"switch_to": "Mudar para {environment}",
|
||||
"table_items_deleted_successfully": "{type}s deletados com sucesso",
|
||||
|
||||
@@ -309,7 +309,6 @@
|
||||
"project_not_found": "Projeto não encontrado",
|
||||
"project_permission_not_found": "Permissão do projeto não encontrada",
|
||||
"projects": "Projetos",
|
||||
"projects_limit_reached": "Limite de projetos atingido",
|
||||
"question": "Pergunta",
|
||||
"question_id": "ID da pergunta",
|
||||
"questions": "Perguntas",
|
||||
|
||||
@@ -309,7 +309,6 @@
|
||||
"project_not_found": "找不到專案",
|
||||
"project_permission_not_found": "找不到專案權限",
|
||||
"projects": "專案",
|
||||
"projects_limit_reached": "已達到專案上限",
|
||||
"question": "問題",
|
||||
"question_id": "問題 ID",
|
||||
"questions": "問題",
|
||||
|
||||
@@ -25,7 +25,9 @@ export const getEnvironmentId = async (
|
||||
*/
|
||||
export const getEnvironmentIdFromSurveyIds = async (
|
||||
surveyIds: string[]
|
||||
): Promise<Result<string, ApiErrorResponseV2>> => {
|
||||
): Promise<Result<string | null, ApiErrorResponseV2>> => {
|
||||
if (surveyIds.length === 0) return ok(null);
|
||||
|
||||
const result = await fetchEnvironmentIdFromSurveyIds(surveyIds);
|
||||
|
||||
if (!result.ok) {
|
||||
|
||||
@@ -75,13 +75,14 @@ export const PUT = async (request: NextRequest, props: { params: Promise<{ webho
|
||||
);
|
||||
}
|
||||
|
||||
// get surveys environment
|
||||
const surveysEnvironmentId = await getEnvironmentIdFromSurveyIds(body.surveyIds);
|
||||
const surveysEnvironmentIdResult = await getEnvironmentIdFromSurveyIds(body.surveyIds);
|
||||
|
||||
if (!surveysEnvironmentId.ok) {
|
||||
return handleApiError(request, surveysEnvironmentId.error, auditLog);
|
||||
if (!surveysEnvironmentIdResult.ok) {
|
||||
return handleApiError(request, surveysEnvironmentIdResult.error, auditLog);
|
||||
}
|
||||
|
||||
const surveysEnvironmentId = surveysEnvironmentIdResult.data;
|
||||
|
||||
// get webhook environment
|
||||
const webhook = await getWebhook(params.webhookId);
|
||||
|
||||
@@ -101,7 +102,7 @@ export const PUT = async (request: NextRequest, props: { params: Promise<{ webho
|
||||
}
|
||||
|
||||
// check if webhook environment matches the surveys environment
|
||||
if (webhook.data.environmentId !== surveysEnvironmentId.data) {
|
||||
if (surveysEnvironmentId && webhook.data.environmentId !== surveysEnvironmentId) {
|
||||
return handleApiError(
|
||||
request,
|
||||
{
|
||||
|
||||
@@ -57,10 +57,12 @@ export const POST = async (request: NextRequest) =>
|
||||
);
|
||||
}
|
||||
|
||||
const environmentIdResult = await getEnvironmentIdFromSurveyIds(body.surveyIds);
|
||||
if (body.surveyIds && body.surveyIds.length > 0) {
|
||||
const environmentIdResult = await getEnvironmentIdFromSurveyIds(body.surveyIds);
|
||||
|
||||
if (!environmentIdResult.ok) {
|
||||
return handleApiError(request, environmentIdResult.error, auditLog);
|
||||
if (!environmentIdResult.ok) {
|
||||
return handleApiError(request, environmentIdResult.error, auditLog);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasPermission(authentication.environmentPermissions, body.environmentId, "POST")) {
|
||||
|
||||
@@ -34,8 +34,8 @@ export const getSegments = reactCache((environmentId: string) =>
|
||||
},
|
||||
{
|
||||
key: createCacheKey.environment.segments(environmentId),
|
||||
// 30 minutes TTL - segment definitions change infrequently
|
||||
ttl: 60 * 30 * 1000, // 30 minutes in milliseconds
|
||||
// This is a temporary fix for the invalidation issues, will be changed later with a proper solution
|
||||
ttl: 5 * 60 * 1000, // 5 minutes in milliseconds
|
||||
}
|
||||
)()
|
||||
);
|
||||
|
||||
@@ -6,13 +6,70 @@ import { ZodOpenApiOperationObject, ZodOpenApiPathsObject } from "zod-openapi";
|
||||
const bulkContactEndpoint: ZodOpenApiOperationObject = {
|
||||
operationId: "uploadBulkContacts",
|
||||
summary: "Upload Bulk Contacts",
|
||||
description: "Uploads contacts in bulk",
|
||||
description:
|
||||
"Uploads contacts in bulk. Each contact in the payload must have an 'email' attribute present in their attributes array. The email attribute is mandatory and must be a valid email format. Without a valid email, the contact will be skipped during processing.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
description: "The contacts to upload",
|
||||
description:
|
||||
"The contacts to upload. Each contact must include an 'email' attribute in their attributes array. The email is used as the unique identifier for the contact.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: ZContactBulkUploadRequest,
|
||||
example: {
|
||||
environmentId: "env_01h2xce9q8p3w4x5y6z7a8b9c0",
|
||||
contacts: [
|
||||
{
|
||||
attributes: [
|
||||
{
|
||||
attributeKey: {
|
||||
key: "email",
|
||||
name: "Email Address",
|
||||
},
|
||||
value: "john.doe@example.com",
|
||||
},
|
||||
{
|
||||
attributeKey: {
|
||||
key: "firstName",
|
||||
name: "First Name",
|
||||
},
|
||||
value: "John",
|
||||
},
|
||||
{
|
||||
attributeKey: {
|
||||
key: "lastName",
|
||||
name: "Last Name",
|
||||
},
|
||||
value: "Doe",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
attributes: [
|
||||
{
|
||||
attributeKey: {
|
||||
key: "email",
|
||||
name: "Email Address",
|
||||
},
|
||||
value: "jane.smith@example.com",
|
||||
},
|
||||
{
|
||||
attributeKey: {
|
||||
key: "firstName",
|
||||
name: "First Name",
|
||||
},
|
||||
value: "Jane",
|
||||
},
|
||||
{
|
||||
attributeKey: {
|
||||
key: "lastName",
|
||||
name: "Last Name",
|
||||
},
|
||||
value: "Smith",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -44,8 +44,6 @@ describe("ProjectLimitModal", () => {
|
||||
test("renders dialog and upgrade prompt with correct props", () => {
|
||||
render(<ProjectLimitModal open={true} setOpen={setOpen} projectLimit={3} buttons={buttons} />);
|
||||
expect(screen.getByTestId("dialog")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("dialog-content")).toHaveClass("bg-white");
|
||||
expect(screen.getByTestId("dialog-title")).toHaveTextContent("common.projects_limit_reached");
|
||||
expect(screen.getByTestId("upgrade-prompt")).toBeInTheDocument();
|
||||
expect(screen.getByText("common.unlock_more_projects_with_a_higher_plan")).toBeInTheDocument();
|
||||
expect(screen.getByText("common.you_have_reached_your_limit_of_project_limit")).toBeInTheDocument();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/modules/ui/components/dialog";
|
||||
import { Dialog, DialogContent } from "@/modules/ui/components/dialog";
|
||||
import { ModalButton, UpgradePrompt } from "@/modules/ui/components/upgrade-prompt";
|
||||
import { useTranslate } from "@tolgee/react";
|
||||
|
||||
@@ -16,8 +16,7 @@ export const ProjectLimitModal = ({ open, setOpen, projectLimit, buttons }: Proj
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="w-full max-w-[564px] bg-white">
|
||||
<DialogTitle>{t("common.projects_limit_reached")}</DialogTitle>
|
||||
<DialogContent>
|
||||
<UpgradePrompt
|
||||
title={t("common.unlock_more_projects_with_a_higher_plan")}
|
||||
description={t("common.you_have_reached_your_limit_of_project_limit", { projectLimit })}
|
||||
|
||||
@@ -13,7 +13,7 @@ export const AddEndingCardButton = ({ localSurvey, addEndingCard }: AddEndingCar
|
||||
const { t } = useTranslate();
|
||||
return (
|
||||
<button
|
||||
className="group inline-flex rounded-lg border border-slate-300 bg-slate-50 hover:cursor-pointer hover:bg-white"
|
||||
className="group inline-flex items-stretch rounded-lg border border-slate-300 bg-slate-50 hover:cursor-pointer hover:bg-white"
|
||||
onClick={() => addEndingCard(localSurvey.endings.length)}>
|
||||
<div className="flex w-10 items-center justify-center rounded-l-lg bg-slate-400 transition-all duration-300 ease-in-out group-hover:bg-slate-500 group-aria-expanded:rounded-bl-none group-aria-expanded:rounded-br">
|
||||
<PlusIcon className="h-6 w-6 text-white" />
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
// Import the actions to access mocked functions
|
||||
import { deleteSurveyAction } from "@/modules/survey/list/actions";
|
||||
import { TSurvey } from "@/modules/survey/list/types/surveys";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import toast from "react-hot-toast";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { SurveyDropDownMenu } from "./survey-dropdown-menu";
|
||||
|
||||
// Cast to mocked functions
|
||||
const mockDeleteSurveyAction = vi.mocked(deleteSurveyAction);
|
||||
const mockToast = vi.mocked(toast);
|
||||
|
||||
// Mock translation
|
||||
vi.mock("@tolgee/react", () => ({
|
||||
useTranslate: () => ({ t: (key: string) => key }),
|
||||
@@ -43,6 +50,24 @@ vi.mock("@/modules/survey/list/actions", () => ({
|
||||
getSurveyAction: vi.fn(() =>
|
||||
Promise.resolve({ data: { id: "duplicatedSurveyId", name: "Duplicated Survey" } })
|
||||
),
|
||||
deleteSurveyAction: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock next/navigation
|
||||
const mockRouterRefresh = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
refresh: mockRouterRefresh,
|
||||
push: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock react-hot-toast
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("SurveyDropDownMenu", () => {
|
||||
@@ -240,4 +265,245 @@ describe("SurveyDropDownMenu", () => {
|
||||
expect(mockDuplicateSurvey).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleDeleteSurvey", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("successfully deletes survey - calls all expected functions and shows success toast", async () => {
|
||||
const mockDeleteSurvey = vi.fn();
|
||||
mockDeleteSurveyAction.mockResolvedValueOnce({ data: true });
|
||||
|
||||
render(
|
||||
<SurveyDropDownMenu
|
||||
environmentId="env123"
|
||||
survey={fakeSurvey}
|
||||
publicDomain="http://survey.test"
|
||||
refreshSingleUseId={vi.fn()}
|
||||
duplicateSurvey={vi.fn()}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
|
||||
// Open dropdown and click delete
|
||||
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
|
||||
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
|
||||
await userEvent.click(triggerElement);
|
||||
|
||||
const deleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(deleteButton);
|
||||
|
||||
// Confirm deletion in dialog
|
||||
const confirmDeleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(confirmDeleteButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteSurveyAction).toHaveBeenCalledWith({ surveyId: "testSurvey" });
|
||||
expect(mockDeleteSurvey).toHaveBeenCalledWith("testSurvey");
|
||||
expect(mockToast.success).toHaveBeenCalledWith("environments.surveys.survey_deleted_successfully");
|
||||
expect(mockRouterRefresh).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test("handles deletion error - shows error toast and resets loading state", async () => {
|
||||
const mockDeleteSurvey = vi.fn();
|
||||
const deletionError = new Error("Deletion failed");
|
||||
mockDeleteSurveyAction.mockRejectedValueOnce(deletionError);
|
||||
|
||||
render(
|
||||
<SurveyDropDownMenu
|
||||
environmentId="env123"
|
||||
survey={fakeSurvey}
|
||||
publicDomain="http://survey.test"
|
||||
refreshSingleUseId={vi.fn()}
|
||||
duplicateSurvey={vi.fn()}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
|
||||
// Open dropdown and click delete
|
||||
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
|
||||
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
|
||||
await userEvent.click(triggerElement);
|
||||
|
||||
const deleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(deleteButton);
|
||||
|
||||
// Confirm deletion in dialog
|
||||
const confirmDeleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(confirmDeleteButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteSurveyAction).toHaveBeenCalledWith({ surveyId: "testSurvey" });
|
||||
expect(mockDeleteSurvey).not.toHaveBeenCalled();
|
||||
expect(mockToast.error).toHaveBeenCalledWith("environments.surveys.error_deleting_survey");
|
||||
expect(mockRouterRefresh).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test("manages loading state correctly during successful deletion", async () => {
|
||||
const mockDeleteSurvey = vi.fn();
|
||||
mockDeleteSurveyAction.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(() => resolve({ data: true }), 100))
|
||||
);
|
||||
|
||||
render(
|
||||
<SurveyDropDownMenu
|
||||
environmentId="env123"
|
||||
survey={fakeSurvey}
|
||||
publicDomain="http://survey.test"
|
||||
refreshSingleUseId={vi.fn()}
|
||||
duplicateSurvey={vi.fn()}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
|
||||
// Open dropdown and click delete
|
||||
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
|
||||
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
|
||||
await userEvent.click(triggerElement);
|
||||
|
||||
const deleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(deleteButton);
|
||||
|
||||
// Confirm deletion in dialog using a more reliable selector
|
||||
const confirmDeleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(confirmDeleteButton);
|
||||
|
||||
// Wait for the deletion process to complete
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteSurveyAction).toHaveBeenCalled();
|
||||
expect(mockDeleteSurvey).toHaveBeenCalled();
|
||||
expect(mockToast.success).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test("manages loading state correctly during failed deletion", async () => {
|
||||
const mockDeleteSurvey = vi.fn();
|
||||
mockDeleteSurveyAction.mockImplementation(
|
||||
() => new Promise((_, reject) => setTimeout(() => reject(new Error("Network error")), 100))
|
||||
);
|
||||
|
||||
render(
|
||||
<SurveyDropDownMenu
|
||||
environmentId="env123"
|
||||
survey={fakeSurvey}
|
||||
publicDomain="http://survey.test"
|
||||
refreshSingleUseId={vi.fn()}
|
||||
duplicateSurvey={vi.fn()}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
|
||||
// Open dropdown and click delete
|
||||
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
|
||||
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
|
||||
await userEvent.click(triggerElement);
|
||||
|
||||
const deleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(deleteButton);
|
||||
|
||||
// Confirm deletion in dialog using a more reliable selector
|
||||
const confirmDeleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(confirmDeleteButton);
|
||||
|
||||
// Wait for the error to occur
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteSurveyAction).toHaveBeenCalled();
|
||||
expect(mockToast.error).toHaveBeenCalledWith("environments.surveys.error_deleting_survey");
|
||||
});
|
||||
|
||||
// Verify that deleteSurvey callback was not called due to error
|
||||
expect(mockDeleteSurvey).not.toHaveBeenCalled();
|
||||
expect(mockRouterRefresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does not call router.refresh or success toast when deleteSurveyAction throws", async () => {
|
||||
const mockDeleteSurvey = vi.fn();
|
||||
mockDeleteSurveyAction.mockRejectedValueOnce(new Error("API Error"));
|
||||
|
||||
render(
|
||||
<SurveyDropDownMenu
|
||||
environmentId="env123"
|
||||
survey={fakeSurvey}
|
||||
publicDomain="http://survey.test"
|
||||
refreshSingleUseId={vi.fn()}
|
||||
duplicateSurvey={vi.fn()}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
|
||||
// Open dropdown and click delete
|
||||
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
|
||||
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
|
||||
await userEvent.click(triggerElement);
|
||||
|
||||
const deleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(deleteButton);
|
||||
|
||||
// Confirm deletion in dialog
|
||||
const confirmDeleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(confirmDeleteButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteSurveyAction).toHaveBeenCalled();
|
||||
expect(mockToast.error).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Verify success-path functions are not called
|
||||
expect(mockDeleteSurvey).not.toHaveBeenCalled();
|
||||
expect(mockToast.success).not.toHaveBeenCalled();
|
||||
expect(mockRouterRefresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("calls functions in correct order during successful deletion", async () => {
|
||||
const mockDeleteSurvey = vi.fn();
|
||||
const callOrder: string[] = [];
|
||||
|
||||
mockDeleteSurveyAction.mockImplementation(async () => {
|
||||
callOrder.push("deleteSurveyAction");
|
||||
return { data: true };
|
||||
});
|
||||
|
||||
mockDeleteSurvey.mockImplementation(() => {
|
||||
callOrder.push("deleteSurvey");
|
||||
});
|
||||
|
||||
(mockToast.success as any).mockImplementation(() => {
|
||||
callOrder.push("toast.success");
|
||||
});
|
||||
|
||||
mockRouterRefresh.mockImplementation(() => {
|
||||
callOrder.push("router.refresh");
|
||||
});
|
||||
|
||||
render(
|
||||
<SurveyDropDownMenu
|
||||
environmentId="env123"
|
||||
survey={fakeSurvey}
|
||||
publicDomain="http://survey.test"
|
||||
refreshSingleUseId={vi.fn()}
|
||||
duplicateSurvey={vi.fn()}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
|
||||
// Open dropdown and click delete
|
||||
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
|
||||
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
|
||||
await userEvent.click(triggerElement);
|
||||
|
||||
const deleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(deleteButton);
|
||||
|
||||
// Confirm deletion in dialog
|
||||
const confirmDeleteButton = screen.getByText("common.delete");
|
||||
await userEvent.click(confirmDeleteButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(callOrder).toEqual(["deleteSurveyAction", "deleteSurvey", "toast.success", "router.refresh"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -71,13 +71,13 @@ export const SurveyDropDownMenu = ({
|
||||
try {
|
||||
await deleteSurveyAction({ surveyId });
|
||||
deleteSurvey(surveyId);
|
||||
router.refresh();
|
||||
setDeleteDialogOpen(false);
|
||||
toast.success(t("environments.surveys.survey_deleted_successfully"));
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
toast.error(t("environments.surveys.error_deleting_survey"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleCopyLink = async (e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
@@ -242,6 +242,7 @@ export const SurveyDropDownMenu = ({
|
||||
setOpen={setDeleteDialogOpen}
|
||||
onDelete={() => handleDeleteSurvey(survey.id)}
|
||||
text={t("environments.surveys.delete_survey_and_responses_warning")}
|
||||
isDeleting={loading}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import { TProjectConfigChannel } from "@formbricks/types/project";
|
||||
import { TSurveyFilters } from "@formbricks/types/surveys/types";
|
||||
import { TUserLocale } from "@formbricks/types/user";
|
||||
import { SurveyCard } from "./survey-card";
|
||||
import { SurveyFilters } from "./survey-filters";
|
||||
import { SurveysList, initialFilters as surveyFiltersInitialFiltersFromModule } from "./survey-list";
|
||||
import { SurveyLoading } from "./survey-loading";
|
||||
|
||||
@@ -324,6 +323,24 @@ describe("SurveysList", () => {
|
||||
expect(screen.getByText("Survey Two")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("handleDeleteSurvey shows loading state when the last survey is deleted", async () => {
|
||||
const surveysData = [{ ...surveyMock, id: "s1", name: "Last Survey" }];
|
||||
vi.mocked(getSurveysAction).mockResolvedValueOnce({ data: surveysData });
|
||||
const user = userEvent.setup();
|
||||
render(<SurveysList {...defaultProps} />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("Last Survey")).toBeInTheDocument());
|
||||
expect(screen.queryByTestId("survey-loading")).not.toBeInTheDocument();
|
||||
|
||||
const deleteButtonS1 = screen.getByTestId("delete-s1");
|
||||
await user.click(deleteButtonS1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("Last Survey")).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId("survey-loading")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
test("handleDuplicateSurvey adds the duplicated survey to the beginning of the list", async () => {
|
||||
const initialSurvey = { ...surveyMock, id: "s1", name: "Original Survey" };
|
||||
vi.mocked(getSurveysAction).mockResolvedValueOnce({ data: [initialSurvey] });
|
||||
|
||||
@@ -123,6 +123,7 @@ export const SurveysList = ({
|
||||
const handleDeleteSurvey = async (surveyId: string) => {
|
||||
const newSurveys = surveys.filter((survey) => survey.id !== surveyId);
|
||||
setSurveys(newSurveys);
|
||||
if (newSurveys.length === 0) setIsFetching(true);
|
||||
};
|
||||
|
||||
const handleDuplicateSurvey = async (survey: TSurvey) => {
|
||||
|
||||
@@ -5,7 +5,11 @@ import { useTranslate } from "@tolgee/react";
|
||||
import { ArrowLeftIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export const BackButton = () => {
|
||||
interface BackButtonProps {
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export const BackButton = ({ path }: BackButtonProps) => {
|
||||
const router = useRouter();
|
||||
const { t } = useTranslate();
|
||||
return (
|
||||
@@ -13,7 +17,11 @@ export const BackButton = () => {
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
router.back();
|
||||
if (path) {
|
||||
router.push(path);
|
||||
} else {
|
||||
router.back();
|
||||
}
|
||||
}}>
|
||||
<ArrowLeftIcon />
|
||||
{t("common.back")}
|
||||
|
||||
@@ -7,7 +7,7 @@ export const MenuBar = () => {
|
||||
<>
|
||||
<div className="border-b border-slate-200 bg-white px-5 py-2.5 sm:flex sm:items-center sm:justify-between">
|
||||
<div className="flex items-center space-x-2 whitespace-nowrap">
|
||||
<BackButton />
|
||||
<BackButton path="/" />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -12,6 +12,7 @@ vi.mock("react-confetti", () => ({
|
||||
data-colors={JSON.stringify(props.colors)}
|
||||
data-number-of-pieces={props.numberOfPieces}
|
||||
data-recycle={props.recycle}
|
||||
style={props.style}
|
||||
/>
|
||||
)),
|
||||
}));
|
||||
@@ -36,6 +37,10 @@ describe("Confetti", () => {
|
||||
expect(confettiElement).toHaveAttribute("data-colors", JSON.stringify(["#00C4B8", "#eee"]));
|
||||
expect(confettiElement).toHaveAttribute("data-number-of-pieces", "400");
|
||||
expect(confettiElement).toHaveAttribute("data-recycle", "false");
|
||||
expect(confettiElement).toHaveAttribute(
|
||||
"style",
|
||||
"position: fixed; top: 0px; left: 0px; z-index: 9999; pointer-events: none;"
|
||||
);
|
||||
});
|
||||
|
||||
test("renders with custom colors", () => {
|
||||
|
||||
@@ -13,5 +13,20 @@ export const Confetti: React.FC<ConfettiProps> = ({
|
||||
colors?: string[];
|
||||
}) => {
|
||||
const { width, height } = useWindowSize();
|
||||
return <ReactConfetti width={width} height={height} colors={colors} numberOfPieces={400} recycle={false} />;
|
||||
return (
|
||||
<ReactConfetti
|
||||
width={width}
|
||||
height={height}
|
||||
colors={colors}
|
||||
numberOfPieces={400}
|
||||
recycle={false}
|
||||
style={{
|
||||
position: "fixed",
|
||||
top: 0,
|
||||
left: 0,
|
||||
zIndex: 9999,
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "./index";
|
||||
} from ".";
|
||||
|
||||
// Mock Radix UI Dialog components
|
||||
vi.mock("@radix-ui/react-dialog", () => {
|
||||
@@ -120,7 +120,7 @@ describe("Dialog Components", () => {
|
||||
</DialogContent>
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId("dialog-close")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("dialog-close")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("x-icon")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -11,19 +11,19 @@ const DialogTrigger = DialogPrimitive.Trigger;
|
||||
|
||||
const DialogPortal = ({ children, ...props }: DialogPrimitive.DialogPortalProps) => (
|
||||
<DialogPrimitive.Portal {...props}>
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center sm:items-center">{children}</div>
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center md:items-center">{children}</div>
|
||||
</DialogPrimitive.Portal>
|
||||
);
|
||||
DialogPortal.displayName = DialogPrimitive.Portal.displayName;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"bg-background/80 data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=open]:fade-in fixed inset-0 z-50 backdrop-blur-sm transition-all duration-100",
|
||||
"data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=open]:fade-in fixed inset-0 z-50 bg-black/80 backdrop-blur-sm transition-all duration-100",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -31,29 +31,43 @@ const DialogOverlay = React.forwardRef<
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
interface DialogContentProps {
|
||||
hideCloseButton?: boolean;
|
||||
disableCloseOnOutsideClick?: boolean;
|
||||
width?: "default" | "wide";
|
||||
}
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
|
||||
hideCloseButton?: boolean;
|
||||
}
|
||||
>(({ className, children, hideCloseButton, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"bg-background animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 sm:zoom-in-90 data-[state=open]:sm:slide-in-from-bottom-0 fixed z-50 grid gap-4 rounded-b-lg border p-6 shadow-lg sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none">
|
||||
{!hideCloseButton ? <X className="h-4 w-4" /> : null}
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
React.ComponentRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & DialogContentProps
|
||||
>(
|
||||
(
|
||||
{ className, children, hideCloseButton, disableCloseOnOutsideClick, width = "default", ...props },
|
||||
ref
|
||||
) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 md:zoom-in-90 data-[state=open]:md:slide-in-from-bottom-0 fixed z-50 flex max-h-[90dvh] w-full flex-col space-y-4 rounded-t-lg border bg-white p-4 shadow-lg md:overflow-hidden md:rounded-lg",
|
||||
width === "default" ? "md:w-[720px]" : "md:w-[720px] lg:w-[960px]",
|
||||
className
|
||||
)}
|
||||
onPointerDownOutside={disableCloseOnOutsideClick ? (e) => e.preventDefault() : undefined}
|
||||
onEscapeKeyDown={disableCloseOnOutsideClick ? (e) => e.preventDefault() : undefined}
|
||||
{...props}>
|
||||
{children}
|
||||
{!hideCloseButton && (
|
||||
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent absolute right-3 top-[-0.25rem] z-10 rounded-sm bg-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:text-slate-500">
|
||||
<X className="size-4 text-slate-500" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
);
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
type DialogHeaderProps = Omit<React.HTMLAttributes<HTMLDivElement>, "dangerouslySetInnerHTML"> & {
|
||||
@@ -63,7 +77,14 @@ type DialogHeaderProps = Omit<React.HTMLAttributes<HTMLDivElement>, "dangerously
|
||||
};
|
||||
|
||||
const DialogHeader = ({ className, ...props }: DialogHeaderProps) => (
|
||||
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
|
||||
<div
|
||||
className={cn(
|
||||
"sticky top-[-32px] z-10 flex flex-shrink-0 flex-col gap-y-1 bg-white text-left",
|
||||
"[&>svg]:text-primary [&>svg]:absolute [&>svg]:size-4 [&>svg~*]:items-center [&>svg~*]:pl-6 md:[&>svg~*]:flex",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogHeader.displayName = "DialogHeader";
|
||||
|
||||
@@ -75,35 +96,56 @@ type DialogFooterProps = Omit<React.HTMLAttributes<HTMLDivElement>, "dangerously
|
||||
|
||||
const DialogFooter = ({ className, ...props }: DialogFooterProps) => (
|
||||
<div
|
||||
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
|
||||
className={cn(
|
||||
"bottom-0 z-10 flex flex-shrink-0 flex-col-reverse bg-white md:sticky md:flex-row md:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
DialogFooter.displayName = "DialogFooter";
|
||||
|
||||
const DialogBody = ({ className, ...props }: React.HTMLAttributes<HTMLElement>) => (
|
||||
<section
|
||||
className={cn("flex-1 overflow-y-auto text-sm", className)}
|
||||
aria-label="Dialog content"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogBody.displayName = "DialogBody";
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
|
||||
className={cn("text-primary min-h-4 text-sm font-medium leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
className={cn("font-regular text-sm text-slate-500", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger };
|
||||
export {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogBody,
|
||||
};
|
||||
|
||||
460
apps/web/modules/ui/components/dialog/stories.tsx
Normal file
460
apps/web/modules/ui/components/dialog/stories.tsx
Normal file
@@ -0,0 +1,460 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { Button } from "../button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogBody,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "./index";
|
||||
|
||||
// Story options separate from component props
|
||||
interface StoryOptions {
|
||||
triggerText: string;
|
||||
showHeader: boolean;
|
||||
showIcon: boolean;
|
||||
title: string;
|
||||
showDescription: boolean;
|
||||
description: string;
|
||||
bodyContent?: React.ReactNode;
|
||||
showFooter: boolean;
|
||||
footerButtonConfiguration: "1" | "2" | "3";
|
||||
primaryButtonText: string;
|
||||
secondaryButtonText: string;
|
||||
tertiaryButtonText: string;
|
||||
bodyElementCount: number;
|
||||
}
|
||||
|
||||
type StoryProps = React.ComponentProps<typeof DialogContent> & StoryOptions;
|
||||
|
||||
const DefaultBodyContent = (elementCount: number): React.ReactNode => {
|
||||
return (
|
||||
<div>
|
||||
{Array(elementCount)
|
||||
.fill(0)
|
||||
.map((_, i) => (
|
||||
<p key={i}>Scrollable content line {i + 1}</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const meta: Meta<StoryProps> = {
|
||||
title: "UI/Modal",
|
||||
component: DialogContent,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
layout: "centered",
|
||||
controls: {
|
||||
sort: "requiredFirst",
|
||||
exclude: [],
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
// Component Props - Behavior Category
|
||||
hideCloseButton: {
|
||||
control: "boolean",
|
||||
description: "Whether to hide the close button (X)",
|
||||
table: {
|
||||
category: "Behavior",
|
||||
type: { summary: "boolean" },
|
||||
defaultValue: { summary: "false" },
|
||||
},
|
||||
order: 2,
|
||||
},
|
||||
disableCloseOnOutsideClick: {
|
||||
control: "boolean",
|
||||
description: "Whether to disable closing when clicking outside",
|
||||
table: {
|
||||
category: "Behavior",
|
||||
type: { summary: "boolean" },
|
||||
defaultValue: { summary: "false" },
|
||||
},
|
||||
order: 1,
|
||||
},
|
||||
|
||||
// Story Options - Appearance Category
|
||||
width: {
|
||||
control: "select",
|
||||
options: ["default", "wide"],
|
||||
description: "Width of the modal",
|
||||
table: {
|
||||
category: "Appearance",
|
||||
type: { summary: "string" },
|
||||
defaultValue: { summary: "default" },
|
||||
},
|
||||
order: 1,
|
||||
},
|
||||
showHeader: {
|
||||
control: "boolean",
|
||||
description: "Whether to show the header section",
|
||||
table: {
|
||||
category: "Appearance",
|
||||
type: { summary: "boolean" },
|
||||
},
|
||||
order: 2,
|
||||
},
|
||||
showIcon: {
|
||||
control: "boolean",
|
||||
description: "Whether to show an icon in the header",
|
||||
table: {
|
||||
category: "Appearance",
|
||||
type: { summary: "boolean" },
|
||||
},
|
||||
order: 3,
|
||||
},
|
||||
showDescription: {
|
||||
control: "boolean",
|
||||
description: "Whether to show a description in the header",
|
||||
table: {
|
||||
category: "Appearance",
|
||||
type: { summary: "boolean" },
|
||||
},
|
||||
order: 4,
|
||||
},
|
||||
showFooter: {
|
||||
control: "boolean",
|
||||
description: "Whether to show the footer section",
|
||||
table: {
|
||||
category: "Appearance",
|
||||
type: { summary: "boolean" },
|
||||
},
|
||||
order: 5,
|
||||
},
|
||||
footerButtonConfiguration: {
|
||||
control: "select",
|
||||
options: ["1", "2", "3"],
|
||||
description: "Number of buttons to show in footer",
|
||||
table: {
|
||||
category: "Appearance",
|
||||
type: { summary: "string" },
|
||||
},
|
||||
order: 6,
|
||||
},
|
||||
|
||||
// Story Options - Content Category
|
||||
triggerText: {
|
||||
control: "text",
|
||||
description: "Text for the trigger button",
|
||||
table: {
|
||||
category: "Content",
|
||||
type: { summary: "string" },
|
||||
},
|
||||
order: 1,
|
||||
},
|
||||
title: {
|
||||
control: "text",
|
||||
description: "Modal title text",
|
||||
table: {
|
||||
category: "Content",
|
||||
type: { summary: "string" },
|
||||
},
|
||||
order: 2,
|
||||
},
|
||||
description: {
|
||||
control: "text",
|
||||
description: "Modal description text",
|
||||
table: {
|
||||
category: "Content",
|
||||
type: { summary: "string" },
|
||||
},
|
||||
order: 3,
|
||||
},
|
||||
primaryButtonText: {
|
||||
control: "text",
|
||||
description: "Text for the primary button",
|
||||
table: {
|
||||
category: "Content",
|
||||
type: { summary: "string" },
|
||||
},
|
||||
order: 4,
|
||||
},
|
||||
secondaryButtonText: {
|
||||
control: "text",
|
||||
description: "Text for the secondary button",
|
||||
table: {
|
||||
category: "Content",
|
||||
type: { summary: "string" },
|
||||
},
|
||||
order: 5,
|
||||
},
|
||||
tertiaryButtonText: {
|
||||
control: "text",
|
||||
description: "Text for the tertiary button",
|
||||
table: {
|
||||
category: "Content",
|
||||
type: { summary: "string" },
|
||||
},
|
||||
order: 6,
|
||||
},
|
||||
bodyElementCount: {
|
||||
control: { type: "number", min: 1, max: 100, step: 1 },
|
||||
description: "Number of elements in the body content",
|
||||
table: {
|
||||
category: "Content",
|
||||
type: { summary: "number" },
|
||||
},
|
||||
order: 7,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof DialogContent> & { args: StoryOptions };
|
||||
|
||||
// Create a common render function to reduce duplication
|
||||
const renderModal = (args: StoryProps) => {
|
||||
// Extract component props
|
||||
const {
|
||||
hideCloseButton = false,
|
||||
disableCloseOnOutsideClick = false,
|
||||
width = "default",
|
||||
className = "",
|
||||
} = args;
|
||||
|
||||
// Extract story content options
|
||||
const {
|
||||
triggerText = "Open Modal",
|
||||
showHeader = true,
|
||||
showIcon = false,
|
||||
title = "Modal Title",
|
||||
showDescription = true,
|
||||
description = "Modal description",
|
||||
showFooter = true,
|
||||
footerButtonConfiguration = "3",
|
||||
primaryButtonText = "Confirm",
|
||||
secondaryButtonText = "Cancel",
|
||||
tertiaryButtonText = "Learn more",
|
||||
bodyElementCount = 5,
|
||||
} = args as StoryOptions;
|
||||
|
||||
const bodyContent = DefaultBodyContent(bodyElementCount);
|
||||
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline">{triggerText}</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent
|
||||
hideCloseButton={hideCloseButton}
|
||||
disableCloseOnOutsideClick={disableCloseOnOutsideClick}
|
||||
width={width}
|
||||
className={className}>
|
||||
{showHeader && (
|
||||
<DialogHeader>
|
||||
{showIcon && <AlertCircle />}
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
{showDescription && <DialogDescription>{description}</DialogDescription>}
|
||||
</DialogHeader>
|
||||
)}
|
||||
<DialogBody>{bodyContent}</DialogBody>
|
||||
{showFooter && footerButtonConfiguration === "3" && (
|
||||
<DialogFooter className="md:justify-between">
|
||||
<div className="flex w-full flex-col space-y-2 md:hidden">
|
||||
<Button className="w-full">{primaryButtonText}</Button>
|
||||
<Button className="w-full" variant="secondary">
|
||||
{secondaryButtonText}
|
||||
</Button>
|
||||
<Button className="w-full" variant="ghost">
|
||||
{tertiaryButtonText}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="hidden md:block">
|
||||
<Button className="justify-self-start" variant="ghost">
|
||||
{tertiaryButtonText}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="hidden md:flex md:space-x-2">
|
||||
<Button variant="secondary">{secondaryButtonText}</Button>
|
||||
<Button>{primaryButtonText}</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
)}
|
||||
{showFooter && footerButtonConfiguration !== "3" && (
|
||||
<DialogFooter>
|
||||
<div className="flex w-full flex-col space-y-2 md:hidden">
|
||||
<Button className="w-full">{primaryButtonText}</Button>
|
||||
{footerButtonConfiguration !== "1" && (
|
||||
<Button className="w-full" variant="secondary">
|
||||
{secondaryButtonText}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="hidden md:flex md:space-x-2">
|
||||
{footerButtonConfiguration !== "1" && (
|
||||
<Button variant="secondary">{secondaryButtonText}</Button>
|
||||
)}
|
||||
<Button>{primaryButtonText}</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export const Default: Story = {
|
||||
render: renderModal,
|
||||
args: {
|
||||
triggerText: "Open Modal",
|
||||
showHeader: true,
|
||||
showIcon: true,
|
||||
title: "Modal Title",
|
||||
showDescription: true,
|
||||
description: "This is a description of what this modal is for.",
|
||||
showFooter: true,
|
||||
footerButtonConfiguration: "3",
|
||||
primaryButtonText: "Confirm",
|
||||
secondaryButtonText: "Cancel",
|
||||
tertiaryButtonText: "Learn more",
|
||||
bodyElementCount: 5,
|
||||
hideCloseButton: false,
|
||||
disableCloseOnOutsideClick: false,
|
||||
width: "default",
|
||||
},
|
||||
};
|
||||
|
||||
export const OnlyBody: Story = {
|
||||
render: renderModal,
|
||||
args: {
|
||||
triggerText: "Open Modal - Body Only",
|
||||
showHeader: false,
|
||||
showIcon: false,
|
||||
title: "",
|
||||
showDescription: false,
|
||||
description: "",
|
||||
showFooter: false,
|
||||
footerButtonConfiguration: "1",
|
||||
primaryButtonText: "",
|
||||
secondaryButtonText: "",
|
||||
tertiaryButtonText: "",
|
||||
bodyElementCount: 50,
|
||||
hideCloseButton: false,
|
||||
disableCloseOnOutsideClick: false,
|
||||
width: "default",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story: "A minimal modal with only body content, useful for simple content display.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const NoFooter: Story = {
|
||||
render: renderModal,
|
||||
args: {
|
||||
triggerText: "Open Modal - No Footer",
|
||||
showHeader: true,
|
||||
showIcon: true,
|
||||
title: "Modal Without Footer",
|
||||
showDescription: false,
|
||||
description: "This modal has a header and body but no footer buttons.",
|
||||
showFooter: false,
|
||||
footerButtonConfiguration: "1",
|
||||
primaryButtonText: "",
|
||||
secondaryButtonText: "",
|
||||
tertiaryButtonText: "",
|
||||
bodyElementCount: 10,
|
||||
hideCloseButton: false,
|
||||
disableCloseOnOutsideClick: false,
|
||||
width: "default",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story: "Modal with header and body content but no footer actions.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const NoHeader: Story = {
|
||||
render: renderModal,
|
||||
args: {
|
||||
triggerText: "Open Modal - No Header",
|
||||
showHeader: false,
|
||||
showIcon: false,
|
||||
title: "",
|
||||
showDescription: false,
|
||||
description: "",
|
||||
showFooter: true,
|
||||
footerButtonConfiguration: "2",
|
||||
primaryButtonText: "Confirm",
|
||||
secondaryButtonText: "Cancel",
|
||||
tertiaryButtonText: "",
|
||||
bodyElementCount: 8,
|
||||
hideCloseButton: false,
|
||||
disableCloseOnOutsideClick: false,
|
||||
width: "default",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story: "Modal without header, useful when you want to focus on content and actions.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const RestrictClose: Story = {
|
||||
render: renderModal,
|
||||
args: {
|
||||
triggerText: "Open Modal - Restrict Close",
|
||||
showHeader: true,
|
||||
showIcon: true,
|
||||
title: "Modal with Restricted Close",
|
||||
showDescription: false,
|
||||
description: "This modal hides the close button and prevents closing on outside click.",
|
||||
showFooter: true,
|
||||
footerButtonConfiguration: "2",
|
||||
primaryButtonText: "Save",
|
||||
secondaryButtonText: "Cancel",
|
||||
tertiaryButtonText: "",
|
||||
bodyElementCount: 5,
|
||||
hideCloseButton: true,
|
||||
disableCloseOnOutsideClick: true,
|
||||
width: "default",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story: "Use when you need to force user interaction with the modal content before closing.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const WideModal: Story = {
|
||||
render: renderModal,
|
||||
args: {
|
||||
triggerText: "Open Modal - Wide Modal",
|
||||
showHeader: true,
|
||||
showIcon: true,
|
||||
title: "Modal with more width",
|
||||
showDescription: false,
|
||||
description: "This modal has more width than the default modal.",
|
||||
showFooter: true,
|
||||
footerButtonConfiguration: "2",
|
||||
primaryButtonText: "Save",
|
||||
secondaryButtonText: "Cancel",
|
||||
tertiaryButtonText: "",
|
||||
bodyElementCount: 5,
|
||||
hideCloseButton: false,
|
||||
disableCloseOnOutsideClick: false,
|
||||
width: "wide",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story: "Use when you need to force user interaction with the modal content before closing.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react";
|
||||
import { fn } from "@storybook/test";
|
||||
import { Modal } from "./index";
|
||||
|
||||
const meta = {
|
||||
title: "UI/Modal",
|
||||
component: Modal,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
layout: "centered",
|
||||
docs: {
|
||||
description: {
|
||||
component: "Modal component for displaying content in an overlay.",
|
||||
},
|
||||
story: {
|
||||
inline: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
open: { control: "boolean" },
|
||||
setOpen: { action: "setOpen" },
|
||||
title: { control: "text" },
|
||||
noPadding: { control: "boolean" },
|
||||
blur: { control: "boolean" },
|
||||
closeOnOutsideClick: { control: "boolean" },
|
||||
size: { control: { type: "select", options: ["md", "lg"] } },
|
||||
hideCloseButton: { control: "boolean" },
|
||||
restrictOverflow: { control: "boolean" },
|
||||
},
|
||||
args: { setOpen: fn() },
|
||||
} satisfies Meta<typeof Modal>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Default: Story = {
|
||||
args: {
|
||||
open: true,
|
||||
children: <div>Default Modal Content</div>,
|
||||
title: "Default Modal",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
primary: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const LargeSize: Story = {
|
||||
args: {
|
||||
...Default.args,
|
||||
size: "lg",
|
||||
title: "Large Modal",
|
||||
},
|
||||
};
|
||||
|
||||
export const NoPadding: Story = {
|
||||
args: {
|
||||
...Default.args,
|
||||
noPadding: true,
|
||||
title: "Modal without Padding",
|
||||
},
|
||||
};
|
||||
|
||||
export const WithBlur: Story = {
|
||||
args: {
|
||||
...Default.args,
|
||||
blur: true,
|
||||
title: "Modal with Blur",
|
||||
},
|
||||
};
|
||||
|
||||
export const HideCloseButton: Story = {
|
||||
args: {
|
||||
...Default.args,
|
||||
hideCloseButton: true,
|
||||
title: "Modal without Close Button",
|
||||
},
|
||||
};
|
||||
|
||||
export const PreventCloseOnOutsideClick: Story = {
|
||||
args: {
|
||||
...Default.args,
|
||||
closeOnOutsideClick: false,
|
||||
title: "Modal that doesn't close on outside click",
|
||||
},
|
||||
};
|
||||
|
||||
export const RestrictOverflow: Story = {
|
||||
args: {
|
||||
...Default.args,
|
||||
restrictOverflow: true,
|
||||
title: "Modal with Restricted Overflow",
|
||||
children: (
|
||||
<div style={{ height: "500px", overflowY: "auto" }}>
|
||||
{Array(50)
|
||||
.fill(0)
|
||||
.map((_, i) => (
|
||||
<p key={i}>Scrollable content line {i + 1}</p>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
};
|
||||
@@ -23,7 +23,7 @@ export const UpgradePrompt = ({ title, description, buttons }: UpgradePromptProp
|
||||
<KeyIcon className="h-6 w-6 text-slate-900" />
|
||||
</div>
|
||||
<div className="flex max-w-[80%] flex-col items-center gap-2 text-center">
|
||||
<p className="text-xl font-semibold text-slate-900">{title}</p>
|
||||
<h2 className="text-xl font-semibold text-slate-900">{title}</h2>
|
||||
<p className="text-sm text-slate-500">{description}</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
|
||||
@@ -4,11 +4,19 @@ import { logger } from "@formbricks/logger";
|
||||
|
||||
// Define the v1 (now v2) client endpoints to be merged
|
||||
const v1ClientEndpoints = {
|
||||
"/responses/{responseId}": {
|
||||
"/client/{environmentId}/responses/{responseId}": {
|
||||
put: {
|
||||
security: [],
|
||||
description:
|
||||
"Update an existing response for example when you want to mark a response as finished or you want to change an existing response's value.",
|
||||
parameters: [
|
||||
{
|
||||
in: "path",
|
||||
name: "environmentId",
|
||||
required: true,
|
||||
schema: { type: "string" },
|
||||
description: "The ID of the environment.",
|
||||
},
|
||||
{
|
||||
in: "path",
|
||||
name: "responseId",
|
||||
@@ -57,14 +65,15 @@ const v1ClientEndpoints = {
|
||||
tags: ["Client API > Response"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/responses": {
|
||||
"/client/{environmentId}/responses": {
|
||||
post: {
|
||||
security: [],
|
||||
description:
|
||||
"Create a response for a survey and its fields with the user's responses. The userId & meta here is optional",
|
||||
requestBody: {
|
||||
@@ -89,14 +98,15 @@ const v1ClientEndpoints = {
|
||||
tags: ["Client API > Response"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/contacts/{userId}/attributes": {
|
||||
"/client/{environmentId}/contacts/{userId}/attributes": {
|
||||
put: {
|
||||
security: [],
|
||||
description:
|
||||
"Update a contact's attributes in Formbricks to keep them in sync with your app or when you want to set a custom attribute in Formbricks.",
|
||||
parameters: [
|
||||
@@ -138,14 +148,15 @@ const v1ClientEndpoints = {
|
||||
tags: ["Client API > Contacts"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/identify/contacts/{userId}": {
|
||||
"/client/{environmentId}/identify/contacts/{userId}": {
|
||||
get: {
|
||||
security: [],
|
||||
description:
|
||||
"Retrieves a contact's state including their segments, displays, responses and other tracking information. If the contact doesn't exist, it will be created.",
|
||||
parameters: [
|
||||
@@ -167,14 +178,15 @@ const v1ClientEndpoints = {
|
||||
tags: ["Client API > Contacts"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/displays": {
|
||||
"/client/{environmentId}/displays": {
|
||||
post: {
|
||||
security: [],
|
||||
description:
|
||||
"Create a new display for a valid survey ID. If a userId is passed, the display is linked to the user.",
|
||||
requestBody: {
|
||||
@@ -199,48 +211,26 @@ const v1ClientEndpoints = {
|
||||
tags: ["Client API > Display"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/displays/{displayId}": {
|
||||
put: {
|
||||
description:
|
||||
"Update a Display for a user. A use case can be when a user submits a response & you want to link it to an existing display.",
|
||||
parameters: [{ in: "path", name: "displayId", required: true, schema: { type: "string" } }],
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: { example: { responseId: "response123" }, type: "object" },
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
"200": {
|
||||
content: {
|
||||
"application/json": {
|
||||
example: { displayId: "display123" },
|
||||
schema: { type: "object" },
|
||||
},
|
||||
},
|
||||
description: "OK",
|
||||
},
|
||||
},
|
||||
summary: "Update Display",
|
||||
tags: ["Client API > Display"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/environment": {
|
||||
"/client/{environmentId}/environment": {
|
||||
get: {
|
||||
description: "Retrieves the environment state to be used in Formbricks SDKs",
|
||||
security: [],
|
||||
description:
|
||||
"Retrieves the environment state to be used in Formbricks SDKs. **Cache Behavior**: This endpoint uses server-side caching with a **5-minute TTL (Time To Live)**. Any changes to surveys, action classes, project settings, or other environment data will take up to 5 minutes to reflect in the API response. This caching is implemented to improve performance for high-frequency SDK requests.",
|
||||
parameters: [
|
||||
{
|
||||
in: "path",
|
||||
name: "environmentId",
|
||||
required: true,
|
||||
schema: { type: "string" },
|
||||
description: "The ID of the environment.",
|
||||
},
|
||||
],
|
||||
responses: {
|
||||
"200": {
|
||||
content: {
|
||||
@@ -256,14 +246,15 @@ const v1ClientEndpoints = {
|
||||
tags: ["Client API > Environment"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/user": {
|
||||
"/client/{environmentId}/user": {
|
||||
post: {
|
||||
security: [],
|
||||
description:
|
||||
"Endpoint for creating or identifying a user within the specified environment. If the user already exists, this will identify them and potentially update user attributes. If they don't exist, it will create a new user.",
|
||||
requestBody: {
|
||||
@@ -288,14 +279,15 @@ const v1ClientEndpoints = {
|
||||
tags: ["Client API > User"],
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks Client",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/storage": {
|
||||
"/client/{environmentId}/storage": {
|
||||
post: {
|
||||
security: [],
|
||||
summary: "Upload Private File",
|
||||
description:
|
||||
"API endpoint for uploading private files. Uploaded files are kept private so that only users with access to the specified environment can retrieve them. The endpoint validates the survey ID, file name, and file type from the request body, and returns a signed URL for S3 uploads along with a local upload URL.",
|
||||
@@ -442,14 +434,15 @@ const v1ClientEndpoints = {
|
||||
},
|
||||
servers: [
|
||||
{
|
||||
url: "https://app.formbricks.com/api/v2/client",
|
||||
url: "https://app.formbricks.com/api/v2",
|
||||
description: "Formbricks API Server",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"/{environmentId}/storage/local": {
|
||||
"/client/{environmentId}/storage/local": {
|
||||
post: {
|
||||
security: [],
|
||||
summary: "Upload Private File to Local Storage",
|
||||
description:
|
||||
'API endpoint for uploading private files to local storage. The request must include a valid signature, UUID, and timestamp to verify the upload. The file is provided as a Base64 encoded string in the request body. The "Content-Type" header must be set to a valid MIME type, and the file data must be a valid file object (buffer).',
|
||||
@@ -478,7 +471,8 @@ const v1ClientEndpoints = {
|
||||
},
|
||||
fileName: {
|
||||
type: "string",
|
||||
description: "The URI encoded file name.",
|
||||
description:
|
||||
"This must be the `fileName` returned from the [Upload Private File](/api-v2-reference/client-api->-file-upload/upload-private-file) endpoint (Step 1).",
|
||||
},
|
||||
fileType: {
|
||||
type: "string",
|
||||
|
||||
@@ -197,6 +197,7 @@ tls:
|
||||
alpnProtocols:
|
||||
- h2
|
||||
- http/1.1
|
||||
- acme-tls/1
|
||||
EOT
|
||||
|
||||
echo "💡 Created traefik.yaml and traefik-dynamic.yaml file."
|
||||
|
||||
@@ -632,7 +632,7 @@
|
||||
},
|
||||
"/api/v1/client/{environmentId}/environment": {
|
||||
"get": {
|
||||
"description": "Retrieves the environment state to be used in Formbricks SDKs",
|
||||
"description": "Retrieves the environment state to be used in Formbricks SDKs **Cache Behavior**: This endpoint uses server-side caching with a **5-minute TTL (Time To Live)**. Any changes to surveys, action classes, project settings, or other environment data will take up to 5 minutes to reflect in the API response. This caching is implemented to improve performance for high-frequency SDK requests.",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "The ID of the environment",
|
||||
@@ -2336,13 +2336,8 @@
|
||||
"example": {
|
||||
"description": "From API Docs (optional)",
|
||||
"environmentId": "{{environmentId}}",
|
||||
"key": "my-action",
|
||||
"name": "My Action from Postman",
|
||||
"noCodeConfig": {
|
||||
"innerHtml": {
|
||||
"value": "sign-up"
|
||||
},
|
||||
"type": "innerHtml"
|
||||
},
|
||||
"type": "code"
|
||||
},
|
||||
"type": "object"
|
||||
|
||||
@@ -34,11 +34,18 @@ tags:
|
||||
security:
|
||||
- apiKeyAuth: []
|
||||
paths:
|
||||
/responses/{responseId}:
|
||||
/client/{environmentId}/responses/{responseId}:
|
||||
put:
|
||||
security: []
|
||||
description: Update an existing response for example when you want to mark a
|
||||
response as finished or you want to change an existing response's value.
|
||||
parameters:
|
||||
- in: path
|
||||
name: environmentId
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
description: The ID of the environment.
|
||||
- in: path
|
||||
name: responseId
|
||||
required: true
|
||||
@@ -77,10 +84,11 @@ paths:
|
||||
tags:
|
||||
- Client API > Response
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks Client
|
||||
/{environmentId}/responses:
|
||||
/client/{environmentId}/responses:
|
||||
post:
|
||||
security: []
|
||||
description: Create a response for a survey and its fields with the user's
|
||||
responses. The userId & meta here is optional
|
||||
requestBody:
|
||||
@@ -104,10 +112,11 @@ paths:
|
||||
tags:
|
||||
- Client API > Response
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks Client
|
||||
/{environmentId}/contacts/{userId}/attributes:
|
||||
/client/{environmentId}/contacts/{userId}/attributes:
|
||||
put:
|
||||
security: []
|
||||
description: Update a contact's attributes in Formbricks to keep them in sync
|
||||
with your app or when you want to set a custom attribute in Formbricks.
|
||||
parameters:
|
||||
@@ -152,10 +161,11 @@ paths:
|
||||
tags:
|
||||
- Client API > Contacts
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks Client
|
||||
/{environmentId}/identify/contacts/{userId}:
|
||||
/client/{environmentId}/identify/contacts/{userId}:
|
||||
get:
|
||||
security: []
|
||||
description: Retrieves a contact's state including their segments, displays,
|
||||
responses and other tracking information. If the contact doesn't exist,
|
||||
it will be created.
|
||||
@@ -184,10 +194,11 @@ paths:
|
||||
tags:
|
||||
- Client API > Contacts
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks Client
|
||||
/{environmentId}/displays:
|
||||
/client/{environmentId}/displays:
|
||||
post:
|
||||
security: []
|
||||
description: Create a new display for a valid survey ID. If a userId is passed,
|
||||
the display is linked to the user.
|
||||
requestBody:
|
||||
@@ -211,43 +222,24 @@ paths:
|
||||
tags:
|
||||
- Client API > Display
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks Client
|
||||
/{environmentId}/displays/{displayId}:
|
||||
put:
|
||||
description: Update a Display for a user. A use case can be when a user submits
|
||||
a response & you want to link it to an existing display.
|
||||
/client/{environmentId}/environment:
|
||||
get:
|
||||
security: []
|
||||
description: "Retrieves the environment state to be used in Formbricks SDKs.
|
||||
**Cache Behavior**: This endpoint uses server-side caching with a
|
||||
**5-minute TTL (Time To Live)**. Any changes to surveys, action classes,
|
||||
project settings, or other environment data will take up to 5 minutes to
|
||||
reflect in the API response. This caching is implemented to improve
|
||||
performance for high-frequency SDK requests."
|
||||
parameters:
|
||||
- in: path
|
||||
name: displayId
|
||||
name: environmentId
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
example:
|
||||
responseId: response123
|
||||
type: object
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
example:
|
||||
displayId: display123
|
||||
schema:
|
||||
type: object
|
||||
description: OK
|
||||
summary: Update Display
|
||||
tags:
|
||||
- Client API > Display
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
description: Formbricks Client
|
||||
/{environmentId}/environment:
|
||||
get:
|
||||
description: Retrieves the environment state to be used in Formbricks SDKs
|
||||
description: The ID of the environment.
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
@@ -262,10 +254,11 @@ paths:
|
||||
tags:
|
||||
- Client API > Environment
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks Client
|
||||
/{environmentId}/user:
|
||||
/client/{environmentId}/user:
|
||||
post:
|
||||
security: []
|
||||
description: Endpoint for creating or identifying a user within the specified
|
||||
environment. If the user already exists, this will identify them and
|
||||
potentially update user attributes. If they don't exist, it will create
|
||||
@@ -292,10 +285,11 @@ paths:
|
||||
tags:
|
||||
- Client API > User
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks Client
|
||||
/{environmentId}/storage:
|
||||
/client/{environmentId}/storage:
|
||||
post:
|
||||
security: []
|
||||
summary: Upload Private File
|
||||
description: API endpoint for uploading private files. Uploaded files are kept
|
||||
private so that only users with access to the specified environment can
|
||||
@@ -402,10 +396,11 @@ paths:
|
||||
example:
|
||||
error: Survey survey123 not found
|
||||
servers:
|
||||
- url: https://app.formbricks.com/api/v2/client
|
||||
- url: https://app.formbricks.com/api/v2
|
||||
description: Formbricks API Server
|
||||
/{environmentId}/storage/local:
|
||||
/client/{environmentId}/storage/local:
|
||||
post:
|
||||
security: []
|
||||
summary: Upload Private File to Local Storage
|
||||
description: API endpoint for uploading private files to local storage. The
|
||||
request must include a valid signature, UUID, and timestamp to verify
|
||||
@@ -433,7 +428,9 @@ paths:
|
||||
description: The ID of the survey associated with the file.
|
||||
fileName:
|
||||
type: string
|
||||
description: The URI encoded file name.
|
||||
description: This must be the `fileName` returned from the [Upload Private
|
||||
File](/api-v2-reference/client-api->-file-upload/upload-private-file)
|
||||
endpoint (Step 1).
|
||||
fileType:
|
||||
type: string
|
||||
description: The MIME type of the file.
|
||||
@@ -1531,12 +1528,17 @@ paths:
|
||||
put:
|
||||
operationId: uploadBulkContacts
|
||||
summary: Upload Bulk Contacts
|
||||
description: Uploads contacts in bulk
|
||||
description: Uploads contacts in bulk. Each contact in the payload must have an
|
||||
'email' attribute present in their attributes array. The email attribute
|
||||
is mandatory and must be a valid email format. Without a valid email,
|
||||
the contact will be skipped during processing.
|
||||
tags:
|
||||
- Management API > Contacts
|
||||
requestBody:
|
||||
required: true
|
||||
description: The contacts to upload
|
||||
description: The contacts to upload. Each contact must include an 'email'
|
||||
attribute in their attributes array. The email is used as the unique
|
||||
identifier for the contact.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@@ -1571,10 +1573,39 @@ paths:
|
||||
- value
|
||||
required:
|
||||
- attributes
|
||||
maxItems: 1000
|
||||
maxItems: 250
|
||||
required:
|
||||
- environmentId
|
||||
- contacts
|
||||
example:
|
||||
environmentId: env_01h2xce9q8p3w4x5y6z7a8b9c0
|
||||
contacts:
|
||||
- attributes:
|
||||
- attributeKey:
|
||||
key: email
|
||||
name: Email Address
|
||||
value: john.doe@example.com
|
||||
- attributeKey:
|
||||
key: firstName
|
||||
name: First Name
|
||||
value: John
|
||||
- attributeKey:
|
||||
key: lastName
|
||||
name: Last Name
|
||||
value: Doe
|
||||
- attributes:
|
||||
- attributeKey:
|
||||
key: email
|
||||
name: Email Address
|
||||
value: jane.smith@example.com
|
||||
- attributeKey:
|
||||
key: firstName
|
||||
name: First Name
|
||||
value: Jane
|
||||
- attributeKey:
|
||||
key: lastName
|
||||
name: Last Name
|
||||
value: Smith
|
||||
responses:
|
||||
"200":
|
||||
description: Contacts uploaded successfully.
|
||||
@@ -4383,6 +4414,22 @@ components:
|
||||
- enabled
|
||||
- message
|
||||
description: Email verification configuration (deprecated)
|
||||
recaptcha:
|
||||
type:
|
||||
- object
|
||||
- "null"
|
||||
properties:
|
||||
enabled:
|
||||
type: boolean
|
||||
threshold:
|
||||
type: number
|
||||
multipleOf: 0.1
|
||||
minimum: 0.1
|
||||
maximum: 0.9
|
||||
required:
|
||||
- enabled
|
||||
- threshold
|
||||
description: Google reCAPTCHA configuration
|
||||
displayPercentage:
|
||||
type:
|
||||
- number
|
||||
@@ -4431,6 +4478,7 @@ components:
|
||||
- inlineTriggers
|
||||
- isBackButtonHidden
|
||||
- verifyEmail
|
||||
- recaptcha
|
||||
- displayPercentage
|
||||
- questions
|
||||
webhook:
|
||||
|
||||
@@ -80,11 +80,24 @@ When PUBLIC_URL is configured, the following routes are automatically served fro
|
||||
#### Survey Routes
|
||||
|
||||
- `/s/{surveyId}` - Individual survey access
|
||||
- `/c/{jwt}` - Personalized link survey access (JWT-based access)
|
||||
- Embedded survey endpoints
|
||||
|
||||
#### API Routes
|
||||
|
||||
- `/api/v1/client/{environmentId}/*` - Client API endpoints
|
||||
- `/api/v1/client/{environmentId}/*` - Client API endpoints (v1)
|
||||
- `/api/v2/client/{environmentId}/*` - Client API endpoints (v2)
|
||||
|
||||
#### Static Assets & Next.js Routes
|
||||
|
||||
- `/favicon.ico` - Favicon
|
||||
- `/_next/*` - Next.js static assets and build files
|
||||
- `/js/*` - JavaScript files
|
||||
- `/css/*` - CSS stylesheets
|
||||
- `/images/*` - Image assets
|
||||
- `/fonts/*` - Font files
|
||||
- `/icons/*` - Icon assets
|
||||
- `/public/*` - Public static files
|
||||
|
||||
#### Storage Routes
|
||||
|
||||
|
||||
@@ -11,18 +11,21 @@ icon: "code"
|
||||
The user performs an action in your application.
|
||||
</Step>
|
||||
|
||||
<Step title="Formbricks widget detects action">
|
||||
The embedded widget (SDK) detects the action, if you set up a [No Code Action](/xm-and-surveys/surveys/website-app-surveys/actions#setting-up-no-code-actions) or a [Code Action](/xm-and-surveys/surveys/website-app-surveys/actions#setting-up-code-actions) to do so.
|
||||
</Step>
|
||||
<Step title="Formbricks widget detects action">
|
||||
The embedded widget (SDK) detects the action, if you set up a [No Code
|
||||
Action](/xm-and-surveys/surveys/website-app-surveys/actions#setting-up-no-code-actions) or a [Code
|
||||
Action](/xm-and-surveys/surveys/website-app-surveys/actions#setting-up-code-actions) to do so.
|
||||
</Step>
|
||||
|
||||
<Step title="Check for survey trigger">
|
||||
If a survey is set to trigger on that action, Formbricks checks if the user or visitor qualifies.
|
||||
</Step>
|
||||
<Step title="Check for survey trigger">
|
||||
If a survey is set to trigger on that action, Formbricks checks if the user or visitor qualifies.
|
||||
</Step>
|
||||
|
||||
<Step title="Check for user or visitor qualification">
|
||||
If the user or visitor already filled out a survey in the past couple of days (see [Global Waiting Time](/xm-and-surveys/surveys/website-app-surveys/recontact#project-wide-global-waiting-time)), the survey will not be shown to prevent survey fatigue.
|
||||
|
||||
Also, if this user or visitor has seen this specific survey before, Formbricks might not show it as this is dependent on the [Recontact Options](/xm-and-surveys/surveys/website-app-surveys/recontact).
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Show survey">
|
||||
@@ -31,15 +34,29 @@ icon: "code"
|
||||
</Steps>
|
||||
|
||||
<Tip>
|
||||
Tying surveys to specific user actions enables **context-aware surveying**: You make sure that your user research is relevant to the current user context which leads to sign**ificantly higher response and completions rates** as well as lower survey fatigue.
|
||||
Tying surveys to specific user actions enables **context-aware surveying**: You make sure that your user
|
||||
research is relevant to the current user context which leads to sign**ificantly higher response and
|
||||
completions rates** as well as lower survey fatigue.
|
||||
</Tip>
|
||||
|
||||
<Note>
|
||||
**Important**: Any changes to actions, surveys, or environment configuration will take up to 5 minutes to
|
||||
reflect in your app/website running the formbricks sdk with debug mode enabled due to server-side caching.
|
||||
This includes new actions, modified action configurations, and survey trigger updates. For quick updates
|
||||
during development and testing, you can enable [Debug
|
||||
Mode](/xm-and-surveys/surveys/website-app-surveys/framework-guides#activate-debug-mode) in your SDK
|
||||
configuration.
|
||||
</Note>
|
||||
|
||||
## **Setting Up No-Code Actions**
|
||||
|
||||
Formbricks offers an intuitive No-Code interface that allows you to configure actions without needing to write any code.
|
||||
|
||||
<Note>
|
||||
No Code Actions are **not available for surveys in mobile apps**. No Code Action tracking are heavily dependent on JavaScript and most mobile apps are compiled into a different programming language. To track user actions in mobile apps use [Code Actions.](/xm-and-surveys/surveys/website-app-surveys/actions#setting-up-code-actions)
|
||||
No Code Actions are **not available for surveys in mobile apps**. No Code Action tracking are heavily
|
||||
dependent on JavaScript and most mobile apps are compiled into a different programming language. To track
|
||||
user actions in mobile apps use [Code
|
||||
Actions.](/xm-and-surveys/surveys/website-app-surveys/actions#setting-up-code-actions)
|
||||
</Note>
|
||||
|
||||
<Steps>
|
||||
@@ -55,27 +72,31 @@ Formbricks offers an intuitive No-Code interface that allows you to configure ac
|
||||
There are four types of No-Code actions:
|
||||
|
||||
### **1. Click Action**
|
||||
|
||||

|
||||
|
||||
A Click Action is triggered when a user clicks on a specific element within your application. You can define the element's inner text, CSS selector or both to trigger the survey.
|
||||
|
||||
* **Inner Text**: Checks if the innerText of a clicked HTML element, like a button label, matches a specific text. This action allows you to display a survey based on text interactions within your application.
|
||||
- **Inner Text**: Checks if the innerText of a clicked HTML element, like a button label, matches a specific text. This action allows you to display a survey based on text interactions within your application.
|
||||
|
||||
* **CSS Selector**: Verifies if a clicked HTML element matches a provided CSS selector, such as a class, ID, or any other CSS selector used in your website. It enables survey triggers based on element interactions.
|
||||
- **CSS Selector**: Verifies if a clicked HTML element matches a provided CSS selector, such as a class, ID, or any other CSS selector used in your website. It enables survey triggers based on element interactions.
|
||||
|
||||
* **Both**: Only if both is true, the action is triggered
|
||||
- **Both**: Only if both is true, the action is triggered
|
||||
|
||||
### **2. Page View Action**
|
||||
|
||||

|
||||
|
||||
This action is triggered when a user visits a page within your application.
|
||||
|
||||
### **3. Exit Intent Action**
|
||||
|
||||

|
||||
|
||||
This action is triggered when a user is about to leave your application. It helps capture user feedback before they exit, providing valuable insights into user experiences and potential improvements.
|
||||
|
||||
### **4. 50% Scroll Action**
|
||||
|
||||

|
||||
|
||||
This action is triggered when a user scrolls through 50% of a page within your application. It helps capture user feedback at a specific point in their journey, enabling you to gather insights based on user interactions.
|
||||
@@ -88,17 +109,17 @@ You can combine the url filters with any of the no-code actions to trigger the s
|
||||
|
||||
You can limit action tracking to specific subpages of your website or web app by using the Page Filter. Here you can use a variety of URL filter settings:
|
||||
|
||||
* **exactMatch**: Triggers the action when the URL exactly matches the specified string.
|
||||
- **exactMatch**: Triggers the action when the URL exactly matches the specified string.
|
||||
|
||||
* **contains**: Activates when the URL contains the specified substring.
|
||||
- **contains**: Activates when the URL contains the specified substring.
|
||||
|
||||
* **startsWith**: Fires when the URL starts with the specified string.
|
||||
- **startsWith**: Fires when the URL starts with the specified string.
|
||||
|
||||
* **endsWith**: Executes when the URL ends with the specified string.
|
||||
- **endsWith**: Executes when the URL ends with the specified string.
|
||||
|
||||
* **notMatch**: Triggers when the URL does not match the specified condition.
|
||||
- **notMatch**: Triggers when the URL does not match the specified condition.
|
||||
|
||||
* **notContains**: Activates when the URL does not contain the specified substring.
|
||||
- **notContains**: Activates when the URL does not contain the specified substring.
|
||||
|
||||
## **Setting Up Code Actions**
|
||||
|
||||
@@ -108,7 +129,7 @@ For more granular control, you can implement actions directly in your code:
|
||||
<Step title="Configure action in Formbricks">
|
||||
First, add the action via the Formbricks web interface to make it available for survey configuration:
|
||||
|
||||

|
||||

|
||||
|
||||
</Step>
|
||||
|
||||
@@ -128,5 +149,6 @@ For more granular control, you can implement actions directly in your code:
|
||||
|
||||
return <button onClick={handleClick}>Click Me</button>;
|
||||
```
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
</Steps>
|
||||
|
||||
@@ -16,33 +16,37 @@ sidebarTitle: "Quickstart"
|
||||
You can create In-product and Link Surveys with both options, but the onboarding will prompt you to connect your app/website to Formbricks.
|
||||
|
||||

|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Connect your App/Website">
|
||||
Follow the instructions to connect your app or website:
|
||||

|
||||
</Step>
|
||||
<Step title="Connect your App/Website">
|
||||
Follow the instructions to connect your app or website: 
|
||||
</Step>
|
||||
|
||||
<Step title="Confirm setup">
|
||||
As soon as Formbricks receives the first data point, you will see a message in the onboarding:
|
||||
|
||||

|
||||
|
||||
|
||||
Onboarding is complete! Now let's create our first survey as you should see templates to choose from after clicking on **Next**:
|
||||
|
||||

|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Create your first survey">
|
||||
To be able to see a survey in your app, you need to create one. We'll choose one of the templates and head over to the survey settings:
|
||||
|
||||
Pick the Survey Type as **Website & App Survey**.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Create trigger to show survey">
|
||||
Scroll to **Survey Trigger**, click **+ Add Action**, and select **Page View**. This ensures the survey appears when the Formbricks Widget detects any page load.
|
||||
|
||||

|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Set Recontact Options right">
|
||||
@@ -52,17 +56,22 @@ sidebarTitle: "Quickstart"
|
||||
<Note>
|
||||
Please change this setting after testing your survey to avoid user fatigue.
|
||||
</Note>
|
||||
</Step>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Publish the survey">
|
||||
Publish the survey to make it available for the SDK to pull into the website or app where you want to show it.
|
||||
</Step>
|
||||
<Step title="Enable debug mode in website / app">
|
||||
For better scalability, we cache the request the SDK makes to the server. This allows you to use Formbricks on websites with millions of visitors without high hosting cost. On the downside, there can be **up to a 10 minute delay** until the SDK pulls the newest surveys from the server.
|
||||
|
||||
<Step title="Enable debug mode in website / app">
|
||||
For better scalability, we cache the request the SDK makes to the server. This allows you to use Formbricks on websites with millions of visitors without high hosting cost. On the downside, there can be **up to a 5 minute delay** until the SDK pulls the newest surveys from the server.
|
||||
|
||||
To avoid the delay, please switch on the [Debug Mode.](/xm-and-surveys/surveys/website-app-surveys/framework-guides#activate-debug-mode)
|
||||
<Note>
|
||||
**Important**: Any changes to surveys, action classes, project settings, or environment configuration will take up to 5 minutes to reflect in debug mode in your app/website due to server-side caching. This includes survey modifications, new triggers, styling changes, and other updates.
|
||||
</Note>
|
||||
|
||||
To avoid the delay during development and testing, please switch on the [Debug Mode.](/xm-and-surveys/surveys/website-app-surveys/framework-guides#activate-debug-mode)
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
Need help? Join us in [**GitHub Discussions**](https://github.com/formbricks/formbricks/discussions), and we’ll be happy to assist!
|
||||
Need help? Join us in [**GitHub Discussions**](https://github.com/formbricks/formbricks/discussions), and we'll be happy to assist!
|
||||
|
||||
@@ -74,6 +74,8 @@ cronJob:
|
||||
|
||||
## Deployment & Autoscaling
|
||||
deployment:
|
||||
image:
|
||||
pullPolicy: Always
|
||||
resources:
|
||||
limits:
|
||||
cpu: 2
|
||||
|
||||
@@ -28,9 +28,14 @@ export const ZWebhook = z.object({
|
||||
environmentId: z.string().cuid2().openapi({
|
||||
description: "The ID of the environment",
|
||||
}),
|
||||
triggers: z.array(z.enum(["responseFinished", "responseCreated", "responseUpdated"])).openapi({
|
||||
description: "The triggers of the webhook",
|
||||
}),
|
||||
triggers: z
|
||||
.array(z.enum(["responseFinished", "responseCreated", "responseUpdated"]))
|
||||
.openapi({
|
||||
description: "The triggers of the webhook",
|
||||
})
|
||||
.min(1, {
|
||||
message: "At least one trigger is required",
|
||||
}),
|
||||
surveyIds: z.array(z.string().cuid2()).openapi({
|
||||
description: "The IDs of the surveys ",
|
||||
}),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { checkForLoomUrl, checkForVimeoUrl, checkForYoutubeUrl, convertToEmbedUrl } from "@/lib/video-upload";
|
||||
import { useState } from "preact/hooks";
|
||||
|
||||
@@ -26,7 +27,7 @@ export function QuestionMedia({ imgUrl, videoUrl, altText = "Image" }: QuestionM
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
return (
|
||||
<div className="fb-group/image fb-relative fb-mb-4 fb-block fb-min-h-40 fb-rounded-md">
|
||||
<div className="fb-group/image fb-relative fb-mb-6 fb-block fb-min-h-40 fb-rounded-md">
|
||||
{isLoading ? (
|
||||
<div className="fb-absolute fb-inset-auto fb-flex fb-h-full fb-w-full fb-animate-pulse fb-items-center fb-justify-center fb-rounded-md fb-bg-slate-200" />
|
||||
) : null}
|
||||
@@ -35,10 +36,16 @@ export function QuestionMedia({ imgUrl, videoUrl, altText = "Image" }: QuestionM
|
||||
key={imgUrl}
|
||||
src={imgUrl}
|
||||
alt={altText}
|
||||
className="fb-rounded-custom"
|
||||
className={cn(
|
||||
"fb-rounded-custom fb-max-h-[40dvh] fb-mx-auto fb-object-contain",
|
||||
isLoading ? "fb-opacity-0" : ""
|
||||
)}
|
||||
onLoad={() => {
|
||||
setIsLoading(false);
|
||||
}}
|
||||
onError={() => {
|
||||
setIsLoading(false);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{videoUrlWithParams ? (
|
||||
@@ -48,10 +55,13 @@ export function QuestionMedia({ imgUrl, videoUrl, altText = "Image" }: QuestionM
|
||||
src={videoUrlWithParams}
|
||||
title="Question Video"
|
||||
frameBorder="0"
|
||||
className="fb-rounded-custom fb-aspect-video fb-w-full"
|
||||
className={cn("fb-rounded-custom fb-aspect-video fb-w-full", isLoading ? "fb-opacity-0" : "")}
|
||||
onLoad={() => {
|
||||
setIsLoading(false);
|
||||
}}
|
||||
onError={() => {
|
||||
setIsLoading(false);
|
||||
}}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"
|
||||
referrerPolicy="strict-origin-when-cross-origin"
|
||||
/>
|
||||
|
||||
@@ -207,7 +207,7 @@ export function MultipleChoiceMultiQuestion({
|
||||
name={question.id}
|
||||
tabIndex={-1}
|
||||
value={getLocalizedValue(choice.label, languageCode)}
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-flex-shrink-0 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
aria-labelledby={`${choice.id}-label`}
|
||||
onChange={(e) => {
|
||||
if ((e.target as HTMLInputElement).checked) {
|
||||
@@ -251,7 +251,7 @@ export function MultipleChoiceMultiQuestion({
|
||||
id={otherOption.id}
|
||||
name={question.id}
|
||||
value={getLocalizedValue(otherOption.label, languageCode)}
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-flex-shrink-0 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
aria-labelledby={`${otherOption.id}-label`}
|
||||
onChange={() => {
|
||||
if (otherSelected) {
|
||||
|
||||
@@ -168,7 +168,7 @@ export function MultipleChoiceSingleQuestion({
|
||||
name={question.id}
|
||||
value={getLocalizedValue(choice.label, languageCode)}
|
||||
dir="auto"
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-flex-shrink-0 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
aria-labelledby={`${choice.id}-label`}
|
||||
onChange={() => {
|
||||
setOtherSelected(false);
|
||||
@@ -210,7 +210,7 @@ export function MultipleChoiceSingleQuestion({
|
||||
id={otherOption.id}
|
||||
name={question.id}
|
||||
value={getLocalizedValue(otherOption.label, languageCode)}
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
className="fb-border-brand fb-text-brand fb-h-4 fb-w-4 fb-flex-shrink-0 fb-border focus:fb-ring-0 focus:fb-ring-offset-0"
|
||||
aria-labelledby={`${otherOption.id}-label`}
|
||||
onChange={() => {
|
||||
setOtherSelected(!otherSelected);
|
||||
|
||||
@@ -171,7 +171,7 @@ describe("PictureSelectionQuestion", () => {
|
||||
render(<PictureSelectionQuestion {...mockProps} />);
|
||||
|
||||
const images = screen.getAllByRole("img");
|
||||
const label = images[0].closest("label");
|
||||
const label = images[0].closest("button");
|
||||
|
||||
fireEvent.keyDown(label!, { key: " " });
|
||||
|
||||
|
||||
@@ -43,6 +43,13 @@ export function PictureSelectionQuestion({
|
||||
isBackButtonHidden,
|
||||
}: Readonly<PictureSelectionProps>) {
|
||||
const [startTime, setStartTime] = useState(performance.now());
|
||||
const [loadingImages, setLoadingImages] = useState<Record<string, boolean>>(() => {
|
||||
const initialLoadingState: Record<string, boolean> = {};
|
||||
question.choices.forEach((choice) => {
|
||||
initialLoadingState[choice.id] = true;
|
||||
});
|
||||
return initialLoadingState;
|
||||
});
|
||||
const isMediaAvailable = question.imageUrl || question.videoUrl;
|
||||
const isCurrent = question.id === currentQuestionId;
|
||||
useTtc(question.id, ttc, setTtc, startTime, setStartTime, isCurrent);
|
||||
@@ -115,35 +122,75 @@ export function PictureSelectionQuestion({
|
||||
<div className="fb-mt-4">
|
||||
<fieldset>
|
||||
<legend className="fb-sr-only">Options</legend>
|
||||
<div className="fb-bg-survey-bg fb-relative fb-grid fb-grid-cols-2 fb-gap-4">
|
||||
<div className="fb-bg-survey-bg fb-relative fb-grid fb-grid-cols-1 sm:fb-grid-cols-2 fb-gap-4">
|
||||
{questionChoices.map((choice) => (
|
||||
<label
|
||||
key={choice.id}
|
||||
tabIndex={isCurrent ? 0 : -1}
|
||||
htmlFor={choice.id}
|
||||
onKeyDown={(e) => {
|
||||
// Accessibility: if spacebar was pressed pass this down to the input
|
||||
if (e.key === " ") {
|
||||
e.preventDefault();
|
||||
document.getElementById(choice.id)?.click();
|
||||
document.getElementById(choice.id)?.focus();
|
||||
}
|
||||
}}
|
||||
onClick={() => {
|
||||
handleChange(choice.id);
|
||||
}}
|
||||
className={cn(
|
||||
"fb-relative fb-w-full fb-cursor-pointer fb-overflow-hidden fb-border fb-rounded-custom focus:fb-outline-none fb-aspect-[4/3] fb-min-h-[7rem] fb-max-h-[50vh] focus:fb-border-brand focus:fb-border-4 group/image",
|
||||
Array.isArray(value) && value.includes(choice.id)
|
||||
? "fb-border-brand fb-text-brand fb-z-10 fb-border-4 fb-shadow-sm"
|
||||
: ""
|
||||
)}>
|
||||
<img
|
||||
src={choice.imageUrl}
|
||||
id={choice.id}
|
||||
alt={getOriginalFileNameFromUrl(choice.imageUrl)}
|
||||
className="fb-h-full fb-w-full fb-object-cover"
|
||||
/>
|
||||
<div className="fb-relative" key={choice.id}>
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={isCurrent ? 0 : -1}
|
||||
onKeyDown={(e) => {
|
||||
// Accessibility: if spacebar was pressed pass this down to the input
|
||||
if (e.key === " ") {
|
||||
e.preventDefault();
|
||||
e.currentTarget.click();
|
||||
e.currentTarget.focus();
|
||||
}
|
||||
}}
|
||||
onClick={() => {
|
||||
handleChange(choice.id);
|
||||
}}
|
||||
className={cn(
|
||||
"fb-relative fb-w-full fb-cursor-pointer fb-overflow-hidden fb-border fb-rounded-custom focus-visible:fb-outline-none focus-visible:fb-ring-2 focus-visible:fb-ring-brand focus-visible:fb-ring-offset-2 fb-aspect-[4/3] fb-min-h-[7rem] fb-max-h-[50vh] group/image",
|
||||
Array.isArray(value) && value.includes(choice.id)
|
||||
? "fb-border-brand fb-text-brand fb-z-10 fb-border-4 fb-shadow-sm"
|
||||
: ""
|
||||
)}>
|
||||
{loadingImages[choice.id] && (
|
||||
<div className="fb-absolute fb-inset-0 fb-flex fb-h-full fb-w-full fb-animate-pulse fb-items-center fb-justify-center fb-rounded-md fb-bg-slate-200" />
|
||||
)}
|
||||
<img
|
||||
src={choice.imageUrl}
|
||||
id={choice.id}
|
||||
alt={getOriginalFileNameFromUrl(choice.imageUrl)}
|
||||
className={cn(
|
||||
"fb-h-full fb-w-full fb-object-cover",
|
||||
loadingImages[choice.id] ? "fb-opacity-0" : ""
|
||||
)}
|
||||
onLoad={() => {
|
||||
setLoadingImages((prev) => ({ ...prev, [choice.id]: false }));
|
||||
}}
|
||||
onError={() => {
|
||||
setLoadingImages((prev) => ({ ...prev, [choice.id]: false }));
|
||||
}}
|
||||
/>
|
||||
{question.allowMulti ? (
|
||||
<input
|
||||
id={`${choice.id}-checked`}
|
||||
name={`${choice.id}-checkbox`}
|
||||
type="checkbox"
|
||||
tabIndex={-1}
|
||||
checked={value.includes(choice.id)}
|
||||
className={cn(
|
||||
"fb-border-border fb-rounded-custom fb-pointer-events-none fb-absolute fb-right-2 fb-top-2 fb-z-20 fb-h-5 fb-w-5 fb-border",
|
||||
value.includes(choice.id) ? "fb-border-brand fb-text-brand" : ""
|
||||
)}
|
||||
required={question.required && value.length ? false : question.required}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
id={`${choice.id}-radio`}
|
||||
name={`${question.id}`}
|
||||
type="radio"
|
||||
tabIndex={-1}
|
||||
checked={value.includes(choice.id)}
|
||||
className={cn(
|
||||
"fb-border-border fb-pointer-events-none fb-absolute fb-right-2 fb-top-2 fb-z-20 fb-h-5 fb-w-5 fb-rounded-full fb-border",
|
||||
value.includes(choice.id) ? "fb-border-brand fb-text-brand" : ""
|
||||
)}
|
||||
required={question.required && value.length ? false : question.required}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
<a
|
||||
tabIndex={-1}
|
||||
href={choice.imageUrl}
|
||||
@@ -153,52 +200,25 @@ export function PictureSelectionQuestion({
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="fb-absolute fb-bottom-2 fb-right-2 fb-flex fb-items-center fb-gap-2 fb-whitespace-nowrap fb-rounded-md fb-bg-slate-800 fb-bg-opacity-40 fb-p-1.5 fb-text-white fb-opacity-0 fb-backdrop-blur-lg fb-transition fb-duration-300 fb-ease-in-out hover:fb-bg-opacity-65 group-hover/image:fb-opacity-100">
|
||||
className="fb-absolute fb-bottom-4 fb-right-2 fb-flex fb-items-center fb-gap-2 fb-whitespace-nowrap fb-rounded-md fb-bg-slate-800 fb-bg-opacity-40 fb-p-1.5 fb-text-white fb-backdrop-blur-lg fb-transition fb-duration-300 fb-ease-in-out hover:fb-bg-opacity-65 group-hover/image:fb-opacity-100 fb-z-20">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="lucide lucide-expand">
|
||||
<path d="m21 21-6-6m6 6v-4.8m0 4.8h-4.8" />
|
||||
<path d="M3 16.2V21m0 0h4.8M3 21l6-6" />
|
||||
<path d="M21 7.8V3m0 0h-4.8M21 3l-6 6" />
|
||||
<path d="M3 7.8V3m0 0h4.8M3 3l6 6" />
|
||||
className="lucide lucide-image-down-icon lucide-image-down">
|
||||
<path d="M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21" />
|
||||
<path d="m14 19 3 3v-5.5" />
|
||||
<path d="m17 22 3-3" />
|
||||
<circle cx="9" cy="9" r="2" />
|
||||
</svg>
|
||||
</a>
|
||||
{question.allowMulti ? (
|
||||
<input
|
||||
id={`${choice.id}-checked`}
|
||||
name={`${choice.id}-checkbox`}
|
||||
type="checkbox"
|
||||
tabIndex={-1}
|
||||
checked={value.includes(choice.id)}
|
||||
className={cn(
|
||||
"fb-border-border fb-rounded-custom fb-pointer-events-none fb-absolute fb-right-2 fb-top-2 fb-z-20 fb-h-5 fb-w-5 fb-border",
|
||||
value.includes(choice.id) ? "fb-border-brand fb-text-brand" : ""
|
||||
)}
|
||||
required={question.required && value.length ? false : question.required}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
id={`${choice.id}-radio`}
|
||||
name={`${choice.id}-radio`}
|
||||
type="radio"
|
||||
tabIndex={-1}
|
||||
checked={value.includes(choice.id)}
|
||||
className={cn(
|
||||
"fb-border-border fb-pointer-events-none fb-absolute fb-right-2 fb-top-2 fb-z-20 fb-h-5 fb-w-5 fb-rounded-full fb-border",
|
||||
value.includes(choice.id) ? "fb-border-brand fb-text-brand" : ""
|
||||
)}
|
||||
required={question.required && value.length ? false : question.required}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { ZId } from "./common";
|
||||
|
||||
export const ZActionClassMatchType = z.union([
|
||||
z.literal("exactMatch"),
|
||||
@@ -91,8 +92,8 @@ const ZActionClassInputBase = z.object({
|
||||
.string({ message: "Name is required" })
|
||||
.trim()
|
||||
.min(1, { message: "Name must be at least 1 character long" }),
|
||||
description: z.string().nullable(),
|
||||
environmentId: z.string(),
|
||||
description: z.string().nullish(),
|
||||
environmentId: ZId.min(1, { message: "Environment ID cannot be empty" }),
|
||||
type: ZActionClassType,
|
||||
});
|
||||
|
||||
@@ -108,6 +109,9 @@ const ZActionClassInputNoCode = ZActionClassInputBase.extend({
|
||||
noCodeConfig: ZActionClassNoCodeConfig.nullable(),
|
||||
});
|
||||
|
||||
export const ZActionClassInput = z.union([ZActionClassInputCode, ZActionClassInputNoCode]);
|
||||
export const ZActionClassInput = z.discriminatedUnion("type", [
|
||||
ZActionClassInputCode,
|
||||
ZActionClassInputNoCode,
|
||||
]);
|
||||
|
||||
export type TActionClassInput = z.infer<typeof ZActionClassInput>;
|
||||
|
||||
Reference in New Issue
Block a user