Compare commits

...

9 Commits

Author SHA1 Message Date
Piyush Gupta
fa6bf73f51 Merge branch 'main' of https://github.com/formbricks/formbricks into personalized-links-demo 2025-07-08 18:09:20 +05:30
Dhruwang Jariwala
b0a7e212dd fix: suid copy issue on safari (#6174) 2025-07-08 10:50:02 +00:00
Dhruwang Jariwala
0c1f6f3c3a fix: translations (#6186) 2025-07-08 08:52:36 +00:00
Matti Nannt
9399b526b8 fix: run PR checks on every pull requests (#6185) 2025-07-08 11:07:03 +02:00
Dhruwang Jariwala
cd60032bc9 fix: row/column deletion in matrix question (#6184) 2025-07-08 07:12:16 +00:00
Dhruwang Jariwala
a941f994ea fix: removed userId from contact endpoint response (#6175)
Co-authored-by: Piyush Gupta <piyushguptaa2z123@gmail.com>
2025-07-08 06:36:56 +00:00
Piyush Gupta
6ac748389f fix: translations 2025-07-07 21:35:22 +05:30
Piyush Gupta
e619a62f01 fixing: translations 2025-07-07 21:23:04 +05:30
Jakob Schott
75d170bce5 chore: removed unnecessary text bullet point from dialog (#6180) 2025-07-07 15:29:44 +00:00
20 changed files with 491 additions and 65 deletions

View File

@@ -10,8 +10,6 @@ permissions:
on:
pull_request:
branches:
- main
merge_group:
workflow_dispatch:

View File

@@ -169,7 +169,7 @@ export const resetPasswordAction = authenticatedActionClient.action(
"user",
async ({ ctx }: { ctx: AuthenticatedActionClientCtx; parsedInput: undefined }) => {
if (ctx.user.identityProvider !== "email") {
throw new OperationNotAllowedError("auth.reset-password.not-allowed");
throw new OperationNotAllowedError("Password reset is not allowed for this user.");
}
await sendForgotPasswordEmail(ctx.user);

View File

@@ -145,7 +145,7 @@ export const EditProfileDetailsForm = ({
});
} else {
const errorMessage = getFormattedErrorMessage(result);
toast.error(t(errorMessage));
toast.error(errorMessage);
}
setIsResettingPassword(false);

View File

@@ -143,7 +143,6 @@ export const mockPrismaPerson: Prisma.ContactGetPayload<{
include: typeof selectContact;
}> = {
id: mockId,
userId: mockId,
attributes: [
{
value: "de",

View File

@@ -207,6 +207,7 @@
"formbricks_version": "Formbricks Version",
"full_name": "Name",
"gathering_responses": "Antworten sammeln",
"general": "Allgemein",
"go_back": "Geh zurück",
"go_to_dashboard": "Zum Dashboard gehen",
"hidden": "Versteckt",
@@ -377,6 +378,7 @@
"switch_to": "Wechseln zu {environment}",
"table_items_deleted_successfully": "{type}s erfolgreich gelöscht",
"table_settings": "Tabelleinstellungen",
"tags": "Tags",
"targeting": "Targeting",
"team": "Team",
"team_access": "Teamzugriff",
@@ -1303,12 +1305,11 @@
"casual": "Lässig",
"caution_edit_duplicate": "Duplizieren & bearbeiten",
"caution_edit_published_survey": "Eine veröffentlichte Umfrage bearbeiten?",
"caution_explanation_all_data_as_download": "Alle Daten, einschließlich früherer Antworten, stehen als Download zur Verfügung.",
"caution_explanation_intro": "Wir verstehen, dass du vielleicht noch Änderungen vornehmen möchtest. Hier erfährst du, was passiert, wenn du das tust:",
"caution_explanation_new_responses_separated": "Neue Antworten werden separat gesammelt.",
"caution_explanation_only_new_responses_in_summary": "Nur neue Antworten erscheinen in der Umfragezusammenfassung.",
"caution_explanation_responses_are_safe": "Vorhandene Antworten bleiben sicher.",
"caution_recommendation": "Das Bearbeiten deiner Umfrage kann zu Dateninkonsistenzen in der Umfragezusammenfassung führen. Wir empfehlen stattdessen, die Umfrage zu duplizieren.",
"caution_explanation_new_responses_separated": "Antworten vor der Änderung werden möglicherweise nicht oder nur teilweise in der Umfragezusammenfassung berücksichtigt.",
"caution_explanation_only_new_responses_in_summary": "Alle Daten, einschließlich früherer Antworten, bleiben auf der Umfrageübersichtsseite als Download verfügbar.",
"caution_explanation_responses_are_safe": "Ältere und neuere Antworten vermischen sich, was zu irreführenden Datensummen führen kann.",
"caution_recommendation": "Dies kann im Umfrageübersicht zu Dateninkonsistenzen führen. Wir empfehlen stattdessen, die Umfrage zu duplizieren.",
"caution_text": "Änderungen werden zu Inkonsistenzen führen",
"centered_modal_overlay_color": "Zentrierte modale Überlagerungsfarbe",
"change_anyway": "Trotzdem ändern",

View File

@@ -207,6 +207,7 @@
"formbricks_version": "Formbricks Version",
"full_name": "Full name",
"gathering_responses": "Gathering responses",
"general": "General",
"go_back": "Go Back",
"go_to_dashboard": "Go to Dashboard",
"hidden": "Hidden",
@@ -377,6 +378,7 @@
"switch_to": "Switch to {environment}",
"table_items_deleted_successfully": "{type}s deleted successfully",
"table_settings": "Table settings",
"tags": "Tags",
"targeting": "Targeting",
"team": "Team",
"team_access": "Team Access",
@@ -1303,12 +1305,11 @@
"casual": "Casual",
"caution_edit_duplicate": "Duplicate & edit",
"caution_edit_published_survey": "Edit a published survey?",
"caution_explanation_all_data_as_download": "All data, including past responses are available as download.",
"caution_explanation_intro": "We understand you might still want to make changes. Heres what happens if you do: ",
"caution_explanation_new_responses_separated": "New responses are collected separately.",
"caution_explanation_only_new_responses_in_summary": "Only new responses appear in the survey summary.",
"caution_explanation_responses_are_safe": "Existing responses remain safe.",
"caution_recommendation": "Editing your survey may cause data inconsistencies in the survey summary. We recommend duplicating the survey instead.",
"caution_explanation_new_responses_separated": "Responses before the change may not or only partially be included in the survey summary.",
"caution_explanation_only_new_responses_in_summary": "All data, including past responses, remain available as download on the survey summary page.",
"caution_explanation_responses_are_safe": "Older and newer responses get mixed which can lead to misleading data summaries.",
"caution_recommendation": "This may cause data inconsistencies in the survey summary. We recommend duplicating the survey instead.",
"caution_text": "Changes will lead to inconsistencies",
"centered_modal_overlay_color": "Centered modal overlay color",
"change_anyway": "Change anyway",

View File

@@ -207,6 +207,7 @@
"formbricks_version": "Version de Formbricks",
"full_name": "Nom complet",
"gathering_responses": "Collecte des réponses",
"general": "Général",
"go_back": "Retourner",
"go_to_dashboard": "Aller au tableau de bord",
"hidden": "Caché",
@@ -377,6 +378,7 @@
"switch_to": "Passer à {environment}",
"table_items_deleted_successfully": "{type}s supprimés avec succès",
"table_settings": "Réglages de table",
"tags": "Étiquettes",
"targeting": "Ciblage",
"team": "Équipe",
"team_access": "Accès Équipe",
@@ -1303,12 +1305,11 @@
"casual": "Décontracté",
"caution_edit_duplicate": "Dupliquer et modifier",
"caution_edit_published_survey": "Modifier un sondage publié ?",
"caution_explanation_all_data_as_download": "Toutes les données, y compris les réponses passées, sont disponibles en téléchargement.",
"caution_explanation_intro": "Nous comprenons que vous souhaitiez encore apporter des modifications. Voici ce qui se passe si vous le faites : ",
"caution_explanation_new_responses_separated": "Les nouvelles réponses sont collectées séparément.",
"caution_explanation_only_new_responses_in_summary": "Seules les nouvelles réponses apparaissent dans le résumé de l'enquête.",
"caution_explanation_responses_are_safe": "Les réponses existantes restent en sécurité.",
"caution_recommendation": "Modifier votre enquête peut entraîner des incohérences dans le résumé de l'enquête. Nous vous recommandons de dupliquer l'enquête à la place.",
"caution_explanation_new_responses_separated": "Les réponses avant le changement peuvent ne pas être ou ne faire partie que partiellement du résumé de l'enquête.",
"caution_explanation_only_new_responses_in_summary": "Toutes les données, y compris les réponses passées, restent disponibles en téléchargement sur la page de résumé de l'enquête.",
"caution_explanation_responses_are_safe": "Les réponses anciennes et nouvelles se mélangent, ce qui peut entraîner des résumés de données trompeurs.",
"caution_recommendation": "Cela peut entraîner des incohérences de données dans le résumé du sondage. Nous recommandons de dupliquer le sondage à la place.",
"caution_text": "Les changements entraîneront des incohérences.",
"centered_modal_overlay_color": "Couleur de superposition modale centrée",
"change_anyway": "Changer de toute façon",

View File

@@ -207,6 +207,7 @@
"formbricks_version": "Versão do Formbricks",
"full_name": "Nome completo",
"gathering_responses": "Recolhendo respostas",
"general": "Geral",
"go_back": "Voltar",
"go_to_dashboard": "Ir para o Painel",
"hidden": "Escondido",
@@ -377,6 +378,7 @@
"switch_to": "Mudar para {environment}",
"table_items_deleted_successfully": "{type}s deletados com sucesso",
"table_settings": "Arrumação da mesa",
"tags": "Etiquetas",
"targeting": "mirando",
"team": "Time",
"team_access": "Acesso da equipe",
@@ -1303,12 +1305,11 @@
"casual": "Casual",
"caution_edit_duplicate": "Duplicar e editar",
"caution_edit_published_survey": "Editar uma pesquisa publicada?",
"caution_explanation_all_data_as_download": "Todos os dados, incluindo respostas anteriores, estão disponíveis para download.",
"caution_explanation_intro": "Entendemos que você ainda pode querer fazer alterações. Aqui está o que acontece se você fizer:",
"caution_explanation_new_responses_separated": "Novas respostas são coletadas separadamente.",
"caution_explanation_only_new_responses_in_summary": "Apenas novas respostas aparecem no resumo da pesquisa.",
"caution_explanation_responses_are_safe": "As respostas existentes permanecem seguras.",
"caution_recommendation": "Editar sua pesquisa pode causar inconsistências de dados no resumo da pesquisa. Recomendamos duplicar a pesquisa em vez disso.",
"caution_explanation_new_responses_separated": "Respostas antes da mudança podem não ser ou apenas parcialmente incluídas no resumo da pesquisa.",
"caution_explanation_only_new_responses_in_summary": "Todos os dados, incluindo respostas anteriores, permanecem disponíveis para download na página de resumo da pesquisa.",
"caution_explanation_responses_are_safe": "Respostas antigas e novas são misturadas, o que pode levar a resumos de dados enganosos.",
"caution_recommendation": "Isso pode causar inconsistências de dados no resumo da pesquisa. Recomendamos duplicar a pesquisa em vez disso.",
"caution_text": "Mudanças vão levar a inconsistências",
"centered_modal_overlay_color": "cor de sobreposição modal centralizada",
"change_anyway": "Mudar mesmo assim",

View File

@@ -207,6 +207,7 @@
"formbricks_version": "Versão do Formbricks",
"full_name": "Nome completo",
"gathering_responses": "A recolher respostas",
"general": "Geral",
"go_back": "Voltar",
"go_to_dashboard": "Ir para o Painel",
"hidden": "Oculto",
@@ -377,6 +378,7 @@
"switch_to": "Mudar para {environment}",
"table_items_deleted_successfully": "{type}s eliminados com sucesso",
"table_settings": "Configurações da tabela",
"tags": "Etiquetas",
"targeting": "Segmentação",
"team": "Equipa",
"team_access": "Acesso da Equipa",
@@ -1303,12 +1305,11 @@
"casual": "Casual",
"caution_edit_duplicate": "Duplicar e editar",
"caution_edit_published_survey": "Editar um inquérito publicado?",
"caution_explanation_all_data_as_download": "Todos os dados, incluindo respostas anteriores, estão disponíveis para download.",
"caution_explanation_intro": "Entendemos que ainda pode querer fazer alterações. Eis o que acontece se o fizer:",
"caution_explanation_new_responses_separated": "As novas respostas são recolhidas separadamente.",
"caution_explanation_only_new_responses_in_summary": "Apenas novas respostas aparecem no resumo do inquérito.",
"caution_explanation_responses_are_safe": "As respostas existentes permanecem seguras.",
"caution_recommendation": "Editar o seu inquérito pode causar inconsistências de dados no resumo do inquérito. Recomendamos duplicar o inquérito em vez disso.",
"caution_explanation_new_responses_separated": "Respostas antes da alteração podem não estar incluídas ou estar apenas parcialmente incluídas no resumo do inquérito.",
"caution_explanation_only_new_responses_in_summary": "Todos os dados, incluindo respostas anteriores, permanecem disponíveis para download na página de resumo do inquérito.",
"caution_explanation_responses_are_safe": "As respostas mais antigas e mais recentes se misturam, o que pode levar a resumos de dados enganosos.",
"caution_recommendation": "Isso pode causar inconsistências de dados no resumo do inquérito. Recomendamos duplicar o inquérito em vez disso.",
"caution_text": "As alterações levarão a inconsistências",
"centered_modal_overlay_color": "Cor da sobreposição modal centralizada",
"change_anyway": "Alterar mesmo assim",

View File

@@ -207,6 +207,7 @@
"formbricks_version": "Formbricks 版本",
"full_name": "全名",
"gathering_responses": "收集回應中",
"general": "一般",
"go_back": "返回",
"go_to_dashboard": "前往儀表板",
"hidden": "隱藏",
@@ -377,6 +378,7 @@
"switch_to": "切換至 '{'environment'}'",
"table_items_deleted_successfully": "'{'type'}' 已成功刪除",
"table_settings": "表格設定",
"tags": "標籤",
"targeting": "目標設定",
"team": "團隊",
"team_access": "團隊存取權限",
@@ -1303,12 +1305,11 @@
"casual": "隨意",
"caution_edit_duplicate": "複製 & 編輯",
"caution_edit_published_survey": "編輯已發佈的調查?",
"caution_explanation_all_data_as_download": "所有數據,包括過去的回應,都可以下載。",
"caution_explanation_intro": "我們了解您可能仍然想要進行更改。如果您這樣做,將會發生以下情況:",
"caution_explanation_new_responses_separated": "新回應會分開收集。",
"caution_explanation_only_new_responses_in_summary": "只有新的回應會出現在調查摘要。",
"caution_explanation_responses_are_safe": "現有回應仍然安全。",
"caution_recommendation": "編輯您的調查可能導致調查摘要中的數據不一致。我們建議複製調查。",
"caution_explanation_new_responses_separated": "更改前的回應可能未被納入或只有部分包含在調查摘要中。",
"caution_explanation_only_new_responses_in_summary": "所有數據,包括過去的回應,仍可在調查摘要頁面下載。",
"caution_explanation_responses_are_safe": "較舊和較新的回應會混在一起,可能導致數據摘要失準。",
"caution_recommendation": "可能導致調查摘要中的數據不一致。我們建議複製這個調查。",
"caution_text": "變更會導致不一致",
"centered_modal_overlay_color": "置中彈窗覆蓋顏色",
"change_anyway": "仍然變更",

View File

@@ -20,7 +20,6 @@ const mockContact = {
environmentId: mockEnvironmentId,
createdAt: new Date(),
updatedAt: new Date(),
attributes: [],
};
describe("contact lib", () => {
@@ -38,7 +37,9 @@ describe("contact lib", () => {
const result = await getContact(mockContactId);
expect(result).toEqual(mockContact);
expect(prisma.contact.findUnique).toHaveBeenCalledWith({ where: { id: mockContactId } });
expect(prisma.contact.findUnique).toHaveBeenCalledWith({
where: { id: mockContactId },
});
});
test("should return null if contact not found", async () => {
@@ -46,7 +47,9 @@ describe("contact lib", () => {
const result = await getContact(mockContactId);
expect(result).toBeNull();
expect(prisma.contact.findUnique).toHaveBeenCalledWith({ where: { id: mockContactId } });
expect(prisma.contact.findUnique).toHaveBeenCalledWith({
where: { id: mockContactId },
});
});
test("should throw DatabaseError if prisma throws PrismaClientKnownRequestError", async () => {

View File

@@ -20,18 +20,12 @@ const mockContacts = [
{
id: "contactId1",
environmentId: mockEnvironmentId1,
name: "Contact 1",
email: "contact1@example.com",
attributes: {},
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "contactId2",
environmentId: mockEnvironmentId2,
name: "Contact 2",
email: "contact2@example.com",
attributes: {},
createdAt: new Date(),
updatedAt: new Date(),
},

View File

@@ -65,9 +65,6 @@ describe("EditPublicSurveyAlertDialog", () => {
expect(
screen.getByText("environments.surveys.edit.caution_explanation_only_new_responses_in_summary")
).toBeInTheDocument();
expect(
screen.getByText("environments.surveys.edit.caution_explanation_all_data_as_download")
).toBeInTheDocument();
});
test("renders default close button and calls setOpen when clicked", () => {

View File

@@ -74,7 +74,6 @@ export const EditPublicSurveyAlertDialog = ({
<li>{t("environments.surveys.edit.caution_explanation_responses_are_safe")}</li>
<li>{t("environments.surveys.edit.caution_explanation_new_responses_separated")}</li>
<li>{t("environments.surveys.edit.caution_explanation_only_new_responses_in_summary")}</li>
<li>{t("environments.surveys.edit.caution_explanation_all_data_as_download")}</li>
</ul>
</DialogBody>

View File

@@ -2,7 +2,8 @@ import { createI18nString } from "@/lib/i18n/utils";
import { findOptionUsedInLogic } from "@/modules/survey/editor/lib/utils";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, test, vi } from "vitest";
import React from "react";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
TSurvey,
TSurveyLanguage,
@@ -12,6 +13,16 @@ import {
import { TUserLocale } from "@formbricks/types/user";
import { MatrixQuestionForm } from "./matrix-question-form";
// Mock cuid2 to track CUID generation
const mockCuids = ["cuid1", "cuid2", "cuid3", "cuid4", "cuid5", "cuid6"];
let cuidIndex = 0;
vi.mock("@paralleldrive/cuid2", () => ({
default: {
createId: vi.fn(() => mockCuids[cuidIndex++]),
},
}));
// Mock window.matchMedia - required for useAutoAnimate
Object.defineProperty(window, "matchMedia", {
writable: true,
@@ -386,4 +397,223 @@ describe("MatrixQuestionForm", () => {
expect(mockUpdateQuestion).not.toHaveBeenCalled();
});
// CUID functionality tests
describe("CUID Management", () => {
beforeEach(() => {
// Reset CUID index before each test
cuidIndex = 0;
});
test("generates stable CUIDs for rows and columns on initial render", () => {
const { rerender } = render(<MatrixQuestionForm {...defaultProps} />);
// Check that CUIDs are generated for initial items
expect(cuidIndex).toBe(6); // 3 rows + 3 columns
// Rerender with the same props - no new CUIDs should be generated
rerender(<MatrixQuestionForm {...defaultProps} />);
expect(cuidIndex).toBe(6); // Should remain the same
});
test("maintains stable CUIDs across rerenders", () => {
const TestComponent = ({ question }: { question: TSurveyMatrixQuestion }) => {
return <MatrixQuestionForm {...defaultProps} question={question} />;
};
const { rerender } = render(<TestComponent question={mockMatrixQuestion} />);
// Check initial CUID count
expect(cuidIndex).toBe(6); // 3 rows + 3 columns
// Rerender multiple times
rerender(<TestComponent question={mockMatrixQuestion} />);
rerender(<TestComponent question={mockMatrixQuestion} />);
rerender(<TestComponent question={mockMatrixQuestion} />);
// CUIDs should remain stable
expect(cuidIndex).toBe(6); // Should not increase
});
test("generates new CUIDs only when rows are added", async () => {
const user = userEvent.setup();
// Create a test component that can update its props
const TestComponent = () => {
const [question, setQuestion] = React.useState(mockMatrixQuestion);
const handleUpdateQuestion = (_: number, updates: Partial<TSurveyMatrixQuestion>) => {
setQuestion((prev) => ({ ...prev, ...updates }));
};
return (
<MatrixQuestionForm {...defaultProps} question={question} updateQuestion={handleUpdateQuestion} />
);
};
const { getByText } = render(<TestComponent />);
// Initial render should generate 6 CUIDs (3 rows + 3 columns)
expect(cuidIndex).toBe(6);
// Add a new row
const addRowButton = getByText("environments.surveys.edit.add_row");
await user.click(addRowButton);
// Should generate 1 new CUID for the new row
expect(cuidIndex).toBe(7);
});
test("generates new CUIDs only when columns are added", async () => {
const user = userEvent.setup();
// Create a test component that can update its props
const TestComponent = () => {
const [question, setQuestion] = React.useState(mockMatrixQuestion);
const handleUpdateQuestion = (_: number, updates: Partial<TSurveyMatrixQuestion>) => {
setQuestion((prev) => ({ ...prev, ...updates }));
};
return (
<MatrixQuestionForm {...defaultProps} question={question} updateQuestion={handleUpdateQuestion} />
);
};
const { getByText } = render(<TestComponent />);
// Initial render should generate 6 CUIDs (3 rows + 3 columns)
expect(cuidIndex).toBe(6);
// Add a new column
const addColumnButton = getByText("environments.surveys.edit.add_column");
await user.click(addColumnButton);
// Should generate 1 new CUID for the new column
expect(cuidIndex).toBe(7);
});
test("maintains CUID stability when items are deleted", async () => {
const user = userEvent.setup();
const { findAllByTestId, rerender } = render(<MatrixQuestionForm {...defaultProps} />);
// Mock that no items are used in logic
vi.mocked(findOptionUsedInLogic).mockReturnValue(-1);
// Initial render: 6 CUIDs generated
expect(cuidIndex).toBe(6);
// Delete a row
const deleteButtons = await findAllByTestId("tooltip-renderer");
await user.click(deleteButtons[0].querySelector("button") as HTMLButtonElement);
// No new CUIDs should be generated for deletion
expect(cuidIndex).toBe(6);
// Rerender should not generate new CUIDs
rerender(<MatrixQuestionForm {...defaultProps} />);
expect(cuidIndex).toBe(6);
});
test("handles mixed operations maintaining CUID stability", async () => {
const user = userEvent.setup();
// Create a test component that can update its props
const TestComponent = () => {
const [question, setQuestion] = React.useState(mockMatrixQuestion);
const handleUpdateQuestion = (_: number, updates: Partial<TSurveyMatrixQuestion>) => {
setQuestion((prev) => ({ ...prev, ...updates }));
};
return (
<MatrixQuestionForm {...defaultProps} question={question} updateQuestion={handleUpdateQuestion} />
);
};
const { getByText, findAllByTestId } = render(<TestComponent />);
// Mock that no items are used in logic
vi.mocked(findOptionUsedInLogic).mockReturnValue(-1);
// Initial: 6 CUIDs
expect(cuidIndex).toBe(6);
// Add a row: +1 CUID
const addRowButton = getByText("environments.surveys.edit.add_row");
await user.click(addRowButton);
expect(cuidIndex).toBe(7);
// Add a column: +1 CUID
const addColumnButton = getByText("environments.surveys.edit.add_column");
await user.click(addColumnButton);
expect(cuidIndex).toBe(8);
// Delete a row: no new CUIDs
const deleteButtons = await findAllByTestId("tooltip-renderer");
await user.click(deleteButtons[0].querySelector("button") as HTMLButtonElement);
expect(cuidIndex).toBe(8);
// Delete a column: no new CUIDs
const updatedDeleteButtons = await findAllByTestId("tooltip-renderer");
await user.click(updatedDeleteButtons[2].querySelector("button") as HTMLButtonElement);
expect(cuidIndex).toBe(8);
});
test("CUID arrays are properly maintained when items are deleted in order", async () => {
const user = userEvent.setup();
const propsWithManyRows = {
...defaultProps,
question: {
...mockMatrixQuestion,
rows: [
createI18nString("Row 1", ["en"]),
createI18nString("Row 2", ["en"]),
createI18nString("Row 3", ["en"]),
createI18nString("Row 4", ["en"]),
],
},
};
const { findAllByTestId } = render(<MatrixQuestionForm {...propsWithManyRows} />);
// Mock that no items are used in logic
vi.mocked(findOptionUsedInLogic).mockReturnValue(-1);
// Initial: 7 CUIDs (4 rows + 3 columns)
expect(cuidIndex).toBe(7);
// Delete first row
const deleteButtons = await findAllByTestId("tooltip-renderer");
await user.click(deleteButtons[0].querySelector("button") as HTMLButtonElement);
// Verify the correct row was deleted (should be Row 2, Row 3, Row 4 remaining)
expect(mockUpdateQuestion).toHaveBeenLastCalledWith(0, {
rows: [
propsWithManyRows.question.rows[1],
propsWithManyRows.question.rows[2],
propsWithManyRows.question.rows[3],
],
});
// No new CUIDs should be generated
expect(cuidIndex).toBe(7);
});
test("CUID generation is consistent across component instances", () => {
// Reset CUID index
cuidIndex = 0;
// Render first instance
const { unmount } = render(<MatrixQuestionForm {...defaultProps} />);
expect(cuidIndex).toBe(6);
// Unmount and render second instance
unmount();
render(<MatrixQuestionForm {...defaultProps} />);
// Should generate 6 more CUIDs for the new instance
expect(cuidIndex).toBe(12);
});
});
});

View File

@@ -8,9 +8,10 @@ import { Label } from "@/modules/ui/components/label";
import { ShuffleOptionSelect } from "@/modules/ui/components/shuffle-option-select";
import { TooltipRenderer } from "@/modules/ui/components/tooltip";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import cuid2 from "@paralleldrive/cuid2";
import { useTranslate } from "@tolgee/react";
import { PlusIcon, TrashIcon } from "lucide-react";
import type { JSX } from "react";
import { type JSX, useMemo, useRef } from "react";
import toast from "react-hot-toast";
import { TI18nString, TSurvey, TSurveyMatrixQuestion } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
@@ -39,6 +40,45 @@ export const MatrixQuestionForm = ({
}: MatrixQuestionFormProps): JSX.Element => {
const languageCodes = extractLanguageCodes(localSurvey.languages);
const { t } = useTranslate();
// Refs to maintain stable CUIDs across renders
const cuidRefs = useRef<{
rows: string[];
columns: string[];
}>({
rows: [],
columns: [],
});
// Generic function to ensure CUIDs are synchronized with the current state
const ensureCuids = (type: "rows" | "columns", currentItems: TI18nString[]) => {
const currentCuids = cuidRefs.current[type];
if (currentCuids.length !== currentItems.length) {
if (currentItems.length > currentCuids.length) {
// Add new CUIDs for added items
const newCuids = Array(currentItems.length - currentCuids.length)
.fill(null)
.map(() => cuid2.createId());
cuidRefs.current[type] = [...currentCuids, ...newCuids];
} else {
// Remove CUIDs for deleted items (keep the remaining ones in order)
cuidRefs.current[type] = currentCuids.slice(0, currentItems.length);
}
}
};
// Generic function to get items with CUIDs
const getItemsWithCuid = (type: "rows" | "columns", items: TI18nString[]) => {
ensureCuids(type, items);
return items.map((item, index) => ({
...item,
id: cuidRefs.current[type][index],
}));
};
const rowsWithCuid = useMemo(() => getItemsWithCuid("rows", question.rows), [question.rows]);
const columnsWithCuid = useMemo(() => getItemsWithCuid("columns", question.columns), [question.columns]);
// Function to add a new Label input field
const handleAddLabel = (type: "row" | "column") => {
if (type === "row") {
@@ -79,6 +119,11 @@ export const MatrixQuestionForm = ({
}
const updatedLabels = labels.filter((_, idx) => idx !== index);
// Update the CUID arrays when deleting
const cuidType = type === "row" ? "rows" : "columns";
cuidRefs.current[cuidType] = cuidRefs.current[cuidType].filter((_, idx) => idx !== index);
if (type === "row") {
updateQuestion(questionIdx, { rows: updatedLabels });
} else {
@@ -182,8 +227,8 @@ export const MatrixQuestionForm = ({
{/* Rows section */}
<Label htmlFor="rows">{t("environments.surveys.edit.rows")}</Label>
<div className="mt-2 flex flex-col gap-2" ref={parent}>
{question.rows.map((row, index) => (
<div className="flex items-center" key={`${row}-${index}`}>
{rowsWithCuid.map((row, index) => (
<div className="flex items-center" key={row.id}>
<QuestionFormInput
id={`row-${index}`}
label={""}
@@ -232,8 +277,8 @@ export const MatrixQuestionForm = ({
{/* Columns section */}
<Label htmlFor="columns">{t("environments.surveys.edit.columns")}</Label>
<div className="mt-2 flex flex-col gap-2" ref={parent}>
{question.columns.map((column, index) => (
<div className="flex items-center" key={`${column}-${index}`}>
{columnsWithCuid.map((column, index) => (
<div className="flex items-center" key={column.id}>
<QuestionFormInput
id={`column-${index}`}
label={""}

View File

@@ -70,6 +70,14 @@ vi.mock("react-hot-toast", () => ({
},
}));
// Mock clipboard API
Object.defineProperty(navigator, "clipboard", {
value: {
writeText: vi.fn(),
},
writable: true,
});
describe("SurveyDropDownMenu", () => {
afterEach(() => {
cleanup();
@@ -78,7 +86,6 @@ describe("SurveyDropDownMenu", () => {
test("calls copySurveyLink when copy link is clicked", async () => {
const mockRefresh = vi.fn().mockResolvedValue("fakeSingleUseId");
const mockDeleteSurvey = vi.fn();
const mockDuplicateSurvey = vi.fn();
render(
<SurveyDropDownMenu
@@ -149,6 +156,135 @@ describe("SurveyDropDownMenu", () => {
responseCount: 5,
} as unknown as TSurvey;
describe("clipboard functionality", () => {
beforeEach(() => {
vi.clearAllMocks();
});
test("pre-fetches single-use ID when dropdown opens", async () => {
const mockRefreshSingleUseId = vi.fn().mockResolvedValue("test-single-use-id");
render(
<SurveyDropDownMenu
environmentId="env123"
survey={{ ...fakeSurvey, status: "completed" }}
publicDomain="http://survey.test"
refreshSingleUseId={mockRefreshSingleUseId}
deleteSurvey={vi.fn()}
/>
);
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
// Initially, refreshSingleUseId should not have been called
expect(mockRefreshSingleUseId).not.toHaveBeenCalled();
// Open dropdown
await userEvent.click(triggerElement);
// Now it should have been called
await waitFor(() => {
expect(mockRefreshSingleUseId).toHaveBeenCalledTimes(1);
});
});
test("does not pre-fetch single-use ID when dropdown is closed", async () => {
const mockRefreshSingleUseId = vi.fn().mockResolvedValue("test-single-use-id");
render(
<SurveyDropDownMenu
environmentId="env123"
survey={{ ...fakeSurvey, status: "completed" }}
publicDomain="http://survey.test"
refreshSingleUseId={mockRefreshSingleUseId}
deleteSurvey={vi.fn()}
/>
);
// Don't open dropdown
// Wait a bit to ensure useEffect doesn't run
await waitFor(() => {
expect(mockRefreshSingleUseId).not.toHaveBeenCalled();
});
});
test("copies link with pre-fetched single-use ID", async () => {
const mockRefreshSingleUseId = vi.fn().mockResolvedValue("test-single-use-id");
const mockWriteText = vi.fn().mockResolvedValue(undefined);
navigator.clipboard.writeText = mockWriteText;
render(
<SurveyDropDownMenu
environmentId="env123"
survey={{ ...fakeSurvey, status: "completed" }}
publicDomain="http://survey.test"
refreshSingleUseId={mockRefreshSingleUseId}
deleteSurvey={vi.fn()}
/>
);
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
// Open dropdown to trigger pre-fetch
await userEvent.click(triggerElement);
// Wait for pre-fetch to complete
await waitFor(() => {
expect(mockRefreshSingleUseId).toHaveBeenCalled();
});
// Click copy link
const copyLinkButton = screen.getByTestId("copy-link");
await userEvent.click(copyLinkButton);
// Verify clipboard was called with the correct URL including single-use ID
await waitFor(() => {
expect(mockWriteText).toHaveBeenCalledWith("http://survey.test/s/testSurvey?suId=test-single-use-id");
expect(mockToast.success).toHaveBeenCalledWith("common.copied_to_clipboard");
});
});
test("handles copy link with undefined single-use ID", async () => {
const mockRefreshSingleUseId = vi.fn().mockResolvedValue(undefined);
const mockWriteText = vi.fn().mockResolvedValue(undefined);
navigator.clipboard.writeText = mockWriteText;
render(
<SurveyDropDownMenu
environmentId="env123"
survey={{ ...fakeSurvey, status: "completed" }}
publicDomain="http://survey.test"
refreshSingleUseId={mockRefreshSingleUseId}
deleteSurvey={vi.fn()}
/>
);
const menuWrapper = screen.getByTestId("survey-dropdown-menu");
const triggerElement = menuWrapper.querySelector("[class*='p-2']") as HTMLElement;
// Open dropdown to trigger pre-fetch
await userEvent.click(triggerElement);
// Wait for pre-fetch to complete
await waitFor(() => {
expect(mockRefreshSingleUseId).toHaveBeenCalled();
});
// Click copy link
const copyLinkButton = screen.getByTestId("copy-link");
await userEvent.click(copyLinkButton);
// Verify clipboard was called with base URL (no single-use ID)
await waitFor(() => {
expect(mockWriteText).toHaveBeenCalledWith("http://survey.test/s/testSurvey");
expect(mockToast.success).toHaveBeenCalledWith("common.copied_to_clipboard");
});
});
});
test("handleEditforActiveSurvey opens EditPublicSurveyAlertDialog for active surveys", async () => {
render(
<SurveyDropDownMenu
@@ -285,7 +421,6 @@ describe("SurveyDropDownMenu", () => {
expect(mockDeleteSurveyAction).toHaveBeenCalledWith({ surveyId: "testSurvey" });
expect(mockDeleteSurvey).toHaveBeenCalledWith("testSurvey");
expect(mockToast.success).toHaveBeenCalledWith("environments.surveys.survey_deleted_successfully");
expect(mockRouterRefresh).toHaveBeenCalled();
});
});
@@ -396,7 +531,6 @@ describe("SurveyDropDownMenu", () => {
// 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 () => {
@@ -480,7 +614,7 @@ describe("SurveyDropDownMenu", () => {
await userEvent.click(confirmDeleteButton);
await waitFor(() => {
expect(callOrder).toEqual(["deleteSurveyAction", "deleteSurvey", "toast.success", "router.refresh"]);
expect(callOrder).toEqual(["deleteSurveyAction", "deleteSurvey", "toast.success"]);
});
});
});

View File

@@ -30,8 +30,9 @@ import {
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { logger } from "@formbricks/logger";
import { CopySurveyModal } from "./copy-survey-modal";
interface SurveyDropDownMenuProps {
@@ -61,18 +62,33 @@ export const SurveyDropDownMenu = ({
const [isDropDownOpen, setIsDropDownOpen] = useState(false);
const [isCopyFormOpen, setIsCopyFormOpen] = useState(false);
const [isCautionDialogOpen, setIsCautionDialogOpen] = useState(false);
const [newSingleUseId, setNewSingleUseId] = useState<string | undefined>(undefined);
const router = useRouter();
const surveyLink = useMemo(() => publicDomain + "/s/" + survey.id, [survey.id, publicDomain]);
// Pre-fetch single-use ID when dropdown opens to avoid async delay during clipboard operation
// This ensures Safari's clipboard API works by maintaining the user gesture context
useEffect(() => {
if (!isDropDownOpen) return;
const fetchNewId = async () => {
try {
const newId = await refreshSingleUseId();
setNewSingleUseId(newId ?? undefined);
} catch (error) {
logger.error(error);
}
};
fetchNewId();
}, [refreshSingleUseId, isDropDownOpen]);
const handleDeleteSurvey = async (surveyId: string) => {
setLoading(true);
try {
await deleteSurveyAction({ surveyId });
deleteSurvey(surveyId);
toast.success(t("environments.surveys.survey_deleted_successfully"));
router.refresh();
} catch (error) {
toast.error(t("environments.surveys.error_deleting_survey"));
} finally {
@@ -84,12 +100,11 @@ export const SurveyDropDownMenu = ({
try {
e.preventDefault();
setIsDropDownOpen(false);
const newId = await refreshSingleUseId();
const copiedLink = copySurveyLink(surveyLink, newId);
const copiedLink = copySurveyLink(surveyLink, newSingleUseId);
navigator.clipboard.writeText(copiedLink);
toast.success(t("common.copied_to_clipboard"));
router.refresh();
} catch (error) {
logger.error(error);
toast.error(t("environments.surveys.summary.failed_to_copy_link"));
}
};

View File

@@ -0,0 +1,8 @@
/*
Warnings:
- You are about to drop the column `userId` on the `Contact` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "Contact" DROP COLUMN "userId";

View File

@@ -112,14 +112,12 @@ model ContactAttributeKey {
/// Contacts are environment-specific and can have multiple attributes and responses.
///
/// @property id - Unique identifier for the contact
/// @property userId - Optional external user identifier
/// @property environment - The environment this contact belongs to
/// @property responses - Survey responses from this contact
/// @property attributes - Custom attributes associated with this contact
/// @property displays - Record of surveys shown to this contact
model Contact {
id String @id @default(cuid())
userId String?
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
environment Environment @relation(fields: [environmentId], references: [id], onDelete: Cascade)