mirror of
https://github.com/formbricks/formbricks.git
synced 2026-03-13 01:58:40 -05:00
feat: Add Server-side pagination to Surveys List (#2197)
Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
This commit is contained in:
@@ -80,6 +80,9 @@ const ResponsePage = ({
|
||||
|
||||
const deleteResponse = (responseId: string) => {
|
||||
setResponses(responses.filter((response) => response.id !== responseId));
|
||||
if (responseCount) {
|
||||
setResponseCount(responseCount - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const updateResponse = (responseId: string, updatedResponse: TResponse) => {
|
||||
|
||||
@@ -48,21 +48,10 @@ export default function SurveyEditor({
|
||||
}: SurveyEditorProps): JSX.Element {
|
||||
const [activeView, setActiveView] = useState<"questions" | "settings">("questions");
|
||||
const [activeQuestionId, setActiveQuestionId] = useState<string | null>(null);
|
||||
const [localSurvey, setLocalSurvey] = useState<TSurvey | null>();
|
||||
const [localSurvey, setLocalSurvey] = useState<TSurvey | null>(survey);
|
||||
const [invalidQuestions, setInvalidQuestions] = useState<String[] | null>(null);
|
||||
const [localProduct, setLocalProduct] = useState<TProduct>(product);
|
||||
|
||||
useEffect(() => {
|
||||
if (survey) {
|
||||
const surveyClone = structuredClone(survey);
|
||||
setLocalSurvey(surveyClone);
|
||||
|
||||
if (survey.questions.length > 0) {
|
||||
setActiveQuestionId(survey.questions[0].id);
|
||||
}
|
||||
}
|
||||
}, [survey]);
|
||||
|
||||
useEffect(() => {
|
||||
const listener = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
|
||||
@@ -4,13 +4,13 @@ import { Metadata } from "next";
|
||||
import { getServerSession } from "next-auth";
|
||||
|
||||
import { authOptions } from "@formbricks/lib/authOptions";
|
||||
import { WEBAPP_URL } from "@formbricks/lib/constants";
|
||||
import { SURVEYS_PER_PAGE, WEBAPP_URL } from "@formbricks/lib/constants";
|
||||
import { getEnvironment } from "@formbricks/lib/environment/service";
|
||||
import { getEnvironments } from "@formbricks/lib/environment/service";
|
||||
import { getMembershipByUserIdTeamId } from "@formbricks/lib/membership/service";
|
||||
import { getAccessFlags } from "@formbricks/lib/membership/utils";
|
||||
import { getProductByEnvironmentId } from "@formbricks/lib/product/service";
|
||||
import { getSurveys } from "@formbricks/lib/survey/service";
|
||||
import { getSurveyCount } from "@formbricks/lib/survey/service";
|
||||
import { getTeamByEnvironmentId } from "@formbricks/lib/team/service";
|
||||
import ContentWrapper from "@formbricks/ui/ContentWrapper";
|
||||
import SurveysList from "@formbricks/ui/SurveysList";
|
||||
@@ -42,21 +42,22 @@ export default async function SurveysPage({ params }) {
|
||||
if (!environment) {
|
||||
throw new Error("Environment not found");
|
||||
}
|
||||
const surveys = await getSurveys(params.environmentId, 1); // workaround for now; only get the first page; better approach is in development
|
||||
|
||||
const surveyCount = await getSurveyCount(params.environmentId);
|
||||
|
||||
const environments = await getEnvironments(product.id);
|
||||
const otherEnvironment = environments.find((e) => e.type !== environment.type)!;
|
||||
|
||||
return (
|
||||
<ContentWrapper className="flex h-full flex-col justify-between">
|
||||
{surveys.length > 0 ? (
|
||||
{surveyCount > 0 ? (
|
||||
<SurveysList
|
||||
environment={environment}
|
||||
surveys={surveys}
|
||||
otherEnvironment={otherEnvironment}
|
||||
isViewer={isViewer}
|
||||
WEBAPP_URL={WEBAPP_URL}
|
||||
userId={session.user.id}
|
||||
surveysPerPage={SURVEYS_PER_PAGE}
|
||||
/>
|
||||
) : (
|
||||
<SurveyStarter
|
||||
@@ -66,7 +67,7 @@ export default async function SurveysPage({ params }) {
|
||||
user={session.user}
|
||||
/>
|
||||
)}
|
||||
{/* <SurveysList environmentId={params.environmentId} /> */}
|
||||
|
||||
<WidgetStatusIndicator environmentId={params.environmentId} type="mini" />
|
||||
</ContentWrapper>
|
||||
);
|
||||
|
||||
@@ -12,15 +12,17 @@ test.describe("JS Package Test", async () => {
|
||||
await signUpAndLogin(page, name, email, password);
|
||||
await finishOnboarding(page);
|
||||
|
||||
await page.waitForURL(/\/environments\/[^/]+\/surveys/);
|
||||
// await page.waitForURL(/\/environments\/[^/]+\/surveys/);
|
||||
|
||||
await page.getByRole("link", { name: "New survey", exact: true }).click();
|
||||
await page
|
||||
.getByText("Product ExperienceProduct Market Fit (Superhuman)Measure PMF by assessing how")
|
||||
.isVisible();
|
||||
|
||||
await page
|
||||
.getByText("Product ExperienceProduct Market Fit (Superhuman)Measure PMF by assessing how")
|
||||
.click();
|
||||
await page.getByRole("button", { name: "Use this template" }).click();
|
||||
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click();
|
||||
|
||||
await expect(page.locator("#howToSendCardTrigger")).toBeVisible();
|
||||
@@ -31,7 +33,7 @@ test.describe("JS Package Test", async () => {
|
||||
await page.locator("#howToSendCardOption-web").click();
|
||||
|
||||
await expect(page.getByText("Survey Trigger")).toBeVisible();
|
||||
await page.getByText("Survey Trigger").click();
|
||||
// await page.getByText("Survey Trigger").click();
|
||||
|
||||
await page.getByRole("combobox").click();
|
||||
await page.getByLabel("New Session").click();
|
||||
@@ -44,6 +46,12 @@ test.describe("JS Package Test", async () => {
|
||||
})();
|
||||
|
||||
await page.waitForURL(/\/environments\/[^/]+\/surveys\/[^/]+\/summary/);
|
||||
|
||||
expect(page.getByRole("link", { name: "Surveys" })).toBeVisible();
|
||||
await page.getByRole("link", { name: "Surveys" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Surveys" })).toBeVisible();
|
||||
|
||||
await page.screenshot();
|
||||
});
|
||||
|
||||
test("JS Display Survey on Page", async ({ page }) => {
|
||||
@@ -105,7 +113,7 @@ test.describe("JS Package Test", async () => {
|
||||
// Formbricks Modal is not visible
|
||||
await expect(page.getByText("Powered by Formbricks")).not.toBeVisible({ timeout: 10000 });
|
||||
await page.waitForLoadState("networkidle");
|
||||
await page.waitForTimeout(1500);
|
||||
await page.waitForTimeout(3000);
|
||||
});
|
||||
|
||||
test("Admin validates Displays & Response", async ({ page }) => {
|
||||
|
||||
@@ -86,7 +86,7 @@ test.describe("Invite, accept and remove team member", async () => {
|
||||
await page.getByRole("link", { name: "Create account" }).click();
|
||||
|
||||
await signupUsingInviteToken(page, name, email, password);
|
||||
await finishOnboarding(page);
|
||||
await finishOnboarding(page, false);
|
||||
});
|
||||
|
||||
test("Remove member", async ({ page }) => {
|
||||
|
||||
@@ -54,24 +54,40 @@ export const login = async (page: Page, email: string, password: string): Promis
|
||||
await page.getByRole("button", { name: "Login with Email" }).click();
|
||||
};
|
||||
|
||||
export const finishOnboarding = async (page: Page): Promise<void> => {
|
||||
export const finishOnboarding = async (page: Page, deleteExampleSurvey: boolean = true): Promise<void> => {
|
||||
await page.waitForURL("/onboarding");
|
||||
await expect(page).toHaveURL("/onboarding");
|
||||
|
||||
const hiddenSkipButton = page.locator("#FB__INTERNAL__SKIP_ONBOARDING");
|
||||
hiddenSkipButton.evaluate((el: HTMLElement) => el.click());
|
||||
|
||||
// await page.getByRole("button", { name: "In-app Surveys Run a survey" }).click();
|
||||
|
||||
// await page.getByRole("button", { name: "Skip" }).click();
|
||||
// await page.getByRole("button", { name: "Skip" }).click();
|
||||
|
||||
// await page.getByRole("button", { name: "I am not sure how to do this" }).click();
|
||||
// await page.locator("input").click();
|
||||
// await page.locator("input").fill("test@gmail.com");
|
||||
// await page.getByRole("button", { name: "Invite" }).click();
|
||||
await page.waitForURL(/\/environments\/[^/]+\/surveys/);
|
||||
await expect(page.getByText("My Product")).toBeVisible();
|
||||
|
||||
let currentDir = process.cwd();
|
||||
let htmlFilePath = currentDir + "/packages/js/index.html";
|
||||
|
||||
const environmentId =
|
||||
/\/environments\/([^/]+)\/surveys/.exec(page.url())?.[1] ??
|
||||
(() => {
|
||||
throw new Error("Unable to parse environmentId from URL");
|
||||
})();
|
||||
|
||||
let htmlFile = replaceEnvironmentIdInHtml(htmlFilePath, environmentId);
|
||||
await page.goto(htmlFile);
|
||||
|
||||
// Formbricks In App Sync has happened
|
||||
const syncApi = await page.waitForResponse((response) => response.url().includes("/in-app/sync"));
|
||||
expect(syncApi.status()).toBe(200);
|
||||
|
||||
await page.goto("/");
|
||||
await page.waitForURL(/\/environments\/[^/]+\/surveys/);
|
||||
|
||||
if (deleteExampleSurvey) {
|
||||
await page.click("#example-survey-survey-actions");
|
||||
await page.getByRole("menuitem", { name: "Delete" }).click();
|
||||
await page.getByRole("button", { name: "Delete" }).click();
|
||||
await page.reload();
|
||||
}
|
||||
};
|
||||
|
||||
export const replaceEnvironmentIdInHtml = (filePath: string, environmentId: string): string => {
|
||||
@@ -113,9 +129,11 @@ export const createSurvey = async (
|
||||
const addQuestion = "Add QuestionAdd a new question to your survey";
|
||||
|
||||
await signUpAndLogin(page, name, email, password);
|
||||
await finishOnboarding(page);
|
||||
await finishOnboarding(page, false);
|
||||
|
||||
await page.getByRole("link", { name: "New survey", exact: true }).click();
|
||||
await page.getByRole("heading", { name: "Start from Scratch" }).click();
|
||||
await page.getByRole("button", { name: "Create survey", exact: true }).click();
|
||||
|
||||
// Welcome Card
|
||||
await expect(page.locator("#welcome-toggle")).toBeVisible();
|
||||
@@ -226,11 +244,7 @@ export const createSurvey = async (
|
||||
await page.getByLabel("Question").fill(params.fileUploadQuestion.question);
|
||||
|
||||
// Thank You Card
|
||||
await page
|
||||
.locator("div")
|
||||
.filter({ hasText: /^Thank You CardShown$/ })
|
||||
.nth(1)
|
||||
.click();
|
||||
page.getByText("Thank You CardShownShow").click();
|
||||
await page.getByLabel("Question").fill(params.thankYouCard.headline);
|
||||
await page.getByLabel("Description").fill(params.thankYouCard.description);
|
||||
};
|
||||
|
||||
@@ -75,6 +75,7 @@ export const MAIL_FROM = env.MAIL_FROM;
|
||||
|
||||
export const NEXTAUTH_SECRET = env.NEXTAUTH_SECRET;
|
||||
export const ITEMS_PER_PAGE = 50;
|
||||
export const SURVEYS_PER_PAGE = 20;
|
||||
export const RESPONSES_PER_PAGE = 10;
|
||||
export const TEXT_RESPONSES_PER_PAGE = 5;
|
||||
|
||||
|
||||
@@ -263,19 +263,29 @@ export const getSurveysByActionClassId = async (actionClassId: string, page?: nu
|
||||
return surveys.map((survey) => formatDateFields(survey, ZSurvey));
|
||||
};
|
||||
|
||||
export const getSurveys = async (environmentId: string, page?: number): Promise<TSurvey[]> => {
|
||||
export const getSurveys = async (
|
||||
environmentId: string,
|
||||
limit?: number,
|
||||
offset?: number
|
||||
): Promise<TSurvey[]> => {
|
||||
const surveys = await unstable_cache(
|
||||
async () => {
|
||||
validateInputs([environmentId, ZId], [page, ZOptionalNumber]);
|
||||
validateInputs([environmentId, ZId], [limit, ZOptionalNumber], [offset, ZOptionalNumber]);
|
||||
let surveysPrisma;
|
||||
|
||||
try {
|
||||
surveysPrisma = await prisma.survey.findMany({
|
||||
where: {
|
||||
environmentId,
|
||||
},
|
||||
select: selectSurvey,
|
||||
take: page ? ITEMS_PER_PAGE : undefined,
|
||||
skip: page ? ITEMS_PER_PAGE * (page - 1) : undefined,
|
||||
orderBy: [
|
||||
{
|
||||
updatedAt: "desc",
|
||||
},
|
||||
],
|
||||
take: limit ? limit : undefined,
|
||||
skip: offset ? offset : undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
@@ -308,7 +318,7 @@ export const getSurveys = async (environmentId: string, page?: number): Promise<
|
||||
}
|
||||
return surveys;
|
||||
},
|
||||
[`getSurveys-${environmentId}-${page}`],
|
||||
[`getSurveys-${environmentId}-${limit}-${offset}`],
|
||||
{
|
||||
tags: [surveyCache.tag.byEnvironmentId(environmentId)],
|
||||
revalidate: SERVICES_REVALIDATION_INTERVAL,
|
||||
@@ -320,6 +330,37 @@ export const getSurveys = async (environmentId: string, page?: number): Promise<
|
||||
return surveys.map((survey) => formatDateFields(survey, ZSurvey));
|
||||
};
|
||||
|
||||
export const getSurveyCount = async (environmentId: string): Promise<number> => {
|
||||
const count = await unstable_cache(
|
||||
async () => {
|
||||
validateInputs([environmentId, ZId]);
|
||||
try {
|
||||
const surveyCount = await prisma.survey.count({
|
||||
where: {
|
||||
environmentId: environmentId,
|
||||
},
|
||||
});
|
||||
|
||||
return surveyCount;
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
console.error(error);
|
||||
throw new DatabaseError(error.message);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
[`getSurveyCount-${environmentId}`],
|
||||
{
|
||||
tags: [surveyCache.tag.byEnvironmentId(environmentId)],
|
||||
revalidate: SERVICES_REVALIDATION_INTERVAL,
|
||||
}
|
||||
)();
|
||||
|
||||
return count;
|
||||
};
|
||||
|
||||
export const updateSurvey = async (updatedSurvey: TSurvey): Promise<TSurvey> => {
|
||||
validateInputs([updatedSurvey, ZSurveyWithRefinements]);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
deleteSurvey,
|
||||
duplicateSurvey,
|
||||
getSurvey,
|
||||
getSurveyCount,
|
||||
getSurveys,
|
||||
getSurveysByActionClassId,
|
||||
getSyncSurveys,
|
||||
@@ -31,6 +32,10 @@ import {
|
||||
updateSurveyInput,
|
||||
} from "./__mock__/survey.mock";
|
||||
|
||||
beforeEach(() => {
|
||||
prisma.survey.count.mockResolvedValue(1);
|
||||
});
|
||||
|
||||
describe("Tests for getSurvey", () => {
|
||||
describe("Happy Path", () => {
|
||||
it("Returns a survey", async () => {
|
||||
@@ -95,7 +100,7 @@ describe("Tests for getSurveysByActionClassId", () => {
|
||||
|
||||
describe("Tests for getSurveys", () => {
|
||||
describe("Happy Path", () => {
|
||||
it("Returns an array of surveys for a given environmentId and page", async () => {
|
||||
it("Returns an array of surveys for a given environmentId, limit(optional) and offset(optional)", async () => {
|
||||
prisma.survey.findMany.mockResolvedValueOnce([mockSurveyOutput]);
|
||||
const surveys = await getSurveys(mockId);
|
||||
expect(surveys).toEqual([mockTransformedSurveyOutput]);
|
||||
@@ -311,3 +316,29 @@ describe("Tests for getSyncedSurveys", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tests for getSurveyCount service", () => {
|
||||
describe("Happy Path", () => {
|
||||
it("Counts the total number of surveys for a given environment ID", async () => {
|
||||
const count = await getSurveyCount(mockId);
|
||||
expect(count).toEqual(1);
|
||||
});
|
||||
|
||||
it("Returns zero count when there are no surveys for a given environment ID", async () => {
|
||||
prisma.survey.count.mockResolvedValue(0);
|
||||
const count = await getSurveyCount(mockId);
|
||||
expect(count).toEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Sad Path", () => {
|
||||
testInputValidation(getSurveyCount, "123");
|
||||
|
||||
it("Throws a generic Error for other unexpected issues", async () => {
|
||||
const mockErrorMessage = "Mock error message";
|
||||
prisma.survey.count.mockRejectedValue(new Error(mockErrorMessage));
|
||||
|
||||
await expect(getSurveyCount(mockId)).rejects.toThrow(Error);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,10 +8,20 @@ import { authOptions } from "@formbricks/lib/authOptions";
|
||||
import { hasUserEnvironmentAccess } from "@formbricks/lib/environment/auth";
|
||||
import { canUserAccessSurvey, verifyUserRoleAccess } from "@formbricks/lib/survey/auth";
|
||||
import { surveyCache } from "@formbricks/lib/survey/cache";
|
||||
import { deleteSurvey, duplicateSurvey, getSurvey } from "@formbricks/lib/survey/service";
|
||||
import { deleteSurvey, duplicateSurvey, getSurvey, getSurveys } from "@formbricks/lib/survey/service";
|
||||
import { generateSurveySingleUseId } from "@formbricks/lib/utils/singleUseSurveys";
|
||||
import { AuthorizationError, ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
|
||||
export const getSurveyAction = async (surveyId: string) => {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) throw new AuthorizationError("Not authorized");
|
||||
|
||||
const isAuthorized = await canUserAccessSurvey(session.user.id, surveyId);
|
||||
if (!isAuthorized) throw new AuthorizationError("Not authorized");
|
||||
|
||||
return await getSurvey(surveyId);
|
||||
};
|
||||
|
||||
export async function duplicateSurveyAction(environmentId: string, surveyId: string) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) throw new AuthorizationError("Not authorized");
|
||||
@@ -212,3 +222,13 @@ export async function generateSingleUseIdAction(surveyId: string, isEncrypted: b
|
||||
|
||||
return generateSurveySingleUseId(isEncrypted);
|
||||
}
|
||||
|
||||
export async function getSurveysAction(environmentId: string, limit?: number, offset?: number) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) throw new AuthorizationError("Not authorized");
|
||||
|
||||
const isAuthorized = await hasUserEnvironmentAccess(session.user.id, environmentId);
|
||||
if (!isAuthorized) throw new AuthorizationError("Not authorized");
|
||||
|
||||
return await getSurveys(environmentId, limit, offset);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ interface SurveyCardProps {
|
||||
isViewer: boolean;
|
||||
WEBAPP_URL: string;
|
||||
orientation: string;
|
||||
duplicateSurvey: (survey: TSurvey) => void;
|
||||
deleteSurvey: (surveyId: string) => void;
|
||||
}
|
||||
export default function SurveyCard({
|
||||
survey,
|
||||
@@ -26,6 +28,8 @@ export default function SurveyCard({
|
||||
isViewer,
|
||||
WEBAPP_URL,
|
||||
orientation,
|
||||
deleteSurvey,
|
||||
duplicateSurvey,
|
||||
}: SurveyCardProps) {
|
||||
const isSurveyCreationDeletionDisabled = isViewer;
|
||||
|
||||
@@ -85,6 +89,8 @@ export default function SurveyCard({
|
||||
webAppUrl={WEBAPP_URL}
|
||||
singleUseId={singleUseId}
|
||||
isSurveyCreationDeletionDisabled={isSurveyCreationDeletionDisabled}
|
||||
duplicateSurvey={duplicateSurvey}
|
||||
deleteSurvey={deleteSurvey}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
@@ -145,6 +151,8 @@ export default function SurveyCard({
|
||||
webAppUrl={WEBAPP_URL}
|
||||
singleUseId={singleUseId}
|
||||
isSurveyCreationDeletionDisabled={isSurveyCreationDeletionDisabled}
|
||||
duplicateSurvey={duplicateSurvey}
|
||||
deleteSurvey={deleteSurvey}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -19,7 +19,12 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "../../DropdownMenu";
|
||||
import LoadingSpinner from "../../LoadingSpinner";
|
||||
import { copyToOtherEnvironmentAction, deleteSurveyAction, duplicateSurveyAction } from "../actions";
|
||||
import {
|
||||
copyToOtherEnvironmentAction,
|
||||
deleteSurveyAction,
|
||||
duplicateSurveyAction,
|
||||
getSurveyAction,
|
||||
} from "../actions";
|
||||
|
||||
interface SurveyDropDownMenuProps {
|
||||
environmentId: string;
|
||||
@@ -29,6 +34,8 @@ interface SurveyDropDownMenuProps {
|
||||
webAppUrl: string;
|
||||
singleUseId?: string;
|
||||
isSurveyCreationDeletionDisabled?: boolean;
|
||||
duplicateSurvey: (survey: TSurvey) => void;
|
||||
deleteSurvey: (surveyId: string) => void;
|
||||
}
|
||||
|
||||
export default function SurveyDropDownMenu({
|
||||
@@ -39,6 +46,8 @@ export default function SurveyDropDownMenu({
|
||||
webAppUrl,
|
||||
singleUseId,
|
||||
isSurveyCreationDeletionDisabled,
|
||||
deleteSurvey,
|
||||
duplicateSurvey,
|
||||
}: SurveyDropDownMenuProps) {
|
||||
const [isDeleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -51,6 +60,7 @@ export default function SurveyDropDownMenu({
|
||||
setLoading(true);
|
||||
try {
|
||||
await deleteSurveyAction(survey.id);
|
||||
deleteSurvey(survey.id);
|
||||
router.refresh();
|
||||
setDeleteDialogOpen(false);
|
||||
toast.success("Survey deleted successfully.");
|
||||
@@ -63,8 +73,10 @@ export default function SurveyDropDownMenu({
|
||||
const duplicateSurveyAndRefresh = async (surveyId: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await duplicateSurveyAction(environmentId, surveyId);
|
||||
const duplicatedSurvey = await duplicateSurveyAction(environmentId, surveyId);
|
||||
router.refresh();
|
||||
const transformedDuplicatedSurvey = await getSurveyAction(duplicatedSurvey.id);
|
||||
if (transformedDuplicatedSurvey) duplicateSurvey(transformedDuplicatedSurvey);
|
||||
toast.success("Survey duplicated successfully.");
|
||||
} catch (error) {
|
||||
toast.error("Failed to duplicate the survey.");
|
||||
@@ -95,7 +107,9 @@ export default function SurveyDropDownMenu({
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
id={`${survey.name.toLowerCase().split(" ").join("-")}-survey-actions`}
|
||||
onClick={(e) => e.stopPropagation()}>
|
||||
<DropdownMenu open={isDropDownOpen} onOpenChange={setIsDropDownOpen}>
|
||||
<DropdownMenuTrigger className="z-10 cursor-pointer" asChild>
|
||||
<div className="rounded-lg border p-2 hover:bg-slate-50">
|
||||
@@ -228,6 +242,6 @@ export default function SurveyDropDownMenu({
|
||||
text="Are you sure you want to delete this survey and all of its responses? This action cannot be undone."
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,33 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { TEnvironment } from "@formbricks/types/environment";
|
||||
import { TSurvey } from "@formbricks/types/surveys";
|
||||
|
||||
import { Button } from "../v2/Button";
|
||||
import { getSurveysAction } from "./actions";
|
||||
import SurveyCard from "./components/SurveyCard";
|
||||
import SurveyFilters from "./components/SurveyFilters";
|
||||
|
||||
interface SurveysListProps {
|
||||
environment: TEnvironment;
|
||||
surveys: TSurvey[];
|
||||
otherEnvironment: TEnvironment;
|
||||
isViewer: boolean;
|
||||
WEBAPP_URL: string;
|
||||
userId: string;
|
||||
surveysPerPage: number;
|
||||
}
|
||||
|
||||
export default function SurveysList({
|
||||
environment,
|
||||
surveys,
|
||||
otherEnvironment,
|
||||
isViewer,
|
||||
WEBAPP_URL,
|
||||
userId,
|
||||
surveysPerPage: surveysLimit,
|
||||
}: SurveysListProps) {
|
||||
const [surveys, setSurveys] = useState<TSurvey[]>([]);
|
||||
const [isFetching, setIsFetching] = useState(true);
|
||||
const [hasMore, setHasMore] = useState<boolean>(true);
|
||||
|
||||
const [filteredSurveys, setFilteredSurveys] = useState<TSurvey[]>(surveys);
|
||||
|
||||
// Initialize orientation state with a function that checks if window is defined
|
||||
const [orientation, setOrientation] = useState(() =>
|
||||
typeof localStorage !== "undefined" ? localStorage.getItem("surveyOrientation") || "grid" : "grid"
|
||||
@@ -38,6 +44,37 @@ export default function SurveysList({
|
||||
localStorage.setItem("surveyOrientation", orientation);
|
||||
}, [orientation]);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchInitialSurveys() {
|
||||
setIsFetching(true);
|
||||
const res = await getSurveysAction(environment.id, surveysLimit);
|
||||
if (res.length < surveysLimit) setHasMore(false);
|
||||
setSurveys(res);
|
||||
setIsFetching(false);
|
||||
}
|
||||
fetchInitialSurveys();
|
||||
}, [environment.id, surveysLimit]);
|
||||
|
||||
const fetchNextPage = useCallback(async () => {
|
||||
setIsFetching(true);
|
||||
const newSurveys = await getSurveysAction(environment.id, surveysLimit, surveys.length);
|
||||
if (newSurveys.length === 0 || newSurveys.length < surveysLimit) {
|
||||
setHasMore(false);
|
||||
}
|
||||
setSurveys([...surveys, ...newSurveys]);
|
||||
setIsFetching(false);
|
||||
}, [environment.id, surveys, surveysLimit]);
|
||||
|
||||
const handleDeleteSurvey = async (surveyId: string) => {
|
||||
const newSurveys = surveys.filter((survey) => survey.id !== surveyId);
|
||||
setSurveys(newSurveys);
|
||||
};
|
||||
|
||||
const handleDuplicateSurvey = async (survey: TSurvey) => {
|
||||
const newSurveys = [survey, ...surveys];
|
||||
setSurveys(newSurveys);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between">
|
||||
@@ -77,6 +114,8 @@ export default function SurveysList({
|
||||
isViewer={isViewer}
|
||||
WEBAPP_URL={WEBAPP_URL}
|
||||
orientation={orientation}
|
||||
duplicateSurvey={handleDuplicateSurvey}
|
||||
deleteSurvey={handleDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -94,17 +133,27 @@ export default function SurveysList({
|
||||
isViewer={isViewer}
|
||||
WEBAPP_URL={WEBAPP_URL}
|
||||
orientation={orientation}
|
||||
duplicateSurvey={handleDuplicateSurvey}
|
||||
deleteSurvey={handleDeleteSurvey}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasMore && (
|
||||
<div className="flex justify-center py-5">
|
||||
<Button onClick={fetchNextPage} variant="secondary" size="sm" loading={isFetching}>
|
||||
Load more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-full flex-col items-center justify-center">
|
||||
<span className="mb-4 h-24 w-24 rounded-full bg-slate-100 p-6 text-5xl">🕵️</span>
|
||||
|
||||
<div className="text-slate-600">No surveys found</div>
|
||||
<div className="text-slate-600">{isFetching ? "Fetching Surveys" : "No surveys found"}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user