Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Show the getting-started checklist only to users who need it (#8313)

EthanHealy01850f2459297d
diff --git a/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.module.css b/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.module.css
index 8b08ec5d31..abf39b2be9 100644
--- a/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.module.css
+++ b/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.module.css
@@ -75,10 +75,6 @@
color: var(--mantine-color-text);
}
-.completeIcon {
- color: var(--c-accent-text);
-}
-
.progressTrack {
margin-top: 0.5rem;
height: 4px;
diff --git a/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.tsx b/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.tsx
index 2074728c57..f4b82e6c0a 100644
--- a/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.tsx
+++ b/frontend/editor/src/cloud/components/onboarding/OnboardingChecklist.tsx
@@ -7,10 +7,11 @@ import {
useChecklistSetupItem,
type ChecklistItem,
} from "@app/components/onboarding/checklistSetupItem";
+import { useAccountCreatedAt } from "@app/components/onboarding/accountCreatedAt";
import {
+ getFlowDismissedAt,
getFlowProgress,
- hasSeenFlow,
- markFlowSeen,
+ markFlowDismissed,
setStepDone,
} from "@app/components/onboarding/orchestrator/onboardingStorage";
import { openAppSettings } from "@app/utils/appSettings";
@@ -22,15 +23,29 @@ const FLOW_ID = "saas-checklist";
const STEP_INVITE_TEAM = "invite-team";
const STEP_TAKE_TOUR = "take-tour";
-/** Getting-started checklist above the sidebar footer. Ticks and the X dismissal
- * persist per browser in the shared onboarding store. */
+const DAY_MS = 24 * 60 * 60 * 1000;
+const DISMISS_SNOOZE_MS = 7 * DAY_MS;
+const NEW_ACCOUNT_MAX_AGE_MS = 14 * DAY_MS;
+
+function isSnoozed(): boolean {
+ const dismissedAt = getFlowDismissedAt(FLOW_ID);
+ return dismissedAt !== null && Date.now() - dismissedAt < DISMISS_SNOOZE_MS;
+}
+
+/** Getting-started checklist above the sidebar footer, for accounts under two weeks
+ * old. Ticks persist per browser in the shared onboarding store; the X snoozes it for
+ * a week, and it is gone for good once every applicable step is done. Steps finished
+ * before this mount are left out, so a returning user sees only what is left. */
export function OnboardingChecklist() {
const { t } = useTranslation();
const { isAnonymous, loading } = useAuth();
- const inviteTarget = useChecklistInviteTarget();
+ const account = useAccountCreatedAt();
+ const invite = useChecklistInviteTarget();
+ const inviteTarget = invite.target;
- const [dismissed, setDismissed] = useState(() => hasSeenFlow(FLOW_ID));
+ const [dismissed, setDismissed] = useState(isSnoozed);
const [done, setDone] = useState<string[]>(() => getFlowProgress(FLOW_ID));
+ const [doneBeforeMount] = useState(done);
const [expanded, setExpanded] = useState(true);
const markDone = useCallback((stepId: string) => {
@@ -78,15 +93,31 @@ export function OnboardingChecklist() {
const doneCount = items.filter((item) => done.includes(item.id)).length;
const total = items.length;
- const allDone = total > 0 && doneCount === total;
+ const allDone = doneCount === total;
+ const visibleItems = items.filter(
+ (item) => !doneBeforeMount.includes(item.id),
+ );
const handleDismiss = useCallback(() => {
- markFlowSeen(FLOW_ID);
+ markFlowDismissed(FLOW_ID);
setDismissed(true);
}, []);
- if (loading || isAnonymous || dismissed) {
- return null;
+ const isEstablishedAccount =
+ account.createdAt !== null &&
+ Date.now() - account.createdAt.getTime() > NEW_ACCOUNT_MAX_AGE_MS;
+
+ if (
+ loading ||
+ account.loading ||
+ invite.loading ||
+ isAnonymous ||
+ isEstablishedAccount ||
+ dismissed ||
+ allDone
+ ) {
+ // The download slide marks its step done on close, so it must outlive the card.
+ return <>{setup.dialog}</>;
}
return (
@@ -149,15 +180,7 @@ export function OnboardingChecklist() {
}
}}
>
- {allDone ? (
- <Icon
- name="circle-check"
- size="1.05rem"
- className={styles.completeIcon}
- />
- ) : (
- <Icon name="x" size="0.95rem" />
- )}
+ <Icon name="x" size="0.95rem" />
</span>
</span>
</div>
@@ -171,7 +194,7 @@ export function OnboardingChecklist() {
{expanded && (
<div className={styles.items}>
- {items.map((item) => {
+ {visibleItems.map((item) => {
const isDone = done.includes(item.id);
return (
<div
diff --git a/frontend/editor/src/cloud/components/onboarding/accountCreatedAt.ts b/frontend/editor/src/cloud/components/onboarding/accountCreatedAt.ts
new file mode 100644
index 0000000000..8c8efbdb5d
--- /dev/null
+++ b/frontend/editor/src/cloud/components/onboarding/accountCreatedAt.ts
@@ -0,0 +1,11 @@
+export interface AccountCreatedAt {
+ /** True while the lookup is in flight; the checklist stays hidden until it settles. */
+ loading: boolean;
+ /** Null when the platform cannot tell, which never hides the checklist. */
+ createdAt: Date | null;
+}
+
+/** When the signed-in user's account was created. */
+export function useAccountCreatedAt(): AccountCreatedAt {
+ return { loading: false, createdAt: null };
+}
diff --git a/frontend/editor/src/cloud/components/onboarding/checklistInviteTarget.ts b/frontend/editor/src/cloud/components/onboarding/checklistInviteTarget.ts
index 9b307e08c3..e7ff7b7798 100644
--- a/frontend/editor/src/cloud/components/onboarding/checklistInviteTarget.ts
+++ b/frontend/editor/src/cloud/components/onboarding/checklistInviteTarget.ts
@@ -1,11 +1,29 @@
+import { useState } from "react";
import { useAuth } from "@app/auth/UseSession";
import type { NavKey } from "@app/components/shared/config/types";
import { useSaaSTeam } from "@app/contexts/SaaSTeamContext";
-/** The settings section where this user can invite people, or null if they can't.
- * Guests never can: they lead the personal team created for them, but have no account. */
-export function useChecklistInviteTarget(): NavKey | null {
+export interface ChecklistInviteTarget {
+ /** True until the data behind `target` first settles; the checklist stays hidden
+ * meanwhile, since the row's absence would otherwise read as a finished checklist. */
+ loading: boolean;
+ /** The settings section where this user can invite people, or null if they can't
+ * or already have. */
+ target: NavKey | null;
+}
+
+/** Guests never can invite: they lead the personal team created for them, but have
+ * no account. A team with other members has already learned to invite. */
+export function useChecklistInviteTarget(): ChecklistInviteTarget {
const { isAnonymous } = useAuth();
- const { isTeamLeader } = useSaaSTeam();
- return isTeamLeader && !isAnonymous ? "users" : null;
+ const { isTeamLeader, currentTeam, loading } = useSaaSTeam();
+ // Latched: the team refetches after membership changes, and that must not hide the card.
+ const [settled, setSettled] = useState(!loading);
+ if (!loading && !settled) setSettled(true);
+
+ const hasOtherMembers = (currentTeam?.memberCount ?? 0) > 1;
+ return {
+ loading: !settled,
+ target: isTeamLeader && !isAnonymous && !hasOtherMembers ? "users" : null,
+ };
}
diff --git a/frontend/editor/src/core/components/onboarding/orchestrator/onboardingStorage.ts b/frontend/editor/src/core/components/onboarding/orchestrator/onboardingStorage.ts
index 084761849d..2fee8a91ed 100644
--- a/frontend/editor/src/core/components/onboarding/orchestrator/onboardingStorage.ts
+++ b/frontend/editor/src/core/components/onboarding/orchestrator/onboardingStorage.ts
@@ -9,6 +9,8 @@ const flowSeenKey = (flowId: string) =>
`${STORAGE_PREFIX}::flow::${flowId}::seen`;
const flowProgressKey = (flowId: string) =>
`${STORAGE_PREFIX}::flow::${flowId}::progress`;
+const flowDismissedAtKey = (flowId: string) =>
+ `${STORAGE_PREFIX}::flow::${flowId}::dismissedAt`;
function readJson<T>(key: string, fallback: T): T {
if (typeof window === "undefined") return fallback;
@@ -49,6 +51,17 @@ export function markFlowSeen(flowId: string): void {
}
}
+/** When a snoozable flow was last dismissed, in epoch milliseconds, or null if never. */
+export function getFlowDismissedAt(flowId: string): number | null {
+ const value = readJson<unknown>(flowDismissedAtKey(flowId), null);
+ return typeof value === "number" ? value : null;
+}
+
+/** Records that a snoozable flow was dismissed now. */
+export function markFlowDismissed(flowId: string): void {
+ writeJson(flowDismissedAtKey(flowId), Date.now());
+}
+
/** Completed step ids for a checklist-style flow, in completion order. */
export function getFlowProgress(flowId: string): string[] {
const value = readJson<string[]>(flowProgressKey(flowId), []);
@@ -67,12 +80,13 @@ export function setStepDone(flowId: string, stepId: string): void {
writeJson(flowProgressKey(flowId), [...progress, stepId]);
}
-/** Clears both the seen flag and step progress for a flow. */
+/** Clears every stored flag, timestamp and step for a flow. */
export function resetFlow(flowId: string): void {
if (typeof window === "undefined") return;
try {
localStorage.removeItem(flowSeenKey(flowId));
localStorage.removeItem(flowProgressKey(flowId));
+ localStorage.removeItem(flowDismissedAtKey(flowId));
} catch (error) {
console.error(
`[onboardingStorage] Error resetting flow "${flowId}":`,
diff --git a/frontend/editor/src/desktop/components/onboarding/accountCreatedAt.ts b/frontend/editor/src/desktop/components/onboarding/accountCreatedAt.ts
new file mode 100644
index 0000000000..cb95321c59
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/accountCreatedAt.ts
@@ -0,0 +1,48 @@
+import { useEffect, useState } from "react";
+import { useAuth } from "@app/auth/UseSession";
+import { getAccessToken } from "@app/auth/session";
+import { supabase } from "@app/auth/supabase";
+import { useSaaSMode } from "@app/hooks/useSaaSMode";
+import type { AccountCreatedAt } from "@cloud/components/onboarding/accountCreatedAt";
+
+export type { AccountCreatedAt } from "@cloud/components/onboarding/accountCreatedAt";
+
+/** The desktop session is a bare JWT, so the creation date comes from Supabase.
+ * Self-hosted accounts carry no creation date and resolve to null. */
+export function useAccountCreatedAt(): AccountCreatedAt {
+ const isSaaSMode = useSaaSMode();
+ const { user, loading: authLoading } = useAuth();
+ const userId = user?.id ?? null;
+ const [state, setState] = useState<AccountCreatedAt>({
+ loading: true,
+ createdAt: null,
+ });
+
+ useEffect(() => {
+ if (authLoading) return;
+ if (!isSaaSMode || !userId) {
+ setState({ loading: false, createdAt: null });
+ return;
+ }
+ let cancelled = false;
+ setState({ loading: true, createdAt: null });
+ void (async () => {
+ const token = await getAccessToken();
+ const { data } = token
+ ? await supabase.auth.getUser(token)
+ : { data: { user: null } };
+ if (cancelled) return;
+ const createdAt = data.user?.created_at
+ ? new Date(data.user.created_at)
+ : null;
+ setState({ loading: false, createdAt });
+ })().catch(() => {
+ if (!cancelled) setState({ loading: false, createdAt: null });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [authLoading, isSaaSMode, userId]);
+
+ return state;
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/checklistInviteTarget.test.ts b/frontend/editor/src/desktop/components/onboarding/checklistInviteTarget.test.ts
new file mode 100644
index 0000000000..e99210ef64
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/checklistInviteTarget.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useChecklistInviteTarget } from "@app/components/onboarding/checklistInviteTarget";
+
+interface UserCount {
+ totalUsers: number | null;
+ userCountSource: "admin" | "estimate" | "unknown";
+ userCountError: string | null;
+}
+
+const { userCount } = vi.hoisted(() => ({
+ userCount: vi.fn<() => UserCount>(),
+}));
+
+vi.mock("@cloud/components/onboarding/checklistInviteTarget", () => ({
+ useChecklistInviteTarget: () => ({ loading: false, target: null }),
+}));
+vi.mock("@app/hooks/useSelfHostedAuth", () => ({
+ useSelfHostedAuth: () => ({ isSelfHosted: true, isAuthenticated: true }),
+}));
+vi.mock("@app/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { enableLogin: true, isAdmin: true } }),
+}));
+vi.mock("@app/hooks/useServerExperience", () => ({
+ useServerExperience: userCount,
+}));
+
+const target = () =>
+ renderHook(() => useChecklistInviteTarget()).result.current;
+
+describe("useChecklistInviteTarget (self-hosted)", () => {
+ beforeEach(() => {
+ userCount.mockReturnValue({
+ totalUsers: 1,
+ userCountSource: "admin",
+ userCountError: null,
+ });
+ });
+
+ it("points the server's only admin at People", () => {
+ expect(target()).toEqual({ loading: false, target: "people" });
+ });
+
+ it("is loading before the user count arrives", () => {
+ userCount.mockReturnValue({
+ totalUsers: null,
+ userCountSource: "unknown",
+ userCountError: null,
+ });
+ expect(target().loading).toBe(true);
+ });
+
+ it("drops the target once the server has other users", () => {
+ userCount.mockReturnValue({
+ totalUsers: 4,
+ userCountSource: "admin",
+ userCountError: null,
+ });
+ expect(target()).toEqual({ loading: false, target: null });
+ });
+
+ it("settles on a failed count and keeps the row", () => {
+ userCount.mockReturnValue({
+ totalUsers: null,
+ userCountSource: "unknown",
+ userCountError: "network",
+ });
+ expect(target()).toEqual({ loading: false, target: "people" });
+ });
+});
diff --git a/frontend/editor/src/desktop/components/onboarding/checklistInviteTarget.ts b/frontend/editor/src/desktop/components/onboarding/checklistInviteTarget.ts
index 224bc195df..ce092cb113 100644
--- a/frontend/editor/src/desktop/components/onboarding/checklistInviteTarget.ts
+++ b/frontend/editor/src/desktop/components/onboarding/checklistInviteTarget.ts
@@ -1,21 +1,33 @@
-import type { NavKey } from "@app/components/shared/config/types";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useSelfHostedAuth } from "@app/hooks/useSelfHostedAuth";
-import { useChecklistInviteTarget as useCloudInviteTarget } from "@cloud/components/onboarding/checklistInviteTarget";
+import { useServerExperience } from "@app/hooks/useServerExperience";
+import {
+ useChecklistInviteTarget as useCloudInviteTarget,
+ type ChecklistInviteTarget,
+} from "@cloud/components/onboarding/checklistInviteTarget";
-/** Cloud team leaders invite from Users; self-hosted admins from People, once login is on.
- * Guests are excluded by the Cloud check and are never self-hosted admins. */
-export function useChecklistInviteTarget(): NavKey | null {
+export type { ChecklistInviteTarget } from "@cloud/components/onboarding/checklistInviteTarget";
+
+/** Cloud team leaders invite from Users; self-hosted admins from People, once login
+ * is on and they are still the server's only user. Guests are excluded by the Cloud
+ * check and are never self-hosted admins. */
+export function useChecklistInviteTarget(): ChecklistInviteTarget {
const cloudTarget = useCloudInviteTarget();
const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
const { config } = useAppConfig();
- if (
- isSelfHosted &&
- isAuthenticated &&
- config?.enableLogin &&
- config.isAdmin
- ) {
- return "people";
+ const { totalUsers, userCountSource, userCountError } = useServerExperience();
+ if (isSelfHosted) {
+ const isAdmin = Boolean(
+ isAuthenticated && config?.enableLogin && config.isAdmin,
+ );
+ // A successful fetch sets the source, a failed one the error; a refresh keeps both.
+ const countPending = userCountSource === "unknown" && !userCountError;
+ // Only the admin count is exact; the WAU fallback estimates browsers, not accounts.
+ const hasOtherUsers = userCountSource === "admin" && (totalUsers ?? 0) > 1;
+ return {
+ loading: isAdmin && countPending,
+ target: isAdmin && !hasOtherUsers ? "people" : null,
+ };
}
return cloudTarget;
}
diff --git a/frontend/editor/src/saas/components/onboarding/OnboardingChecklist.test.tsx b/frontend/editor/src/saas/components/onboarding/OnboardingChecklist.test.tsx
new file mode 100644
index 0000000000..31577d8104
--- /dev/null
+++ b/frontend/editor/src/saas/components/onboarding/OnboardingChecklist.test.tsx
@@ -0,0 +1,146 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { OnboardingChecklist } from "@app/components/onboarding/OnboardingChecklist";
+import type { AccountCreatedAt } from "@app/components/onboarding/accountCreatedAt";
+import type { ChecklistInviteTarget } from "@app/components/onboarding/checklistInviteTarget";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const FLOW = "onboarding::flow::saas-checklist";
+const DOWNLOAD = "onboarding.checklist.downloadDesktop.title";
+const INVITE = "onboarding.checklist.inviteTeam.title";
+const TOUR = "onboarding.checklist.takeTour.title";
+
+const { account, inviteTarget } = vi.hoisted(() => ({
+ account: vi.fn<() => AccountCreatedAt>(),
+ inviteTarget: vi.fn<() => ChecklistInviteTarget>(),
+}));
+
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({ isAnonymous: false, loading: false }),
+}));
+vi.mock("@app/components/onboarding/accountCreatedAt", () => ({
+ useAccountCreatedAt: account,
+}));
+vi.mock("@app/components/onboarding/checklistInviteTarget", () => ({
+ useChecklistInviteTarget: inviteTarget,
+}));
+vi.mock("@app/components/onboarding/checklistSetupItem", () => ({
+ useChecklistSetupItem: () => ({
+ item: {
+ id: "download-desktop",
+ titleKey: "onboarding.checklist.downloadDesktop.title",
+ titleFallback: "Download Stirling for Desktop",
+ descriptionKey: "onboarding.checklist.downloadDesktop.description",
+ descriptionFallback: "Run Stirling natively on your machine",
+ onClick: () => {},
+ },
+ dialog: null,
+ }),
+}));
+vi.mock("@app/utils/appSettings", () => ({ openAppSettings: vi.fn() }));
+vi.mock("@app/constants/events", () => ({ requestStartTour: vi.fn() }));
+
+const checklist = () => screen.queryByTestId("onboarding-checklist");
+
+describe("OnboardingChecklist", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ account.mockReturnValue({
+ loading: false,
+ createdAt: new Date(Date.now() - DAY_MS),
+ });
+ inviteTarget.mockReturnValue({ loading: false, target: "users" });
+ });
+
+ it("shows every step to a new account", () => {
+ render(<OnboardingChecklist />);
+ expect(checklist()).not.toBeNull();
+ expect(screen.getByText(DOWNLOAD)).toBeTruthy();
+ expect(screen.getByText(INVITE)).toBeTruthy();
+ expect(screen.getByText(TOUR)).toBeTruthy();
+ expect(screen.getByText("0 / 3")).toBeTruthy();
+ });
+
+ it("stays hidden for accounts older than two weeks", () => {
+ account.mockReturnValue({
+ loading: false,
+ createdAt: new Date(Date.now() - 15 * DAY_MS),
+ });
+ render(<OnboardingChecklist />);
+ expect(checklist()).toBeNull();
+ });
+
+ it("stays hidden while the account age is resolving", () => {
+ account.mockReturnValue({ loading: true, createdAt: null });
+ render(<OnboardingChecklist />);
+ expect(checklist()).toBeNull();
+ });
+
+ it("shows when the account age is unknown", () => {
+ account.mockReturnValue({ loading: false, createdAt: null });
+ render(<OnboardingChecklist />);
+ expect(checklist()).not.toBeNull();
+ });
+
+ it("stays hidden while the invite step is resolving", () => {
+ inviteTarget.mockReturnValue({ loading: true, target: null });
+ render(<OnboardingChecklist />);
+ expect(checklist()).toBeNull();
+ });
+
+ it("drops the invite step when there is no one to invite", () => {
+ inviteTarget.mockReturnValue({ loading: false, target: null });
+ render(<OnboardingChecklist />);
+ expect(screen.queryByText(INVITE)).toBeNull();
+ expect(screen.getByText("0 / 2")).toBeTruthy();
+ });
+
+ it("lists only the steps left from earlier sessions", () => {
+ localStorage.setItem(
+ `${FLOW}::progress`,
+ JSON.stringify(["download-desktop", "invite-team"]),
+ );
+ render(<OnboardingChecklist />);
+ expect(screen.queryByText(DOWNLOAD)).toBeNull();
+ expect(screen.queryByText(INVITE)).toBeNull();
+ expect(screen.getByText(TOUR)).toBeTruthy();
+ expect(screen.getByText("2 / 3")).toBeTruthy();
+ });
+
+ it("disappears once every step is done", () => {
+ localStorage.setItem(
+ `${FLOW}::progress`,
+ JSON.stringify(["download-desktop", "invite-team"]),
+ );
+ render(<OnboardingChecklist />);
+ fireEvent.click(screen.getByText(TOUR));
+ expect(checklist()).toBeNull();
+ });
+
+ it("snoozes for a week when closed", () => {
+ const { unmount } = render(<OnboardingChecklist />);
+ fireEvent.click(
+ screen.getByRole("button", { name: "onboarding.checklist.dismiss" }),
+ );
+ expect(checklist()).toBeNull();
+ unmount();
+
+ render(<OnboardingChecklist />);
+ expect(checklist()).toBeNull();
+ });
+
+ it("returns a week after it was closed", () => {
+ localStorage.setItem(
+ `${FLOW}::dismissedAt`,
+ JSON.stringify(Date.now() - 8 * DAY_MS),
+ );
+ render(<OnboardingChecklist />);
+ expect(checklist()).not.toBeNull();
+ });
+
+ it("ignores the permanent dismissal flag from before snoozing", () => {
+ localStorage.setItem(`${FLOW}::seen`, "true");
+ render(<OnboardingChecklist />);
+ expect(checklist()).not.toBeNull();
+ });
+});
diff --git a/frontend/editor/src/saas/components/onboarding/accountCreatedAt.ts b/frontend/editor/src/saas/components/onboarding/accountCreatedAt.ts
new file mode 100644
index 0000000000..53e792c5bf
--- /dev/null
+++ b/frontend/editor/src/saas/components/onboarding/accountCreatedAt.ts
@@ -0,0 +1,10 @@
+import { useAuth } from "@app/auth/UseSession";
+import type { AccountCreatedAt } from "@cloud/components/onboarding/accountCreatedAt";
+
+export type { AccountCreatedAt } from "@cloud/components/onboarding/accountCreatedAt";
+
+export function useAccountCreatedAt(): AccountCreatedAt {
+ const { user, loading } = useAuth();
+ const createdAt = user?.created_at ? new Date(user.created_at) : null;
+ return { loading, createdAt };
+}
diff --git a/frontend/editor/src/saas/components/onboarding/checklistInviteTarget.test.ts b/frontend/editor/src/saas/components/onboarding/checklistInviteTarget.test.ts
new file mode 100644
index 0000000000..ea438166f2
--- /dev/null
+++ b/frontend/editor/src/saas/components/onboarding/checklistInviteTarget.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useChecklistInviteTarget } from "@app/components/onboarding/checklistInviteTarget";
+
+const { team } = vi.hoisted(() => ({
+ team: vi.fn<
+ () => {
+ isTeamLeader: boolean;
+ loading: boolean;
+ currentTeam: { memberCount: number } | null;
+ }
+ >(),
+}));
+
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({ isAnonymous: false }),
+}));
+vi.mock("@app/contexts/SaaSTeamContext", () => ({ useSaaSTeam: team }));
+
+describe("useChecklistInviteTarget", () => {
+ beforeEach(() => {
+ team.mockReturnValue({
+ isTeamLeader: true,
+ loading: false,
+ currentTeam: { memberCount: 1 },
+ });
+ });
+
+ it("points a solo team leader at Users", () => {
+ const { result } = renderHook(() => useChecklistInviteTarget());
+ expect(result.current).toEqual({ loading: false, target: "users" });
+ });
+
+ it("drops the target once the team has other members", () => {
+ team.mockReturnValue({
+ isTeamLeader: true,
+ loading: false,
+ currentTeam: { memberCount: 3 },
+ });
+ const { result } = renderHook(() => useChecklistInviteTarget());
+ expect(result.current.target).toBeNull();
+ });
+
+ it("is loading until the team first loads, and not on a refetch", () => {
+ team.mockReturnValue({
+ isTeamLeader: false,
+ loading: true,
+ currentTeam: null,
+ });
+ const { result, rerender } = renderHook(() => useChecklistInviteTarget());
+ expect(result.current.loading).toBe(true);
+
+ team.mockReturnValue({
+ isTeamLeader: true,
+ loading: false,
+ currentTeam: { memberCount: 1 },
+ });
+ rerender();
+ expect(result.current).toEqual({ loading: false, target: "users" });
+
+ team.mockReturnValue({
+ isTeamLeader: true,
+ loading: true,
+ currentTeam: { memberCount: 1 },
+ });
+ rerender();
+ expect(result.current.loading).toBe(false);
+ });
+});