Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

web: use icon keys instead of urls (#1259)

Ameer Al Ashhabbc21c3f87978
diff --git a/apps/web/actions/account/remove-profile-image.ts b/apps/web/actions/account/remove-profile-image.ts
index 268bf7b02..6689ab9dc 100644
--- a/apps/web/actions/account/remove-profile-image.ts
+++ b/apps/web/actions/account/remove-profile-image.ts
@@ -1,10 +1,14 @@
"use server";
+import path from "node:path";
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { users } from "@cap/database/schema";
+import { S3Buckets } from "@cap/web-backend";
import { eq } from "drizzle-orm";
+import { Effect, Option } from "effect";
import { revalidatePath } from "next/cache";
+import { runPromise } from "@/lib/server";
export async function removeProfileImage() {
const user = await getCurrentUser();
@@ -13,10 +17,50 @@ export async function removeProfileImage() {
throw new Error("Unauthorized");
}
+ const image = user.image;
+
+ // Delete the profile image from S3 if it exists
+ if (image) {
+ try {
+ // Extract the S3 key - handle both old URL format and new key format
+ let s3Key = image;
+ if (image.startsWith("http://") || image.startsWith("https://")) {
+ const url = new URL(image);
+ // Only extract key from URLs with amazonaws.com hostname
+ if (
+ url.hostname.endsWith(".amazonaws.com") ||
+ url.hostname === "amazonaws.com"
+ ) {
+ const raw = url.pathname.startsWith("/")
+ ? url.pathname.slice(1)
+ : url.pathname;
+ const decoded = decodeURIComponent(raw);
+ const normalized = path.posix.normalize(decoded);
+ if (normalized.includes("..")) {
+ throw new Error("Invalid S3 key path");
+ }
+ s3Key = normalized;
+ } else {
+ // Not an S3 URL, skip deletion of S3 object; continue with DB update below
+ }
+ }
+
+ // Only delete if it looks like a user profile image key
+ if (s3Key.startsWith("users/")) {
+ await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
+ yield* bucket.deleteObject(s3Key);
+ }).pipe(runPromise);
+ }
+ } catch (error) {
+ console.error("Error deleting profile image from S3:", error);
+ // Continue with database update even if S3 deletion fails
+ }
+ }
+
await db().update(users).set({ image: null }).where(eq(users.id, user.id));
revalidatePath("/dashboard/settings/account");
- revalidatePath("/dashboard", "layout");
return { success: true } as const;
}
diff --git a/apps/web/actions/account/upload-profile-image.ts b/apps/web/actions/account/upload-profile-image.ts
index f445937ea..74c2f6c60 100644
--- a/apps/web/actions/account/upload-profile-image.ts
+++ b/apps/web/actions/account/upload-profile-image.ts
@@ -4,7 +4,6 @@ import { randomUUID } from "node:crypto";
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { users } from "@cap/database/schema";
-import { serverEnv } from "@cap/env";
import { S3Buckets } from "@cap/web-backend";
import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
@@ -43,15 +42,50 @@ export async function uploadProfileImage(formData: FormData) {
throw new Error("File size must be 3MB or less");
}
+ // Get the old profile image to delete it later
+ const oldImageUrlOrKey = user.image;
+
const fileKey = `users/${user.id}/profile-${Date.now()}-${randomUUID()}.${fileExtension}`;
try {
const sanitizedFile = await sanitizeFile(file);
- let imageUrl: string | undefined;
+ let image: string | null = null;
await Effect.gen(function* () {
const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
+ // Delete old profile image if it exists
+ if (oldImageUrlOrKey) {
+ try {
+ // Extract the S3 key - handle both old URL format and new key format
+ let oldS3Key = oldImageUrlOrKey;
+ if (
+ oldImageUrlOrKey.startsWith("http://") ||
+ oldImageUrlOrKey.startsWith("https://")
+ ) {
+ const url = new URL(oldImageUrlOrKey);
+ // Only extract key from URLs with amazonaws.com hostname
+ if (
+ url.hostname.endsWith(".amazonaws.com") ||
+ url.hostname === "amazonaws.com"
+ ) {
+ oldS3Key = url.pathname.substring(1); // Remove leading slash
+ } else {
+ // Not an S3 URL, skip deletion
+ return;
+ }
+ }
+
+ // Only delete if it looks like a user profile image key
+ if (oldS3Key.startsWith("users/")) {
+ yield* bucket.deleteObject(oldS3Key);
+ }
+ } catch (error) {
+ console.error("Error deleting old profile image from S3:", error);
+ // Continue with upload even if deletion fails
+ }
+ }
+
const bodyBytes = yield* Effect.promise(async () => {
const buf = await sanitizedFile.arrayBuffer();
return new Uint8Array(buf);
@@ -61,32 +95,23 @@ export async function uploadProfileImage(formData: FormData) {
contentType: file.type,
});
- if (serverEnv().CAP_AWS_BUCKET_URL) {
- imageUrl = `${serverEnv().CAP_AWS_BUCKET_URL}/${fileKey}`;
- } else if (serverEnv().CAP_AWS_ENDPOINT) {
- imageUrl = `${serverEnv().CAP_AWS_ENDPOINT}/${bucket.bucketName}/${fileKey}`;
- } else {
- imageUrl = `https://${bucket.bucketName}.s3.${
- serverEnv().CAP_AWS_REGION || "us-east-1"
- }.amazonaws.com/${fileKey}`;
- }
+ image = fileKey;
}).pipe(runPromise);
- if (typeof imageUrl !== "string" || imageUrl.length === 0) {
- throw new Error("Failed to resolve uploaded profile image URL");
+ if (!image) {
+ throw new Error("Failed to resolve uploaded profile image key");
}
- const finalImageUrl = imageUrl;
+ const finalImageUrlOrKey = image;
await db()
.update(users)
- .set({ image: finalImageUrl })
+ .set({ image: finalImageUrlOrKey })
.where(eq(users.id, user.id));
revalidatePath("/dashboard/settings/account");
- revalidatePath("/dashboard", "layout");
- return { success: true, imageUrl: finalImageUrl } as const;
+ return { success: true, image: finalImageUrlOrKey } as const;
} catch (error) {
console.error("Error uploading profile image:", error);
throw new Error(error instanceof Error ? error.message : "Upload failed");
diff --git a/apps/web/actions/organization/create-space.ts b/apps/web/actions/organization/create-space.ts
index d50b19348..940763e44 100644
--- a/apps/web/actions/organization/create-space.ts
+++ b/apps/web/actions/organization/create-space.ts
@@ -4,7 +4,6 @@ import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { nanoId, nanoIdLength } from "@cap/database/helpers";
import { spaceMembers, spaces, users } from "@cap/database/schema";
-import { serverEnv } from "@cap/env";
import { S3Buckets } from "@cap/web-backend";
import { Space } from "@cap/web-domain";
import { and, eq, inArray } from "drizzle-orm";
@@ -100,20 +99,7 @@ export async function createSpace(
yield* Effect.promise(() => iconFile.bytes()),
{ contentType: iconFile.type },
);
-
- // Construct the icon URL
- if (serverEnv().CAP_AWS_BUCKET_URL) {
- // If a custom bucket URL is defined, use it
- iconUrl = `${serverEnv().CAP_AWS_BUCKET_URL}/${fileKey}`;
- } else if (serverEnv().CAP_AWS_ENDPOINT) {
- // For custom endpoints like MinIO
- iconUrl = `${serverEnv().CAP_AWS_ENDPOINT}/${bucket.bucketName}/${fileKey}`;
- } else {
- // Default AWS S3 URL format
- iconUrl = `https://${bucket.bucketName}.s3.${
- serverEnv().CAP_AWS_REGION || "us-east-1"
- }.amazonaws.com/${fileKey}`;
- }
+ iconUrl = fileKey;
}).pipe(runPromise);
} catch (error) {
console.error("Error uploading space icon:", error);
@@ -124,18 +110,15 @@ export async function createSpace(
}
}
- await db()
- .insert(spaces)
- .values({
- id: spaceId,
- name,
- organizationId: user.activeOrganizationId,
- createdById: user.id,
- iconUrl,
- description: iconUrl ? `Space with custom icon: ${iconUrl}` : null,
- createdAt: new Date(),
- updatedAt: new Date(),
- });
+ await db().insert(spaces).values({
+ id: spaceId,
+ name,
+ organizationId: user.activeOrganizationId,
+ createdById: user.id,
+ iconUrl,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
// --- Member Management Logic ---
// Collect member emails from formData
diff --git a/apps/web/actions/organization/remove-icon.ts b/apps/web/actions/organization/remove-icon.ts
index 6eba5818c..b0c54b742 100644
--- a/apps/web/actions/organization/remove-icon.ts
+++ b/apps/web/actions/organization/remove-icon.ts
@@ -3,9 +3,12 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { organizations } from "@cap/database/schema";
+import { S3Buckets } from "@cap/web-backend";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
+import { Effect, Option } from "effect";
import { revalidatePath } from "next/cache";
+import { runPromise } from "@/lib/server";
export async function removeOrganizationIcon(
organizationId: Organisation.OrganisationId,
@@ -29,6 +32,39 @@ export async function removeOrganizationIcon(
throw new Error("Only the owner can remove the organization icon");
}
+ const iconUrl = organization[0]?.iconUrl;
+
+ // Delete the icon from S3 if it exists
+ if (iconUrl) {
+ try {
+ // Extract the S3 key - handle both old URL format and new key format
+ let s3Key = iconUrl;
+ if (iconUrl.startsWith("http://") || iconUrl.startsWith("https://")) {
+ const url = new URL(iconUrl);
+ // Only extract key from URLs with amazonaws.com hostname
+ if (
+ url.hostname.endsWith(".amazonaws.com") ||
+ url.hostname === "amazonaws.com"
+ ) {
+ s3Key = url.pathname.substring(1); // Remove leading slash
+ } else {
+ s3Key = "";
+ }
+ }
+
+ // Only delete if it looks like an organization icon key
+ if (s3Key.startsWith("organizations/")) {
+ await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
+ yield* bucket.deleteObject(s3Key);
+ }).pipe(runPromise);
+ }
+ } catch (error) {
+ console.error("Error deleting organization icon from S3:", error);
+ // Continue with database update even if S3 deletion fails
+ }
+ }
+
// Update organization to remove icon URL
await db()
.update(organizations)
diff --git a/apps/web/actions/organization/update-space.ts b/apps/web/actions/organization/update-space.ts
index 0fe974387..bc4805b2e 100644
--- a/apps/web/actions/organization/update-space.ts
+++ b/apps/web/actions/organization/update-space.ts
@@ -52,7 +52,10 @@ export async function updateSpace(formData: FormData) {
const spaceArr = await db().select().from(spaces).where(eq(spaces.id, id));
const space = spaceArr[0];
if (space?.iconUrl) {
- const key = space.iconUrl.match(/organizations\/.+/)?.[0];
+ // Extract the S3 key (it might already be a key or could be a legacy URL)
+ const key = space.iconUrl.startsWith("organizations/")
+ ? space.iconUrl
+ : space.iconUrl.match(/organizations\/.+/)?.[0];
if (key) {
try {
diff --git a/apps/web/actions/organization/upload-organization-icon.ts b/apps/web/actions/organization/upload-organization-icon.ts
index 83c535e31..77b468517 100644
--- a/apps/web/actions/organization/upload-organization-icon.ts
+++ b/apps/web/actions/organization/upload-organization-icon.ts
@@ -3,7 +3,6 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { organizations } from "@cap/database/schema";
-import { serverEnv } from "@cap/env";
import { S3Buckets } from "@cap/web-backend";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
@@ -52,39 +51,60 @@ export async function uploadOrganizationIcon(
throw new Error("File size must be less than 1MB");
}
+ // Get the old icon to delete it later
+ const oldIconUrlOrKey = organization[0]?.iconUrl;
+
// Create a unique file key
const fileExtension = file.name.split(".").pop();
const fileKey = `organizations/${organizationId}/icon-${Date.now()}.${fileExtension}`;
try {
const sanitizedFile = await sanitizeFile(file);
- let iconUrl: string | undefined;
await Effect.gen(function* () {
const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
+ // Delete old icon if it exists
+ if (oldIconUrlOrKey) {
+ try {
+ // Extract the S3 key - handle both old URL format and new key format
+ let oldS3Key = oldIconUrlOrKey;
+ if (
+ oldIconUrlOrKey.startsWith("http://") ||
+ oldIconUrlOrKey.startsWith("https://")
+ ) {
+ const url = new URL(oldIconUrlOrKey);
+ // Only extract key from URLs with amazonaws.com hostname
+ if (
+ url.hostname.endsWith(".amazonaws.com") ||
+ url.hostname === "amazonaws.com"
+ ) {
+ oldS3Key = url.pathname.substring(1); // Remove leading slash
+ } else {
+ return;
+ }
+ }
+
+ // Only delete if it looks like an organization icon key
+ if (oldS3Key.startsWith("organizations/")) {
+ yield* bucket.deleteObject(oldS3Key);
+ }
+ } catch (error) {
+ console.error("Error deleting old organization icon from S3:", error);
+ // Continue with upload even if deletion fails
+ }
+ }
+
const bodyBytes = yield* Effect.promise(async () => {
const buf = await sanitizedFile.arrayBuffer();
return new Uint8Array(buf);
});
yield* bucket.putObject(fileKey, bodyBytes, { contentType: file.type });
- // Construct the icon URL
- if (serverEnv().CAP_AWS_BUCKET_URL) {
- // If a custom bucket URL is defined, use it
- iconUrl = `${serverEnv().CAP_AWS_BUCKET_URL}/${fileKey}`;
- } else if (serverEnv().CAP_AWS_ENDPOINT) {
- // For custom endpoints like MinIO
- iconUrl = `${serverEnv().CAP_AWS_ENDPOINT}/${bucket.bucketName}/${fileKey}`;
- } else {
- // Default AWS S3 URL format
- iconUrl = `https://${bucket.bucketName}.s3.${
- serverEnv().CAP_AWS_REGION || "us-east-1"
- }.amazonaws.com/${fileKey}`;
- }
}).pipe(runPromise);
- // Update organization with new icon URL
+ const iconUrl = fileKey;
+
await db()
.update(organizations)
.set({ iconUrl })
diff --git a/apps/web/actions/organization/upload-space-icon.ts b/apps/web/actions/organization/upload-space-icon.ts
index 395d66802..891885914 100644
--- a/apps/web/actions/organization/upload-space-icon.ts
+++ b/apps/web/actions/organization/upload-space-icon.ts
@@ -65,8 +65,10 @@ export async function uploadSpaceIcon(
try {
// Remove previous icon if exists
if (space.iconUrl) {
- // Try to extract the previous S3 key from the URL
- const key = space.iconUrl.match(/organizations\/.+/)?.[0];
+ // Extract the S3 key (it might already be a key or could be a legacy URL)
+ const key = space.iconUrl.startsWith("organizations/")
+ ? space.iconUrl
+ : space.iconUrl.match(/organizations\/.+/)?.[0];
if (key) {
try {
await bucket.deleteObject(key).pipe(runPromise);
@@ -87,20 +89,8 @@ export async function uploadSpaceIcon(
)
.pipe(runPromise);
- let iconUrl: string | undefined;
-
- // Construct the icon URL
- if (serverEnv().CAP_AWS_BUCKET_URL) {
- iconUrl = `${serverEnv().CAP_AWS_BUCKET_URL}/${fileKey}`;
- } else if (serverEnv().CAP_AWS_ENDPOINT) {
- iconUrl = `${serverEnv().CAP_AWS_ENDPOINT}/${bucket.bucketName}/${fileKey}`;
- } else {
- iconUrl = `https://${bucket.bucketName}.s3.${
- serverEnv().CAP_AWS_REGION || "us-east-1"
- }.amazonaws.com/${fileKey}`;
- }
+ const iconUrl = fileKey;
- // Update space with new icon URL
await db().update(spaces).set({ iconUrl }).where(eq(spaces.id, spaceId));
revalidatePath("/dashboard");
diff --git a/apps/web/actions/videos/new-comment.ts b/apps/web/actions/videos/new-comment.ts
index 9f83404a9..742753e1f 100644
--- a/apps/web/actions/videos/new-comment.ts
+++ b/apps/web/actions/videos/new-comment.ts
@@ -67,7 +67,7 @@ export async function newComment(data: {
const commentWithAuthor = {
...newComment,
authorName: user.name,
- authorImage: user.image ?? null,
+ authorImageUrlOrKey: user.image ?? null,
sending: false,
};
diff --git a/apps/web/app/(org)/dashboard/_components/MobileTab.tsx b/apps/web/app/(org)/dashboard/_components/MobileTab.tsx
index b474227c5..ce1b469a9 100644
--- a/apps/web/app/(org)/dashboard/_components/MobileTab.tsx
+++ b/apps/web/app/(org)/dashboard/_components/MobileTab.tsx
@@ -1,11 +1,9 @@
"use client";
-import { Avatar } from "@cap/ui";
import { useClickAway } from "@uidotdev/usehooks";
import clsx from "clsx";
import { Check, ChevronDown } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
-import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
@@ -16,6 +14,7 @@ import {
useRef,
useState,
} from "react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { useDashboardContext } from "../Contexts";
import { CapIcon, CogIcon, LayersIcon } from "./AnimatedIcons";
import { updateActiveOrganization } from "./Navbar/server";
@@ -76,22 +75,13 @@ const Orgs = ({
ref={containerRef}
className="flex gap-1.5 items-center p-2 rounded-full border bg-gray-3 border-gray-5"
>
- {activeOrg?.organization.iconUrl ? (
- <div className="overflow-hidden relative flex-shrink-0 rounded-full size-[24px]">
- <Image
- src={activeOrg.organization.iconUrl}
- alt={activeOrg.organization.name || "Organization icon"}
- fill
- className="object-cover"
- />
- </div>
- ) : (
- <Avatar
- letterClass="text-xs"
- className="relative flex-shrink-0 mx-auto size-6"
- name={activeOrg?.organization.name ?? "No organization found"}
- />
- )}
+ <SignedImageUrl
+ image={activeOrg?.organization.iconUrl}
+ name={activeOrg?.organization.name ?? "No organization found"}
+ type="organization"
+ letterClass="text-xs"
+ className="relative flex-shrink-0 mx-auto size-6"
+ />
<p className="text-sm mr-2 text-gray-12 truncate w-fit max-w-[90px]">
{activeOrg?.organization.name}
</p>
@@ -145,22 +135,13 @@ const OrgsMenu = ({
}}
>
<div className="flex gap-2 items-center w-full">
- {organization.organization.iconUrl ? (
- <div className="overflow-hidden relative flex-shrink-0 rounded-full size-5">
- <Image
- src={organization.organization.iconUrl}
- alt={organization.organization.name || "Organization icon"}
- fill
- className="object-cover"
- />
- </div>
- ) : (
- <Avatar
- letterClass="text-xs"
- className="relative flex-shrink-0 size-5"
- name={organization.organization.name}
- />
- )}
+ <SignedImageUrl
+ image={organization.organization.iconUrl}
+ name={organization.organization.name}
+ type="organization"
+ letterClass="text-xs"
+ className="relative flex-shrink-0 size-5"
+ />
<p
className={clsx(
"flex-1 text-sm transition-colors duration-200 group-hover:text-gray-12",
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
index f0eaffb8f..4515df3fe 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
@@ -28,11 +28,11 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import { AnimatePresence, motion } from "framer-motion";
import { Check, ChevronDown, Plus } from "lucide-react";
-import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { cloneElement, type RefObject, useRef, useState } from "react";
import { NewOrganization } from "@/components/forms/NewOrganization";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
import { UsageButton } from "@/components/UsageButton";
import { useDashboardContext } from "../../Contexts";
@@ -122,37 +122,20 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {
)}
>
<div className="flex items-center">
- {activeOrg?.organization.iconUrl ? (
- <div
- className={clsx(
- "overflow-hidden relative flex-shrink-0 rounded-full",
- sidebarCollapsed ? "size-6" : "size-7",
- )}
- >
- <Image
- src={activeOrg.organization.iconUrl}
- alt={
- activeOrg.organization.name || "Organization icon"
- }
- fill
- className="object-cover"
- />
- </div>
- ) : (
- <Avatar
- letterClass={clsx(
- sidebarCollapsed ? "text-sm" : "text-[13px]",
- )}
- className={clsx(
- "relative flex-shrink-0 mx-auto",
- sidebarCollapsed ? "size-6" : "size-7",
- )}
- name={
- activeOrg?.organization.name ??
- "No organization found"
- }
- />
- )}
+ <SignedImageUrl
+ image={activeOrg?.organization.iconUrl}
+ name={
+ activeOrg?.organization.name ?? "No organization found"
+ }
+ type="organization"
+ letterClass={clsx(
+ sidebarCollapsed ? "text-sm" : "text-[13px]",
+ )}
+ className={clsx(
+ "relative flex-shrink-0 mx-auto",
+ sidebarCollapsed ? "size-6" : "size-7",
+ )}
+ />
</div>
<div className="flex flex-col flex-1 items-center h-10">
<div className="flex justify-between items-center w-full">
@@ -230,25 +213,13 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {
}}
>
<div className="flex gap-2 items-center w-full">
- {organization.organization.iconUrl ? (
- <div className="overflow-hidden relative flex-shrink-0 rounded-full size-5">
- <Image
- src={organization.organization.iconUrl}
- alt={
- organization.organization.name ||
- "Organization icon"
- }
- fill
- className="object-cover"
- />
- </div>
- ) : (
- <Avatar
- letterClass="text-xs"
- className="relative flex-shrink-0 size-5"
- name={organization.organization.name}
- />
- )}
+ <SignedImageUrl
+ image={organization.organization.iconUrl}
+ name={organization.organization.name}
+ type="organization"
+ letterClass="text-xs"
+ className="relative flex-shrink-0 size-5"
+ />
<p
className={clsx(
"flex-1 text-sm transition-colors duration-200 group-hover:text-gray-12",
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
index 1f4779a40..a8fb79804 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
@@ -17,12 +17,14 @@ import {
import { faLayerGroup } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
-import React, { useRef, useState } from "react";
+import type React from "react";
+import { useEffect, useId, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod";
import { updateSpace } from "@/actions/organization/update-space";
import { FileInput } from "@/components/FileInput";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { useDashboardContext } from "../../Contexts";
import { MemberSelect } from "../../spaces/[spaceId]/components/MemberSelect";
import { createSpace } from "./server";
@@ -51,10 +53,9 @@ const SpaceDialog = ({
const formRef = useRef<HTMLFormElement | null>(null);
const [spaceName, setSpaceName] = useState(space?.name || "");
- // Reset spaceName when dialog opens or space changes
- React.useEffect(() => {
+ useEffect(() => {
setSpaceName(space?.name || "");
- }, [space, open]);
+ }, [space]);
return (
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
@@ -141,7 +142,7 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
mode: "onChange",
});
- React.useEffect(() => {
+ useEffect(() => {
if (space) {
form.reset({
name: space.name,
@@ -255,7 +256,7 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
.map((m) => ({
value: m.user.id,
label: m.user.name || m.user.email,
- image: m.user.image || undefined,
+ image: m.user.image ?? undefined,
}))}
onSelect={(selected) =>
field.onChange(selected.map((opt) => opt.value))
@@ -275,8 +276,9 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
<div className="relative mt-2">
<FileInput
- id="icon"
+ id="space-icon"
name="icon"
+ type="organization"
initialPreviewUrl={space?.iconUrl || null}
notDraggingClassName="hover:bg-gray-3"
onChange={setSelectedFile}
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx
index 69bd0541d..8933d19b8 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Avatar, Button } from "@cap/ui";
+import { Button } from "@cap/ui";
import type { Space } from "@cap/web-domain";
import {
faLayerGroup,
@@ -11,13 +11,13 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import { AnimatePresence, motion } from "framer-motion";
import { ChevronDown, ChevronUp } from "lucide-react";
-import Image from "next/image";
import Link from "next/link";
import { useParams, usePathname, useRouter } from "next/navigation";
import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { shareCap } from "@/actions/caps/share";
import { deleteSpace } from "@/actions/organization/delete-space";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
import { useDashboardContext } from "../../Contexts";
import type { Spaces } from "../../dashboard-data";
@@ -279,26 +279,18 @@ const SpacesList = ({ toggleMobileNav }: { toggleMobileNav?: () => void }) => {
space.primary ? "h-10" : "h-fit",
)}
>
- {space.iconUrl ? (
- <Image
- src={space.iconUrl}
- alt={space.name}
- className="relative flex-shrink-0 rounded-full"
- width={sidebarCollapsed ? 24 : 20}
- height={sidebarCollapsed ? 24 : 20}
- />
- ) : (
- <Avatar
- letterClass={clsx(
- sidebarCollapsed ? "text-sm" : "text-[11px]",
- )}
- className={clsx(
- "relative flex-shrink-0",
- sidebarCollapsed ? "size-6" : "size-5",
- )}
- name={space.name}
- />
- )}
+ <SignedImageUrl
+ image={space.iconUrl}
+ name={space.name}
+ type="organization"
+ letterClass={clsx(
+ sidebarCollapsed ? "text-sm" : "text-[11px]",
+ )}
+ className={clsx(
+ "relative flex-shrink-0",
+ sidebarCollapsed ? "size-6" : "size-5",
+ )}
+ />
{!sidebarCollapsed && (
<>
<span className="ml-2.5 text-sm truncate transition-colors text-gray-11 group-hover:text-gray-12">
@@ -358,6 +350,10 @@ const SpacesList = ({ toggleMobileNav }: { toggleMobileNav?: () => void }) => {
<SpaceDialog
open={showSpaceDialog}
onClose={() => setShowSpaceDialog(false)}
+ onSpaceUpdated={() => {
+ router.refresh();
+ setShowSpaceDialog(false);
+ }}
/>
</div>
);
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
index 59bf7b4f7..c1bc6469b 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
@@ -2,7 +2,6 @@
import { buildEnv } from "@cap/env";
import {
- Avatar,
Command,
CommandGroup,
CommandItem,
@@ -17,7 +16,6 @@ import { useClickAway } from "@uidotdev/usehooks";
import clsx from "clsx";
import { AnimatePresence } from "framer-motion";
import { MoreVertical } from "lucide-react";
-import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { signOut } from "next-auth/react";
@@ -32,6 +30,7 @@ import {
} from "react";
import { markAsRead } from "@/actions/notifications/mark-as-read";
import Notifications from "@/app/(org)/dashboard/_components/Notifications";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { UpgradeModal } from "@/components/UpgradeModal";
import { useDashboardContext, useTheme } from "../../Contexts";
import {
@@ -101,22 +100,15 @@ const Top = () => {
<div className="flex flex-col gap-0.5">
{activeSpace && <span className="text-xs text-gray-11">Space</span>}
<div className="flex gap-1.5 items-center">
- {activeSpace &&
- (activeSpace.iconUrl ? (
- <Image
- src={activeSpace?.iconUrl}
- alt={activeSpace?.name || "Space"}
- width={20}
- height={20}
- className="rounded-full"
- />
- ) : (
- <Avatar
- letterClass="text-xs"
- className="relative flex-shrink-0 size-5"
- name={activeSpace?.name}
- />
- ))}
+ {activeSpace && (
+ <SignedImageUrl
+ image={activeSpace.iconUrl}
+ name={activeSpace?.name}
+ type="organization"
+ letterClass="text-xs"
+ className="relative flex-shrink-0 size-5"
+ />
+ )}
<p className="relative text-lg truncate text-gray-12 lg:text-2xl">
{title}
</p>
@@ -269,10 +261,11 @@ const User = () => {
className="flex gap-2 justify-between items-center p-2 rounded-xl border data-[state=open]:border-gray-3 data-[state=open]:bg-gray-3 border-transparent transition-colors cursor-pointer group lg:gap-6 hover:border-gray-3"
>
<div className="flex items-center">
- <Avatar
- letterClass="text-xs lg:text-md"
+ <SignedImageUrl
+ image={user.image}
name={user.name ?? "User"}
- imageUrl={user.image ?? undefined}
+ type="user"
+ letterClass="text-xs lg:text-md"
className="flex-shrink-0 size-[24px] text-gray-12"
/>
<span className="ml-2 text-sm truncate lg:ml-2 lg:text-md text-gray-12">
diff --git a/apps/web/app/(org)/dashboard/_components/Notifications/Skeleton.tsx b/apps/web/app/(org)/dashboard/_components/Notifications/Skeleton.tsx
index 444283dfc..16da8109d 100644
--- a/apps/web/app/(org)/dashboard/_components/Notifications/Skeleton.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Notifications/Skeleton.tsx
@@ -59,7 +59,7 @@ export const NotificationsSkeleton = ({ count = 5 }: { count?: number }) => {
<div>
{Array.from({ length: count }).map((_, i) => (
<NotificationItemSkeleton
- key={i}
+ key={i.toString()}
className={clsx(i !== count - 1 && "border-b border-gray-3")}
/>
))}
diff --git a/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
index b3d7c0ca5..5db9749c0 100644
--- a/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
@@ -16,12 +16,12 @@ import { useMutation } from "@tanstack/react-query";
import clsx from "clsx";
import { motion } from "framer-motion";
import { Check, Globe2, Search } from "lucide-react";
-import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { shareCap } from "@/actions/caps/share";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
import type { Spaces } from "@/app/(org)/dashboard/dashboard-data";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
interface SharingDialogProps {
@@ -262,9 +262,9 @@ export const SharingDialog: React.FC<SharingDialogProps> = ({
{activeTab === "Share" ? (
<>
{/* Public sharing toggle */}
- <div className="flex items-center justify-between p-3 mb-4 rounded-lg border bg-gray-1 border-gray-4">
- <div className="flex items-center gap-3">
- <div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-3">
+ <div className="flex justify-between items-center p-3 mb-4 rounded-lg border bg-gray-1 border-gray-4">
+ <div className="flex gap-3 items-center">
+ <div className="flex justify-center items-center w-8 h-8 rounded-full bg-gray-3">
<Globe2 className="w-4 h-4 text-gray-11" />
</div>
<div>
@@ -416,23 +416,13 @@ const SpaceCard = ({
)}
onClick={() => handleToggleSpace(space.id)}
>
- {space.iconUrl ? (
- <div className="overflow-hidden relative flex-shrink-0 rounded-full size-5">
- <Image
- src={space.iconUrl}
- alt={space.name}
- width={24}
- height={24}
- className="object-cover w-full h-full"
- />
- </div>
- ) : (
- <Avatar
- letterClass="text-[11px]"
- className="relative z-10 flex-shrink-0 size-5"
- name={space.name}
- />
- )}
+ <SignedImageUrl
+ image={space.iconUrl}
+ name={space.name}
+ type="organization"
+ letterClass="text-[11px]"
+ className="relative z-10 flex-shrink-0 size-5"
+ />
<p className="max-w-full text-xs truncate transition-colors duration-200 text-gray-10">
{space.name}
</p>
diff --git a/apps/web/app/(org)/dashboard/caps/loading.tsx b/apps/web/app/(org)/dashboard/caps/loading.tsx
index 0d5d06564..026044fa0 100644
--- a/apps/web/app/(org)/dashboard/caps/loading.tsx
+++ b/apps/web/app/(org)/dashboard/caps/loading.tsx
@@ -27,7 +27,7 @@ export default function Loading() {
.fill(0)
.map((_, index) => (
<Skeleton
- key={index}
+ key={index.toString()}
baseColor="var(--gray-4)"
highlightColor="var(--gray-5)"
className="!h-[72px] w-full !rounded-xl"
@@ -40,7 +40,7 @@ export default function Loading() {
.fill(0)
.map((_, index) => (
<div
- key={index}
+ key={index.toString()}
className="flex relative flex-col gap-4 w-full h-full bg-gray-3 rounded-2xl border-gray-4 border-[1px]"
>
{/* Thumbnail */}
diff --git a/apps/web/app/(org)/dashboard/dashboard-data.ts b/apps/web/app/(org)/dashboard/dashboard-data.ts
index 0f7655c6d..ffb09e8ae 100644
--- a/apps/web/app/(org)/dashboard/dashboard-data.ts
+++ b/apps/web/app/(org)/dashboard/dashboard-data.ts
@@ -47,6 +47,7 @@ export async function getDashboardData(user: typeof userSelectProps) {
organization: organizations,
settings: organizations.settings,
member: organizationMembers,
+ iconUrl: organizations.iconUrl,
user: {
id: users.id,
name: users.name,
@@ -130,15 +131,17 @@ export async function getDashboardData(user: typeof userSelectProps) {
organizationId: spaces.organizationId,
createdById: spaces.createdById,
iconUrl: spaces.iconUrl,
+ memberImage: users.image,
memberCount: sql<number>`(
- SELECT COUNT(*) FROM space_members WHERE space_members.spaceId = spaces.id
- )`,
+ SELECT COUNT(*) FROM space_members WHERE space_members.spaceId = spaces.id
+ )`,
videoCount: sql<number>`(
- SELECT COUNT(*) FROM space_videos WHERE space_videos.spaceId = spaces.id
- )`,
+ SELECT COUNT(*) FROM space_videos WHERE space_videos.spaceId = spaces.id
+ )`,
})
.from(spaces)
.leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))
+ .leftJoin(users, eq(spaceMembers.userId, users.id))
.where(
and(
eq(spaces.organizationId, activeOrganizationId),
@@ -152,7 +155,7 @@ export async function getDashboardData(user: typeof userSelectProps) {
),
),
)
- .groupBy(spaces.id);
+ .groupBy(spaces.id, users.image);
// Add a single 'All spaces' entry for the active organization
const activeOrgInfo = organizationsWithMembers.find(
@@ -203,7 +206,7 @@ export async function getDashboardData(user: typeof userSelectProps) {
name: `All ${activeOrgInfo.organization.name}`,
description: `View all content in ${activeOrgInfo.organization.name}`,
organizationId: activeOrgInfo.organization.id,
- iconUrl: null,
+ iconUrl: activeOrgInfo.organization.iconUrl,
memberCount: orgMemberCount,
createdById: activeOrgInfo.organization.ownerId,
videoCount: orgVideoCount,
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx b/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx
index 9d135f4c1..ca6c2de19 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx
@@ -3,12 +3,12 @@
import { Avatar } from "@cap/ui";
import type { Space, Video } from "@cap/web-domain";
import clsx from "clsx";
-import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { moveVideoToFolder } from "@/actions/folders/moveVideoToFolder";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { useDashboardContext } from "../../../Contexts";
import { registerDropTarget } from "./ClientCapCard";
@@ -124,23 +124,14 @@ export function ClientMyCapsLink({
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
- {activeSpace && activeSpace.iconUrl ? (
- <Image
- src={activeSpace.iconUrl}
- alt={activeSpace.name || "Space"}
- width={20}
- height={20}
- className="rounded-full"
+ {activeSpace && (
+ <SignedImageUrl
+ image={activeSpace.iconUrl}
+ name={activeSpace.name}
+ type="organization"
+ letterClass="text-xs"
+ className="relative flex-shrink-0 size-5"
/>
- ) : (
- activeSpace &&
- !activeSpace.iconUrl && (
- <Avatar
- letterClass="text-xs"
- className="relative flex-shrink-0 size-5"
- name={activeSpace?.name}
- />
- )
)}
{activeSpace ? activeSpace.name : "My Caps"}
</Link>
diff --git a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
index 114e02d5a..8c4c56b28 100644
--- a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
@@ -116,7 +116,7 @@ export const Settings = ({
const removeProfileImageMutation = useMutation({
mutationFn: removeProfileImage,
onSuccess: (result) => {
- if (result.success) {
+ if (result?.success) {
setProfileImageOverride(null);
toast.success("Profile image removed");
router.refresh();
@@ -174,6 +174,7 @@ export const Settings = ({
disabled={isProfileImageMutating}
isUploading={uploadProfileImageMutation.isPending}
isRemoving={removeProfileImageMutation.isPending}
+ userName={user?.name}
/>
</Card>
<Card className="space-y-4">
diff --git a/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx b/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx
index e2a6948e1..d494ab89a 100644
--- a/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx
@@ -4,9 +4,9 @@ import { Button } from "@cap/ui";
import { faImage, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
-import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
interface ProfileImageProps {
@@ -16,6 +16,7 @@ interface ProfileImageProps {
disabled?: boolean;
isUploading?: boolean;
isRemoving?: boolean;
+ userName?: string | null;
}
export function ProfileImage({
@@ -25,16 +26,19 @@ export function ProfileImage({
disabled = false,
isUploading = false,
isRemoving = false,
+ userName,
}: ProfileImageProps) {
const [previewUrl, setPreviewUrl] = useState<string | null>(
initialPreviewUrl || null,
);
+ const [isLocalPreview, setIsLocalPreview] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Reset isRemoving when the parent confirms the operation completed
useEffect(() => {
if (initialPreviewUrl !== undefined) {
setPreviewUrl(initialPreviewUrl);
+ setIsLocalPreview(false);
}
}, [initialPreviewUrl]);
@@ -46,16 +50,21 @@ export function ProfileImage({
toast.error("File size must be 1MB or less");
return;
}
- if (previewUrl && previewUrl !== initialPreviewUrl) {
+ if (previewUrl && isLocalPreview) {
URL.revokeObjectURL(previewUrl);
}
const objectUrl = URL.createObjectURL(file);
setPreviewUrl(objectUrl);
+ setIsLocalPreview(true);
onChange?.(file);
};
const handleRemove = () => {
+ if (previewUrl && isLocalPreview) {
+ URL.revokeObjectURL(previewUrl);
+ }
setPreviewUrl(null);
+ setIsLocalPreview(false);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
@@ -80,15 +89,20 @@ export function ProfileImage({
)}
>
{previewUrl ? (
- <Image
- src={previewUrl}
- alt="Profile Image"
- width={56}
- className="object-cover rounded-full size-14"
- height={56}
+ <SignedImageUrl
+ image={previewUrl}
+ name={userName || "User"}
+ type="user"
+ letterClass="text-lg"
+ className="size-full"
/>
) : (
- <FontAwesomeIcon icon={faImage} className="size-4 text-gray-9" />
+ <div className="flex justify-center items-center rounded-full size-full bg-gray-5">
+ <FontAwesomeIcon
+ icon={faImage}
+ className="mx-auto size-5 text-gray-8"
+ />
+ </div>
)}
</div>
<input
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
index ad4dcc9bc..7b7813aa8 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
@@ -1,6 +1,7 @@
"use client";
import { CardDescription, Label } from "@cap/ui";
+import { useRouter } from "next/navigation";
import { useId, useState } from "react";
import { toast } from "sonner";
import { removeOrganizationIcon } from "@/actions/organization/remove-icon";
@@ -9,10 +10,11 @@ import { FileInput } from "@/components/FileInput";
import { useDashboardContext } from "../../../Contexts";
export const OrganizationIcon = () => {
+ const router = useRouter();
const iconInputId = useId();
const { activeOrganization } = useDashboardContext();
const organizationId = activeOrganization?.organization.id;
- const existingIconUrl = activeOrganization?.organization.iconUrl;
+ const existingIconUrl = activeOrganization?.organization.iconUrl ?? null;
const [isUploading, setIsUploading] = useState(false);
@@ -29,6 +31,7 @@ export const OrganizationIcon = () => {
if (result.success) {
toast.success("Organization icon updated successfully");
+ router.refresh();
}
} catch (error) {
toast.error(
@@ -45,8 +48,9 @@ export const OrganizationIcon = () => {
try {
const result = await removeOrganizationIcon(organizationId);
- if (result.success) {
+ if (result?.success) {
toast.success("Organization icon removed successfully");
+ router.refresh();
}
} catch (error) {
console.error("Error removing organization icon:", error);
@@ -69,10 +73,11 @@ export const OrganizationIcon = () => {
previewIconSize={20}
id={iconInputId}
name="icon"
+ type="organization"
onChange={handleFileChange}
disabled={isUploading}
isLoading={isUploading}
- initialPreviewUrl={existingIconUrl || null}
+ initialPreviewUrl={existingIconUrl}
onRemove={handleRemoveIcon}
maxFileSizeBytes={1 * 1024 * 1024} // 1MB
/>
diff --git a/apps/web/app/(org)/dashboard/settings/organization/page.tsx b/apps/web/app/(org)/dashboard/settings/organization/page.tsx
index b2c0e29f1..8e134c645 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/page.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/page.tsx
@@ -34,7 +34,7 @@ export default async function OrganizationPage() {
),
);
- if (member?.role !== "owner") {
+ if (!member || member.role !== "owner") {
redirect("/dashboard/caps");
}
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
index 3ef262d73..0f372b7c3 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
@@ -1,7 +1,6 @@
"use client";
import {
- Avatar,
Button,
DropdownMenu,
DropdownMenuContent,
@@ -13,6 +12,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import { ChevronDown } from "lucide-react";
import { forwardRef, useEffect, useRef, useState } from "react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { useDashboardContext } from "../../../Contexts";
// Define types for organization member objects
@@ -195,9 +195,10 @@ export const MemberSelect = forwardRef<HTMLDivElement, MemberSelectProps>(
key={opt.value}
className="flex gap-2 items-center justify-start p-1.5 text-[13px] rounded-xl cursor-pointer"
>
- <Avatar
+ <SignedImageUrl
name={opt.label}
- imageUrl={opt.image}
+ image={opt.image}
+ type="user"
className="w-5 h-5"
letterClass="text-[11px]"
/>
@@ -218,9 +219,10 @@ export const MemberSelect = forwardRef<HTMLDivElement, MemberSelectProps>(
className="flex gap-4 items-center hover:scale-[1.02] transition-transform h-full px-2 py-1.5 min-h-full text-xs rounded-xl bg-gray-3 text-gray-11 wobble"
>
<div className="flex gap-2 items-center">
- <Avatar
+ <SignedImageUrl
name={tag.label}
- imageUrl={tag.image}
+ image={tag.image}
+ type="user"
className="w-5 h-5"
letterClass="text-[11px]"
/>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx
index 16aaf3465..c6bec9528 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx
@@ -1,10 +1,5 @@
-import {
- Avatar,
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@cap/ui";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@cap/ui";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
interface OrganizationMember {
id: string;
@@ -19,6 +14,7 @@ interface OrganizationMember {
email: string;
firstName?: string | null;
lastName?: string | null;
+ memberImage?: string | null;
};
}
@@ -46,10 +42,12 @@ export const MembersDialog = ({
key={member.userId}
className="flex items-center p-2 rounded-lg hover:bg-gray-3"
>
- <Avatar
- letterClass="text-md"
+ <SignedImageUrl
+ image={member.user?.memberImage || undefined}
name={member.user?.name || "User"}
- className="mr-3 size-8 text-gray-12"
+ type="user"
+ className="mr-3 size-8"
+ letterClass="text-md"
/>
<div className="flex flex-col">
<span className="text-sm font-medium text-gray-12">
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
index 81bf454ab..885d7c7c0 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
@@ -1,7 +1,6 @@
"use client";
import {
- Avatar,
Button,
Dialog,
DialogContent,
@@ -21,6 +20,7 @@ import { useCallback, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { useDashboardContext } from "../../../Contexts";
import { setSpaceMembers } from "../actions";
import type { SpaceMemberData } from "../page";
@@ -165,9 +165,10 @@ export const MembersIndicator = ({
key={member.userId}
className="flex gap-2 items-center p-3 rounded-lg border bg-gray-3 border-gray-4"
>
- <Avatar
+ <SignedImageUrl
name={member.name || member.email}
- imageUrl={member.image || undefined}
+ image={member.image || undefined}
+ type="user"
className="size-8"
letterClass="text-sm"
/>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx
index 502522475..33d57ce70 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx
@@ -1,7 +1,6 @@
"use client";
import {
- Avatar,
Button,
Dialog,
DialogContent,
@@ -13,8 +12,8 @@ import {
import { faBuilding, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
-import Image from "next/image";
import { useState } from "react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { useDashboardContext } from "../../../Contexts";
export type OrganizationMemberData = {
@@ -73,21 +72,13 @@ export const OrganizationIndicator = ({
key={member.id}
className="flex gap-3 items-center px-3 py-2 rounded-lg border transition-colors bg-gray-3 border-gray-4"
>
- {member.image ? (
- <Image
- src={member.image}
- alt={member.name || member.email}
- width={36}
- height={36}
- className="rounded-full"
- />
- ) : (
- <Avatar
- letterClass="text-md"
- name={member.name || member.email}
- className="size-9 text-gray-12"
- />
- )}
+ <SignedImageUrl
+ image={member.image || undefined}
+ name={member.name || member.email}
+ type="user"
+ className="size-8"
+ letterClass="text-sm"
+ />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate text-gray-12">
{member.name || member.email}
@@ -101,7 +92,9 @@ export const OrganizationIndicator = ({
<p
className={clsx(
"px-2.5 py-1.5 text-xs font-medium capitalize text-white rounded-full",
- member.role == "owner" ? "bg-blue-500" : "bg-gray-10",
+ member.role === "owner"
+ ? "bg-blue-500"
+ : "bg-gray-10",
)}
>
{member.role}
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/loading.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/loading.tsx
index 0d5d06564..026044fa0 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/loading.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/loading.tsx
@@ -27,7 +27,7 @@ export default function Loading() {
.fill(0)
.map((_, index) => (
<Skeleton
- key={index}
+ key={index.toString()}
baseColor="var(--gray-4)"
highlightColor="var(--gray-5)"
className="!h-[72px] w-full !rounded-xl"
@@ -40,7 +40,7 @@ export default function Loading() {
.fill(0)
.map((_, index) => (
<div
- key={index}
+ key={index.toString()}
className="flex relative flex-col gap-4 w-full h-full bg-gray-3 rounded-2xl border-gray-4 border-[1px]"
>
{/* Thumbnail */}
diff --git a/apps/web/app/(org)/dashboard/spaces/browse/loading.tsx b/apps/web/app/(org)/dashboard/spaces/browse/loading.tsx
index b4120922c..539afdbd2 100644
--- a/apps/web/app/(org)/dashboard/spaces/browse/loading.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/browse/loading.tsx
@@ -75,7 +75,7 @@ export default function Loading() {
.fill(0)
.map((_, index) => (
<div
- key={index}
+ key={index.toString()}
className="border-t border-gray-3 hover:bg-gray-2"
>
<div className="flex items-center">
diff --git a/apps/web/app/(org)/dashboard/spaces/browse/page.tsx b/apps/web/app/(org)/dashboard/spaces/browse/page.tsx
index caf8debbc..b34d20368 100644
--- a/apps/web/app/(org)/dashboard/spaces/browse/page.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/browse/page.tsx
@@ -9,12 +9,12 @@ import {
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Search } from "lucide-react";
-import Image from "next/image";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { deleteSpace } from "@/actions/organization/delete-space";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { ConfirmationDialog } from "../../_components/ConfirmationDialog";
import SpaceDialog from "../../_components/Navbar/SpaceDialog";
import { useDashboardContext } from "../../Contexts";
@@ -132,21 +132,13 @@ export default function BrowseSpacesPage() {
className="border-t transition-colors cursor-pointer hover:bg-gray-2 border-gray-3"
>
<td className="flex gap-3 items-center px-6 py-4">
- {space.iconUrl ? (
- <Image
- src={space.iconUrl}
- alt={space.name}
- width={24}
- height={24}
- className="object-cover flex-shrink-0 w-7 h-7 rounded-full"
- />
- ) : (
- <Avatar
- className="relative flex-shrink-0 size-7"
- letterClass="text-sm"
- name={space.name}
- />
- )}
+ <SignedImageUrl
+ image={space.iconUrl}
+ name={space.name}
+ type="organization"
+ className="relative flex-shrink-0 size-7"
+ letterClass="text-sm"
+ />
<span className="text-sm font-semibold text-gray-12">
{space.name}
</span>
@@ -197,7 +189,7 @@ export default function BrowseSpacesPage() {
</Button>
</div>
) : (
- <div className="h-[32px]">
+ <div className="h-8 text-gray-10">
<p>...</p>
</div>
)}
diff --git a/apps/web/app/(org)/onboarding/components/Bottom.tsx b/apps/web/app/(org)/onboarding/components/Bottom.tsx
index c2f1f51bf..c1a1eb5ed 100644
--- a/apps/web/app/(org)/onboarding/components/Bottom.tsx
+++ b/apps/web/app/(org)/onboarding/components/Bottom.tsx
@@ -43,7 +43,7 @@ export const Bottom = () => {
<Button
className="px-0 w-fit"
variant="transparent"
- spinner={true}
+ spinner={skipToDashboard.isPending}
spinnerColor="black"
spinnerBorderColor="rgba(0, 0, 0, 0.2)"
disabled={skipToDashboard.isPending || skipToDashboard.isSuccess}
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 63dd9a922..ef7d9a270 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -25,12 +25,12 @@ import { Toolbar } from "./_components/Toolbar";
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
- authorImage: string | null;
+ authorImageUrlOrKey: string | null;
};
export type CommentType = typeof commentsSchema.$inferSelect & {
authorName?: string | null;
- authorImage?: string | null;
+ authorImageUrlOrKey?: string | null;
sending?: boolean;
};
@@ -287,8 +287,8 @@ export const Share = ({
<div className="mt-4">
<div className="flex flex-col gap-4 lg:flex-row">
<div className="flex-1">
- <div className="overflow-hidden relative bg-white rounded-2xl border aspect-video border-gray-5">
- <div className="absolute inset-3 w-[calc(100%-1.5rem)] h-[calc(100%-1.5rem)] overflow-hidden rounded-xl">
+ <div className="overflow-visible relative bg-white rounded-2xl border aspect-video border-gray-5">
+ <div className="absolute inset-3 w-[calc(100%-1.5rem)] h-[calc(100%-1.5rem)] overflow-visible rounded-xl">
<ShareVideo
data={{ ...data, transcriptionStatus }}
user={user}
diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
index a346cc8fc..39f79e5f5 100644
--- a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
@@ -50,7 +50,7 @@ interface Props {
type: "text" | "emoji";
content: string;
authorName?: string | null;
- authorImage?: string | null;
+ authorImageUrlOrKey?: string | null;
}>;
onSeek?: (time: number) => void;
}
@@ -521,7 +521,7 @@ export function CapVideoPlayer({
)}
<div
className={clsx(
- "flex absolute inset-0 z-10 justify-center items-center bg-black transition-opacity duration-300",
+ "flex absolute inset-0 z-10 justify-center items-center bg-black transition-opacity duration-300 overflow-visible",
videoLoaded || !!uploadProgress
? "opacity-0 pointer-events-none"
: "opacity-100",
diff --git a/apps/web/app/s/[videoId]/_components/CommentStamp.tsx b/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
index b4feeabd6..91d8b538d 100644
--- a/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
+++ b/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
@@ -1,6 +1,6 @@
-import { Avatar } from "@cap/ui";
import { faComment } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
interface CommentStampsProps {
comment: {
@@ -9,7 +9,7 @@ interface CommentStampsProps {
type: "text" | "emoji";
content: string;
authorName?: string | null;
- authorImage?: string | null;
+ authorImageUrlOrKey?: string | null;
};
adjustedPosition: string;
handleMouseEnter: (id: string) => void;
@@ -62,12 +62,15 @@ const CommentStamp: React.FC<CommentStampsProps> = ({
<div className="flex gap-2 items-center">
{/* User avatar/initial */}
- <Avatar
- className="size-6"
- letterClass="text-sm"
- name={comment.authorName}
- imageUrl={comment.authorImage ?? undefined}
- />
+ {comment.authorName && (
+ <SignedImageUrl
+ image={comment.authorImageUrlOrKey}
+ name={comment.authorName}
+ type="user"
+ className="size-6"
+ letterClass="text-sm"
+ />
+ )}
{/* Comment content */}
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-white truncate">
diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
index 1afab5a43..490e22e11 100644
--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
@@ -3,7 +3,7 @@
import type { userSelectProps } from "@cap/database/auth/session";
import type { videos } from "@cap/database/schema";
import { buildEnv, NODE_ENV } from "@cap/env";
-import { Avatar, Button } from "@cap/ui";
+import { Button } from "@cap/ui";
import { userIsPro } from "@cap/utils";
import { faChevronDown, faLock } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
@@ -16,6 +16,7 @@ import { editTitle } from "@/actions/videos/edit-title";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
import { SharingDialog } from "@/app/(org)/dashboard/caps/components/SharingDialog";
import type { Spaces } from "@/app/(org)/dashboard/dashboard-data";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { UpgradeModal } from "@/components/UpgradeModal";
import { usePublicEnv } from "@/utils/public-env";
@@ -235,9 +236,10 @@ export const ShareHeader = ({
</div>
<div className="flex gap-7 items-center">
<div className="flex gap-2 items-center">
- <Avatar
- name={data.ownerName}
- imageUrl={data.ownerImage ?? undefined}
+ <SignedImageUrl
+ name={data.ownerName ?? "User"}
+ image={data.ownerImage}
+ type="user"
className="size-8"
letterClass="text-base"
/>
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 6f006c658..6dd3c6529 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -29,7 +29,7 @@ declare global {
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
- authorImage: string | null;
+ authorImageUrlOrKey: string | null;
};
export const ShareVideo = forwardRef<
@@ -187,7 +187,7 @@ export const ShareVideo = forwardRef<
{data.source.type === "desktopMP4" ? (
<CapVideoPlayer
videoId={data.id}
- mediaPlayerClassName="w-full h-full max-w-full max-h-full rounded-xl"
+ mediaPlayerClassName="w-full h-full max-w-full max-h-full rounded-xl overflow-visible"
videoSrc={videoSrc}
disableCaptions={areCaptionsDisabled ?? false}
disableCommentStamps={areCommentStampsDisabled ?? false}
@@ -203,6 +203,7 @@ export const ShareVideo = forwardRef<
timestamp: comment.timestamp,
content: comment.content,
authorName: comment.authorName,
+ authorImageUrlOrKey: comment.authorImageUrlOrKey ?? undefined,
}))}
onSeek={handleSeek}
/>
diff --git a/apps/web/app/s/[videoId]/_components/Toolbar.tsx b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
index 9fe6d3125..9bb617844 100644
--- a/apps/web/app/s/[videoId]/_components/Toolbar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
@@ -40,7 +40,7 @@ export const Toolbar = ({
id: Comment.CommentId.make(`temp-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
authorName: user?.name || "Anonymous",
- authorImage: user?.image ?? null,
+ authorImageUrlOrKey: user?.image ?? null,
content: emoji,
createdAt: new Date(),
videoId: data.id,
@@ -82,7 +82,7 @@ export const Toolbar = ({
id: Comment.CommentId.make(`temp-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
authorName: user?.name || "Anonymous",
- authorImage: user?.image ?? null,
+ authorImageUrlOrKey: user?.image ?? null,
content: comment,
createdAt: new Date(),
videoId: data.id,
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
index e856f48e5..0367b2cd2 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
@@ -8,6 +8,7 @@ import clsx from "clsx";
import { motion } from "framer-motion";
import { useSearchParams } from "next/navigation";
import type React from "react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
import type { CommentType } from "../../../Share";
import CommentInput from "./CommentInput";
@@ -74,12 +75,15 @@ const CommentComponent: React.FC<{
)}
>
<div className="flex items-start space-x-2.5">
- <Avatar
- className="size-6"
- letterClass="text-sm"
- name={comment.authorName}
- imageUrl={comment.authorImage ?? undefined}
- />
+ {comment.authorName && (
+ <SignedImageUrl
+ image={comment.authorImageUrlOrKey}
+ name={comment.authorName}
+ type="user"
+ className="size-6"
+ letterClass="text-sm"
+ />
+ )}
<motion.div
viewport={{
once: true,
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
index e26d8ff2c..10152e2f9 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
@@ -88,7 +88,7 @@ export const Comments = Object.assign(
id: Comment.CommentId.make(`temp-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
authorName: user?.name || "Anonymous",
- authorImage: user?.image ?? null,
+ authorImageUrlOrKey: user?.image ?? null,
content,
createdAt: new Date(),
videoId: props.videoId,
@@ -131,7 +131,7 @@ export const Comments = Object.assign(
id: Comment.CommentId.make(`temp-reply-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
authorName: user?.name || "Anonymous",
- authorImage: user?.image ?? null,
+ authorImageUrlOrKey: user?.image ?? null,
content,
createdAt: new Date(),
videoId: props.videoId,
diff --git a/apps/web/app/s/[videoId]/_components/video/media-player.tsx b/apps/web/app/s/[videoId]/_components/video/media-player.tsx
index d793e3431..3d576b71c 100644
--- a/apps/web/app/s/[videoId]/_components/video/media-player.tsx
+++ b/apps/web/app/s/[videoId]/_components/video/media-player.tsx
@@ -776,7 +776,7 @@ function MediaPlayerRootImpl(props: MediaPlayerRootProps) {
onKeyDown={onKeyDown}
onKeyUp={onKeyUp}
className={cn(
- "dark relative isolate flex flex-col overflow-hidden bg-background outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_video]:relative [&_video]:object-contain",
+ "dark relative isolate flex flex-col overflow-visible bg-background outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_video]:relative [&_video]:object-contain",
"data-[state=fullscreen]:[&_video]:size-full [:fullscreen_&]:flex [:fullscreen_&]:h-full [:fullscreen_&]:max-h-screen [:fullscreen_&]:flex-col [:fullscreen_&]:justify-between",
"[&_[data-slider]::before]:-top-4 [&_[data-slider]::before]:-bottom-2 [&_[data-slider]::before]:absolute [&_[data-slider]::before]:inset-x-0 [&_[data-slider]::before]:z-10 [&_[data-slider]::before]:h-8 [&_[data-slider]::before]:cursor-pointer [&_[data-slider]::before]:content-[''] [&_[data-slider]]:relative [&_[data-slot='media-player-seek']:not([data-hovering])::before]:cursor-default",
"[&_video::-webkit-media-text-track-display]:top-auto! [&_video::-webkit-media-text-track-display]:bottom-[4%]! [&_video::-webkit-media-text-track-display]:mb-0! data-[state=fullscreen]:data-[controls-visible]:[&_video::-webkit-media-text-track-display]:bottom-[9%]! data-[controls-visible]:[&_video::-webkit-media-text-track-display]:bottom-[13%]! data-[state=fullscreen]:[&_video::-webkit-media-text-track-display]:bottom-[7%]!",
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index eb83b755a..81c089826 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -272,6 +272,7 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {
ownerId: videos.ownerId,
ownerName: users.name,
ownerImage: users.image,
+ ownerImageUrlOrKey: users.image,
orgId: videos.orgId,
createdAt: videos.createdAt,
updatedAt: videos.updatedAt,
@@ -366,7 +367,7 @@ async function AuthorizedContent({
hasPassword: boolean;
ownerIsPro?: boolean;
ownerName?: string | null;
- ownerImage?: string | null;
+ ownerImageUrlOrKey?: string | null;
orgSettings?: OrganizationSettings | null;
videoSettings?: OrganizationSettings | null;
};
@@ -471,7 +472,7 @@ async function AuthorizedContent({
name: videos.name,
ownerId: videos.ownerId,
ownerName: users.name,
- ownerImage: users.image,
+ ownerImageUrlOrKey: users.image,
ownerIsPro:
sql`${users.stripeSubscriptionStatus} IN ('active','trialing','complete','paid') OR ${users.thirdPartyStripeSubscriptionId} IS NOT NULL`.mapWith(
Boolean,
@@ -661,7 +662,7 @@ async function AuthorizedContent({
updatedAt: comments.updatedAt,
parentCommentId: comments.parentCommentId,
authorName: users.name,
- authorImage: users.image,
+ authorImageUrlOrKey: users.image,
})
.from(comments)
.leftJoin(users, eq(comments.authorId, users.id))
diff --git a/apps/web/components/FileInput.tsx b/apps/web/components/FileInput.tsx
index ecac31dce..0c0c1b0e2 100644
--- a/apps/web/components/FileInput.tsx
+++ b/apps/web/components/FileInput.tsx
@@ -8,10 +8,10 @@ import {
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
-import Image from "next/image";
import type React from "react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
+import { useSignedImageUrl } from "@/lib/use-signed-image-url";
import { Tooltip } from "./Tooltip";
const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png"]);
@@ -23,6 +23,7 @@ export interface FileInputProps {
disabled?: boolean;
id?: string;
name?: string;
+ type: "user" | "organization";
containerStyle?: React.CSSProperties;
className?: string;
notDraggingClassName?: string;
@@ -40,6 +41,7 @@ export const FileInput: React.FC<FileInputProps> = ({
disabled = false,
id = "file",
name = "file",
+ type,
className = "",
notDraggingClassName = "",
initialPreviewUrl = null,
@@ -54,20 +56,47 @@ export const FileInput: React.FC<FileInputProps> = ({
const [previewUrl, setPreviewUrl] = useState<string | null>(
initialPreviewUrl,
);
+ const [isLocalPreview, setIsLocalPreview] = useState(false);
+
+ // Get signed URL for S3 keys
+ const { data: signedUrl } = useSignedImageUrl(previewUrl, type);
+
+ function isS3Key(imageKeyOrUrl: string | null | undefined): boolean {
+ if (!imageKeyOrUrl) return false;
+ return (
+ imageKeyOrUrl.startsWith("users/") ||
+ imageKeyOrUrl.startsWith("organizations/")
+ );
+ }
+ const previousPreviewRef = useRef<{
+ url: string | null;
+ isLocal: boolean;
+ }>({ url: null, isLocal: false });
// Update preview URL when initialPreviewUrl changes
useEffect(() => {
+ // Clean up old blob URL if it exists
+ if (previousPreviewRef.current.url && previousPreviewRef.current.isLocal) {
+ URL.revokeObjectURL(previousPreviewRef.current.url);
+ }
+
setPreviewUrl(initialPreviewUrl);
+ setIsLocalPreview(false);
+
+ previousPreviewRef.current = {
+ url: initialPreviewUrl,
+ isLocal: false,
+ };
}, [initialPreviewUrl]);
// Clean up the preview URL when component unmounts
useEffect(() => {
return () => {
- if (previewUrl && previewUrl !== initialPreviewUrl) {
+ if (previewUrl && isLocalPreview) {
URL.revokeObjectURL(previewUrl);
}
};
- }, [previewUrl, initialPreviewUrl]);
+ }, [previewUrl, isLocalPreview]);
const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
@@ -144,14 +173,20 @@ export const FileInput: React.FC<FileInputProps> = ({
return;
}
- // Clean up previous preview URL if it's not the initial preview URL
- if (previewUrl && previewUrl !== initialPreviewUrl) {
+ // Clean up previous preview URL if it's a local blob URL
+ if (previewUrl && isLocalPreview) {
URL.revokeObjectURL(previewUrl);
}
// Create a new preview URL for immediate feedback
const newPreviewUrl = URL.createObjectURL(file);
setPreviewUrl(newPreviewUrl);
+ setIsLocalPreview(true);
+
+ previousPreviewRef.current = {
+ url: newPreviewUrl,
+ isLocal: true,
+ };
// Call the onChange callback
if (onChange) {
@@ -163,12 +198,18 @@ export const FileInput: React.FC<FileInputProps> = ({
const handleRemove = (e: React.MouseEvent) => {
e.stopPropagation();
- // Clean up preview URL if it's not the initial preview URL
- if (previewUrl && previewUrl !== initialPreviewUrl) {
+ // Clean up preview URL if it's a local blob URL
+ if (previewUrl && isLocalPreview) {
URL.revokeObjectURL(previewUrl);
}
setPreviewUrl(null);
+ setIsLocalPreview(false);
+
+ previousPreviewRef.current = {
+ url: null,
+ isLocal: false,
+ };
if (fileInputRef.current) {
fileInputRef.current.value = "";
@@ -210,12 +251,16 @@ export const FileInput: React.FC<FileInputProps> = ({
className="flex overflow-hidden relative flex-shrink-0 justify-center items-center rounded-full"
>
{previewUrl && (
- <Image
- src={previewUrl}
+ <img
+ src={
+ isS3Key(previewUrl) ? (signedUrl ?? "") : previewUrl
+ }
+ alt="File preview"
width={32}
height={32}
- alt="File preview"
- className="object-cover rounded-full"
+ loading="eager"
+ referrerPolicy="no-referrer"
+ className="object-cover rounded-full size-8"
/>
)}
</div>
diff --git a/apps/web/components/SignedImageUrl.tsx b/apps/web/components/SignedImageUrl.tsx
new file mode 100644
index 000000000..4d389930a
--- /dev/null
+++ b/apps/web/components/SignedImageUrl.tsx
@@ -0,0 +1,64 @@
+"use client";
+
+import { Avatar } from "@cap/ui";
+import { useSignedImageUrl } from "@/lib/use-signed-image-url";
+
+interface SignedImageUrlProps {
+ image: string | null | undefined;
+ name: string;
+ type: "user" | "organization";
+ className?: string;
+ letterClass?: string;
+ noFallback?: boolean;
+}
+
+/**
+ * Component that handles both S3 keys (via RPC) and direct URLs
+ * For S3 keys, it uses the RPC hook to get signed URLs
+ * For direct URLs, it uses them as-is
+ */
+export function SignedImageUrl({
+ image,
+ name,
+ type,
+ className,
+ letterClass,
+}: SignedImageUrlProps) {
+ const { data: signedUrl, isLoading } = useSignedImageUrl(image, type);
+
+ function isS3Key(imageKeyOrUrl: string | null | undefined): boolean {
+ if (!imageKeyOrUrl) return false;
+ return (
+ imageKeyOrUrl.startsWith("users/") ||
+ imageKeyOrUrl.startsWith("organizations/")
+ );
+ }
+
+ // If it's an S3 key, use the signed URL from RPC
+ // If it's a direct URL, use it as-is
+ const imageUrl = isS3Key(image) ? (signedUrl as string | null) : image;
+
+ if (isS3Key(image) && isLoading) {
+ return (
+ <div
+ className={className}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: "var(--gray-5)",
+ borderRadius: "50%",
+ }}
+ />
+ );
+ }
+
+ return (
+ <Avatar
+ name={name}
+ imageUrl={imageUrl ?? undefined}
+ className={className}
+ letterClass={letterClass}
+ />
+ );
+}
diff --git a/apps/web/components/Tooltip.tsx b/apps/web/components/Tooltip.tsx
index 599d46bd8..a6db805a7 100644
--- a/apps/web/components/Tooltip.tsx
+++ b/apps/web/components/Tooltip.tsx
@@ -40,7 +40,7 @@ const Tooltip = ({
{kbd.map((key, index) => (
<div
className="flex justify-center items-center px-1 rounded-md border shadow-sm bg-gray-3 border-gray-4 size-5 min-w-fit shadow-gray-3/50"
- key={index}
+ key={index.toString()}
>
<kbd className="text-[11px] text-gray-10">{key}</kbd>
</div>
diff --git a/apps/web/components/forms/NewOrganization.tsx b/apps/web/components/forms/NewOrganization.tsx
index d48641afe..50c78e734 100644
--- a/apps/web/components/forms/NewOrganization.tsx
+++ b/apps/web/components/forms/NewOrganization.tsx
@@ -99,6 +99,7 @@ export const NewOrganization: React.FC<NewOrganizationProps> = (props) => {
<FileInput
id="icon"
name="icon"
+ type="organization"
notDraggingClassName="hover:bg-gray-3"
onChange={setSelectedFile}
disabled={isUploading}
diff --git a/apps/web/components/forms/server.ts b/apps/web/components/forms/server.ts
index ca96a87df..2c9f677e3 100644
--- a/apps/web/components/forms/server.ts
+++ b/apps/web/components/forms/server.ts
@@ -67,8 +67,6 @@ export async function createOrganization(formData: FormData) {
const fileKey = `organizations/${organizationId}/icon-${Date.now()}.${fileExtension}`;
try {
- let iconUrl: string | undefined;
-
await Effect.gen(function* () {
const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
@@ -77,24 +75,9 @@ export async function createOrganization(formData: FormData) {
yield* Effect.promise(() => iconFile.bytes()),
{ contentType: iconFile.type },
);
-
- // Construct the icon URL
- if (serverEnv().CAP_AWS_BUCKET_URL) {
- // If a custom bucket URL is defined, use it
- iconUrl = `${serverEnv().CAP_AWS_BUCKET_URL}/${fileKey}`;
- } else if (serverEnv().CAP_AWS_ENDPOINT) {
- // For custom endpoints like MinIO
- iconUrl = `${serverEnv().CAP_AWS_ENDPOINT}/${bucket.bucketName}/${fileKey}`;
- } else {
- // Default AWS S3 URL format
- iconUrl = `https://${bucket.bucketName}.s3.${
- serverEnv().CAP_AWS_REGION || "us-east-1"
- }.amazonaws.com/${fileKey}`;
- }
}).pipe(runPromise);
- // Add the icon URL to the organization values
- orgValues.iconUrl = iconUrl;
+ orgValues.iconUrl = fileKey;
} catch (error) {
console.error("Error uploading organization icon:", error);
throw new Error(error instanceof Error ? error.message : "Upload failed");
diff --git a/apps/web/lib/use-signed-image-url.ts b/apps/web/lib/use-signed-image-url.ts
new file mode 100644
index 000000000..d5d3caf3a
--- /dev/null
+++ b/apps/web/lib/use-signed-image-url.ts
@@ -0,0 +1,28 @@
+import { Effect } from "effect";
+import { useEffectQuery } from "@/lib/EffectRuntime";
+import { withRpc } from "./Rpcs";
+
+/**
+ * Hook to get signed URL for an S3 image key
+ * @param key - S3 key
+ * @param type - Type of image ("user" or "organization")
+ * @returns Object with url, isLoading, error
+ */
+export function useSignedImageUrl(
+ key: string | null | undefined,
+ type: "user" | "organization",
+) {
+ return useEffectQuery({
+ queryKey: ["signedImageUrl", key, type],
+ queryFn: () => {
+ if (!key) {
+ return Effect.succeed(key);
+ }
+
+ return withRpc((rpc) => rpc.GetSignedImageUrl({ key, type }))
+ .pipe(Effect.map((result) => result.url))
+ .pipe(Effect.catchTag("InternalError", () => Effect.succeed(null)));
+ },
+ enabled: !!key,
+ });
+}
diff --git a/packages/ui/src/components/Avatar.tsx b/packages/ui/src/components/Avatar.tsx
index 2bac16450..64cbb988f 100644
--- a/packages/ui/src/components/Avatar.tsx
+++ b/packages/ui/src/components/Avatar.tsx
@@ -67,6 +67,7 @@ export interface AvatarProps {
imageUrl?: string | null;
className?: string;
letterClass?: string;
+ noFallback?: boolean;
}
export const Avatar: React.FC<AvatarProps> = ({
@@ -80,7 +81,7 @@ export const Avatar: React.FC<AvatarProps> = ({
<img
src={imageUrl}
alt={name ?? "Avatar"}
- className={clsx("rounded-full object-cover size-4", className)}
+ className={clsx("object-cover rounded-full size-4", className)}
loading="lazy"
referrerPolicy="no-referrer"
/>
diff --git a/packages/web-backend/src/Users/UsersRpcs.ts b/packages/web-backend/src/Users/UsersRpcs.ts
index ce4b32abd..41a6d8054 100644
--- a/packages/web-backend/src/Users/UsersRpcs.ts
+++ b/packages/web-backend/src/Users/UsersRpcs.ts
@@ -1,10 +1,12 @@
import { InternalError, User } from "@cap/web-domain";
-import { Effect, Layer } from "effect";
+import { Effect, Layer, Option } from "effect";
+import { S3Buckets } from "../S3Buckets";
import { UsersOnboarding } from "./UsersOnboarding";
export const UsersRpcsLive = User.UserRpcs.toLayer(
Effect.gen(function* () {
const onboarding = yield* UsersOnboarding;
+ const s3Buckets = yield* S3Buckets;
return {
UserCompleteOnboardingStep: (payload) =>
Effect.gen(function* () {
@@ -37,6 +39,22 @@ export const UsersRpcsLive = User.UserRpcs.toLayer(
() => new InternalError({ type: "database" }),
),
),
+ GetSignedImageUrl: (payload: {
+ key: string;
+ type: "user" | "organization";
+ }) =>
+ Effect.gen(function* () {
+ const [bucket] = yield* s3Buckets.getBucketAccess(Option.none());
+ const url = yield* bucket.getSignedObjectUrl(payload.key);
+ return { url };
+ }).pipe(
+ Effect.catchTag("S3Error", () => new InternalError({ type: "s3" })),
+ Effect.catchTag(
+ "DatabaseError",
+ () => new InternalError({ type: "database" }),
+ ),
+ Effect.catchAll(() => new InternalError({ type: "unknown" })),
+ ),
};
}),
).pipe(Layer.provide(UsersOnboarding.Default));
diff --git a/packages/web-domain/src/User.ts b/packages/web-domain/src/User.ts
index 2f5f96fdd..7a0a1b281 100644
--- a/packages/web-domain/src/User.ts
+++ b/packages/web-domain/src/User.ts
@@ -68,10 +68,24 @@ export const OnboardingStepResult = Schema.Union(
}),
);
+export const GetSignedImageUrlPayload = Schema.Struct({
+ key: Schema.String,
+ type: Schema.Literal("user", "organization"),
+});
+
+export const GetSignedImageUrlResult = Schema.Struct({
+ url: Schema.String,
+});
+
export class UserRpcs extends RpcGroup.make(
Rpc.make("UserCompleteOnboardingStep", {
payload: OnboardingStepPayload,
success: OnboardingStepResult,
error: InternalError,
}).middleware(RpcAuthMiddleware),
+ Rpc.make("GetSignedImageUrl", {
+ payload: GetSignedImageUrlPayload,
+ success: GetSignedImageUrlResult,
+ error: InternalError,
+ }).middleware(RpcAuthMiddleware),
) {}