Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): switch to the Cap's organization before going back to the dashboard

Richie McIlroy3898d2fbe5ea
diff --git a/apps/web/__tests__/unit/share-dashboard-destination.test.ts b/apps/web/__tests__/unit/share-dashboard-destination.test.ts
index b46853cc3..492be07d6 100644
--- a/apps/web/__tests__/unit/share-dashboard-destination.test.ts
+++ b/apps/web/__tests__/unit/share-dashboard-destination.test.ts
@@ -1,27 +1,98 @@
-import { describe, expect, it, vi } from "vitest";
+import type { User, Video } from "@cap/web-domain";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+type Column = { table: string; column: string };
+type Condition =
+ | { eq: [Column, unknown] }
+ | { and: Condition[] }
+ | { isNull: Column };
+
+const table = (name: string) =>
+ new Proxy({ __table: name } as Record<string, unknown>, {
+ get: (target, column) =>
+ column === "__table" ? target.__table : { table: name, column },
+ });
-vi.mock("@cap/database", () => ({ db: vi.fn() }));
vi.mock("@cap/database/schema", () => ({
- folders: {},
- organizationMembers: {},
- organizations: {},
- sharedVideos: {},
- spaceMembers: {},
- spaces: {},
- spaceVideos: {},
- videos: {},
+ folders: table("folders"),
+ organizationMembers: table("organizationMembers"),
+ organizations: table("organizations"),
+ sharedVideos: table("sharedVideos"),
+ spaceMembers: table("spaceMembers"),
+ spaces: table("spaces"),
+ spaceVideos: table("spaceVideos"),
+ videos: table("videos"),
+}));
+
+vi.mock("drizzle-orm", () => ({
+ and: (...and: Condition[]) => ({ and }),
+ eq: (left: Column, right: unknown) => ({ eq: [left, right] }),
+ isNull: (isNull: Column) => ({ isNull }),
+}));
+
+type Query = {
+ from: string;
+ joins: { table: string; on: Condition }[];
+ where?: Condition;
+};
+
+const queries: Query[] = [];
+let rowsFor: Record<string, unknown[]> = {};
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => {
+ const query: Query = { from: "", joins: [] };
+ queries.push(query);
+ const chain = {
+ from: (source: { __table: string }) => {
+ query.from = source.__table;
+ return chain;
+ },
+ innerJoin: (source: { __table: string }, on: Condition) => {
+ query.joins.push({ table: source.__table, on });
+ return chain;
+ },
+ where: (where: Condition) => {
+ query.where = where;
+ const rows = Promise.resolve(rowsFor[query.from] ?? []) as Promise<
+ unknown[]
+ > & { limit: () => Promise<unknown[]> };
+ rows.limit = () => rows;
+ return rows;
+ },
+ };
+ return chain;
+ },
+ }),
}));
-import {
- pickShareDashboardDestination,
- type ShareDashboardAccess,
-} from "@/lib/share-dashboard-destination";
+const { getShareDashboardDestination, pickShareDashboardDestination } =
+ await import("@/lib/share-dashboard-destination");
+type ShareDashboardAccess = Parameters<typeof pickShareDashboardDestination>[0];
+
+const flatten = (condition: Condition | undefined): Condition[] =>
+ !condition
+ ? []
+ : "and" in condition
+ ? condition.and.flatMap(flatten)
+ : [condition];
+
+const restrictsTo = (condition: Condition, table: string, value: unknown) =>
+ flatten(condition).some(
+ (part) =>
+ "eq" in part &&
+ part.eq[0].table === table &&
+ part.eq[0].column === "userId" &&
+ part.eq[1] === value,
+ );
const access = (
overrides: Partial<ShareDashboardAccess>,
): ShareDashboardAccess => ({
isOwner: false,
activeOrganizationId: "org-active",
+ videoOrganizationId: "org-active",
ownerFolder: null,
memberSpaces: [],
memberOrganizations: [],
@@ -34,6 +105,7 @@ describe("pickShareDashboardDestination", () => {
kind: "caps",
href: "/dashboard/caps",
label: "My Caps",
+ switchOrganizationId: null,
});
});
@@ -49,6 +121,7 @@ describe("pickShareDashboardDestination", () => {
kind: "folder",
href: "/dashboard/folder/folder-1",
label: "Launch",
+ switchOrganizationId: null,
});
});
@@ -78,6 +151,7 @@ describe("pickShareDashboardDestination", () => {
kind: "space",
href: "/dashboard/spaces/space-1",
label: "Design",
+ switchOrganizationId: null,
});
});
@@ -92,6 +166,7 @@ describe("pickShareDashboardDestination", () => {
kind: "organization",
href: "/dashboard/spaces/org-active",
label: "Acme",
+ switchOrganizationId: null,
});
});
@@ -122,4 +197,111 @@ describe("pickShareDashboardDestination", () => {
it("offers nothing to a signed-in viewer the Cap was never shared with", () => {
expect(pickShareDashboardDestination(access({}))).toBeNull();
});
+
+ it("switches to the organization the destination lives in", () => {
+ expect(
+ pickShareDashboardDestination(
+ access({ isOwner: true, videoOrganizationId: "org-other" }),
+ )?.switchOrganizationId,
+ ).toBe("org-other");
+
+ expect(
+ pickShareDashboardDestination(
+ access({
+ memberSpaces: [
+ { id: "space-other", name: "Other", organizationId: "org-other" },
+ ],
+ }),
+ )?.switchOrganizationId,
+ ).toBe("org-other");
+
+ expect(
+ pickShareDashboardDestination(
+ access({ isOwner: true, activeOrganizationId: null }),
+ )?.switchOrganizationId,
+ ).toBe("org-active");
+ });
+});
+
+describe("getShareDashboardDestination", () => {
+ const VIEWER = "user-viewer" as User.UserId;
+ const OWNER = "user-owner" as User.UserId;
+ const VIDEO = "video-1" as Video.VideoId;
+
+ beforeEach(() => {
+ queries.length = 0;
+ rowsFor = {};
+ });
+
+ const resolve = (viewerId: User.UserId | null) =>
+ getShareDashboardDestination({
+ viewer: viewerId
+ ? { id: viewerId, activeOrganizationId: "org-active" }
+ : null,
+ videoId: VIDEO,
+ ownerId: OWNER,
+ videoOrganizationId: "org-active",
+ });
+
+ it("resolves nothing for a signed-out viewer without querying", async () => {
+ expect(await resolve(null)).toBeNull();
+ expect(queries).toEqual([]);
+ });
+
+ it("looks up only the owner's personal folder for the owner", async () => {
+ rowsFor = { videos: [{ id: "folder-1", name: "Launch" }] };
+
+ expect(await resolve(OWNER)).toMatchObject({
+ kind: "folder",
+ href: "/dashboard/folder/folder-1",
+ });
+ expect(queries).toHaveLength(1);
+ const [query] = queries;
+ expect(query?.joins.map((join) => join.table)).toEqual(["folders"]);
+ expect(
+ flatten(query?.where).some(
+ (part) => "isNull" in part && part.isNull.column === "spaceId",
+ ),
+ ).toBe(true);
+ });
+
+ it("only offers spaces and organizations the viewer is a member of", async () => {
+ rowsFor = {
+ spaceVideos: [
+ { id: "space-1", name: "Design", organizationId: "org-active" },
+ ],
+ };
+
+ expect(await resolve(VIEWER)).toMatchObject({
+ kind: "space",
+ href: "/dashboard/spaces/space-1",
+ });
+
+ const spaceQuery = queries.find((query) => query.from === "spaceVideos");
+ const spaceMembership = spaceQuery?.joins.find(
+ (join) => join.table === "spaceMembers",
+ );
+ expect(
+ spaceMembership &&
+ restrictsTo(spaceMembership.on, "spaceMembers", VIEWER),
+ ).toBe(true);
+
+ const organizationQuery = queries.find(
+ (query) => query.from === "sharedVideos",
+ );
+ const organizationMembership = organizationQuery?.joins.find(
+ (join) => join.table === "organizationMembers",
+ );
+ expect(
+ organizationMembership &&
+ restrictsTo(organizationMembership.on, "organizationMembers", VIEWER),
+ ).toBe(true);
+ expect(
+ queries.some((query) => query.joins.some((j) => j.table === "folders")),
+ ).toBe(false);
+ });
+
+ it("resolves nothing when the viewer has no membership", async () => {
+ expect(await resolve(VIEWER)).toBeNull();
+ });
});
diff --git a/apps/web/app/s/[videoId]/_components/DashboardBackLink.tsx b/apps/web/app/s/[videoId]/_components/DashboardBackLink.tsx
index 37a3c104b..d8b1912f8 100644
--- a/apps/web/app/s/[videoId]/_components/DashboardBackLink.tsx
+++ b/apps/web/app/s/[videoId]/_components/DashboardBackLink.tsx
@@ -1,6 +1,12 @@
+"use client";
+
+import type { Organisation } from "@cap/web-domain";
import clsx from "clsx";
import { ChevronLeft, Folder, LayoutGrid, Users } from "lucide-react";
import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { type MouseEvent, useState } from "react";
+import { updateActiveOrganization } from "@/app/(org)/dashboard/_components/Navbar/server";
import type { ShareDashboardDestination } from "@/lib/share-dashboard-destination";
const DESTINATION_ICONS = {
@@ -19,14 +25,43 @@ export function DashboardBackLink({
compact?: boolean;
className?: string;
}) {
+ const router = useRouter();
+ const [isSwitching, setIsSwitching] = useState(false);
const Icon = DESTINATION_ICONS[destination.kind];
const accessibleLabel = `Back to ${destination.label}`;
+ const { switchOrganizationId } = destination;
+
+ const handleClick = async (event: MouseEvent<HTMLAnchorElement>) => {
+ if (
+ !switchOrganizationId ||
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ ) {
+ return;
+ }
+ event.preventDefault();
+ if (isSwitching) return;
+ setIsSwitching(true);
+ try {
+ await updateActiveOrganization(
+ switchOrganizationId as Organisation.OrganisationId,
+ );
+ } catch (error) {
+ console.error("Failed to switch organization before going back", error);
+ }
+ router.push(destination.href);
+ };
if (compact) {
return (
<Link
href={destination.href}
+ onClick={handleClick}
aria-label={accessibleLabel}
+ aria-busy={isSwitching}
title={accessibleLabel}
className={clsx(
"flex size-8 shrink-0 items-center justify-center rounded-full border border-gray-5 bg-gray-2 text-gray-11 transition-colors hover:bg-gray-4 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9",
@@ -41,9 +76,12 @@ export function DashboardBackLink({
return (
<Link
href={destination.href}
+ onClick={handleClick}
aria-label={accessibleLabel}
+ aria-busy={isSwitching}
className={clsx(
"group inline-flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-full py-1 pl-1.5 pr-3 text-[13px] text-gray-11 transition-colors hover:bg-gray-3 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9",
+ isSwitching && "opacity-70",
className,
)}
>
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index d015d6d07..9805a60e6 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -781,6 +781,7 @@ async function AuthorizedContent({
: null,
videoId,
ownerId: video.owner.id,
+ videoOrganizationId: video.orgId,
}).catch((error) => {
console.error(
`[ShareVideoPage] Dashboard destination lookup failed for ${videoId}:`,
diff --git a/apps/web/lib/share-dashboard-destination.ts b/apps/web/lib/share-dashboard-destination.ts
index 25ed59c24..ddb75e7ee 100644
--- a/apps/web/lib/share-dashboard-destination.ts
+++ b/apps/web/lib/share-dashboard-destination.ts
@@ -16,11 +16,13 @@ export type ShareDashboardDestination = {
kind: "caps" | "folder" | "space" | "organization";
href: string;
label: string;
+ switchOrganizationId: string | null;
};
export type ShareDashboardAccess = {
isOwner: boolean;
activeOrganizationId: string | null;
+ videoOrganizationId: string;
ownerFolder: { id: string; name: string } | null;
memberSpaces: { id: string; name: string; organizationId: string }[];
memberOrganizations: { id: string; name: string }[];
@@ -40,15 +42,27 @@ const byActiveOrganizationFirst =
export function pickShareDashboardDestination(
access: ShareDashboardAccess,
): ShareDashboardDestination | null {
+ // The dashboard only lists the active organization's content, so a
+ // destination in another organization has to switch to it first.
+ const inOrganization = (organizationId: string) =>
+ organizationId === access.activeOrganizationId ? null : organizationId;
+
if (access.isOwner) {
+ const switchOrganizationId = inOrganization(access.videoOrganizationId);
if (access.ownerFolder) {
return {
kind: "folder",
href: `/dashboard/folder/${access.ownerFolder.id}`,
label: access.ownerFolder.name,
+ switchOrganizationId,
};
}
- return { kind: "caps", href: "/dashboard/caps", label: "My Caps" };
+ return {
+ kind: "caps",
+ href: "/dashboard/caps",
+ label: "My Caps",
+ switchOrganizationId,
+ };
}
const activeFirst = byActiveOrganizationFirst(access.activeOrganizationId);
@@ -71,6 +85,7 @@ export function pickShareDashboardDestination(
kind: "space",
href: `/dashboard/spaces/${space.id}`,
label: space.name,
+ switchOrganizationId: inOrganization(space.organizationId),
};
}
@@ -79,6 +94,7 @@ export function pickShareDashboardDestination(
kind: "organization",
href: `/dashboard/spaces/${organization.id}`,
label: organization.name,
+ switchOrganizationId: inOrganization(organization.id),
};
}
@@ -89,10 +105,12 @@ export async function getShareDashboardDestination({
viewer,
videoId,
ownerId,
+ videoOrganizationId,
}: {
viewer: { id: User.UserId; activeOrganizationId: string | null } | null;
videoId: Video.VideoId;
ownerId: User.UserId;
+ videoOrganizationId: string;
}): Promise<ShareDashboardDestination | null> {
if (!viewer) return null;
@@ -153,6 +171,7 @@ export async function getShareDashboardDestination({
return pickShareDashboardDestination({
isOwner,
activeOrganizationId: viewer.activeOrganizationId,
+ videoOrganizationId,
ownerFolder: ownerFolderRows[0] ?? null,
memberSpaces,
memberOrganizations,