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
13 changes: 9 additions & 4 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ import { PostHogIdentify } from "@/components/posthog-identify";
import { ResearchStateProvider } from "@/lib/research/provider";
import { SETUP_HEADER } from "@/lib/profile/setup";
import { LOOK_COOKIE, lookKey, readCache, WORKSPACE_HEADER } from "@/lib/workspaces/look-cache";
import { ADDRESS_HEADER } from "@/lib/workspaces/paths";
import { ADDRESS_HEADER, addressWorkspace } from "@/lib/workspaces/paths";
import { AssistantPanel } from "@/components/assistant/panel";
import { ItemHome, WorkspaceGone } from "@/components/workspaces/item-home";
import { ItemHome, LastWorkspace, TabWorkspace, WorkspaceGone } from "@/components/workspaces/item-home";
import { WorkspacesProvider } from "@/components/workspaces/parts";
import { QueryHighlightProvider } from "@/components/query-highlight";
import { QUERY_HIGHLIGHT_COOKIE } from "@/lib/search/boolean-query";
Expand Down Expand Up @@ -81,8 +81,10 @@ export default async function RootLayout({
cookies(),
]);
// The rail as this browser last saw it, drawn from the first frame: the person and the address's workspace. None signed out.
const slug = requestHeaders.get(WORKSPACE_HEADER) || null;
const { me, looks } = readCache(requestCookies.get(LOOK_COOKIE)?.value, userId);
const { me, looks, last } = readCache(requestCookies.get(LOOK_COOKIE)?.value, userId);
// A page in no workspace, such as a paper's, is drawn in the organization the rail drew last (`TabWorkspace`).
const kept = addressWorkspace(requestHeaders.get(ADDRESS_HEADER)?.split("?")[0] ?? "/") === undefined ? (last ?? null) : null;
const slug = requestHeaders.get(WORKSPACE_HEADER) || kept;
const look = looks[lookKey(slug)];
// Whether this page is a new account's profile setup instead, as the proxy decided before anything was rendered.
const setupFirst = !!userId && requestHeaders.get(SETUP_HEADER) === "due";
Expand Down Expand Up @@ -113,6 +115,7 @@ export default async function RootLayout({
app's own providers, analytics or research state. */}
{signingOut ? children : (
<ProfileSetupGate due={setupFirst} person={setupPerson}>
<TabWorkspace first={kept}>
<PostHogIdentify />
<ResearchStateProvider>
<QuerySyncProvider>
Expand All @@ -137,6 +140,7 @@ export default async function RootLayout({
<Suspense fallback={null}>
<ItemHome />
<WorkspaceGone />
<LastWorkspace />
</Suspense>
<AssistantPanel />
<CookieConsentBanner />
Expand All @@ -145,6 +149,7 @@ export default async function RootLayout({
</WorkspacesProvider>
</QuerySyncProvider>
</ResearchStateProvider>
</TabWorkspace>
</ProfileSetupGate>
)}
</TooltipProvider>
Expand Down
45 changes: 42 additions & 3 deletions components/workspaces/item-home.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"use client";

import { useEffect, useState, type ReactNode } from "react";
import { redirect, usePathname, useSearchParams } from "next/navigation";
import { useAuth } from "@clerk/nextjs";
import { api } from "@/convex/_generated/api";
import { useProtectedQuery } from "@/lib/auth/use-auth-query";
import { useWorkspaceSlug, workspaceHref } from "@/lib/workspaces/href";
import { bareWorkspacePath, outsiderTarget, pageItem } from "@/lib/workspaces/paths";
import { KeptWorkspace, useWorkspaceSlug, workspaceHref } from "@/lib/workspaces/href";
import { lookCookieIn, lookCookieOut, lookKey, readCache, usedLast, writeCache } from "@/lib/workspaces/look-cache";
import { addressWorkspace, bareWorkspacePath, outsiderTarget, pageItem } from "@/lib/workspaces/paths";
import { useWorkspace } from "@/lib/workspaces/url";

type Item = NonNullable<ReturnType<typeof pageItem>>;
Expand Down Expand Up @@ -36,6 +39,41 @@ export function ItemHome() {
return null;
}

/**
* Keeps a tab in its workspace on a page that is in none, such as a paper's: the organization its address last
* named, or for a tab that opened on such a page, the one this browser's rail drew last (`first`, read from the
* rail's cookie as the page was drawn). An organization the person is no longer in gives way to their own workspace.
*/
export function TabWorkspace({ first, children }: { first: string | null; children: ReactNode }) {
const named = addressWorkspace(usePathname());
const [last, setLast] = useState(named === undefined ? first : named);
if (named !== undefined && named !== last) setLast(named);
const kept = named === undefined ? last : null;
const member = useProtectedQuery(api.workspaces.queries.memberAt, kept ? { slug: kept } : "skip").data;
return <KeptWorkspace value={kept && member !== false ? kept : undefined}>{children}</KeptWorkspace>;
}

/**
* Says in the rail's cookie which workspace this tab is in, on every page it opens, an item opened by the address's
* query included: an address that names no workspace opens in the one used last (proxy.ts `lastWorkspaceStart`,
* `TabWorkspace`). Apart from the rail, which a phone mounts only while its sheet is open, and which redraws in a tab
* left open behind.
*/
export function LastWorkspace() {
const key = lookKey(useWorkspaceSlug());
const pathname = usePathname();
const query = useSearchParams().toString();
const { userId } = useAuth();
// The browser's cookies are the outside system: the proxy and the server read them on the next page load.
useEffect(() => {
if (!userId) return;
const raw = lookCookieIn(document.cookie);
const next = writeCache(usedLast(readCache(raw, userId), key), userId, key, undefined, undefined);
if (next && next !== raw) document.cookie = lookCookieOut(next);
}, [userId, key, pathname, query]);
return null;
}

/**
* Leaves an organization's page once the person can't act in it any more: they were removed,
* they left in another tab, or it was deleted. They go to the same page in their own workspace, item and all,
Expand All @@ -48,6 +86,7 @@ export function WorkspaceGone() {
const params = useSearchParams();
// False once the server says they aren't in it; undefined while it's still being read. One being deleted is still theirs: the deletion may fail.
const member = useProtectedQuery(api.workspaces.queries.memberAt, slug ? { slug } : "skip").data;
if (slug && member === false) redirect(outsiderTarget(pathname, params.size ? `?${params.toString()}` : ""));
// Only from an address that names the organization: a page in no workspace stays, in their own (`TabWorkspace`).
if (slug && member === false && addressWorkspace(pathname) === slug) redirect(outsiderTarget(pathname, params.size ? `?${params.toString()}` : ""));
return null;
}
7 changes: 2 additions & 5 deletions components/workspaces/rail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ import { cn } from "@/lib/utils";
import { bareWorkspacePath, switchTarget } from "@/lib/workspaces/paths";
import { inWorkspace, useWorkspace, useWorkspaceScope } from "@/lib/workspaces/url";
import { useWorkspaceSlug } from "@/lib/workspaces/href";
import { LOOK_COOKIE, lookCookieIn, lookKey, readCache, writeCache, type CachedLook, type CachedMe, type FirstWorkspace } from "@/lib/workspaces/look-cache";
import { lookCookieIn, lookCookieOut, lookKey, readCache, writeCache, type CachedLook, type CachedMe, type FirstWorkspace } from "@/lib/workspaces/look-cache";
import { CreateOrganization, RoleOf, WorkspaceMenu } from "./switcher";
import { Framed, Opening, PlanChip, settingsHref, useCurrentWorkspace, useWorkspaces, workspaceTint, WorkspaceTile, type WorkspaceLook, type WorkspaceRow } from "./parts";

Expand Down Expand Up @@ -101,9 +101,6 @@ function ProgressRing({ value }: { value: number }) {
);
}

/** A year: how long the browser keeps the rail's looks. */
const LOOK_KEPT_S = 365 * 24 * 60 * 60;

/**
* How the rail looked last time in this browser, for the person and the address's workspace:
* what the server drew the page with (`first`), then the cookie as the address changes. Nothing
Expand Down Expand Up @@ -196,7 +193,7 @@ export function SidebarContent({ firstWorkspace, onClose }: { firstWorkspace: Fi
const look: CachedLook | undefined = loaded && (loaded.slug ?? null) === slug ? { kind: loaded.kind, workspaceId: loaded.workspaceId, name: loaded.name, ...(loaded.imageUrl ? { imageUrl: loaded.imageUrl } : {}), ...(loaded.colour ? { colour: loaded.colour } : {}), ...(extract ? { extract: true as const } : {}), ...(publish ? { publish: true as const } : {}), ...(author ? { author: true as const } : {}) } : undefined;
if (!look && !live) return;
const next = writeCache(cache, userId, lookKey(slug), look, live);
if (next && next !== raw) document.cookie = `${LOOK_COOKIE}=${next}; Path=/; Max-Age=${LOOK_KEPT_S}; SameSite=Lax`;
if (next && next !== raw) document.cookie = lookCookieOut(next);
}, [userId, slug, loaded, live?.name, live?.imageUrl, liveExtracts, liveAuthors, livePublishes]);
const { currentQuery } = useCurrentQueryStore();
const { keywords } = useKeywordExpansionStore();
Expand Down
6 changes: 4 additions & 2 deletions convex/workspaces/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const memberAt = query({
},
});

const itemKind = v.union(v.literal("search"), v.literal("screening"), v.literal("extraction"), v.literal("collection"), v.literal("library"), v.literal("profile"));
const itemKind = v.union(v.literal("search"), v.literal("screening"), v.literal("extraction"), v.literal("collection"), v.literal("library"), v.literal("profile"), v.literal("report"));

/** The workspaces a person acts in: their own, then their organizations'. */
async function workspacesOf(ctx: QueryCtx, user: Doc<"users">) {
Expand All @@ -76,7 +76,9 @@ async function searchAt(ctx: QueryCtx, user: Doc<"users">, id: string, here: Id<
}

/** The workspace an item a page's address names is in, or null when there's none such. */
async function itemWorkspace(ctx: QueryCtx, kind: "screening" | "extraction" | "collection" | "library" | "profile", id: string): Promise<Id<"workspaces"> | null> {
async function itemWorkspace(ctx: QueryCtx, kind: "screening" | "extraction" | "collection" | "library" | "profile" | "report", id: string): Promise<Id<"workspaces"> | null> {
// A report being published goes by its key, which its address carries (/publish?report=R…).
if (kind === "report") return (await ctx.db.query("reports").withIndex("by_key", (q) => q.eq("key", id)).unique())?.workspaceId ?? null;
const table = ({ screening: "screeningJobs", extraction: "extractionJobs", collection: "collections", library: "evidenceLibraries", profile: "authorProfiles" } as const)[kind];
const docId = ctx.db.normalizeId(table, id);
const item = docId ? await ctx.db.get(docId) : null;
Expand Down
13 changes: 10 additions & 3 deletions lib/workspaces/href.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,25 @@
// takes the organization's prefix, /o/<slug>, when the page is one of its. No Convex here, so any
// component can link.

import { useCallback, useMemo } from "react";
import { createContext, use, useCallback, useMemo } from "react";
import { useParams, useRouter } from "next/navigation";

import { workspaceHref } from "./paths";

// The rule itself is in ./paths, with the others; components link through here.
export { workspaceHref };

/** The organization a page's address names, or undefined in the person's own workspace. */
/** The organization a tab stays in on a page that is in no workspace (components/workspaces/item-home.tsx `TabWorkspace`); none on any other page. */
export const KeptWorkspace = createContext<string | undefined>(undefined);

/**
* The organization a page is in: the one its address names, or on a page that is in no workspace, the one its tab
* was in. Undefined in the person's own workspace.
*/
export function useWorkspaceSlug(): string | undefined {
const params = useParams();
return typeof params?.slug === "string" ? params.slug : undefined;
const kept = use(KeptWorkspace);
return typeof params?.slug === "string" ? params.slug : kept;
}

/** `workspaceHref` for the workspace the page is in. */
Expand Down
14 changes: 13 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, readCache, writeCache, type CachedLook } from "./look-cache";
import { lookCookieIn, readCache, 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 All @@ -16,6 +16,18 @@ describe("the rail's cookie", () => {
expect(readCache(lookCookieIn(`theme=dark; workspace-looks=${cookie}; other=1`), "user_ada").looks).toEqual({ "lab-1": lab(1) });
});

it("says which organization a tab was in last, and none once one was in the person's own workspace", () => {
const inLab = writeCache(usedLast({ looks: {} }, "lab-1"), "user_ada", "lab-1", undefined, undefined)!;
expect(readCache(inLab, "user_ada").last).toBe("lab-1");
// Someone else signing in on the same browser starts in their own workspace.
expect(readCache(inLab, "user_bob").last).toBeUndefined();
// The rail redrawing a workspace, in a tab left open behind, doesn't make it the one used last.
const redrawn = writeCache(readCache(inLab, "user_ada"), "user_ada", "~", own, ada)!;
expect(readCache(redrawn, "user_ada").last).toBe("lab-1");
const atHome = writeCache(usedLast(readCache(redrawn, "user_ada"), "~"), "user_ada", "~", undefined, undefined)!;
expect(readCache(atHome, "user_ada")).toEqual({ me: ada, looks: { "~": own } });
});

it("drops a colour, photo or section that isn't one, and anything that isn't a look", () => {
const raw = JSON.stringify({
user: "user_ada",
Expand Down
26 changes: 22 additions & 4 deletions lib/workspaces/look-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
// photo, and each workspace's name, colour, logo and the sections it opens, so the server draws
// the rail as it was from the page's first frame, before Clerk or the workspace load. The rail writes it whenever it reads them. It names the account it's for, so someone
// else signing in on the same browser doesn't see it.
// It also keeps the organization a tab was in last (`last`): an address that names no workspace opens in that one
// (lib/workspaces/paths.ts `startIn`, `addressWorkspace`). Every page says it (components/workspaces/item-home.tsx
// `LastWorkspace`), apart from the rail, which a phone mounts only while its sheet is open.

/** The cookie the rail's looks are kept in. */
export const LOOK_COOKIE = "workspace-looks";
Expand All @@ -13,7 +16,8 @@ export const WORKSPACE_HEADER = "x-workspace-slug";
export type CachedLook = { kind: "personal" | "organization"; workspaceId: string; name: string; imageUrl?: string; colour?: string; extract?: true; author?: true; publish?: true };
/** The signed-in person, as the rail's account button shows them. */
export type CachedMe = { name: string; imageUrl?: string };
export type LookCache = { me?: CachedMe; looks: Record<string, CachedLook> };
/** `last`: the organization a tab was in last, none when that was the person's own workspace. */
export type LookCache = { me?: CachedMe; looks: Record<string, CachedLook>; last?: string };

/** What the server knew when it drew the page: the address's workspace, who's signed in, and how the rail looked last time. */
export type FirstWorkspace = { slug: string | null; user?: string; me?: CachedMe; look?: CachedLook };
Expand All @@ -37,7 +41,7 @@ const photo = (value: unknown) => (typeof value === "string" && value.startsWith
export function readCache(raw: string | undefined, user: string | null | undefined): LookCache {
if (!raw || !user) return { looks: {} };
try {
const parsed = JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { user?: unknown; me?: Partial<CachedMe>; looks?: unknown } | null;
const parsed = JSON.parse(raw.startsWith("%") ? decodeURIComponent(raw) : raw) as { user?: unknown; me?: Partial<CachedMe>; looks?: unknown; last?: unknown } | null;
if (parsed?.user !== user) return { looks: {} };
const looks: Record<string, CachedLook> = {};
for (const [key, value] of Object.entries((parsed.looks ?? {}) as Record<string, Partial<CachedLook>>)) {
Expand All @@ -54,12 +58,15 @@ export function readCache(raw: string | undefined, user: string | null | undefin
};
}
const me = typeof parsed.me?.name === "string" ? { name: parsed.me.name, ...photo(parsed.me.imageUrl) } : undefined;
return { ...(me ? { me } : {}), looks };
const last = lastIn(parsed);
return { ...(me ? { me } : {}), looks, ...(last ? { last } : {}) };
} catch {
return { looks: {} };
}
}

const lastIn = (parsed: { last?: unknown } | null) => (typeof parsed?.last === "string" && parsed.last && parsed.last !== OWN ? parsed.last : undefined);

/**
* The cookie's value for `user`, with `me` and the look kept under `key` newest, and the oldest
* organizations dropped, past KEPT or until it fits. Null when even that doesn't fit.
Expand All @@ -70,7 +77,7 @@ export function writeCache(cache: LookCache, user: string, key: string, look: Ca
const keptMe = me ?? cache.me;
const oldest = Object.keys(rest).filter((other) => other !== OWN);
for (const old of oldest.splice(0, Math.max(0, oldest.length - (KEPT - 1)))) delete rest[old];
const encode = () => encodeURIComponent(JSON.stringify({ user, ...(keptMe ? { me: keptMe } : {}), looks: { ...rest, ...(kept ? { [key]: kept } : {}) } }));
const encode = () => encodeURIComponent(JSON.stringify({ user, ...(keptMe ? { me: keptMe } : {}), looks: { ...rest, ...(kept ? { [key]: kept } : {}) }, ...(cache.last ? { last: cache.last } : {}) }));
let value = encode();
while (value.length > MAX_VALUE && oldest.length) {
delete rest[oldest.shift()!];
Expand All @@ -79,5 +86,16 @@ export function writeCache(cache: LookCache, user: string, key: string, look: Ca
return value.length > MAX_VALUE ? null : value;
}

/** `cache` with the workspace under `key` as the one used last. */
export function usedLast(cache: LookCache, key: string): LookCache {
const { last: _, ...rest } = cache;
return key === OWN ? rest : { ...rest, last: key };
}

/** A year: how long the browser keeps the cookie. */
const KEPT_S = 365 * 24 * 60 * 60;
/** What `document.cookie` is given to keep `value`. */
export const lookCookieOut = (value: string) => `${LOOK_COOKIE}=${value}; Path=/; Max-Age=${KEPT_S}; SameSite=Lax`;

/** The cookie's raw value in a `document.cookie` string. */
export const lookCookieIn = (cookies: string) => cookies.split("; ").find((cookie) => cookie.startsWith(`${LOOK_COOKIE}=`))?.slice(LOOK_COOKIE.length + 1);
Loading
Loading