mirror of
https://github.com/formbricks/formbricks.git
synced 2026-01-05 21:32:02 -06:00
Compare commits
1 Commits
devin/1747
...
chore/impr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4811351be |
@@ -11,7 +11,9 @@
|
||||
"clean": "rimraf .turbo node_modules dist storybook-static"
|
||||
},
|
||||
"dependencies": {
|
||||
"eslint-plugin-react-refresh": "0.4.20"
|
||||
"eslint-plugin-react-refresh": "0.4.20",
|
||||
"react": "19.1.0",
|
||||
"react-dom": "19.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@chromatic-com/storybook": "3.2.6",
|
||||
|
||||
@@ -7,133 +7,39 @@ export const GET = async (req: NextRequest) => {
|
||||
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
alignItems: "center",
|
||||
backgroundColor: brandColor ? brandColor + "BF" : "#0000BFBF", // /75 opacity is approximately BF in hex
|
||||
borderRadius: "0.75rem",
|
||||
}}>
|
||||
<div tw={`flex flex-col w-full h-full items-center bg-[${brandColor}]/75 rounded-xl `}>
|
||||
<div
|
||||
tw="flex flex-col w-[80%] h-[60%] bg-white rounded-xl mt-13 absolute left-12 top-3 opacity-20"
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
width: "80%",
|
||||
height: "60%",
|
||||
backgroundColor: "white",
|
||||
borderRadius: "0.75rem",
|
||||
marginTop: "3.25rem",
|
||||
position: "absolute",
|
||||
left: "3rem",
|
||||
top: "0.75rem",
|
||||
opacity: 0.2,
|
||||
transform: "rotate(356deg)",
|
||||
}}></div>
|
||||
<div
|
||||
tw="flex flex-col w-[84%] h-[60%] bg-white rounded-xl mt-12 absolute top-5 left-13 border-2 opacity-60"
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
width: "84%",
|
||||
height: "60%",
|
||||
backgroundColor: "white",
|
||||
borderRadius: "0.75rem",
|
||||
marginTop: "3rem",
|
||||
position: "absolute",
|
||||
top: "1.25rem",
|
||||
left: "3.25rem",
|
||||
borderWidth: "2px",
|
||||
opacity: 0.6,
|
||||
transform: "rotate(357deg)",
|
||||
}}></div>
|
||||
<div
|
||||
tw="flex flex-col w-[85%] h-[67%] items-center bg-white rounded-xl mt-8 absolute top-[2.3rem] left-14"
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
width: "85%",
|
||||
height: "67%",
|
||||
alignItems: "center",
|
||||
backgroundColor: "white",
|
||||
borderRadius: "0.75rem",
|
||||
marginTop: "2rem",
|
||||
position: "absolute",
|
||||
top: "2.3rem",
|
||||
left: "3.5rem",
|
||||
transform: "rotate(360deg)",
|
||||
}}>
|
||||
<div style={{ display: "flex", flexDirection: "column", width: "100%" }}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
width: "100%",
|
||||
justifyContent: "space-between",
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
paddingLeft: "2rem",
|
||||
paddingRight: "2rem",
|
||||
}}>
|
||||
<h2
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
fontSize: "2rem",
|
||||
fontWeight: "700",
|
||||
letterSpacing: "-0.025em",
|
||||
color: "#0f172a",
|
||||
textAlign: "left",
|
||||
marginTop: "3.75rem",
|
||||
}}>
|
||||
<div tw="flex flex-col w-full">
|
||||
<div tw="flex flex-col md:flex-row w-full md:items-center justify-between ">
|
||||
<div tw="flex flex-col px-8">
|
||||
<h2 tw="flex flex-col text-[8] sm:text-4xl font-bold tracking-tight text-slate-900 text-left mt-15">
|
||||
{name}
|
||||
</h2>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: "flex", justifyContent: "flex-end", marginRight: "2.5rem" }}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
borderRadius: "1rem",
|
||||
position: "absolute",
|
||||
right: "-0.5rem",
|
||||
marginTop: "0.5rem",
|
||||
}}>
|
||||
<div
|
||||
content=""
|
||||
style={{
|
||||
borderRadius: "0.75rem",
|
||||
border: "1px solid transparent",
|
||||
backgroundColor: brandColor ?? "#000",
|
||||
height: "4.5rem",
|
||||
width: "9.5rem",
|
||||
opacity: 0.5,
|
||||
}}></div>
|
||||
<div tw="flex justify-end mr-10 ">
|
||||
<div tw="flex rounded-2xl absolute -right-2 mt-2">
|
||||
<a tw={`rounded-xl border border-transparent bg-[${brandColor}] h-18 w-38 opacity-50`}></a>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
borderRadius: "1rem",
|
||||
boxShadow: "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: "0.75rem",
|
||||
border: "1px solid transparent",
|
||||
backgroundColor: brandColor ?? "#000",
|
||||
fontSize: "1.5rem",
|
||||
color: "white",
|
||||
height: "4.5rem",
|
||||
width: "9.5rem",
|
||||
}}>
|
||||
<div tw="flex rounded-2xl shadow ">
|
||||
<a
|
||||
tw={`flex items-center justify-center rounded-xl border border-transparent bg-[${brandColor}] text-2xl text-white h-18 w-38`}>
|
||||
Begin!
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -38,7 +38,7 @@ describe("SentryProvider", () => {
|
||||
expect(initSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dsn: sentryDsn,
|
||||
tracesSampleRate: 0,
|
||||
tracesSampleRate: 1,
|
||||
debug: false,
|
||||
replaysOnErrorSampleRate: 1.0,
|
||||
replaysSessionSampleRate: 0.1,
|
||||
@@ -81,26 +81,6 @@ describe("SentryProvider", () => {
|
||||
expect(screen.getByTestId("child")).toHaveTextContent("Test Content");
|
||||
});
|
||||
|
||||
test("does not reinitialize Sentry when props change after initial render", () => {
|
||||
const initSpy = vi.spyOn(Sentry, "init").mockImplementation(() => undefined);
|
||||
|
||||
const { rerender } = render(
|
||||
<SentryProvider sentryDsn={sentryDsn} isEnabled>
|
||||
<div data-testid="child">Test Content</div>
|
||||
</SentryProvider>
|
||||
);
|
||||
|
||||
expect(initSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(
|
||||
<SentryProvider sentryDsn="https://newDsn@o0.ingest.sentry.io/0" isEnabled={false}>
|
||||
<div data-testid="child">Test Content</div>
|
||||
</SentryProvider>
|
||||
);
|
||||
|
||||
expect(initSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("processes beforeSend correctly", () => {
|
||||
const initSpy = vi.spyOn(Sentry, "init").mockImplementation(() => undefined);
|
||||
|
||||
@@ -129,36 +109,4 @@ describe("SentryProvider", () => {
|
||||
const hintWithoutError = { originalException: undefined };
|
||||
expect(beforeSend(dummyEvent, hintWithoutError)).toEqual(dummyEvent);
|
||||
});
|
||||
|
||||
test("processes beforeSend correctly when hint.originalException is not an Error object", () => {
|
||||
const initSpy = vi.spyOn(Sentry, "init").mockImplementation(() => undefined);
|
||||
|
||||
render(
|
||||
<SentryProvider sentryDsn={sentryDsn} isEnabled>
|
||||
<div data-testid="child">Test Content</div>
|
||||
</SentryProvider>
|
||||
);
|
||||
|
||||
const config = initSpy.mock.calls[0][0];
|
||||
expect(config).toHaveProperty("beforeSend");
|
||||
const beforeSend = config.beforeSend;
|
||||
|
||||
if (!beforeSend) {
|
||||
throw new Error("beforeSend is not defined");
|
||||
}
|
||||
|
||||
const dummyEvent = { some: "event" } as unknown as Sentry.ErrorEvent;
|
||||
|
||||
const hintWithString = { originalException: "string exception" };
|
||||
expect(() => beforeSend(dummyEvent, hintWithString)).not.toThrow();
|
||||
expect(beforeSend(dummyEvent, hintWithString)).toEqual(dummyEvent);
|
||||
|
||||
const hintWithNumber = { originalException: 123 };
|
||||
expect(() => beforeSend(dummyEvent, hintWithNumber)).not.toThrow();
|
||||
expect(beforeSend(dummyEvent, hintWithNumber)).toEqual(dummyEvent);
|
||||
|
||||
const hintWithNull = { originalException: null };
|
||||
expect(() => beforeSend(dummyEvent, hintWithNull)).not.toThrow();
|
||||
expect(beforeSend(dummyEvent, hintWithNull)).toEqual(dummyEvent);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,8 +15,8 @@ export const SentryProvider = ({ children, sentryDsn, isEnabled }: SentryProvide
|
||||
Sentry.init({
|
||||
dsn: sentryDsn,
|
||||
|
||||
// No tracing while Sentry doesn't update to telemetry 2.0.0 - https://github.com/getsentry/sentry-javascript/issues/15737
|
||||
tracesSampleRate: 0,
|
||||
// Adjust this value in production, or use tracesSampler for greater control
|
||||
tracesSampleRate: 1,
|
||||
|
||||
// Setting this option to true will print useful information to the console while you're setting up Sentry.
|
||||
debug: false,
|
||||
|
||||
@@ -15,20 +15,12 @@ import {
|
||||
describe("Time Utilities", () => {
|
||||
describe("convertDateString", () => {
|
||||
test("should format date string correctly", () => {
|
||||
expect(convertDateString("2024-03-20:12:30:00")).toBe("Mar 20, 2024");
|
||||
expect(convertDateString("2024-03-20")).toBe("Mar 20, 2024");
|
||||
});
|
||||
|
||||
test("should return empty string for empty input", () => {
|
||||
expect(convertDateString("")).toBe("");
|
||||
});
|
||||
|
||||
test("should return null for null input", () => {
|
||||
expect(convertDateString(null as any)).toBe(null);
|
||||
});
|
||||
|
||||
test("should handle invalid date strings", () => {
|
||||
expect(convertDateString("not-a-date")).toBe("Invalid Date");
|
||||
});
|
||||
});
|
||||
|
||||
describe("convertDateTimeString", () => {
|
||||
@@ -81,7 +73,7 @@ describe("Time Utilities", () => {
|
||||
|
||||
describe("formatDate", () => {
|
||||
test("should format date correctly", () => {
|
||||
const date = new Date(2024, 2, 20); // March is month 2 (0-based)
|
||||
const date = new Date("2024-03-20");
|
||||
expect(formatDate(date)).toBe("March 20, 2024");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,16 +2,11 @@ import { formatDistance, intlFormat } from "date-fns";
|
||||
import { de, enUS, fr, pt, ptBR, zhTW } from "date-fns/locale";
|
||||
import { TUserLocale } from "@formbricks/types/user";
|
||||
|
||||
export const convertDateString = (dateString: string | null) => {
|
||||
if (dateString === null) return null;
|
||||
export const convertDateString = (dateString: string) => {
|
||||
if (!dateString) {
|
||||
return dateString;
|
||||
}
|
||||
|
||||
const date = new Date(dateString);
|
||||
if (isNaN(date.getTime())) {
|
||||
return "Invalid Date";
|
||||
}
|
||||
return intlFormat(
|
||||
date,
|
||||
{
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { getUser } from "@/lib/user/service";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { DEFAULT_SERVER_ERROR_MESSAGE, createSafeActionClient } from "next-safe-action";
|
||||
import { logger } from "@formbricks/logger";
|
||||
@@ -15,8 +14,6 @@ import {
|
||||
|
||||
export const actionClient = createSafeActionClient({
|
||||
handleServerError(e) {
|
||||
Sentry.captureException(e);
|
||||
|
||||
if (
|
||||
e instanceof ResourceNotFoundError ||
|
||||
e instanceof AuthorizationError ||
|
||||
|
||||
@@ -240,126 +240,4 @@ describe("updateUser", () => {
|
||||
expect(result.state.data).toEqual(expect.objectContaining(mockUserState));
|
||||
expect(result.messages).toEqual([]);
|
||||
});
|
||||
|
||||
test("should handle email attribute update with ignoreEmailAttribute flag", async () => {
|
||||
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(mockContact);
|
||||
const newAttributes = { email: "new@example.com", name: "John Doe" };
|
||||
vi.mocked(updateAttributes).mockResolvedValue({
|
||||
success: true,
|
||||
messages: [],
|
||||
ignoreEmailAttribute: true,
|
||||
});
|
||||
|
||||
vi.mocked(getUserState).mockResolvedValue({
|
||||
...mockUserState,
|
||||
});
|
||||
|
||||
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", newAttributes);
|
||||
|
||||
expect(updateAttributes).toHaveBeenCalledWith(
|
||||
mockContactId,
|
||||
mockUserId,
|
||||
mockEnvironmentId,
|
||||
newAttributes
|
||||
);
|
||||
// Email should not be included in the final attributes
|
||||
expect(result.state.data).toEqual(
|
||||
expect.objectContaining({
|
||||
...mockUserState,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle failed attribute update gracefully", async () => {
|
||||
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(mockContact);
|
||||
const newAttributes = { company: "Formbricks" };
|
||||
vi.mocked(updateAttributes).mockResolvedValue({
|
||||
success: false,
|
||||
messages: ["Update failed"],
|
||||
});
|
||||
|
||||
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", newAttributes);
|
||||
|
||||
expect(updateAttributes).toHaveBeenCalledWith(
|
||||
mockContactId,
|
||||
mockUserId,
|
||||
mockEnvironmentId,
|
||||
newAttributes
|
||||
);
|
||||
// Should still return state even if update failed
|
||||
expect(result.state.data).toEqual(expect.objectContaining(mockUserState));
|
||||
expect(result.messages).toEqual(["Update failed"]);
|
||||
});
|
||||
|
||||
test("should handle multiple attribute updates correctly", async () => {
|
||||
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(mockContact);
|
||||
const newAttributes = {
|
||||
company: "Formbricks",
|
||||
role: "Developer",
|
||||
language: "en",
|
||||
country: "US",
|
||||
};
|
||||
vi.mocked(updateAttributes).mockResolvedValue({
|
||||
success: true,
|
||||
messages: ["Attributes updated successfully"],
|
||||
});
|
||||
|
||||
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", newAttributes);
|
||||
|
||||
expect(updateAttributes).toHaveBeenCalledWith(
|
||||
mockContactId,
|
||||
mockUserId,
|
||||
mockEnvironmentId,
|
||||
newAttributes
|
||||
);
|
||||
expect(result.state.data?.language).toBe("en");
|
||||
expect(result.messages).toEqual(["Attributes updated successfully"]);
|
||||
});
|
||||
|
||||
test("should handle contact creation with multiple initial attributes", async () => {
|
||||
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(null);
|
||||
const initialAttributes = {
|
||||
userId: mockUserId,
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
};
|
||||
vi.mocked(prisma.contact.create).mockResolvedValue({
|
||||
id: mockContactId,
|
||||
attributes: [
|
||||
{ attributeKey: { key: "userId" }, value: mockUserId },
|
||||
{ attributeKey: { key: "email" }, value: "test@example.com" },
|
||||
{ attributeKey: { key: "name" }, value: "Test User" },
|
||||
],
|
||||
} as any);
|
||||
|
||||
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", initialAttributes);
|
||||
|
||||
expect(prisma.contact.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
environment: { connect: { id: mockEnvironmentId } },
|
||||
attributes: {
|
||||
create: [
|
||||
{
|
||||
attributeKey: {
|
||||
connect: { key_environmentId: { key: "userId", environmentId: mockEnvironmentId } },
|
||||
},
|
||||
value: mockUserId,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
attributes: {
|
||||
select: { attributeKey: { select: { key: true } }, value: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(contactCache.revalidate).toHaveBeenCalledWith({
|
||||
environmentId: mockEnvironmentId,
|
||||
userId: mockUserId,
|
||||
id: mockContactId,
|
||||
});
|
||||
expect(result.state.data).toEqual(expect.objectContaining(mockUserState));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -85,26 +85,20 @@ export const updateUser = async (
|
||||
}
|
||||
|
||||
if (shouldUpdate) {
|
||||
const {
|
||||
success,
|
||||
messages: updateAttrMessages,
|
||||
ignoreEmailAttribute,
|
||||
} = await updateAttributes(contact.id, userId, environmentId, attributes);
|
||||
const { success, messages: updateAttrMessages } = await updateAttributes(
|
||||
contact.id,
|
||||
userId,
|
||||
environmentId,
|
||||
attributes
|
||||
);
|
||||
|
||||
messages = updateAttrMessages ?? [];
|
||||
|
||||
// If the attributes update was successful and the language attribute was provided, set the language
|
||||
if (success) {
|
||||
let attributesToUpdate = { ...attributes };
|
||||
|
||||
if (ignoreEmailAttribute) {
|
||||
const { email, ...rest } = attributes;
|
||||
attributesToUpdate = rest;
|
||||
}
|
||||
|
||||
contactAttributes = {
|
||||
...contactAttributes,
|
||||
...attributesToUpdate,
|
||||
...attributes,
|
||||
};
|
||||
|
||||
if (attributes.language) {
|
||||
|
||||
@@ -13,7 +13,7 @@ export const updateAttributes = async (
|
||||
userId: string,
|
||||
environmentId: string,
|
||||
contactAttributesParam: TContactAttributes
|
||||
): Promise<{ success: boolean; messages?: string[]; ignoreEmailAttribute?: boolean }> => {
|
||||
): Promise<{ success: boolean; messages?: string[] }> => {
|
||||
validateInputs(
|
||||
[contactId, ZId],
|
||||
[userId, ZString],
|
||||
@@ -21,8 +21,6 @@ export const updateAttributes = async (
|
||||
[contactAttributesParam, ZContactAttributes]
|
||||
);
|
||||
|
||||
let ignoreEmailAttribute = false;
|
||||
|
||||
// Fetch contact attribute keys and email check in parallel
|
||||
const [contactAttributeKeys, existingEmailAttribute] = await Promise.all([
|
||||
getContactAttributeKeys(environmentId),
|
||||
@@ -60,10 +58,6 @@ export const updateAttributes = async (
|
||||
? ["The email already exists for this environment and was not updated."]
|
||||
: [];
|
||||
|
||||
if (emailExists) {
|
||||
ignoreEmailAttribute = true;
|
||||
}
|
||||
|
||||
// First, update all existing attributes
|
||||
if (existingAttributes.length > 0) {
|
||||
await prisma.$transaction(
|
||||
@@ -130,6 +124,5 @@ export const updateAttributes = async (
|
||||
return {
|
||||
success: true,
|
||||
messages,
|
||||
ignoreEmailAttribute,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -53,10 +53,10 @@ describe("SurveyCard", () => {
|
||||
survey={{ ...dummySurvey, status: "draft" } as unknown as TSurvey}
|
||||
environmentId={environmentId}
|
||||
isReadOnly={false}
|
||||
WEBAPP_URL={WEBAPP_URL}
|
||||
duplicateSurvey={mockDuplicateSurvey}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
locale="en-US"
|
||||
surveyDomain={WEBAPP_URL}
|
||||
/>
|
||||
);
|
||||
// Draft survey => link should point to edit
|
||||
@@ -70,10 +70,10 @@ describe("SurveyCard", () => {
|
||||
survey={{ ...dummySurvey, status: "draft" } as unknown as TSurvey}
|
||||
environmentId={environmentId}
|
||||
isReadOnly={true}
|
||||
WEBAPP_URL={WEBAPP_URL}
|
||||
duplicateSurvey={mockDuplicateSurvey}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
locale="en-US"
|
||||
surveyDomain={WEBAPP_URL}
|
||||
/>
|
||||
);
|
||||
// When it's read only and draft, we expect no link
|
||||
@@ -87,10 +87,10 @@ describe("SurveyCard", () => {
|
||||
survey={{ ...dummySurvey, status: "inProgress" } as unknown as TSurvey}
|
||||
environmentId={environmentId}
|
||||
isReadOnly={false}
|
||||
WEBAPP_URL={WEBAPP_URL}
|
||||
duplicateSurvey={mockDuplicateSurvey}
|
||||
deleteSurvey={mockDeleteSurvey}
|
||||
locale="en-US"
|
||||
surveyDomain={WEBAPP_URL}
|
||||
/>
|
||||
);
|
||||
// For non-draft => link to summary
|
||||
|
||||
@@ -4,8 +4,8 @@ export const NetPromoterScoreIcon: React.FC<React.SVGProps<SVGSVGElement>> = (pr
|
||||
<g id="Frame">
|
||||
<path
|
||||
id="Vector"
|
||||
fillRule="evenodd"
|
||||
clipRule="evenodd"
|
||||
fill-rule="evenodd"
|
||||
clip-rule="evenodd"
|
||||
d="M2.25 2.25C2.05109 2.25 1.86032 2.32902 1.71967 2.46967C1.57902 2.61032 1.5 2.80109 1.5 3C1.5 3.19891 1.57902 3.38968 1.71967 3.53033C1.86032 3.67098 2.05109 3.75 2.25 3.75H3V14.25C3 15.0456 3.31607 15.8087 3.87868 16.3713C4.44129 16.9339 5.20435 17.25 6 17.25H7.21L6.038 20.763C5.97514 20.9518 5.98988 21.1579 6.07896 21.3359C6.16804 21.5138 6.32417 21.6491 6.513 21.712C6.70183 21.7749 6.9079 21.7601 7.08588 21.671C7.26385 21.582 7.39914 21.4258 7.462 21.237L7.791 20.25H16.209L16.539 21.237C16.6073 21.4186 16.7433 21.5666 16.9184 21.6501C17.0935 21.7335 17.2941 21.7459 17.4782 21.6845C17.6622 21.6232 17.8153 21.4929 17.9053 21.3211C17.9954 21.1493 18.0153 20.9492 17.961 20.763L16.791 17.25H18C18.7956 17.25 19.5587 16.9339 20.1213 16.3713C20.6839 15.8087 21 15.0456 21 14.25V3.75H21.75C21.9489 3.75 22.1397 3.67098 22.2803 3.53033C22.421 3.38968 22.5 3.19891 22.5 3C22.5 2.80109 22.421 2.61032 22.2803 2.46967C22.1397 2.32902 21.9489 2.25 21.75 2.25H2.25ZM8.29 18.75L8.79 17.25H15.21L15.71 18.75H8.29ZM15.75 6.75C15.75 6.55109 15.671 6.36032 15.5303 6.21967C15.3897 6.07902 15.1989 6 15 6C14.8011 6 14.6103 6.07902 14.4697 6.21967C14.329 6.36032 14.25 6.55109 14.25 6.75V12.75C14.25 12.9489 14.329 13.1397 14.4697 13.2803C14.6103 13.421 14.8011 13.5 15 13.5C15.1989 13.5 15.3897 13.421 15.5303 13.2803C15.671 13.1397 15.75 12.9489 15.75 12.75V6.75ZM12.75 9C12.75 8.80109 12.671 8.61032 12.5303 8.46967C12.3897 8.32902 12.1989 8.25 12 8.25C11.8011 8.25 11.6103 8.32902 11.4697 8.46967C11.329 8.61032 11.25 8.80109 11.25 9V12.75C11.25 12.9489 11.329 13.1397 11.4697 13.2803C11.6103 13.421 11.8011 13.5 12 13.5C12.1989 13.5 12.3897 13.421 12.5303 13.2803C12.671 13.1397 12.75 12.9489 12.75 12.75V9ZM9.75 11.25C9.75 11.0511 9.67098 10.8603 9.53033 10.7197C9.38968 10.579 9.19891 10.5 9 10.5C8.80109 10.5 8.61032 10.579 8.46967 10.7197C8.32902 10.8603 8.25 11.0511 8.25 11.25V12.75C8.25 12.9489 8.32902 13.1397 8.46967 13.2803C8.61032 13.421 8.80109 13.5 9 13.5C9.19891 13.5 9.38968 13.421 9.53033 13.2803C9.67098 13.1397 9.75 12.9489 9.75 12.75V11.25Z"
|
||||
fill="white"
|
||||
/>
|
||||
|
||||
@@ -19,7 +19,6 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(({ className, isInv
|
||||
isInvalid && "border border-red-500 focus:border-red-500"
|
||||
)}
|
||||
ref={ref}
|
||||
dir="auto"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -133,7 +133,6 @@ export const Modal = ({
|
||||
<div
|
||||
id="preview-survey-base"
|
||||
aria-live="assertive"
|
||||
dir="auto"
|
||||
className={cn(
|
||||
"relative h-full w-full overflow-hidden rounded-b-md",
|
||||
overlayVisible ? (darkOverlay ? "bg-slate-700/80" : "bg-white/50") : "",
|
||||
@@ -150,7 +149,6 @@ export const Modal = ({
|
||||
background,
|
||||
}),
|
||||
}}
|
||||
dir="auto"
|
||||
className={cn(
|
||||
"no-scrollbar pointer-events-auto absolute max-h-[90%] w-full max-w-sm transition-all duration-500 ease-in-out",
|
||||
previewMode === "desktop" ? getPlacementStyle(placement) : "max-w-full",
|
||||
|
||||
@@ -283,7 +283,7 @@ export const PreviewSurvey = ({
|
||||
/>
|
||||
</Modal>
|
||||
) : (
|
||||
<div className="flex h-full w-full flex-col justify-center px-1" dir="auto">
|
||||
<div className="flex h-full w-full flex-col justify-center px-1">
|
||||
<div className="absolute left-5 top-5">
|
||||
{!styling.isLogoHidden && (
|
||||
<ClientLogo environmentId={environment.id} projectLogo={project.logo} previewSurvey />
|
||||
|
||||
@@ -72,5 +72,5 @@ export const SurveyInline = (props: Omit<SurveyContainerProps, "containerId">) =
|
||||
}
|
||||
}, [isScriptLoaded, renderInline]);
|
||||
|
||||
return <div id={containerId} className="h-full w-full" dir="auto" />;
|
||||
return <div id={containerId} className="h-full w-full" />;
|
||||
};
|
||||
|
||||
@@ -127,9 +127,9 @@ input[type="search"]::-ms-reveal {
|
||||
}
|
||||
|
||||
input[type="range"]::-webkit-slider-thumb {
|
||||
background: #0f172a;
|
||||
height: 20px;
|
||||
width: 20px;
|
||||
border-radius: 50%;
|
||||
-webkit-appearance: none;
|
||||
background: #0f172a;
|
||||
}
|
||||
|
||||
@@ -117,9 +117,11 @@
|
||||
"prismjs": "1.30.0",
|
||||
"qr-code-styling": "1.9.2",
|
||||
"qrcode": "1.5.4",
|
||||
"react": "19.1.0",
|
||||
"react-colorful": "5.6.1",
|
||||
"react-confetti": "6.4.0",
|
||||
"react-day-picker": "9.6.7",
|
||||
"react-dom": "19.1.0",
|
||||
"react-hook-form": "7.56.2",
|
||||
"react-hot-toast": "2.5.2",
|
||||
"react-turnstile": "1.1.4",
|
||||
|
||||
@@ -12,8 +12,8 @@ if (SENTRY_DSN) {
|
||||
Sentry.init({
|
||||
dsn: SENTRY_DSN,
|
||||
|
||||
// No tracing while Sentry doesn't update to telemetry 2.0.0 - https://github.com/getsentry/sentry-javascript/issues/15737
|
||||
tracesSampleRate: 0,
|
||||
// Adjust this value in production, or use tracesSampler for greater control
|
||||
tracesSampleRate: 1,
|
||||
|
||||
// Setting this option to true will print useful information to the console while you're setting up Sentry.
|
||||
debug: false,
|
||||
|
||||
@@ -11,8 +11,8 @@ if (SENTRY_DSN) {
|
||||
Sentry.init({
|
||||
dsn: SENTRY_DSN,
|
||||
|
||||
// No tracing while Sentry doesn't update to telemetry 2.0.0 - https://github.com/getsentry/sentry-javascript/issues/15737
|
||||
tracesSampleRate: 0,
|
||||
// Adjust this value in production, or use tracesSampler for greater control
|
||||
tracesSampleRate: 1,
|
||||
|
||||
// Setting this option to true will print useful information to the console while you're setting up Sentry.
|
||||
debug: false,
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
"schema": "packages/database/schema.prisma"
|
||||
},
|
||||
"scripts": {
|
||||
"clean:all": "turbo run clean && rimraf node_modules pnpm-lock.yaml .turbo coverage out",
|
||||
"clean": "turbo run clean && rimraf node_modules .turbo coverage out",
|
||||
"build": "turbo run build",
|
||||
"build:dev": "turbo run build:dev",
|
||||
@@ -36,10 +35,6 @@
|
||||
"fb-migrate-dev": "pnpm --filter @formbricks/database create-migration && pnpm prisma generate",
|
||||
"tolgee-pull": "BRANCH_NAME=$(node -p \"require('./branch.json').branchName\") && tolgee pull --tags \"draft:$BRANCH_NAME\" \"production\" && prettier --write ./apps/web/locales/*.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "19.1.0",
|
||||
"react-dom": "19.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@azure/microsoft-playwright-testing": "1.0.0-beta.7",
|
||||
"@formbricks/eslint-config": "workspace:*",
|
||||
|
||||
@@ -193,6 +193,8 @@ export const setup = async (
|
||||
|
||||
if (environmentStateResponse.ok) {
|
||||
environmentState = environmentStateResponse.data;
|
||||
const backendSurveys = environmentState.data.surveys;
|
||||
logger.debug(`Fetched ${backendSurveys.length.toString()} surveys from the backend`);
|
||||
} else {
|
||||
logger.error(
|
||||
`Error fetching environment state: ${environmentStateResponse.error.code} - ${environmentStateResponse.error.responseMessage ?? ""}`
|
||||
@@ -247,6 +249,7 @@ export const setup = async (
|
||||
|
||||
// filter the environment state wrt the person state
|
||||
const filteredSurveys = filterSurveys(environmentState, userState);
|
||||
logger.debug(`${filteredSurveys.length.toString()} surveys could be shown to current user on trigger.`);
|
||||
|
||||
// update the appConfig with the new filtered surveys and person state
|
||||
config.update({
|
||||
@@ -256,8 +259,8 @@ export const setup = async (
|
||||
filteredSurveys,
|
||||
});
|
||||
|
||||
const surveyNames = filteredSurveys.map((s) => s.name);
|
||||
logger.debug(`Fetched ${surveyNames.length.toString()} surveys during sync: ${surveyNames.join(", ")}`);
|
||||
// const surveyNames = filteredSurveys.map((s) => s.name);
|
||||
// logger.debug(`Fetched ${surveyNames.length.toString()} surveys during sync: ${surveyNames.join(", ")}`);
|
||||
} catch {
|
||||
logger.debug("Error during sync. Please try again.");
|
||||
}
|
||||
@@ -283,6 +286,9 @@ export const setup = async (
|
||||
|
||||
let userState: TUserState = DEFAULT_USER_STATE_NO_USER_ID;
|
||||
|
||||
const backendSurveys = environmentStateResponse.data.data.surveys;
|
||||
logger.debug(`Fetched ${backendSurveys.length.toString()} surveys from the backend`);
|
||||
|
||||
if ("userId" in configInput && configInput.userId) {
|
||||
const updatesResponse = await sendUpdatesToBackend({
|
||||
appUrl: configInput.appUrl,
|
||||
@@ -304,6 +310,7 @@ export const setup = async (
|
||||
|
||||
const environmentState = environmentStateResponse.data;
|
||||
const filteredSurveys = filterSurveys(environmentState, userState);
|
||||
logger.debug(`${filteredSurveys.length.toString()} surveys could be shown to current user on trigger.`);
|
||||
|
||||
config.update({
|
||||
appUrl: configInput.appUrl,
|
||||
|
||||
@@ -53,7 +53,7 @@ export function QuestionMedia({ imgUrl, videoUrl, altText = "Image" }: QuestionM
|
||||
setIsLoading(false);
|
||||
}}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"
|
||||
referrerPolicy="strict-origin-when-cross-origin"
|
||||
referrerpolicy="strict-origin-when-cross-origin"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/preact";
|
||||
import { cleanup, render, screen } from "@testing-library/preact";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { type TSurveyOpenTextQuestion, TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types";
|
||||
@@ -76,7 +76,10 @@ describe("OpenTextQuestion", () => {
|
||||
render(<OpenTextQuestion {...defaultProps} onChange={onChange} />);
|
||||
|
||||
const input = screen.getByPlaceholderText("Type here...");
|
||||
fireEvent.input(input, { target: { value: "Hello" } });
|
||||
|
||||
// Directly set the input value and trigger the input event
|
||||
Object.defineProperty(input, "value", { value: "Hello" });
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ q1: "Hello" });
|
||||
});
|
||||
@@ -160,291 +163,4 @@ describe("OpenTextQuestion", () => {
|
||||
|
||||
expect(focusMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("handles input change for textarea with resize functionality", async () => {
|
||||
// Create a spy on the Element.prototype to monitor style changes
|
||||
const styleSpy = vi.spyOn(HTMLElement.prototype, "style", "get").mockImplementation(
|
||||
() =>
|
||||
({
|
||||
height: "",
|
||||
overflow: "",
|
||||
}) as CSSStyleDeclaration
|
||||
);
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
onChange={onChange}
|
||||
question={{ ...defaultQuestion, longAnswer: true }}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByRole("textbox");
|
||||
// Only trigger a regular input event without trying to modify scrollHeight
|
||||
fireEvent.input(textarea, { target: { value: "Test value for textarea" } });
|
||||
|
||||
// Check that onChange was called with the correct value
|
||||
expect(onChange).toHaveBeenCalledWith({ q1: "Test value for textarea" });
|
||||
|
||||
// Clean up the spy
|
||||
styleSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("handles textarea resize with different heights", async () => {
|
||||
// Mock styles and scrollHeight for handleInputResize testing
|
||||
let heightValue = "";
|
||||
let overflowValue = "";
|
||||
|
||||
// Mock style setter to capture values
|
||||
const originalSetProperty = CSSStyleDeclaration.prototype.setProperty;
|
||||
CSSStyleDeclaration.prototype.setProperty = vi.fn();
|
||||
|
||||
// Mock to capture style changes
|
||||
Object.defineProperty(HTMLElement.prototype, "style", {
|
||||
get: vi.fn(() => ({
|
||||
height: heightValue,
|
||||
overflow: overflowValue,
|
||||
setProperty: (prop: string, value: string) => {
|
||||
if (prop === "height") heightValue = value;
|
||||
if (prop === "overflow") overflowValue = value;
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
onChange={onChange}
|
||||
question={{ ...defaultQuestion, longAnswer: true }}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByRole("textbox");
|
||||
|
||||
// Simulate normal height (less than max)
|
||||
const mockNormalEvent = {
|
||||
target: {
|
||||
style: { height: "", overflow: "" },
|
||||
scrollHeight: 100, // Less than max 160px
|
||||
},
|
||||
};
|
||||
|
||||
// Get the event handler
|
||||
const inputHandler = textarea.oninput as EventListener;
|
||||
if (inputHandler) {
|
||||
inputHandler(mockNormalEvent as unknown as Event);
|
||||
}
|
||||
|
||||
// Now simulate text that exceeds max height
|
||||
const mockOverflowEvent = {
|
||||
target: {
|
||||
style: { height: "", overflow: "" },
|
||||
scrollHeight: 200, // More than max 160px
|
||||
},
|
||||
};
|
||||
|
||||
if (inputHandler) {
|
||||
inputHandler(mockOverflowEvent as unknown as Event);
|
||||
}
|
||||
|
||||
// Restore the original method
|
||||
CSSStyleDeclaration.prototype.setProperty = originalSetProperty;
|
||||
});
|
||||
|
||||
test("handles form submission by enter key", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
const setTtc = vi.fn();
|
||||
|
||||
const { container } = render(
|
||||
<OpenTextQuestion {...defaultProps} value="Test submission" onSubmit={onSubmit} setTtc={setTtc} />
|
||||
);
|
||||
|
||||
// Get the form element using container query
|
||||
const form = container.querySelector("form");
|
||||
expect(form).toBeInTheDocument();
|
||||
|
||||
// Simulate form submission
|
||||
fireEvent.submit(form!);
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledWith({ q1: "Test submission" }, {});
|
||||
expect(setTtc).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("applies minLength constraint when configured", () => {
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
question={{ ...defaultQuestion, charLimit: { min: 5, max: 100 } }}
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText("Type here...");
|
||||
expect(input).toHaveAttribute("minLength", "5");
|
||||
expect(input).toHaveAttribute("maxLength", "100");
|
||||
});
|
||||
|
||||
test("handles video URL in media", () => {
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
question={{ ...defaultQuestion, videoUrl: "https://example.com/video.mp4" }}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("question-media")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("doesn't autofocus when not current question", () => {
|
||||
const focusMock = vi.fn();
|
||||
window.HTMLElement.prototype.focus = focusMock;
|
||||
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
autoFocusEnabled={true}
|
||||
currentQuestionId="q2" // Different from question id (q1)
|
||||
/>
|
||||
);
|
||||
|
||||
expect(focusMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("handles input change for textarea", async () => {
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
onChange={onChange}
|
||||
question={{ ...defaultQuestion, longAnswer: true }}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByRole("textbox");
|
||||
fireEvent.input(textarea, { target: { value: "Long text response" } });
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ q1: "Long text response" });
|
||||
});
|
||||
|
||||
test("applies phone number maxLength constraint", () => {
|
||||
render(<OpenTextQuestion {...defaultProps} question={{ ...defaultQuestion, inputType: "phone" }} />);
|
||||
|
||||
const input = screen.getByPlaceholderText("Type here...");
|
||||
expect(input).toHaveAttribute("maxLength", "30");
|
||||
});
|
||||
|
||||
test("renders without subheader when not provided", () => {
|
||||
const questionWithoutSubheader = {
|
||||
...defaultQuestion,
|
||||
subheader: undefined,
|
||||
};
|
||||
|
||||
render(<OpenTextQuestion {...defaultProps} question={questionWithoutSubheader} />);
|
||||
expect(screen.getByTestId("mock-subheader")).toHaveTextContent("");
|
||||
});
|
||||
|
||||
test("sets correct tabIndex based on current question status", () => {
|
||||
// When it's the current question
|
||||
render(<OpenTextQuestion {...defaultProps} currentQuestionId="q1" />);
|
||||
const inputCurrent = screen.getByPlaceholderText("Type here...");
|
||||
const submitCurrent = screen.getByRole("button", { name: "Submit" });
|
||||
|
||||
expect(inputCurrent).toHaveAttribute("tabIndex", "0");
|
||||
expect(submitCurrent).toHaveAttribute("tabIndex", "0");
|
||||
|
||||
// When it's not the current question
|
||||
cleanup();
|
||||
render(<OpenTextQuestion {...defaultProps} currentQuestionId="q2" />);
|
||||
const inputNotCurrent = screen.getByPlaceholderText("Type here...");
|
||||
const submitNotCurrent = screen.getByRole("button", { name: "Submit" });
|
||||
|
||||
expect(inputNotCurrent).toHaveAttribute("tabIndex", "-1");
|
||||
expect(submitNotCurrent).toHaveAttribute("tabIndex", "-1");
|
||||
});
|
||||
|
||||
test("applies title attribute for phone input in textarea", () => {
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
question={{
|
||||
...defaultQuestion,
|
||||
longAnswer: true,
|
||||
inputType: "phone",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByRole("textbox");
|
||||
expect(textarea).toHaveAttribute("title", "Please enter a valid phone number");
|
||||
});
|
||||
|
||||
test("applies character limits for textarea", () => {
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
question={{
|
||||
...defaultQuestion,
|
||||
longAnswer: true,
|
||||
inputType: "text",
|
||||
charLimit: { min: 10, max: 200 },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByRole("textbox");
|
||||
expect(textarea).toHaveAttribute("minLength", "10");
|
||||
expect(textarea).toHaveAttribute("maxLength", "200");
|
||||
});
|
||||
|
||||
test("renders input with no maxLength for other input types", () => {
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
question={{
|
||||
...defaultQuestion,
|
||||
inputType: "email",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText("Type here...");
|
||||
// Should be undefined for non-text, non-phone types
|
||||
expect(input).not.toHaveAttribute("maxLength");
|
||||
});
|
||||
|
||||
test("applies autofocus attribute to textarea when enabled", () => {
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
autoFocusEnabled={true}
|
||||
question={{
|
||||
...defaultQuestion,
|
||||
longAnswer: true,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByRole("textbox");
|
||||
expect(textarea).toHaveAttribute("autoFocus");
|
||||
});
|
||||
|
||||
test("does not apply autofocus attribute to textarea when not current question", () => {
|
||||
render(
|
||||
<OpenTextQuestion
|
||||
{...defaultProps}
|
||||
autoFocusEnabled={true}
|
||||
currentQuestionId="q2" // different from question.id (q1)
|
||||
question={{
|
||||
...defaultQuestion,
|
||||
longAnswer: true,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByRole("textbox");
|
||||
expect(textarea).not.toHaveAttribute("autoFocus");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,8 +115,8 @@ export function OpenTextQuestion({
|
||||
className="fb-border-border placeholder:fb-text-placeholder fb-text-subheading focus:fb-border-brand fb-bg-input-bg fb-rounded-custom fb-block fb-w-full fb-border fb-p-2 fb-shadow-sm focus:fb-outline-none focus:fb-ring-0 sm:fb-text-sm"
|
||||
pattern={question.inputType === "phone" ? "^[0-9+][0-9+\\- ]*[0-9]$" : ".*"}
|
||||
title={question.inputType === "phone" ? "Enter a valid phone number" : undefined}
|
||||
minLength={question.inputType === "text" ? question.charLimit?.min : undefined}
|
||||
maxLength={
|
||||
minlength={question.inputType === "text" ? question.charLimit?.min : undefined}
|
||||
maxlength={
|
||||
question.inputType === "text"
|
||||
? question.charLimit?.max
|
||||
: question.inputType === "phone"
|
||||
@@ -143,8 +143,8 @@ export function OpenTextQuestion({
|
||||
}}
|
||||
className="fb-border-border placeholder:fb-text-placeholder fb-bg-input-bg fb-text-subheading focus:fb-border-brand fb-rounded-custom fb-block fb-w-full fb-border fb-p-2 fb-shadow-sm focus:fb-ring-0 sm:fb-text-sm"
|
||||
title={question.inputType === "phone" ? "Please enter a valid phone number" : undefined}
|
||||
minLength={question.inputType === "text" ? question.charLimit?.min : undefined}
|
||||
maxLength={question.inputType === "text" ? question.charLimit?.max : undefined}
|
||||
minlength={question.inputType === "text" ? question.charLimit?.min : undefined}
|
||||
maxlength={question.inputType === "text" ? question.charLimit?.max : undefined}
|
||||
/>
|
||||
)}
|
||||
{question.inputType === "text" && question.charLimit?.max !== undefined && (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { type TResponseData, type TResponseVariables } from "@formbricks/types/responses";
|
||||
import { type TSurveyQuestion, TSurveyQuestionTypeEnum } from "../../../types/surveys/types";
|
||||
import { parseRecallInformation, replaceRecallInfo } from "./recall";
|
||||
@@ -15,7 +15,7 @@ vi.mock("./i18n", () => ({
|
||||
vi.mock("./date-time", () => ({
|
||||
isValidDateString: (val: string) => /^\d{4}-\d{2}-\d{2}$/.test(val) || /^\d{2}-\d{2}-\d{4}$/.test(val),
|
||||
formatDateWithOrdinal: (date: Date) =>
|
||||
`${date.getUTCFullYear()}-${("0" + (date.getUTCMonth() + 1)).slice(-2)}-${("0" + date.getUTCDate()).slice(-2)}_formatted`,
|
||||
`${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(-2)}-${("0" + date.getDate()).slice(-2)}_formatted`,
|
||||
}));
|
||||
|
||||
describe("replaceRecallInfo", () => {
|
||||
@@ -34,73 +34,79 @@ describe("replaceRecallInfo", () => {
|
||||
lastLogin: "2024-03-10",
|
||||
};
|
||||
|
||||
test("should replace recall info from responseData", () => {
|
||||
it("should replace recall info from responseData", () => {
|
||||
const text = "Welcome, #recall:name/fallback:Guest#! Your email is #recall:email/fallback:N/A#.";
|
||||
const expected = "Welcome, John Doe! Your email is john.doe@example.com.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should replace recall info from variables if not in responseData", () => {
|
||||
it("should replace recall info from variables if not in responseData", () => {
|
||||
const text = "Product: #recall:productName/fallback:N/A#. Role: #recall:userRole/fallback:User#.";
|
||||
const expected = "Product: Formbricks. Role: Admin.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should use fallback if value is not found in responseData or variables", () => {
|
||||
it("should use fallback if value is not found in responseData or variables", () => {
|
||||
const text = "Your organization is #recall:orgName/fallback:DefaultOrg#.";
|
||||
const expected = "Your organization is DefaultOrg.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle nbsp in fallback", () => {
|
||||
const text = "Status: #recall:status/fallback:Pending Review#.";
|
||||
const expected = "Status: Pending& ;Review.";
|
||||
it("should handle nbsp in fallback", () => {
|
||||
const text = "Status: #recall:status/fallback:PendingnbspReview#.";
|
||||
const expected = "Status: Pending Review.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should format date strings from responseData", () => {
|
||||
it("should format date strings from responseData", () => {
|
||||
const text = "Registered on: #recall:registrationDate/fallback:N/A#.";
|
||||
const expected = "Registered on: 2023-01-15_formatted.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should format date strings from variables", () => {
|
||||
it("should format date strings from variables", () => {
|
||||
const text = "Last login: #recall:lastLogin/fallback:N/A#.";
|
||||
const expected = "Last login: 2024-03-10_formatted.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should join array values with a comma and space", () => {
|
||||
it("should join array values with a comma and space", () => {
|
||||
const text = "Tags: #recall:tags/fallback:none#.";
|
||||
const expected = "Tags: beta, user.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle empty array values, replacing with fallback", () => {
|
||||
it("should handle empty array values, replacing with fallback", () => {
|
||||
const text = "Categories: #recall:emptyArray/fallback:No Categories#.";
|
||||
const expected = "Categories: No& ;Categories.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle multiple recall patterns in a single string", () => {
|
||||
it("should handle null values from responseData, replacing with fallback", () => {
|
||||
const text = "Preference: #recall:nullValue/fallback:Not Set#.";
|
||||
const expected = "Preference: Not& ;Set.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle multiple recall patterns in a single string", () => {
|
||||
const text =
|
||||
"Hi #recall:name/fallback:User#, welcome to #recall:productName/fallback:Our Product#. Your role is #recall:userRole/fallback:Member#.";
|
||||
const expected = "Hi John Doe, welcome to #recall:productName/fallback:Our Product#. Your role is Admin.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should return original text if no recall pattern is found", () => {
|
||||
it("should return original text if no recall pattern is found", () => {
|
||||
const text = "This is a normal text without recall info.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(text);
|
||||
});
|
||||
|
||||
test("should handle recall ID not found, using fallback", () => {
|
||||
it("should handle recall ID not found, using fallback", () => {
|
||||
const text = "Value: #recall:nonExistent/fallback:FallbackValue#.";
|
||||
const expected = "Value: FallbackValue.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle if recall info is incomplete (e.g. missing fallback part), effectively using empty fallback", () => {
|
||||
it("should handle if recall info is incomplete (e.g. missing fallback part), effectively using empty fallback", () => {
|
||||
// This specific pattern is not fully matched by extractRecallInfo, leading to no replacement.
|
||||
// The current extractRecallInfo expects #recall:ID/fallback:VALUE#
|
||||
const text = "Test: #recall:name#";
|
||||
@@ -108,28 +114,10 @@ describe("replaceRecallInfo", () => {
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle complex fallback with spaces and special characters encoded as nbsp", () => {
|
||||
it("should handle complex fallback with spaces and special characters encoded as nbsp", () => {
|
||||
const text =
|
||||
"Details: #recall:extraInfo/fallback:Value With Spaces# and #recall:anotherInfo/fallback:Default#";
|
||||
const expected = "Details: Value& ;With& ;Spaces and Default";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle fallback with only 'nbsp'", () => {
|
||||
const text = "Note: #recall:note/fallback:nbsp#.";
|
||||
const expected = "Note: .";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle fallback with only ' '", () => {
|
||||
const text = "Note: #recall:note/fallback: #.";
|
||||
const expected = "Note: & ;.";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
|
||||
test("should handle fallback with '$nbsp;' (should not replace '$nbsp;')", () => {
|
||||
const text = "Note: #recall:note/fallback:$nbsp;#.";
|
||||
const expected = "Note: $ ;.";
|
||||
"Details: #recall:extraInfo/fallback:ValuenbspWithnbspSpaces# and #recall:anotherInfo/fallback:Default#";
|
||||
const expected = "Details: Value With Spaces and Default";
|
||||
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -163,7 +151,7 @@ describe("parseRecallInformation", () => {
|
||||
// other necessary TSurveyQuestion fields can be added here with default values
|
||||
};
|
||||
|
||||
test("should replace recall info in headline", () => {
|
||||
it("should replace recall info in headline", () => {
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
headline: { en: "Welcome, #recall:name/fallback:Guest#!" },
|
||||
@@ -173,7 +161,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.headline.en).toBe(expectedHeadline);
|
||||
});
|
||||
|
||||
test("should replace recall info in subheader", () => {
|
||||
it("should replace recall info in subheader", () => {
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
headline: { en: "Main Question" },
|
||||
@@ -184,7 +172,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.subheader?.en).toBe(expectedSubheader);
|
||||
});
|
||||
|
||||
test("should replace recall info in both headline and subheader", () => {
|
||||
it("should replace recall info in both headline and subheader", () => {
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
headline: { en: "User: #recall:name/fallback:User#" },
|
||||
@@ -195,7 +183,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.subheader?.en).toBe("Survey: Onboarding");
|
||||
});
|
||||
|
||||
test("should not change text if no recall info is present", () => {
|
||||
it("should not change text if no recall info is present", () => {
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
headline: { en: "A simple question." },
|
||||
@@ -211,7 +199,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.subheader?.en).toBe(question.subheader?.en);
|
||||
});
|
||||
|
||||
test("should handle undefined subheader gracefully", () => {
|
||||
it("should handle undefined subheader gracefully", () => {
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
headline: { en: "Question with #recall:name/fallback:User#" },
|
||||
@@ -222,7 +210,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.subheader).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should not modify subheader if languageCode content is missing, even if recall is in other lang", () => {
|
||||
it("should not modify subheader if languageCode content is missing, even if recall is in other lang", () => {
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
headline: { en: "Hello #recall:name/fallback:User#" },
|
||||
@@ -234,7 +222,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.subheader?.fr).toBe("Bonjour #recall:name/fallback:Utilisateur#");
|
||||
});
|
||||
|
||||
test("should handle malformed recall string (empty ID) leading to no replacement for that pattern", () => {
|
||||
it("should handle malformed recall string (empty ID) leading to no replacement for that pattern", () => {
|
||||
// This tests extractId returning null because extractRecallInfo won't match '#recall:/fallback:foo#'
|
||||
// due to idPattern requiring at least one char for ID.
|
||||
const question: TSurveyQuestion = {
|
||||
@@ -245,7 +233,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.headline.en).toBe("Malformed: #recall:/fallback:foo# and valid: John Doe");
|
||||
});
|
||||
|
||||
test("should use empty string for empty fallback value", () => {
|
||||
it("should use empty string for empty fallback value", () => {
|
||||
// This tests extractFallbackValue returning ""
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
@@ -255,7 +243,7 @@ describe("parseRecallInformation", () => {
|
||||
expect(result.headline.en).toBe("Data: "); // nonExistentData not found, empty fallback used
|
||||
});
|
||||
|
||||
test("should handle recall info if subheader is present but no text for languageCode", () => {
|
||||
it("should handle recall info if subheader is present but no text for languageCode", () => {
|
||||
const question: TSurveyQuestion = {
|
||||
...baseQuestion,
|
||||
headline: { en: "Headline #recall:name/fallback:User#" },
|
||||
|
||||
@@ -7,19 +7,27 @@ import { type TSurveyQuestion } from "@formbricks/types/surveys/types";
|
||||
const extractId = (text: string): string | null => {
|
||||
const pattern = /#recall:([A-Za-z0-9_-]+)/;
|
||||
const match = text.match(pattern);
|
||||
return match?.[1] ?? null;
|
||||
if (match && match[1]) {
|
||||
return match[1];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Extracts the fallback value from a string containing the "fallback" pattern.
|
||||
const extractFallbackValue = (text: string): string => {
|
||||
const pattern = /fallback:(\S*)#/;
|
||||
const match = text.match(pattern);
|
||||
return match?.[1] ?? "";
|
||||
if (match && match[1]) {
|
||||
return match[1];
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
// Extracts the complete recall information (ID and fallback) from a headline string.
|
||||
const extractRecallInfo = (headline: string, id?: string): string | null => {
|
||||
const idPattern = id ?? "[A-Za-z0-9_-]+";
|
||||
const idPattern = id ? id : "[A-Za-z0-9_-]+";
|
||||
const pattern = new RegExp(`#recall:(${idPattern})\\/fallback:(\\S*)#`);
|
||||
const match = headline.match(pattern);
|
||||
return match ? match[0] : null;
|
||||
@@ -39,7 +47,7 @@ export const replaceRecallInfo = (
|
||||
const recallItemId = extractId(recallInfo);
|
||||
if (!recallItemId) return modifiedText; // Return the text if no ID could be extracted
|
||||
|
||||
const fallback = extractFallbackValue(recallInfo).replace(/nbsp/g, " ").trim();
|
||||
const fallback = extractFallbackValue(recallInfo).replaceAll("nbsp", " ");
|
||||
let value: string | null = null;
|
||||
|
||||
// Fetching value from variables based on recallItemId
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import preact from "@preact/preset-vite";
|
||||
import { fileURLToPath } from "url";
|
||||
import { dirname, resolve } from "path";
|
||||
import { loadEnv } from "vite";
|
||||
import { defineConfig, loadEnv } from "vite";
|
||||
import dts from "vite-plugin-dts";
|
||||
import tsconfigPaths from "vite-tsconfig-paths";
|
||||
import { copyCompiledAssetsPlugin } from "../vite-plugins/copy-compiled-assets";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
@@ -30,7 +29,7 @@ const config = ({ mode }) => {
|
||||
},
|
||||
},
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify(mode),
|
||||
"process.env": env,
|
||||
},
|
||||
build: {
|
||||
emptyOutDir: false,
|
||||
|
||||
2702
pnpm-lock.yaml
generated
2702
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user