Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions components/workspaces/rail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { SCREENINGS_PATH } from "@/lib/screening/links";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useAuth, useClerk, useUser } from "@clerk/nextjs";
import { useQuery } from "convex/react";
import { useRememberWorkspace } from "@/lib/workspaces/remember";
import { showStyledToast } from "@/components/ui/sonner";
import { useTheme } from "next-themes";
import { useFormatter, useTranslations } from "next-intl";
Expand Down Expand Up @@ -141,6 +142,9 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi
const own = slug === null ? undefined : workspaces.list?.find((workspace) => workspace.kind === "personal");
const sharedWithYou = useProtectedQuery(api.sharing.shared.counts, own ? { workspaceId: own.workspaceId } : "skip").data?.total;
const router = useRouter();
// A switch is kept on the account as it is made, so another browser opens there too (convex/workspaces/lastUsed.ts):
// a switch changes the page without loading it, which the proxy would only hear of on the next page load.
const rememberWorkspace = useRememberWorkspace();
const [picked, setPicked] = useState<WorkspaceRow | null>(null);
const [switching, startSwitch] = useTransition();
const loading = picked !== null && slug === (picked.slug ?? null) && loaded?.workspaceId !== picked.workspaceId;
Expand Down Expand Up @@ -356,6 +360,7 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi
onSwitch={(slug, to) => {
close();
if (to) setPicked(to);
rememberWorkspace(slug ?? null);
startSwitch(() => router.push(switchTarget(slug, window.location.pathname, window.location.search.slice(1))));
}}
onCreate={() => {
Expand Down
4 changes: 4 additions & 0 deletions components/workspaces/switcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { RoleLabel } from "@/components/ui/identity";
import { Input } from "@/components/ui/input";
import { TooltipHint } from "@/components/ui/tooltip";
import { useAction } from "convex/react";
import { useRememberWorkspace } from "@/lib/workspaces/remember";
import { api } from "@/convex/_generated/api";
import type { Id } from "@/convex/_generated/dataModel";
import { useProtectedQuery } from "@/lib/auth/use-auth-query";
Expand Down Expand Up @@ -263,6 +264,8 @@ function NewOrganization({ close }: { close: () => void }) {
const tc = useTranslations("common");
const router = useRouter();
const create = useWorkspaceAction(api.organizations.manage.create);
// The new organization is where the person now works: kept on the account, as a switch is (rail.tsx).
const rememberWorkspace = useRememberWorkspace();
// The invitations go out from the organization just made, not the workspace the page is in.
const inviteThere = useAction(api.organizations.manage.invite);
const { name: freePlan } = usePlanOf({ kind: "organization", name: "" });
Expand Down Expand Up @@ -309,6 +312,7 @@ function NewOrganization({ close }: { close: () => void }) {
// It's made: trying again would make another. Invitations that fail are sent again from its Members settings.
if (invited.length) await inviteThere({ workspaceId: made.workspaceId, emails: invited, role: "member" }).catch((error) => showStyledToast("error", getErrorMessage(error, t("couldntInvite"))));
close();
rememberWorkspace(made.slug);
router.push(workspaceHref(made.slug, "/library"));
};
return (
Expand Down
17 changes: 16 additions & 1 deletion lib/workspaces/look-cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// The rail's cookie (#651): it's the person's to change, sent with every request, and shared by
// whoever signs in on the browser.
import { describe, expect, it } from "vitest";
import { lookCookieIn, lookKey, readCache, savedValue, unsaved, usedLast, writeCache, type CachedLook } from "./look-cache";
import { lookCookieIn, lookKey, readCache, savedValue, toldValue, unsaved, usedLast, writeCache, type CachedLook } from "./look-cache";

const lab = (n: number): CachedLook => ({ kind: "organization", workspaceId: `w${n}`, name: `Lab ${n}`, colour: "#16a34a", extract: true });
const own: CachedLook = { kind: "personal", workspaceId: "w0", name: "Ada" };
Expand Down Expand Up @@ -78,3 +78,18 @@ describe("telling the account where the person last worked", () => {
expect(unsaved(readCache(raw, user))).toBeUndefined();
});
});

describe("a switch told to the account as it is made", () => {
it("is noted, so moving back without the switcher is told again", () => {
const user = "user_ada";
let raw = writeCache(usedLast(readCache(undefined, user), "lab"), user, "lab", undefined, undefined)!;
raw = savedValue(readCache(raw, user), user)!;
// The switcher tells the account of the board and notes it; the page then remembers the board.
raw = toldValue(readCache(raw, user), user, "board")!;
raw = writeCache(usedLast(readCache(raw, user), "board"), user, "board", undefined, undefined)!;
expect(unsaved(readCache(raw, user))).toBeUndefined();
// Back in the lab by another way (an item moved there): the proxy tells the account again.
raw = writeCache(usedLast(readCache(raw, user), "lab"), user, "lab", undefined, undefined)!;
expect(unsaved(readCache(raw, user))).toBe("lab");
});
});
2 changes: 2 additions & 0 deletions lib/workspaces/look-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ export const unsaved = (cache: LookCache): string | null | undefined => ((cache.

/** The cookie's value once the account has been told what `cache` remembers (`unsaved`). */
export const savedValue = (cache: LookCache, user: string) => writeCache({ ...cache, saved: cache.last ?? OWN }, user, OWN, undefined, undefined);
/** The cookie's value once the account has been told `slug` (null for the person's own workspace) by a switch, whatever the cookie remembers. */
export const toldValue = (cache: LookCache, user: string, slug: string | null) => writeCache({ ...cache, saved: slug ?? OWN }, user, OWN, undefined, undefined);

/** `cache` with the workspace under `key` as the one used last. */
export function usedLast(cache: LookCache, key: string): LookCache {
Expand Down
23 changes: 23 additions & 0 deletions lib/workspaces/remember.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"use client";

// A workspace switch, told to the person's account as it is made (convex/workspaces/lastUsed.ts), so another browser
// opens there too. The cookie then notes what the account was told (`saved`), which the proxy reads to tell it again
// only when the browser moves on without a switch (proxy.ts `keepOnAccount`).
import { useAuth } from "@clerk/nextjs";
import { useMutation } from "convex/react";
import { api } from "@/convex/_generated/api";
import { lookCookieIn, lookCookieOut, readCache, toldValue } from "./look-cache";

/** Tells the account the person now works in `slug`'s organization, or their own workspace for null. A failure is the proxy's to make up for on a later page load. */
export function useRememberWorkspace() {
const { userId } = useAuth();
const remember = useMutation(api.workspaces.lastUsed.remember);
return (slug: string | null) =>
void remember({ slug })
.then(() => {
if (!userId) return;
const next = toldValue(readCache(lookCookieIn(document.cookie), userId), userId, slug);
if (next) document.cookie = lookCookieOut(next);
})
.catch(() => undefined);
}
8 changes: 5 additions & 3 deletions proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,11 @@ async function lastWorkspaceStart(auth: ClerkMiddlewareAuth, request: NextReques
}

/**
* Tells the person's account which workspace their browser remembers them last working in, when the account hasn't
* Tells the person's account which organization their browser remembers them last working in, when the account hasn't
* been told yet: a new browser then opens there (`lastWorkspaceStart`). Only on a page load, and only when the cookie's
* `last` differs from what it says it told (`saved`), so a person who stays in one workspace sends nothing more. The
* `last` differs from what it says it told (`saved`), so a person who stays in one workspace sends nothing more. Their
* own workspace is never told from here: a new browser shows it on its first page before it has asked, and would wipe
* the organization the account remembers. Moving back to it is told by the workspace switch itself (rail.tsx). The
* cookie's new value, with `saved`, is returned for the response to set; null when nothing was sent. A failure is
* logged and lets the page through: it is tried again on the next page.
*/
Expand All @@ -129,7 +131,7 @@ async function keepOnAccount(auth: ClerkMiddlewareAuth, request: NextRequest): P
if (!userId || !cookieIsTheirs(raw, userId)) return null;
const cache = readCache(raw, userId);
const slug = unsaved(cache);
if (slug === undefined) return null;
if (!slug) return null;
try {
const token = await getToken({ template: "convex" });
if (!token) return null;
Expand Down
2 changes: 1 addition & 1 deletion tests/components/app-sidebar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ vi.mock("@/convex/_generated/api", () => ({
screening: { view: { rail: "screening:rail" } },
extraction: { queries: { jobs: { runningJob: "extraction:runningJob" } } },
organizations: { queries: { workspaces: "organizations:workspaces", myInvitations: "organizations:myInvitations" }, manage: { create: "create", invite: "invite", declineInvitation: "decline", confirmJoin: "confirmJoin" } },
workspaces: { queries: { personal: "workspaces:personal", bySlug: "workspaces:bySlug" } },
workspaces: { queries: { personal: "workspaces:personal", bySlug: "workspaces:bySlug" }, lastUsed: { remember: "workspaces:lastUsed:remember" } },
sharing: { shared: { counts: "sharing:counts" }, invitations: { waiting: "sharing:invitationsWaiting" } },
reports: { settings: { open: "reports:open" }, flow: { counts: "reports:counts", waitingElsewhere: "reports:waitingElsewhere" } },
},
Expand Down
Loading