Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(dashboard): wire public collection into space dialogs

Richie McIlroy60bde1040c87
diff --git a/apps/web/actions/organization/create-space.ts b/apps/web/actions/organization/create-space.ts
index 032e9e4c4..40b2107e4 100644
--- a/apps/web/actions/organization/create-space.ts
+++ b/apps/web/actions/organization/create-space.ts
@@ -8,6 +8,7 @@ import { spaceMembers, spaces } from "@cap/database/schema";
import { userIsPro } from "@cap/utils";
import {
type ImageUpload,
+ Organisation,
Space,
SpaceMemberId,
type SpaceMemberRole,
@@ -15,6 +16,7 @@ import {
} from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import { isOrganizationOwnerPro } from "@/lib/org-pro";
import {
getSpaceSettingsFromFormData,
hasProSpaceSettingsEnabled,
@@ -45,6 +47,7 @@ export async function createSpace(
const name = formData.get("name") as string;
const passwordEnabled = formData.get("passwordEnabled") === "true";
const password = formData.get("password") as string | null;
+ const publicEnabled = formData.get("public") === "true";
const settings = getSpaceSettingsFromFormData(formData);
const canUseProFeatures = userIsPro(user);
@@ -76,6 +79,18 @@ export async function createSpace(
};
}
+ if (
+ publicEnabled &&
+ !(await isOrganizationOwnerPro(
+ Organisation.OrganisationId.make(user.activeOrganizationId),
+ ))
+ ) {
+ return {
+ success: false,
+ error: "Upgrade to Cap Pro to create a public collection link",
+ };
+ }
+
const existingSpace = await db()
.select({ id: spaces.id })
.from(spaces)
@@ -110,6 +125,7 @@ export async function createSpace(
iconUrl: null,
settings,
password: hashedPassword,
+ public: publicEnabled,
});
const memberUserIds: string[] = [];
diff --git a/apps/web/actions/organization/update-space.ts b/apps/web/actions/organization/update-space.ts
index 9dd84e615..b1caba2a6 100644
--- a/apps/web/actions/organization/update-space.ts
+++ b/apps/web/actions/organization/update-space.ts
@@ -13,9 +13,10 @@ import {
type SpaceMemberRole,
type User,
} from "@cap/web-domain";
-import { eq } from "drizzle-orm";
+import { eq, type SQL, sql } from "drizzle-orm";
import { Effect, Option } from "effect";
import { revalidatePath } from "next/cache";
+import { isOrganizationOwnerPro } from "@/lib/org-pro";
import { normalizeSpaceRole } from "@/lib/permissions/roles";
import { runPromise } from "@/lib/server";
import { requireSpaceManager } from "./space-authorization";
@@ -39,12 +40,17 @@ export async function updateSpace(formData: FormData) {
| "remove"
| null;
const password = formData.get("password") as string | null;
+ // Only touch the public flag when the form actually submitted it — callers
+ // that omit the field must not silently un-publish the space.
+ const publicField = formData.get("public");
+ const publicEnabled = publicField === "true";
const [space] = await db()
.select({
createdById: spaces.createdById,
organizationId: spaces.organizationId,
settings: spaces.settings,
+ public: spaces.public,
})
.from(spaces)
.where(eq(spaces.id, id))
@@ -59,16 +65,40 @@ export async function updateSpace(formData: FormData) {
return { success: false, error: "Unauthorized" };
}
+ // Publishing is gated on the org owner's plan, but a downgraded org can
+ // always un-publish — so only the false→true transition requires Pro.
+ if (
+ publicEnabled &&
+ !space.public &&
+ !(await isOrganizationOwnerPro(space.organizationId))
+ ) {
+ return {
+ success: false,
+ error: "Upgrade to Cap Pro to create a public collection link",
+ };
+ }
+
const submittedSettings = getSpaceSettingsFromFormData(formData);
const canUseProFeatures = userIsPro(user);
- const settings = canUseProFeatures
+ const viewerSettings = canUseProFeatures
? submittedSettings
: preserveProSpaceSettings(submittedSettings, space.settings);
+ // Atomic per-key merge: the form submits every viewer-settings key
+ // explicitly, while settings.publicPage (managed by the visibility/logo
+ // actions, possibly concurrently) is left untouched instead of being
+ // rewritten from a stale snapshot.
const spaceUpdate: {
name: string;
- settings: ReturnType<typeof getSpaceSettingsFromFormData>;
+ settings: SQL;
+ public?: boolean;
password?: string | null;
- } = { name, settings };
+ } = {
+ name,
+ settings: sql`JSON_MERGE_PATCH(COALESCE(${spaces.settings}, '{}'), CAST(${JSON.stringify(
+ viewerSettings,
+ )} AS JSON))`,
+ };
+ if (publicField !== null) spaceUpdate.public = publicEnabled;
if (passwordAction === "set") {
if (!canUseProFeatures) {
@@ -144,5 +174,6 @@ export async function updateSpace(formData: FormData) {
revalidatePath("/dashboard");
revalidatePath("/dashboard/caps");
revalidatePath(`/dashboard/spaces/${id}`);
+ revalidatePath(`/c/${id}`);
return { success: true };
}
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
index 117a6a2bc..ed5f51eda 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
@@ -16,11 +16,7 @@ import {
Switch,
} from "@cap/ui";
import type { ImageUpload } from "@cap/web-domain";
-import {
- faGear,
- faLayerGroup,
- faLock,
-} from "@fortawesome/free-solid-svg-icons";
+import { faLayerGroup, faLock } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
@@ -34,6 +30,7 @@ import { FileInput } from "@/components/FileInput";
import { useDashboardContext } from "../../Contexts";
import type { OrganizationSettings } from "../../dashboard-data";
import { MemberSelect } from "../../spaces/[spaceId]/components/MemberSelect";
+import { PublicCollectionField } from "../PublicCollectionField";
import { createSpace } from "./server";
interface SpaceDialogProps {
@@ -47,6 +44,7 @@ interface SpaceDialogProps {
iconUrl?: ImageUpload.ImageUrl;
settings?: OrganizationSettings | null;
hasPassword?: boolean;
+ public?: boolean;
} | null;
onSpaceUpdated?: () => void;
}
@@ -68,20 +66,20 @@ const SpaceDialog = ({
return (
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
- <DialogContent className="p-0 w-[calc(100%-20px)] max-w-md rounded-xl border bg-gray-2 border-gray-4">
+ <DialogContent className="p-0 w-[calc(100%-20px)] max-w-2xl rounded-xl border bg-gray-2 border-gray-4">
<DialogHeader
icon={<FontAwesomeIcon icon={faLayerGroup} />}
description={
edit
- ? "Edit your space details"
- : "A new space for your team to collaborate"
+ ? "Manage details, sharing and viewer permissions."
+ : "Set up a space for your team to collaborate."
}
>
<DialogTitle className="text-lg text-gray-12">
{edit ? "Edit Space" : "Create New Space"}
</DialogTitle>
</DialogHeader>
- <div className="p-5 max-h-[70vh] overflow-y-auto">
+ <div className="px-6 py-5 max-h-[70vh] overflow-y-auto">
<NewSpaceForm
formRef={formRef}
setCreateLoading={setIsSubmitting}
@@ -129,6 +127,7 @@ export interface NewSpaceFormProps {
iconUrl?: ImageUpload.ImageUrl;
settings?: OrganizationSettings | null;
hasPassword?: boolean;
+ public?: boolean;
} | null;
}
@@ -225,12 +224,14 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
const [passwordEnabled, setPasswordEnabled] = useState(
Boolean(space?.hasPassword),
);
+ const [publicEnabled, setPublicEnabled] = useState(Boolean(space?.public));
const [passwordValue, setPasswordValue] = useState("");
const iconInputId = useId();
useEffect(() => {
setSettings({ ...defaultSettings, ...space?.settings });
setPasswordEnabled(Boolean(space?.hasPassword));
+ setPublicEnabled(Boolean(space?.public));
setPasswordValue("");
}, [space]);
@@ -308,6 +309,7 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
}
formData.append("passwordEnabled", String(passwordEnabled));
+ formData.append("public", String(publicEnabled));
if (passwordEnabled && passwordValue.trim()) {
formData.append("password", passwordValue.trim());
@@ -376,117 +378,158 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
}
})}
>
- <div className="space-y-4">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormControl>
- <Input
- placeholder="Space name"
- maxLength={25}
- {...field}
- onChange={(e) => {
- field.onChange(e);
- props.onNameChange?.(e.target.value);
- }}
+ <div className="space-y-7">
+ {/* Details */}
+ <section className="space-y-3">
+ <SectionLabel
+ title="Details"
+ description="Name your space and choose who belongs in it."
+ />
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2 md:items-start">
+ <div className="space-y-4">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormControl>
+ <Input
+ placeholder="Space name"
+ maxLength={25}
+ {...field}
+ onChange={(e) => {
+ field.onChange(e);
+ props.onNameChange?.(e.target.value);
+ }}
+ />
+ </FormControl>
+ )}
/>
- </FormControl>
- )}
- />
- {/* Space Members Input */}
- <div className="space-y-1">
- <Label htmlFor="members">Members</Label>
- <CardDescription className="w-full max-w-[400px]">
- Add team members to this space.
- </CardDescription>
- </div>
- <FormField
- control={form.control}
- name="members"
- render={({ field }) => {
- return (
- <FormControl>
- <MemberSelect
- placeholder="Add member..."
- showEmptyIfNoMembers={false}
+ <div className="space-y-2">
+ <div className="space-y-1">
+ <Label htmlFor={iconInputId}>Space icon</Label>
+ <CardDescription>
+ Custom logo or icon (max 1MB).
+ </CardDescription>
+ </div>
+ <FileInput
+ id={iconInputId}
+ name="icon"
+ initialPreviewUrl={space?.iconUrl || null}
+ notDraggingClassName="hover:bg-gray-3"
+ onChange={handleFileChange}
disabled={isUploading}
- canManageMembers={true}
- selected={(activeOrganization?.members ?? [])
- .filter((m) => (field.value ?? []).includes(m.user.id))
- .map((m) => ({
- value: m.user.id,
- label: m.user.name || m.user.email,
- image: m.user.image ?? undefined,
- }))}
- onSelect={(selected) =>
- field.onChange(selected.map((opt) => opt.value))
- }
- />
- </FormControl>
- );
- }}
- />
-
- <div className="space-y-3 rounded-xl border border-gray-4 bg-gray-1 p-3">
- <div className="flex items-start justify-between gap-4">
- <div className="flex gap-3">
- <div className="flex size-8 items-center justify-center rounded-full bg-gray-3">
- <FontAwesomeIcon
- icon={faLock}
- className="size-3 text-gray-11"
+ isLoading={isUploading}
/>
</div>
- <div>
- <p className="text-sm font-medium text-gray-12">
- Require password
- </p>
- <p className="text-xs text-gray-10">
- All caps in this space require this password
- </p>
+ </div>
+
+ <div className="space-y-2">
+ <div className="space-y-1">
+ <Label htmlFor="members">Members</Label>
+ <CardDescription>
+ Add team members to this space.
+ </CardDescription>
</div>
+ <FormField
+ control={form.control}
+ name="members"
+ render={({ field }) => (
+ <FormControl>
+ <MemberSelect
+ placeholder="Add member..."
+ showEmptyIfNoMembers={false}
+ disabled={isUploading}
+ canManageMembers={true}
+ selected={(activeOrganization?.members ?? [])
+ .filter((m) =>
+ (field.value ?? []).includes(m.user.id),
+ )
+ .map((m) => ({
+ value: m.user.id,
+ label: m.user.name || m.user.email,
+ image: m.user.image ?? undefined,
+ }))}
+ onSelect={(selected) =>
+ field.onChange(selected.map((opt) => opt.value))
+ }
+ />
+ </FormControl>
+ )}
+ />
</div>
- <Switch
- checked={passwordEnabled}
- onCheckedChange={handlePasswordToggle}
- />
</div>
- {passwordEnabled && (
- <div className="space-y-1">
- <Input
- type="password"
- value={passwordValue}
- onChange={(e) => setPasswordValue(e.target.value)}
- placeholder={
- space?.hasPassword ? "Enter new password" : "Set a password"
- }
- />
- {space?.hasPassword && !passwordValue && (
- <p className="text-xs text-gray-9">
- Leave blank to keep existing password
- </p>
+ </section>
+
+ {/* Sharing */}
+ <section className="space-y-3">
+ <SectionLabel
+ title="Sharing"
+ description="Control how this space can be reached."
+ />
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2 md:items-start">
+ <PublicCollectionField
+ kind="space"
+ enabled={publicEnabled}
+ onChange={setPublicEnabled}
+ isPro={Boolean(activeOrganization?.ownerIsPro)}
+ onUpgrade={() => setUpgradeModalOpen(true)}
+ collectionId={edit && space?.id ? space.id : undefined}
+ />
+
+ <div className="rounded-xl border border-gray-4 bg-gray-1">
+ <div className="flex gap-3 justify-between items-center p-3.5">
+ <div className="flex gap-3 items-center min-w-0">
+ <div className="flex justify-center items-center rounded-full size-9 bg-gray-3 shrink-0">
+ <FontAwesomeIcon
+ icon={faLock}
+ className="size-3.5 text-gray-11"
+ />
+ </div>
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-gray-12">
+ Require password
+ </p>
+ <p className="text-xs text-gray-10">
+ Protect every cap in this space
+ </p>
+ </div>
+ </div>
+ <Switch
+ checked={passwordEnabled}
+ onCheckedChange={handlePasswordToggle}
+ />
+ </div>
+ {passwordEnabled && (
+ <div className="px-3.5 pb-3.5 space-y-1">
+ <Input
+ type="password"
+ value={passwordValue}
+ onChange={(e) => setPasswordValue(e.target.value)}
+ placeholder={
+ space?.hasPassword
+ ? "Enter new password"
+ : "Set a password"
+ }
+ />
+ {space?.hasPassword && !passwordValue && (
+ <p className="text-xs text-gray-9">
+ Leave blank to keep existing password
+ </p>
+ )}
+ </div>
)}
</div>
- )}
- </div>
-
- <div className="space-y-3 rounded-xl border border-gray-4 bg-gray-1 p-3">
- <div className="flex gap-3">
- <div className="flex size-8 items-center justify-center rounded-full bg-gray-3">
- <FontAwesomeIcon
- icon={faGear}
- className="size-3 text-gray-11"
- />
- </div>
- <div>
- <p className="text-sm font-medium text-gray-12">Viewer rules</p>
- <p className="text-xs text-gray-10">
- These apply to every cap in this space
- </p>
- </div>
</div>
- <div className="grid grid-cols-1 gap-2">
+ </section>
+
+ {/* Viewer permissions */}
+ <section className="space-y-3">
+ <SectionLabel
+ title="Viewer permissions"
+ description="These apply to every cap shared in this space."
+ />
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
{settingOptions.map((option) => {
const disabled =
(option.pro && !user?.isPro) ||
@@ -497,15 +540,15 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
return (
<div
key={option.value}
- className="flex items-center justify-between gap-4 rounded-lg border border-gray-3 bg-gray-2 p-3"
+ className="flex gap-3 justify-between items-center p-3 rounded-lg border border-gray-4 bg-gray-1"
>
<div>
- <div className="flex items-center gap-1.5">
+ <div className="flex gap-1.5 items-center">
<p className="text-sm text-gray-12">{option.label}</p>
{option.pro && (
- <p className="rounded-full bg-blue-11 px-1.5 py-1 text-[10px] font-medium leading-none text-white">
+ <span className="rounded-full bg-blue-11 px-1.5 py-0.5 text-[10px] font-medium leading-none text-white">
Pro
- </p>
+ </span>
)}
</div>
<p className="text-xs text-gray-10">
@@ -521,30 +564,30 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
);
})}
</div>
- </div>
-
- <div className="space-y-1">
- <Label htmlFor={iconInputId}>Space Icon</Label>
- <CardDescription className="w-full max-w-[400px]">
- Upload a custom logo or icon for your space (max 1MB).
- </CardDescription>
- </div>
-
- <div className="relative mt-2">
- <FileInput
- id={iconInputId}
- name="icon"
- initialPreviewUrl={space?.iconUrl || null}
- notDraggingClassName="hover:bg-gray-3"
- onChange={handleFileChange}
- disabled={isUploading}
- isLoading={isUploading}
- />
- </div>
+ </section>
</div>
</form>
</Form>
);
};
+function SectionLabel({
+ title,
+ description,
+}: {
+ title: string;
+ description?: string;
+}) {
+ return (
+ <div>
+ <p className="text-[11px] font-medium tracking-wide uppercase text-gray-9">
+ {title}
+ </p>
+ {description && (
+ <p className="mt-0.5 text-xs text-gray-10">{description}</p>
+ )}
+ </div>
+ );
+}
+
export default SpaceDialog;