Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: expose team folders when moving owned Caps

Richie McIlroy229ddecd7060
diff --git a/apps/web/__tests__/unit/move-items-dialog.test.ts b/apps/web/__tests__/unit/move-items-dialog.test.ts
new file mode 100644
index 000000000..75ce7b805
--- /dev/null
+++ b/apps/web/__tests__/unit/move-items-dialog.test.ts
@@ -0,0 +1,149 @@
+// @vitest-environment jsdom
+
+import { Folder, Video } from "@cap/web-domain";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ destinations: vi.fn(),
+ folders: vi.fn(),
+ place: vi.fn(),
+ move: vi.fn(),
+ moveFolder: vi.fn(),
+ refresh: vi.fn(),
+ close: vi.fn(),
+}));
+vi.mock("@/actions/folders/move-items", () => ({
+ getOwnedVideoMoveDestinations: mocks.destinations,
+ getMoveFolderDestinations: mocks.folders,
+ placeOwnedVideos: mocks.place,
+ moveVideos: mocks.move,
+ moveFolder: mocks.moveFolder,
+}));
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh: mocks.refresh }),
+}));
+vi.mock("@/app/Layout/AuthContext", () => ({
+ useCurrentUser: () => ({ id: "owner", activeOrganizationId: "org" }),
+}));
+vi.mock("@cap/utils", async () => await import("@cap/utils/helpers"));
+vi.mock("@cap/ui", async () => ({
+ ...(await import("../../../../packages/ui/src/components/Button")),
+ ...(await import("../../../../packages/ui/src/components/Dialog")),
+ ...(await import("../../../../packages/ui/src/components/LoadingSpinner")),
+ ...(await import("../../../../packages/ui/src/components/input/Input")),
+}));
+
+import { MoveItemsDialog } from "@/app/(org)/dashboard/caps/components/MoveItemsDialog";
+
+let root: Root;
+let container: HTMLDivElement;
+let queryClient: QueryClient;
+const videoId = Video.VideoId.make("video");
+const folderId = Folder.FolderId.make("team-folder");
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ mocks.destinations.mockResolvedValue([
+ { name: "My Caps", location: { type: "personal" }, folders: [] },
+ {
+ name: "All team members",
+ location: { type: "organization" },
+ folders: [{ id: folderId, name: "Team folder", parentId: null }],
+ },
+ ]);
+ mocks.folders.mockResolvedValue([]);
+ mocks.place.mockResolvedValue({ moved: 1 });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ queryClient.clear();
+});
+async function render(
+ item: React.ComponentProps<typeof MoveItemsDialog>["item"] = {
+ type: "videos",
+ videoIds: [videoId],
+ currentFolderId: null,
+ },
+) {
+ await act(async () => {
+ root.render(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(MoveItemsDialog, {
+ open: true,
+ onOpenChange: mocks.close,
+ location: { type: "personal" },
+ rootLabel: "My Caps",
+ item,
+ }),
+ ),
+ );
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ });
+}
+function button(label: string) {
+ const element = [...document.querySelectorAll("button")].find(
+ (element) => element.textContent?.trim() === label,
+ );
+ if (!element) throw new Error(`Button not found: ${label}`);
+ return element;
+}
+async function chooseTeam() {
+ const select = document.querySelector("select");
+ if (!select) throw new Error("Location selector not found");
+ await act(async () => {
+ select.value = "organization";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+}
+
+describe("moving Caps from My Caps to a team location", () => {
+ it("shows the team folder and explains sharing before submitting its destination", async () => {
+ await render();
+ expect(button("Move").disabled).toBe(true);
+ await chooseTeam();
+ expect(document.body.textContent).toContain(
+ "People with access to All team members",
+ );
+ await act(async () => button("Team folder").click());
+ await act(async () => button("Share & move").click());
+ expect(mocks.place).toHaveBeenCalledWith({
+ videoIds: [videoId],
+ folderId,
+ location: { type: "organization" },
+ });
+ expect(mocks.move).not.toHaveBeenCalled();
+ });
+
+ it("allows the team root even when the Cap starts at the personal root", async () => {
+ await render();
+ await chooseTeam();
+ expect(button("Share & move").disabled).toBe(false);
+ await act(async () => button("Share & move").click());
+ expect(mocks.place).toHaveBeenCalledWith({
+ videoIds: [videoId],
+ folderId: null,
+ location: { type: "organization" },
+ });
+ });
+
+ it("keeps folder moves within their original location", async () => {
+ await render({ type: "folder", folderId, currentParentId: null });
+ expect(document.querySelector("select")).toBeNull();
+ expect(mocks.destinations).not.toHaveBeenCalled();
+ expect(mocks.folders).toHaveBeenCalledWith({ type: "personal" });
+ });
+});
diff --git a/apps/web/__tests__/unit/move-owned-videos.test.ts b/apps/web/__tests__/unit/move-owned-videos.test.ts
new file mode 100644
index 000000000..440559814
--- /dev/null
+++ b/apps/web/__tests__/unit/move-owned-videos.test.ts
@@ -0,0 +1,270 @@
+import { Folder, Space, Video } from "@cap/web-domain";
+import { getTableName, type SQL } from "drizzle-orm";
+import { MySqlDialect, type MySqlTable } from "drizzle-orm/mysql-core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ user: vi.fn(),
+ organization: vi.fn(),
+ space: vi.fn(),
+ select: vi.fn(),
+ insert: vi.fn(),
+ update: vi.fn(),
+ transaction: vi.fn(),
+ revalidate: vi.fn(),
+}));
+vi.mock("@cap/database", () => ({ db: () => mocks }));
+vi.mock("@cap/database/auth/session", () => ({ getCurrentUser: mocks.user }));
+vi.mock("@/actions/organization/authorization", () => ({
+ requireOrganizationAccess: mocks.organization,
+ requireOrganizationSettingsManager: vi.fn(),
+}));
+vi.mock("@/actions/organization/space-authorization", () => ({
+ getSpaceAccess: mocks.space,
+ requireSpaceManager: vi.fn(),
+}));
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidate }));
+
+import {
+ getOwnedVideoMoveDestinations,
+ placeOwnedVideos,
+} from "@/actions/folders/move-items";
+
+const dialect = new MySqlDialect();
+const filters: { table: string; sql: string; params: unknown[] }[] = [];
+const locks: string[] = [];
+let results: unknown[][];
+const writes: { table: string; values: unknown; filter?: SQL }[] = [];
+const ids: [Video.VideoId, Video.VideoId] = [
+ Video.VideoId.make("video-1"),
+ Video.VideoId.make("video-2"),
+];
+const folderId = Folder.FolderId.make("folder-1");
+const spaceId = Space.SpaceId.make("space-1");
+
+beforeEach(() => {
+ results = [];
+ filters.length = 0;
+ locks.length = 0;
+ writes.length = 0;
+ mocks.user.mockResolvedValue({ id: "owner", activeOrganizationId: "org" });
+ mocks.organization.mockResolvedValue({ role: "member" });
+ mocks.space.mockResolvedValue({
+ organizationId: "org",
+ organizationRole: "member",
+ spaceRole: "member",
+ canManage: false,
+ });
+ mocks.transaction.mockImplementation(
+ async (callback: (tx: typeof mocks) => Promise<unknown>) => callback(mocks),
+ );
+ mocks.select.mockImplementation(() => {
+ let table: string;
+ const query = Object.assign(Promise.resolve(results.shift() ?? []), {
+ from(value: MySqlTable) {
+ table = getTableName(value);
+ return query;
+ },
+ leftJoin() {
+ return query;
+ },
+ where(condition: SQL) {
+ filters.push({ table, ...dialect.sqlToQuery(condition) });
+ return query;
+ },
+ orderBy() {
+ return query;
+ },
+ limit() {
+ return query;
+ },
+ for(lock: string) {
+ locks.push(lock);
+ return query;
+ },
+ });
+ return query;
+ });
+ mocks.insert.mockImplementation((table: MySqlTable) => ({
+ values: async (values: unknown) => {
+ writes.push({ table: getTableName(table), values });
+ },
+ }));
+ mocks.update.mockImplementation((table: MySqlTable) => ({
+ set: (values: unknown) => ({
+ where: async (filter: SQL) => {
+ writes.push({ table: getTableName(table), values, filter });
+ },
+ }),
+ }));
+});
+
+describe("placing owned Caps in team folders", () => {
+ it("adds missing team shares, moves existing shares, and preserves personal placement", async () => {
+ results = [
+ ids.map((id) => ({ id })),
+ [{ id: folderId }],
+ [{ videoId: ids[0] }],
+ ];
+ await expect(
+ placeOwnedVideos({
+ videoIds: ids,
+ folderId,
+ location: { type: "organization" },
+ }),
+ ).resolves.toEqual({ moved: 2 });
+ expect(locks).toEqual(["update"]);
+ expect(filters[0]?.sql).toContain("`videos`.`ownerId` = ?");
+ expect(filters[0]?.sql).toContain("`videos`.`orgId` = ?");
+ expect(filters[0]?.params).toEqual([...ids, "owner", "org"]);
+ expect(filters[1]?.params).toEqual([folderId, "org", "org"]);
+ expect(writes).toHaveLength(2);
+ expect(writes[0]).toMatchObject({
+ table: "shared_videos",
+ values: [
+ {
+ videoId: ids[1],
+ folderId,
+ organizationId: "org",
+ sharedByUserId: "owner",
+ },
+ ],
+ });
+ expect(writes[1]).toMatchObject({
+ table: "shared_videos",
+ values: { folderId },
+ });
+ expect(dialect.sqlToQuery(writes[1]?.filter as SQL).params).toEqual([
+ ...ids,
+ "org",
+ ]);
+ expect(mocks.revalidate).toHaveBeenCalledWith("/s/[videoId]", "page");
+ });
+
+ it("lets space members place their own Caps without changing other shares", async () => {
+ results = [[{ id: ids[0] }], [{ id: folderId }], []];
+ await placeOwnedVideos({
+ videoIds: [ids[0]],
+ folderId,
+ location: { type: "space", spaceId },
+ });
+ expect(filters[1]?.params).toEqual([folderId, "org", spaceId]);
+ expect(writes.map((write) => write.table)).toEqual([
+ "space_videos",
+ "space_videos",
+ ]);
+ expect(writes[0]?.values).toEqual([
+ expect.objectContaining({ videoId: ids[0], spaceId, folderId }),
+ ]);
+ });
+
+ it("does not duplicate an existing placement on retry", async () => {
+ results = [[{ id: ids[0] }], [{ videoId: ids[0] }]];
+ await placeOwnedVideos({
+ videoIds: [ids[0]],
+ folderId: null,
+ location: { type: "organization" },
+ });
+ expect(mocks.insert).not.toHaveBeenCalled();
+ expect(writes).toHaveLength(1);
+ });
+
+ it("rejects the whole selection if any Cap is not owned in the active organization", async () => {
+ results = [[{ id: ids[0] }]];
+ await expect(
+ placeOwnedVideos({
+ videoIds: ids,
+ folderId,
+ location: { type: "organization" },
+ }),
+ ).rejects.toThrow("cannot be moved");
+ expect(writes).toEqual([]);
+ });
+
+ it("rejects a folder outside the selected destination", async () => {
+ results = [[{ id: ids[0] }], []];
+ await expect(
+ placeOwnedVideos({
+ videoIds: [ids[0]],
+ folderId,
+ location: { type: "organization" },
+ }),
+ ).rejects.toThrow("Destination folder not found");
+ expect(writes).toEqual([]);
+ });
+
+ it.each([
+ null,
+ { organizationId: "other-org", organizationRole: "owner", canManage: true },
+ {
+ organizationId: "org",
+ organizationRole: "member",
+ spaceRole: null,
+ canManage: false,
+ },
+ {
+ organizationId: "org",
+ organizationRole: null,
+ spaceRole: "admin",
+ canManage: true,
+ },
+ ])("rejects inaccessible space %#", async (access) => {
+ mocks.space.mockResolvedValue(access);
+ await expect(
+ placeOwnedVideos({
+ videoIds: ids,
+ folderId,
+ location: { type: "space", spaceId },
+ }),
+ ).rejects.toThrow("Space not found");
+ expect(mocks.transaction).not.toHaveBeenCalled();
+ });
+
+ it("rejects former organization members before reading or writing placements", async () => {
+ mocks.organization.mockRejectedValue(new Error("Forbidden"));
+ await expect(
+ placeOwnedVideos({
+ videoIds: ids,
+ folderId,
+ location: { type: "organization" },
+ }),
+ ).rejects.toThrow("Forbidden");
+ expect(mocks.transaction).not.toHaveBeenCalled();
+ });
+
+ it("limits the selectable folders to personal and accessible team locations", async () => {
+ results = [
+ [{ id: spaceId, name: "Team space" }],
+ [
+ { id: "mine", name: "Personal", parentId: null, spaceId: null },
+ { id: folderId, name: "Team folder", parentId: null, spaceId: "org" },
+ { id: "space-folder", name: "Space folder", parentId: null, spaceId },
+ ],
+ ];
+ const destinations = await getOwnedVideoMoveDestinations();
+ expect(
+ destinations.map((group) => [
+ group.name,
+ group.folders.map((folder) => folder.id),
+ ]),
+ ).toEqual([
+ ["My Caps", ["mine"]],
+ ["All team members", [folderId]],
+ ["Team space", ["space-folder"]],
+ ]);
+ expect(filters[0]?.params).toEqual(["org", "owner", "owner"]);
+ expect(filters[1]?.params).toEqual(["org", "owner", "org", spaceId]);
+ });
+
+ it("keeps personal moves private and checks personal folder ownership", async () => {
+ results = [[{ id: ids[0] }], [{ id: folderId }]];
+ await placeOwnedVideos({
+ videoIds: [ids[0]],
+ folderId,
+ location: { type: "personal" },
+ });
+ expect(filters[1]?.params).toEqual([folderId, "org", "owner"]);
+ expect(filters[1]?.sql).toContain("`folders`.`spaceId` is null");
+ expect(writes.map((write) => write.table)).toEqual(["videos"]);
+ });
+});
diff --git a/apps/web/actions/folders/move-items.ts b/apps/web/actions/folders/move-items.ts
index eff1c4960..923df0614 100644
--- a/apps/web/actions/folders/move-items.ts
+++ b/apps/web/actions/folders/move-items.ts
@@ -2,22 +2,33 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
+import { nanoId } from "@cap/database/helpers";
import {
folders,
sharedVideos,
+ spaceMembers,
+ spaces,
spaceVideos,
videos,
} from "@cap/database/schema";
import type { Folder, Video } from "@cap/web-domain";
-import { and, asc, eq, inArray, isNull } from "drizzle-orm";
+import { and, asc, eq, inArray, isNull, or } from "drizzle-orm";
import { revalidatePath } from "next/cache";
-import { requireOrganizationSettingsManager } from "@/actions/organization/authorization";
-import { requireSpaceManager } from "@/actions/organization/space-authorization";
+import {
+ requireOrganizationAccess,
+ requireOrganizationSettingsManager,
+} from "@/actions/organization/authorization";
+import {
+ getSpaceAccess,
+ requireSpaceManager,
+} from "@/actions/organization/space-authorization";
import {
MAX_MOVE_ITEMS,
+ type MoveDestinationGroup,
type MoveFolderDestination,
type MoveLocation,
} from "@/lib/move-items";
+import { canManageOrganizationSettings } from "@/lib/permissions/roles";
function requireValidLocation(location: MoveLocation) {
if (
@@ -113,6 +124,202 @@ export async function getMoveFolderDestinations(
.orderBy(asc(folders.name));
}
+export async function getOwnedVideoMoveDestinations(): Promise<
+ MoveDestinationGroup[]
+> {
+ const user = await getCurrentUser();
+ if (!user?.activeOrganizationId) throw new Error("Unauthorized");
+ const access = await requireOrganizationAccess(
+ user.id,
+ user.activeOrganizationId,
+ );
+ const availableSpaces = await db()
+ .select({ id: spaces.id, name: spaces.name })
+ .from(spaces)
+ .leftJoin(
+ spaceMembers,
+ and(
+ eq(spaceMembers.spaceId, spaces.id),
+ eq(spaceMembers.userId, user.id),
+ ),
+ )
+ .where(
+ and(
+ eq(spaces.organizationId, user.activeOrganizationId),
+ canManageOrganizationSettings(access.role)
+ ? undefined
+ : or(
+ eq(spaces.createdById, user.id),
+ eq(spaceMembers.userId, user.id),
+ ),
+ ),
+ )
+ .orderBy(asc(spaces.name));
+ const organizationFolders = await db()
+ .select({
+ id: folders.id,
+ name: folders.name,
+ parentId: folders.parentId,
+ spaceId: folders.spaceId,
+ })
+ .from(folders)
+ .where(
+ and(
+ eq(folders.organizationId, user.activeOrganizationId),
+ or(
+ and(eq(folders.createdById, user.id), isNull(folders.spaceId)),
+ inArray(folders.spaceId, [
+ user.activeOrganizationId,
+ ...availableSpaces.map((space) => space.id),
+ ]),
+ ),
+ ),
+ )
+ .orderBy(asc(folders.name));
+ return [
+ {
+ location: { type: "personal" },
+ name: "My Caps",
+ folders: organizationFolders.filter((folder) => folder.spaceId === null),
+ },
+ {
+ location: { type: "organization" },
+ name: "All team members",
+ folders: organizationFolders.filter(
+ (folder) => folder.spaceId === user.activeOrganizationId,
+ ),
+ },
+ ...availableSpaces.map(
+ (space): MoveDestinationGroup => ({
+ location: { type: "space", spaceId: space.id },
+ name: space.name,
+ folders: organizationFolders.filter(
+ (folder) => folder.spaceId === space.id,
+ ),
+ }),
+ ),
+ ];
+}
+
+export async function placeOwnedVideos({
+ videoIds,
+ folderId,
+ location,
+}: {
+ videoIds: Video.VideoId[];
+ folderId: Folder.FolderId | null;
+ location: MoveLocation;
+}) {
+ const user = await getCurrentUser();
+ if (!user?.activeOrganizationId) throw new Error("Unauthorized");
+ requireValidLocation(location);
+ const ids = normalizeVideoIds(videoIds).sort();
+ await requireOrganizationAccess(user.id, user.activeOrganizationId);
+ if (location.type === "space") {
+ const access = await getSpaceAccess(user.id, location.spaceId);
+ if (
+ !access ||
+ access.organizationId !== user.activeOrganizationId ||
+ !access.organizationRole ||
+ (!access.canManage && !access.spaceRole)
+ ) {
+ throw new Error("Space not found");
+ }
+ }
+ await db().transaction(async (tx) => {
+ const ownedVideos = await tx
+ .select({ id: videos.id })
+ .from(videos)
+ .where(
+ and(
+ inArray(videos.id, ids),
+ eq(videos.ownerId, user.id),
+ eq(videos.orgId, user.activeOrganizationId),
+ ),
+ )
+ .orderBy(asc(videos.id))
+ .for("update");
+ if (ownedVideos.length !== ids.length)
+ throw new Error("One or more Caps cannot be moved");
+ if (folderId) {
+ const [folder] = await tx
+ .select({ id: folders.id })
+ .from(folders)
+ .where(and(eq(folders.id, folderId), getFolderScope(user, location)))
+ .limit(1);
+ if (!folder) throw new Error("Destination folder not found");
+ }
+ if (location.type === "personal") {
+ await tx.update(videos).set({ folderId }).where(inArray(videos.id, ids));
+ } else if (location.type === "organization") {
+ const existing = await tx
+ .select({ videoId: sharedVideos.videoId })
+ .from(sharedVideos)
+ .where(
+ and(
+ inArray(sharedVideos.videoId, ids),
+ eq(sharedVideos.organizationId, user.activeOrganizationId),
+ ),
+ );
+ const shared = new Set(existing.map((row) => row.videoId));
+ const missing = ids.filter((id) => !shared.has(id));
+ if (missing.length)
+ await tx.insert(sharedVideos).values(
+ missing.map((videoId) => ({
+ id: nanoId(),
+ videoId,
+ folderId,
+ organizationId: user.activeOrganizationId,
+ sharedByUserId: user.id,
+ })),
+ );
+ await tx
+ .update(sharedVideos)
+ .set({ folderId })
+ .where(
+ and(
+ inArray(sharedVideos.videoId, ids),
+ eq(sharedVideos.organizationId, user.activeOrganizationId),
+ ),
+ );
+ } else {
+ const existing = await tx
+ .select({ videoId: spaceVideos.videoId })
+ .from(spaceVideos)
+ .where(
+ and(
+ inArray(spaceVideos.videoId, ids),
+ eq(spaceVideos.spaceId, location.spaceId),
+ ),
+ );
+ const shared = new Set(existing.map((row) => row.videoId));
+ const missing = ids.filter((id) => !shared.has(id));
+ if (missing.length)
+ await tx.insert(spaceVideos).values(
+ missing.map((videoId) => ({
+ id: nanoId(),
+ videoId,
+ folderId,
+ spaceId: location.spaceId,
+ addedById: user.id,
+ })),
+ );
+ await tx
+ .update(spaceVideos)
+ .set({ folderId })
+ .where(
+ and(
+ inArray(spaceVideos.videoId, ids),
+ eq(spaceVideos.spaceId, location.spaceId),
+ ),
+ );
+ }
+ });
+ revalidateMoveLocation(location);
+ revalidatePath("/s/[videoId]", "page");
+ return { moved: ids.length };
+}
+
export async function moveVideos({
videoIds,
folderId,
diff --git a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx
index bf65b8bce..666f37da4 100644
--- a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx
@@ -10,7 +10,11 @@ import {
Input,
LoadingSpinner,
} from "@cap/ui";
-import type { Folder as FolderDomain, Video } from "@cap/web-domain";
+import type {
+ Folder as FolderDomain,
+ Organisation,
+ Video,
+} from "@cap/web-domain";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import clsx from "clsx";
import { Check, Folder, FolderInput, FolderRoot, Search } from "lucide-react";
@@ -19,11 +23,16 @@ import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
getMoveFolderDestinations,
+ getOwnedVideoMoveDestinations,
moveFolder,
moveVideos,
+ placeOwnedVideos,
} from "@/actions/folders/move-items";
+import { useDashboardContext } from "@/app/(org)/dashboard/DashboardContext";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import {
buildMoveFolderDestinationRows,
+ type MoveDestinationGroup,
type MoveLocation,
moveLocationKey,
} from "@/lib/move-items";
@@ -45,6 +54,7 @@ interface MoveItemsDialogProps {
onOpenChange: (open: boolean) => void;
location: MoveLocation;
rootLabel: string;
+ organizationId?: Organisation.OrganisationId;
item: MoveItem;
onMoved?: () => void;
}
@@ -54,37 +64,64 @@ export function MoveItemsDialog({
onOpenChange,
location,
rootLabel,
+ organizationId,
item,
onMoved,
}: MoveItemsDialogProps) {
const router = useRouter();
+ const user = useCurrentUser();
+ const { activeOrganization } = useDashboardContext();
const queryClient = useQueryClient();
const currentDestinationId =
item.type === "videos" ? item.currentFolderId : item.currentParentId;
const [selectedFolderId, setSelectedFolderId] =
useState<FolderDomain.FolderId | null>(currentDestinationId);
+ const sourceLocationKey = moveLocationKey(location);
+ const [selectedLocationKey, setSelectedLocationKey] =
+ useState(sourceLocationKey);
+ const ownedVideos = item.type === "videos" && location.type === "personal";
const [search, setSearch] = useState("");
useEffect(() => {
if (!open) return;
setSelectedFolderId(currentDestinationId);
+ setSelectedLocationKey(sourceLocationKey);
setSearch("");
- }, [currentDestinationId, open]);
+ }, [currentDestinationId, open, sourceLocationKey]);
const destinations = useQuery({
- queryKey: ["move-folder-destinations", moveLocationKey(location)],
- queryFn: () => getMoveFolderDestinations(location),
+ queryKey: [
+ "move-folder-destinations",
+ sourceLocationKey,
+ user?.id,
+ organizationId ?? activeOrganization?.organization.id,
+ ownedVideos,
+ ],
+ queryFn: async (): Promise<MoveDestinationGroup[]> =>
+ ownedVideos
+ ? getOwnedVideoMoveDestinations()
+ : [
+ {
+ location,
+ name: rootLabel,
+ folders: await getMoveFolderDestinations(location),
+ },
+ ],
enabled: open,
staleTime: 30_000,
});
+ const selectedGroup = destinations.data?.find(
+ (group) => moveLocationKey(group.location) === selectedLocationKey,
+ );
+ const sameLocation = selectedLocationKey === sourceLocationKey;
const rows = useMemo(
() =>
buildMoveFolderDestinationRows(
- destinations.data ?? [],
+ selectedGroup?.folders ?? [],
item.type === "folder" ? item.folderId : undefined,
),
- [destinations.data, item],
+ [selectedGroup, item],
);
const normalizedSearch = search.trim().toLocaleLowerCase();
const filteredRows = useMemo(
@@ -100,10 +137,12 @@ export function MoveItemsDialog({
const moveMutation = useMutation({
mutationFn: async () => {
if (item.type === "videos") {
- await moveVideos({
+ const move = ownedVideos ? placeOwnedVideos : moveVideos;
+ if (!selectedGroup) throw new Error("Select a destination");
+ await move({
videoIds: item.videoIds,
folderId: selectedFolderId,
- location,
+ location: selectedGroup.location,
});
return;
}
@@ -119,7 +158,7 @@ export function MoveItemsDialog({
toast.success(
item.type === "folder"
? "Folder moved"
- : `${count} Cap${count === 1 ? "" : "s"} moved`,
+ : `${count} Cap${count === 1 ? "" : "s"} ${sameLocation ? "moved" : `added to ${selectedGroup?.name}`}`,
);
onMoved?.();
if (item.type === "folder") {
@@ -140,7 +179,9 @@ export function MoveItemsDialog({
item.type === "folder"
? "Move folder"
: `Move ${itemCount} Cap${itemCount === 1 ? "" : "s"}`;
- const destinationChanged = selectedFolderId !== currentDestinationId;
+ const destinationChanged =
+ !sameLocation || selectedFolderId !== currentDestinationId;
+ const sharing = !sameLocation && selectedGroup?.location.type !== "personal";
return (
<Dialog
@@ -155,6 +196,40 @@ export function MoveItemsDialog({
</DialogHeader>
<div className="flex overflow-hidden flex-col flex-1 gap-3 p-5 min-h-0">
+ {ownedVideos && destinations.data && (
+ <label className="flex flex-col gap-2 text-sm text-gray-12">
+ Location
+ <select
+ value={selectedLocationKey}
+ disabled={moveMutation.isPending}
+ onChange={(event) => {
+ const key = event.target.value;
+ setSelectedLocationKey(key);
+ setSelectedFolderId(
+ key === sourceLocationKey ? currentDestinationId : null,
+ );
+ setSearch("");
+ }}
+ className="h-10 rounded-lg border border-gray-4 bg-gray-1 px-3"
+ >
+ {destinations.data.map((group) => (
+ <option
+ key={moveLocationKey(group.location)}
+ value={moveLocationKey(group.location)}
+ >
+ {group.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {sharing && (
+ <p className="text-sm text-gray-11">
+ People with access to {selectedGroup?.name} will be able to view
+ these Caps. Existing sharing and their location in My Caps will be
+ kept.
+ </p>
+ )}
<div className="relative shrink-0">
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 pointer-events-none text-gray-9" />
<Input
@@ -185,31 +260,36 @@ export function MoveItemsDialog({
<div className="py-1">
<button
type="button"
- disabled={currentDestinationId === null}
+ disabled={
+ moveMutation.isPending ||
+ (sameLocation && currentDestinationId === null)
+ }
onClick={() => setSelectedFolderId(null)}
className={clsx(
"flex gap-3 items-center px-3 w-full h-11 text-left transition-colors",
- currentDestinationId === null
+ sameLocation && currentDestinationId === null
? "cursor-not-allowed opacity-50"
: "hover:bg-gray-3",
selectedFolderId === null &&
- currentDestinationId !== null &&
+ (!sameLocation || currentDestinationId !== null) &&
"bg-blue-3",
)}
>
<FolderRoot className="shrink-0 size-4 text-gray-10" />
<span className="flex-1 min-w-0 text-sm truncate text-gray-12">
- {rootLabel}
+ {selectedGroup?.name ?? rootLabel}
</span>
{selectedFolderId === null &&
- currentDestinationId !== null && (
+ (!sameLocation || currentDestinationId !== null) && (
<Check className="shrink-0 size-4 text-blue-10" />
)}
</button>
{filteredRows.map((row) => {
- const isCurrent = row.id === currentDestinationId;
- const isDisabled = row.disabled || isCurrent;
+ const isCurrent =
+ sameLocation && row.id === currentDestinationId;
+ const isDisabled =
+ moveMutation.isPending || row.disabled || isCurrent;
const isSelected = row.id === selectedFolderId && !isCurrent;
return (
@@ -272,13 +352,18 @@ export function MoveItemsDialog({
spinner={moveMutation.isPending}
disabled={
!destinationChanged ||
+ !selectedGroup ||
destinations.isLoading ||
destinations.isError ||
moveMutation.isPending
}
onClick={() => moveMutation.mutate()}
>
- {moveMutation.isPending ? "Moving..." : "Move"}
+ {moveMutation.isPending
+ ? "Saving..."
+ : sharing
+ ? "Share & move"
+ : "Move"}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
index 60607606a..c9b5cb786 100644
--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
@@ -29,6 +29,7 @@ import {
Clock,
Copy,
Download,
+ FolderInput,
Globe2,
Lock,
MousePointer2,
@@ -91,6 +92,13 @@ const SharingDialog = dynamic(
),
{ ssr: false },
);
+const MoveItemsDialog = dynamic(
+ () =>
+ import("@/app/(org)/dashboard/caps/components/MoveItemsDialog").then(
+ (m) => m.MoveItemsDialog,
+ ),
+ { ssr: false },
+);
const SettingsDialog = dynamic(
() =>
import("@/app/(org)/dashboard/caps/components/SettingsDialog").then(
@@ -155,6 +163,7 @@ export const ShareHeader = ({
branding,
canManageSharePageBranding = false,
canDownload = false,
+ canMoveToFolder = false,
hasEdits = false,
views,
dashboardDestination = null,
@@ -186,6 +195,7 @@ export const ShareHeader = ({
branding?: SharePageBranding | null;
canManageSharePageBranding?: boolean;
canDownload?: boolean;
+ canMoveToFolder?: boolean;
hasEdits?: boolean;
/**
* Shown to every viewer, not just the owner. The sidebar's analytics row is
@@ -202,6 +212,8 @@ export const ShareHeader = ({
queryKey: ["videoStatus", data.id],
queryFn: skipToken,
});
+ const [moveDialogOpen, setMoveDialogOpen] = useState(false);
+ const [moveDialogMounted, setMoveDialogMounted] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [displayTitle, setDisplayTitle] = useState(data.name);
const [editValue, setEditValue] = useState(data.name);
@@ -867,6 +879,20 @@ export const ShareHeader = ({
)}
{isOwner && (
<>
+ {moveDialogMounted && (
+ <MoveItemsDialog
+ open={moveDialogOpen}
+ onOpenChange={setMoveDialogOpen}
+ location={{ type: "personal" }}
+ rootLabel="My Caps"
+ organizationId={data.orgId ?? undefined}
+ item={{
+ type: "videos",
+ videoIds: [data.id],
+ currentFolderId: data.folderId,
+ }}
+ />
+ )}
{settingsDialogMounted && (
<SettingsDialog
isOpen={isSettingsDialogOpen}
@@ -1173,6 +1199,20 @@ export const ShareHeader = ({
Sharing & access
</p>
</DropdownMenuItem>
+ {canMoveToFolder && (
+ <DropdownMenuItem
+ onClick={() => {
+ setMoveDialogMounted(true);
+ setMoveDialogOpen(true);
+ }}
+ className="flex items-center gap-2 rounded-lg"
+ >
+ <FolderInput className="size-3" />
+ <p className="text-sm text-gray-12">
+ Move to folder
+ </p>
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
onClick={() => setIsSettingsDialogOpen(true)}
className="flex items-center gap-2 rounded-lg"
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 9805a60e6..1a7148e43 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -344,6 +344,7 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {
db()
.select({
id: videos.id,
+ folderId: videos.folderId,
name: videos.name,
orgId: videos.orgId,
createdAt: videos.createdAt,
@@ -440,7 +441,7 @@ async function AuthorizedContent({
}: {
video: Omit<
InferSelectModel<typeof videos>,
- "folderId" | "password" | "settings" | "ownerId"
+ "password" | "settings" | "ownerId"
> & {
owner: InferSelectModel<typeof users>;
sharedOrganization: { organizationId: Organisation.OrganisationId } | null;
@@ -897,7 +898,7 @@ async function AuthorizedContent({
},
sharedOrganizations: sharedOrganizations,
password: null,
- folderId: null,
+ folderId: user?.id === video.owner.id ? video.folderId : null,
orgSettings: video.orgSettings || null,
organizationName: video.organizationName,
organizationIconUrl: resolvedImages.organization,
@@ -943,6 +944,10 @@ async function AuthorizedContent({
<Share
header={
<ShareHeader
+ canMoveToFolder={
+ user?.id === video.owner.id &&
+ user?.activeOrganizationId === video.orgId
+ }
data={{
...videoWithOrganizationInfo,
createdAt: video.metadata?.customCreatedAt
diff --git a/apps/web/lib/move-items.ts b/apps/web/lib/move-items.ts
index 52814884e..e4dc88451 100644
--- a/apps/web/lib/move-items.ts
+++ b/apps/web/lib/move-items.ts
@@ -13,6 +13,12 @@ export type MoveFolderDestination = {
parentId: Folder.FolderId | null;
};
+export type MoveDestinationGroup = {
+ location: MoveLocation;
+ name: string;
+ folders: MoveFolderDestination[];
+};
+
export type MoveFolderDestinationRow = MoveFolderDestination & {
depth: number;
path: string;