feat(media): add Blurhash placeholders for images across feed, stories, and admin views
Gitea #1: prevents blank image flashes while photos load. Blurhash is computed client-side at upload time (canvas downsampling + the blurhash package) for posts, milestones, and stories, stored alongside each PostImage/Story row, and decoded into a smooth color placeholder via the new BlurImage component that cross-fades to the loaded photo. Wired into every content-photo surface: feed cards, post detail zoom, reposts, milestone cards, story viewer, explore/search grids, notification thumbnails, profile grid, and the admin posts/reports panels. Pet avatars and ad creatives intentionally excluded — separate content pipelines with disproportionate effort for the payoff.
This commit is contained in:
1 parent
5473978763
commit
b6610ca7a7
26 files changed
+267
-83
No files matched your search
Generated
+7
@@ -21,6 +21,7 @@
|
||||
"@trpc/client": "^11.17.0",
|
||||
"@trpc/server": "^11.17.0",
|
||||
"@trpc/tanstack-react-query": "^11.17.0",
|
||||
"blurhash": "^2.0.5",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
@@ -7377,6 +7378,12 @@
|
||||
"require-from-string": "^2.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/blurhash": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/blurhash/-/blurhash-2.0.5.tgz",
|
||||
"integrity": "sha512-cRygWd7kGBQO3VEhPiTgq4Wc43ctsM+o46urrmPOiuAe+07fzlSB9OJVdpgDL0jPqXUVQ9ht7aq7kxOeJHRK+w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"@trpc/client": "^11.17.0",
|
||||
"@trpc/server": "^11.17.0",
|
||||
"@trpc/tanstack-react-query": "^11.17.0",
|
||||
"blurhash": "^2.0.5",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
|
||||
@@ -221,13 +221,14 @@ model Post {
|
||||
}
|
||||
|
||||
model PostImage {
|
||||
id String @id @default(cuid())
|
||||
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
|
||||
id String @id @default(cuid())
|
||||
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
|
||||
postId String
|
||||
storageKey String // Supabase Storage object key
|
||||
position Int // 0-based order in carousel
|
||||
width Int?
|
||||
height Int?
|
||||
blurhash String? // computed client-side at upload (src/lib/blurhash.ts), decoded as a loading placeholder
|
||||
|
||||
@@unique([postId, position])
|
||||
@@index([postId])
|
||||
@@ -246,6 +247,7 @@ model Story {
|
||||
pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade)
|
||||
petId String
|
||||
storageKey String // Supabase Storage object key
|
||||
blurhash String? // computed client-side at upload (src/lib/blurhash.ts), decoded as a loading placeholder
|
||||
expiresAt DateTime // set to NOW() + 24 hours on create (D-07)
|
||||
views StoryView[]
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@ -121,7 +121,7 @@ describe("posts.create", () => {
|
||||
const result = await caller.create({
|
||||
petId: "pet-1",
|
||||
caption: "Hello world",
|
||||
imageKeys: ["posts/owner-1/pet-1/uuid.jpg"],
|
||||
images: [{ key: "posts/owner-1/pet-1/uuid.jpg", blurhash: "L6PZfSi_.AyE_3t7t7R**0o#DgR4" }],
|
||||
});
|
||||
|
||||
// Post was created
|
||||
@@ -157,10 +157,10 @@ describe("posts.create", () => {
|
||||
caller.create({
|
||||
petId: "pet-1",
|
||||
caption: null,
|
||||
imageKeys: Array.from(
|
||||
{ length: 11 },
|
||||
(_, i) => `posts/owner-1/pet-1/img-${i}.jpg`
|
||||
),
|
||||
images: Array.from({ length: 11 }, (_, i) => ({
|
||||
key: `posts/owner-1/pet-1/img-${i}.jpg`,
|
||||
blurhash: null,
|
||||
})),
|
||||
})
|
||||
).rejects.toThrow(TRPCError);
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { PostDetailDialog } from "@/components/feed/PostDetailDialog";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import type { PostCardPost } from "@/components/feed/PostCard";
|
||||
import {
|
||||
Select,
|
||||
@@ -202,7 +203,7 @@ type TrendingPost = {
|
||||
caption: string | null;
|
||||
createdAt: Date | string;
|
||||
pet: { id: string; name: string; avatarKey: string | null };
|
||||
images: { storageKey: string; position: number }[];
|
||||
images: { storageKey: string; position: number; blurhash?: string | null }[];
|
||||
milestone: { milestoneType: string; notes: string | null } | null;
|
||||
reactionCount: number;
|
||||
commentCount: number;
|
||||
@@ -299,9 +300,9 @@ function TrendingContent({
|
||||
aria-label={post.caption ?? "View trending post"}
|
||||
>
|
||||
{mediaUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={mediaUrl}
|
||||
blurhash={firstImage?.blurhash}
|
||||
alt={post.caption ?? "Trending post"}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useEffect } from "react";
|
||||
import { Layers2, Loader2 } from "lucide-react";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ tag: string }>;
|
||||
@@ -62,7 +63,7 @@ export default function HashtagPage({ params }: PageProps) {
|
||||
const p = post as {
|
||||
id: string;
|
||||
caption: string | null;
|
||||
images: Array<{ storageKey: string; position?: number }>;
|
||||
images: Array<{ storageKey: string; position?: number; blurhash?: string | null }>;
|
||||
};
|
||||
const firstImage = p.images?.[0];
|
||||
const isCarousel = (p.images?.length ?? 0) > 1;
|
||||
@@ -74,9 +75,9 @@ export default function HashtagPage({ params }: PageProps) {
|
||||
className="relative aspect-square overflow-hidden bg-muted"
|
||||
>
|
||||
{mediaUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={mediaUrl}
|
||||
blurhash={firstImage?.blurhash}
|
||||
alt={p.caption ?? "Post"}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useActivePet } from "@/context/ActivePetContext";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
|
||||
@@ -191,9 +192,9 @@ export default function NotificationsPage() {
|
||||
{/* Post thumbnail (for REACTION / COMMENT) */}
|
||||
{postThumbUrl && (
|
||||
<div className="shrink-0 w-10 h-10 rounded overflow-hidden bg-muted">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
<BlurImage
|
||||
src={postThumbUrl}
|
||||
blurhash={notif.post?.images?.[0]?.blurhash}
|
||||
alt="Post"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
|
||||
@@ -15,6 +15,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { FollowButton } from "@/components/social/FollowButton";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
|
||||
export default function SearchPage() {
|
||||
const t = useTranslations("Search");
|
||||
@@ -250,7 +251,7 @@ export default function SearchPage() {
|
||||
const p = post as {
|
||||
id: string;
|
||||
caption: string | null;
|
||||
images: Array<{ storageKey: string }>;
|
||||
images: Array<{ storageKey: string; blurhash?: string | null }>;
|
||||
};
|
||||
const firstImage = p.images?.[0];
|
||||
const isCarousel = (p.images?.length ?? 0) > 1;
|
||||
@@ -258,9 +259,9 @@ export default function SearchPage() {
|
||||
return (
|
||||
<div key={p.id} className="relative aspect-square overflow-hidden bg-muted">
|
||||
{mediaUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={mediaUrl}
|
||||
blurhash={firstImage?.blurhash}
|
||||
alt={p.caption ?? "Post"}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
|
||||
export default function AdminPostsPage() {
|
||||
const trpc = useTRPC();
|
||||
@@ -90,9 +91,9 @@ export default function AdminPostsPage() {
|
||||
className="flex items-center gap-4 rounded-xl border border-zinc-800 bg-zinc-900 px-4 py-3"
|
||||
>
|
||||
{thumb ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(thumb.storageKey) ?? ""}
|
||||
blurhash={thumb.blurhash}
|
||||
alt=""
|
||||
className="h-12 w-12 rounded-lg object-cover shrink-0"
|
||||
/>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { Flag, Trash2, X, Loader2, CheckCheck, MessageCircle, Heart, ImageOff } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -150,10 +151,10 @@ export default function AdminReportsPage() {
|
||||
<div className="flex gap-1 shrink-0">
|
||||
{report.post.images.length > 0 ? (
|
||||
report.post.images.map((img, i) => (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
key={i}
|
||||
src={getMediaUrl(img.storageKey) ?? ""}
|
||||
blurhash={img.blurhash}
|
||||
alt=""
|
||||
className="h-20 w-20 rounded-lg object-cover"
|
||||
/>
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { MilestoneType } from "@prisma/client";
|
||||
import { MILESTONE_META } from "@/lib/milestone-meta";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
|
||||
type MilestoneCardPost = {
|
||||
@@ -11,7 +12,7 @@ type MilestoneCardPost = {
|
||||
caption: string | null;
|
||||
createdAt: Date | string;
|
||||
pet: { id: string; name: string; avatarKey: string | null };
|
||||
images: { id: string; storageKey: string; position: number }[];
|
||||
images: { id: string; storageKey: string; position: number; blurhash?: string | null }[];
|
||||
milestone: { milestoneType: MilestoneType; notes: string | null } | null;
|
||||
};
|
||||
|
||||
@@ -71,9 +72,9 @@ export function MilestoneCard({ post }: MilestoneCardProps) {
|
||||
{/* Optional photo */}
|
||||
{photo && (
|
||||
<div className="w-full">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(photo.storageKey) ?? ""}
|
||||
blurhash={photo.blurhash}
|
||||
alt={caption ?? `${pet.name}'s milestone`}
|
||||
className="w-full object-cover max-h-[400px]"
|
||||
/>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useMutation } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { useActivePet } from "@/context/ActivePetContext";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
@@ -69,6 +70,7 @@ type PostImage = {
|
||||
id: string;
|
||||
storageKey: string;
|
||||
position: number;
|
||||
blurhash?: string | null;
|
||||
};
|
||||
|
||||
type PostPet = {
|
||||
@@ -324,9 +326,9 @@ function PostCardImpl({ post, onDeleted, variant = "feed" }: PostCardProps) {
|
||||
<CarouselContent>
|
||||
{images.map((img) => (
|
||||
<CarouselItem key={img.id} className="basis-full">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(img.storageKey) ?? ""}
|
||||
blurhash={img.blurhash}
|
||||
alt={currentCaption ?? `${pet.name}'s post`}
|
||||
className="w-full object-cover max-h-[560px] cursor-pointer"
|
||||
onClick={() => setShowDetailDialog(true)}
|
||||
@@ -361,9 +363,9 @@ function PostCardImpl({ post, onDeleted, variant = "feed" }: PostCardProps) {
|
||||
</div>
|
||||
) : (
|
||||
/* Single image */
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(images[0].storageKey) ?? ""}
|
||||
blurhash={images[0].blurhash}
|
||||
alt={currentCaption ?? `${pet.name}'s post`}
|
||||
className="w-full object-cover max-h-[560px] cursor-pointer"
|
||||
onClick={() => setShowDetailDialog(true)}
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
import Link from "next/link";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { parseCaption } from "@/lib/parse-caption";
|
||||
import { formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
import { PawButton } from "@/components/feed/PawButton";
|
||||
@@ -260,9 +261,9 @@ export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailD
|
||||
<CarouselContent className="h-full">
|
||||
{images.map((img) => (
|
||||
<CarouselItem key={img.id} className="basis-full flex items-center justify-center h-full">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(img.storageKey) ?? ""}
|
||||
blurhash={img.blurhash}
|
||||
alt={currentCaption ?? `${pet.name}'s post`}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
/>
|
||||
@@ -287,9 +288,9 @@ export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailD
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(images[0].storageKey) ?? ""}
|
||||
blurhash={images[0].blurhash}
|
||||
alt={currentCaption ?? `${pet.name}'s post`}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
/>
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "@/components/ui/carousel";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { MilestoneCard } from "@/components/feed/MilestoneCard";
|
||||
import type { PostCardPost } from "@/components/feed/PostCard";
|
||||
|
||||
@@ -119,9 +120,9 @@ function RepostCardInner({
|
||||
<CarouselContent>
|
||||
{origImages.map((img) => (
|
||||
<CarouselItem key={img.id} className="basis-full">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(img.storageKey) ?? ""}
|
||||
blurhash={img.blurhash}
|
||||
alt={originalPost.caption ?? `${origPet.name}'s post`}
|
||||
className="w-full object-cover max-h-[480px]"
|
||||
/>
|
||||
@@ -137,9 +138,9 @@ function RepostCardInner({
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
<BlurImage
|
||||
src={getMediaUrl(origImages[0].storageKey) ?? ""}
|
||||
blurhash={origImages[0].blurhash}
|
||||
alt={originalPost.caption ?? `${origPet.name}'s post`}
|
||||
className="w-full object-cover max-h-[480px]"
|
||||
/>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { MILESTONE_META, USER_INITIATED_MILESTONE_TYPES } from "@/lib/milestone-meta";
|
||||
import { computeBlurhash } from "@/lib/blurhash";
|
||||
|
||||
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp"] as const;
|
||||
type AllowedContentType = (typeof ALLOWED_TYPES)[number];
|
||||
@@ -55,6 +56,7 @@ export function MilestoneForm({ onClose }: MilestoneFormProps) {
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [uploadedKey, setUploadedKey] = useState<string | null>(null);
|
||||
const [uploadedBlurhash, setUploadedBlurhash] = useState<string | null>(null);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
|
||||
const getPresignedUrlMutation = useMutation(
|
||||
@@ -95,11 +97,14 @@ export function MilestoneForm({ onClose }: MilestoneFormProps) {
|
||||
setUploadProgress(0);
|
||||
|
||||
try {
|
||||
const { presignedUrl, key } = await getPresignedUrlMutation.mutateAsync({
|
||||
petId: activePetId,
|
||||
contentType: file.type as AllowedContentType,
|
||||
fileSize: file.size,
|
||||
});
|
||||
const [{ presignedUrl, key }, blurhash] = await Promise.all([
|
||||
getPresignedUrlMutation.mutateAsync({
|
||||
petId: activePetId,
|
||||
contentType: file.type as AllowedContentType,
|
||||
fileSize: file.size,
|
||||
}),
|
||||
computeBlurhash(file),
|
||||
]);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
@@ -114,6 +119,7 @@ export function MilestoneForm({ onClose }: MilestoneFormProps) {
|
||||
});
|
||||
|
||||
setUploadedKey(key);
|
||||
setUploadedBlurhash(blurhash);
|
||||
setUploadState("ready");
|
||||
} catch {
|
||||
setUploadError(t("uploadFailed"));
|
||||
@@ -142,8 +148,9 @@ export function MilestoneForm({ onClose }: MilestoneFormProps) {
|
||||
notes: selectedType === MilestoneType.LITTER ? notes.trim() || undefined : undefined,
|
||||
caption: caption.trim() || undefined,
|
||||
imageKey: uploadedKey ?? undefined,
|
||||
imageBlurhash: uploadedBlurhash,
|
||||
});
|
||||
}, [activePetId, selectedType, notes, caption, uploadedKey, createMutation]);
|
||||
}, [activePetId, selectedType, notes, caption, uploadedKey, uploadedBlurhash, createMutation]);
|
||||
|
||||
const selectedMeta = selectedType ? MILESTONE_META[selectedType] : null;
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { toast } from "sonner";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { uploadFileWithProgress } from "@/lib/upload-xhr";
|
||||
import { computeBlurhash } from "@/lib/blurhash";
|
||||
|
||||
/**
|
||||
* MultiImageUpload — multi-file upload zone for post images (up to 10).
|
||||
@@ -36,6 +37,8 @@ interface UploadedImage {
|
||||
previewUrl: string;
|
||||
/** Supabase storage key — only set after successful upload */
|
||||
storageKey: string | null;
|
||||
/** Blurhash placeholder computed client-side from the selected file (Gitea #1) */
|
||||
blurhash: string | null;
|
||||
/** File size for display */
|
||||
fileName: string;
|
||||
/** Upload state */
|
||||
@@ -45,15 +48,15 @@ interface UploadedImage {
|
||||
|
||||
interface MultiImageUploadProps {
|
||||
petId: string;
|
||||
/** Called with all successfully uploaded storage keys */
|
||||
onKeysChange: (keys: string[]) => void;
|
||||
/** Called with all successfully uploaded storage keys + their blurhash placeholders */
|
||||
onImagesChange: (images: { key: string; blurhash: string | null }[]) => void;
|
||||
/** Max number of images (default 10) */
|
||||
maxImages?: number;
|
||||
}
|
||||
|
||||
export function MultiImageUpload({
|
||||
petId,
|
||||
onKeysChange,
|
||||
onImagesChange,
|
||||
maxImages = MAX_IMAGES,
|
||||
}: MultiImageUploadProps) {
|
||||
const trpc = useTRPC();
|
||||
@@ -61,14 +64,14 @@ export function MultiImageUpload({
|
||||
const [images, setImages] = useState<UploadedImage[]>([]);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
|
||||
// Notify parent of done keys whenever images change — must be outside setImages updater
|
||||
// Notify parent of done images whenever they change — must be outside setImages updater
|
||||
// to avoid "Cannot update a component while rendering a different component" warning.
|
||||
useEffect(() => {
|
||||
const keys = images
|
||||
const done = images
|
||||
.filter((img) => img.status === "done" && img.storageKey)
|
||||
.map((img) => img.storageKey as string);
|
||||
onKeysChange(keys);
|
||||
}, [images, onKeysChange]);
|
||||
.map((img) => ({ key: img.storageKey as string, blurhash: img.blurhash }));
|
||||
onImagesChange(done);
|
||||
}, [images, onImagesChange]);
|
||||
|
||||
const getPresignedUrlMutation = useMutation(
|
||||
trpc.posts.getPresignedUrl.mutationOptions()
|
||||
@@ -106,12 +109,16 @@ export function MultiImageUpload({
|
||||
});
|
||||
|
||||
try {
|
||||
// Step 1: Get presigned URL
|
||||
const { presignedUrl, key } = await getPresignedUrlMutation.mutateAsync({
|
||||
petId,
|
||||
contentType: file.type as AllowedContentType,
|
||||
fileSize: file.size,
|
||||
});
|
||||
// Step 1: Get presigned URL, and in parallel compute the blurhash placeholder
|
||||
// client-side (Gitea #1) — both run concurrently since neither depends on the other.
|
||||
const [{ presignedUrl, key }, blurhash] = await Promise.all([
|
||||
getPresignedUrlMutation.mutateAsync({
|
||||
petId,
|
||||
contentType: file.type as AllowedContentType,
|
||||
fileSize: file.size,
|
||||
}),
|
||||
computeBlurhash(file),
|
||||
]);
|
||||
|
||||
// Step 2: PUT file directly to Supabase Storage, tracking progress
|
||||
await uploadFileWithProgress(presignedUrl, file, {
|
||||
@@ -125,13 +132,14 @@ export function MultiImageUpload({
|
||||
},
|
||||
});
|
||||
|
||||
// Step 3: Mark as done with storage key
|
||||
// Step 3: Mark as done with storage key + blurhash
|
||||
setImages((prev) => {
|
||||
const updated = [...prev];
|
||||
updated[index] = {
|
||||
...updated[index],
|
||||
status: "done",
|
||||
storageKey: key,
|
||||
blurhash,
|
||||
uploadProgress: 100,
|
||||
};
|
||||
return updated;
|
||||
@@ -171,6 +179,7 @@ export function MultiImageUpload({
|
||||
const newImages: UploadedImage[] = toUpload.map((file) => ({
|
||||
previewUrl: URL.createObjectURL(file),
|
||||
storageKey: null,
|
||||
blurhash: null,
|
||||
fileName: file.name,
|
||||
status: "pending",
|
||||
uploadProgress: 0,
|
||||
|
||||
@@ -44,7 +44,7 @@ export function PhotoPostForm({ onClose }: PhotoPostFormProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { activePetId } = useActivePet();
|
||||
|
||||
const [imageKeys, setImageKeys] = useState<string[]>([]);
|
||||
const [images, setImages] = useState<{ key: string; blurhash: string | null }[]>([]);
|
||||
const [caption, setCaption] = useState("");
|
||||
const [captionError, setCaptionError] = useState<string | null>(null);
|
||||
|
||||
@@ -70,7 +70,7 @@ export function PhotoPostForm({ onClose }: PhotoPostFormProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (imageKeys.length === 0) {
|
||||
if (images.length === 0) {
|
||||
toast.error(t("noPhoto"));
|
||||
return;
|
||||
}
|
||||
@@ -83,9 +83,9 @@ export function PhotoPostForm({ onClose }: PhotoPostFormProps) {
|
||||
createMutation.mutate({
|
||||
petId: activePetId,
|
||||
caption: caption.trim() || null,
|
||||
imageKeys,
|
||||
images,
|
||||
});
|
||||
}, [activePetId, imageKeys, caption, createMutation, t]);
|
||||
}, [activePetId, images, caption, createMutation, t]);
|
||||
|
||||
if (!activePetId) {
|
||||
return (
|
||||
@@ -100,7 +100,7 @@ export function PhotoPostForm({ onClose }: PhotoPostFormProps) {
|
||||
{/* Multi-image upload zone */}
|
||||
<MultiImageUpload
|
||||
petId={activePetId}
|
||||
onKeysChange={setImageKeys}
|
||||
onImagesChange={setImages}
|
||||
/>
|
||||
|
||||
{/* Caption textarea */}
|
||||
@@ -134,7 +134,7 @@ export function PhotoPostForm({ onClose }: PhotoPostFormProps) {
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={
|
||||
imageKeys.length === 0 ||
|
||||
images.length === 0 ||
|
||||
createMutation.isPending ||
|
||||
!!captionError
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { MilestoneCard } from "@/components/feed/MilestoneCard";
|
||||
import { PostDetailDialog } from "@/components/feed/PostDetailDialog";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import type { PostCardPost } from "@/components/feed/PostCard";
|
||||
|
||||
interface ProfileTabsProps {
|
||||
@@ -89,9 +90,9 @@ export function ProfileTabs({ petId }: ProfileTabsProps) {
|
||||
aria-label={post.caption ?? "View post"}
|
||||
>
|
||||
{mediaUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={mediaUrl}
|
||||
blurhash={firstImage?.blurhash}
|
||||
alt={post.caption ?? "Post"}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useTRPC } from "@/trpc/client";
|
||||
import { useActivePet } from "@/context/ActivePetContext";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { computeBlurhash } from "@/lib/blurhash";
|
||||
|
||||
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp"] as const;
|
||||
type AllowedContentType = (typeof ALLOWED_TYPES)[number];
|
||||
@@ -40,6 +41,7 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [uploadedKey, setUploadedKey] = useState<string | null>(null);
|
||||
const [uploadedBlurhash, setUploadedBlurhash] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const getPresignedUrlMutation = useMutation(
|
||||
@@ -88,11 +90,14 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
setUploadProgress(0);
|
||||
|
||||
try {
|
||||
const { presignedUrl, key } = await getPresignedUrlMutation.mutateAsync({
|
||||
petId: activePetId,
|
||||
contentType: file.type as AllowedContentType,
|
||||
fileSize: file.size,
|
||||
});
|
||||
const [{ presignedUrl, key }, blurhash] = await Promise.all([
|
||||
getPresignedUrlMutation.mutateAsync({
|
||||
petId: activePetId,
|
||||
contentType: file.type as AllowedContentType,
|
||||
fileSize: file.size,
|
||||
}),
|
||||
computeBlurhash(file),
|
||||
]);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
@@ -110,6 +115,7 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
});
|
||||
|
||||
setUploadedKey(key);
|
||||
setUploadedBlurhash(blurhash);
|
||||
setUploadState("ready");
|
||||
} catch {
|
||||
setErrorMessage(t("uploadFailed"));
|
||||
@@ -132,8 +138,12 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
const handleSubmit = useCallback(() => {
|
||||
if (!activePetId || !uploadedKey) return;
|
||||
setUploadState("submitting");
|
||||
createStoryMutation.mutate({ petId: activePetId, storageKey: uploadedKey });
|
||||
}, [activePetId, uploadedKey, createStoryMutation]);
|
||||
createStoryMutation.mutate({
|
||||
petId: activePetId,
|
||||
storageKey: uploadedKey,
|
||||
blurhash: uploadedBlurhash,
|
||||
});
|
||||
}, [activePetId, uploadedKey, uploadedBlurhash, createStoryMutation]);
|
||||
|
||||
return (
|
||||
<div className="px-4 pb-6 space-y-5">
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from "@/components/ui/sheet";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
|
||||
interface StoryViewerProps {
|
||||
petId: string;
|
||||
@@ -155,9 +156,9 @@ export function StoryViewer({
|
||||
|
||||
{/* Story image */}
|
||||
{mediaUrl && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
<BlurImage
|
||||
src={mediaUrl}
|
||||
blurhash={currentStory.blurhash}
|
||||
alt={t("storyAriaLabel", { petName })}
|
||||
className="max-h-screen max-w-full object-contain"
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { decode } from "blurhash";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Matches the encode side (src/lib/blurhash.ts) — small enough to decode
|
||||
// instantly, large enough that the upscaled canvas still reads as a smooth
|
||||
// color blur rather than visible blocks.
|
||||
const DECODE_SIZE = 32;
|
||||
|
||||
interface BlurImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
|
||||
blurhash?: string | null;
|
||||
/** Classes for the sizing/positioning wrapper (defaults fill the nearest sized parent). */
|
||||
wrapperClassName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop-in `<img>` replacement (Gitea #1): renders a decoded Blurhash canvas
|
||||
* behind the real image so there is never a blank flash while it loads, then
|
||||
* cross-fades to the loaded photo. Falls back to a plain lazy-loaded `<img>`
|
||||
* when no blurhash is available (e.g. content uploaded before this feature).
|
||||
*/
|
||||
export function BlurImage({
|
||||
blurhash,
|
||||
className,
|
||||
wrapperClassName,
|
||||
onLoad,
|
||||
alt,
|
||||
...imgProps
|
||||
}: BlurImageProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!blurhash || !canvasRef.current) return;
|
||||
try {
|
||||
const pixels = decode(blurhash, DECODE_SIZE, DECODE_SIZE);
|
||||
const canvas = canvasRef.current;
|
||||
canvas.width = DECODE_SIZE;
|
||||
canvas.height = DECODE_SIZE;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
const imageData = ctx.createImageData(DECODE_SIZE, DECODE_SIZE);
|
||||
imageData.data.set(pixels);
|
||||
ctx.putImageData(imageData, 0, 0);
|
||||
} catch {
|
||||
// Malformed hash — the plain <img> below still renders on its own.
|
||||
}
|
||||
}, [blurhash]);
|
||||
|
||||
return (
|
||||
<span className={cn("relative block h-full w-full overflow-hidden", wrapperClassName)}>
|
||||
{blurhash && (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"absolute inset-0 h-full w-full object-cover transition-opacity duration-300",
|
||||
loaded ? "opacity-0" : "opacity-100"
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
{...imgProps}
|
||||
alt={alt}
|
||||
loading={imgProps.loading ?? "lazy"}
|
||||
onLoad={(e) => {
|
||||
setLoaded(true);
|
||||
onLoad?.(e);
|
||||
}}
|
||||
className={cn(
|
||||
"relative transition-opacity duration-300",
|
||||
loaded || !blurhash ? "opacity-100" : "opacity-0",
|
||||
className
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { encode } from "blurhash";
|
||||
|
||||
// Small enough to encode near-instantly, large enough to preserve the image's
|
||||
// dominant colors/shapes for the decoded placeholder.
|
||||
const ENCODE_MAX_DIMENSION = 32;
|
||||
const COMPONENT_X = 4;
|
||||
const COMPONENT_Y = 3;
|
||||
|
||||
/**
|
||||
* Computes a Blurhash string for an image File, entirely client-side (no
|
||||
* bytes leave the browser before upload — consistent with the direct-to-storage
|
||||
* upload architecture). Downsamples onto a small canvas first so encoding a
|
||||
* multi-megapixel photo stays fast.
|
||||
*
|
||||
* Returns null on any failure (unsupported file, decode error) — callers
|
||||
* treat a null blurhash as "no placeholder available" rather than fatal.
|
||||
*/
|
||||
export async function computeBlurhash(file: File): Promise<string | null> {
|
||||
try {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
const scale = ENCODE_MAX_DIMENSION / Math.max(bitmap.width, bitmap.height);
|
||||
const width = Math.max(1, Math.round(bitmap.width * scale));
|
||||
const height = Math.max(1, Math.round(bitmap.height * scale));
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return null;
|
||||
|
||||
ctx.drawImage(bitmap, 0, 0, width, height);
|
||||
bitmap.close();
|
||||
|
||||
const { data } = ctx.getImageData(0, 0, width, height);
|
||||
return encode(data, width, height, COMPONENT_X, COMPONENT_Y);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -374,7 +374,7 @@ export const adminRouter = router({
|
||||
images: {
|
||||
orderBy: { position: "asc" },
|
||||
take: 4,
|
||||
select: { storageKey: true, position: true },
|
||||
select: { storageKey: true, position: true, blurhash: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -30,6 +30,7 @@ export const milestonesRouter = router({
|
||||
notes: z.string().max(500).optional(),
|
||||
caption: z.string().max(500).optional(),
|
||||
imageKey: z.string().startsWith("posts/").optional(),
|
||||
imageBlurhash: z.string().max(100).nullable().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
@@ -49,7 +50,13 @@ export const milestonesRouter = router({
|
||||
...(input.imageKey
|
||||
? {
|
||||
images: {
|
||||
create: [{ storageKey: input.imageKey, position: 0 }],
|
||||
create: [
|
||||
{
|
||||
storageKey: input.imageKey,
|
||||
blurhash: input.imageBlurhash ?? null,
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -20,8 +20,8 @@ import { assertPetOwnership } from "@/lib/assert-pet-ownership";
|
||||
*
|
||||
* Security (T-02-30 to T-02-35):
|
||||
* - All mutations assert pet ownership via ctx.userId before any write
|
||||
* - imageKeys validated with .startsWith('posts/') — prevents path traversal (T-02-31)
|
||||
* - imageKeys.max(10) — prevents carousel injection (T-02-32)
|
||||
* - images[].key validated with .startsWith('posts/') — prevents path traversal (T-02-31)
|
||||
* - images.max(10) — prevents carousel injection (T-02-32)
|
||||
* - getPresignedUrl scopes key to posts/{ownerId}/{petId}/ (T-02-31)
|
||||
* - supabase-storage.ts is server-only — client only receives signed URL (T-02-33)
|
||||
* - updateCaption/delete assert ownership via post→pet→ownerId (T-02-34)
|
||||
@@ -95,8 +95,13 @@ export const postsRouter = router({
|
||||
z.object({
|
||||
petId: z.string().min(1),
|
||||
caption: z.string().max(500).nullable().optional(),
|
||||
imageKeys: z
|
||||
.array(z.string().startsWith("posts/"))
|
||||
images: z
|
||||
.array(
|
||||
z.object({
|
||||
key: z.string().startsWith("posts/"),
|
||||
blurhash: z.string().max(100).nullable().optional(),
|
||||
})
|
||||
)
|
||||
.min(1)
|
||||
.max(10),
|
||||
})
|
||||
@@ -112,8 +117,9 @@ export const postsRouter = router({
|
||||
type: "PHOTO",
|
||||
caption: input.caption ?? null,
|
||||
images: {
|
||||
create: input.imageKeys.map((storageKey, position) => ({
|
||||
storageKey,
|
||||
create: input.images.map((img, position) => ({
|
||||
storageKey: img.key,
|
||||
blurhash: img.blurhash ?? null,
|
||||
position,
|
||||
})),
|
||||
},
|
||||
|
||||
@@ -52,6 +52,7 @@ export const storiesRouter = router({
|
||||
z.object({
|
||||
petId: z.string().min(1),
|
||||
storageKey: z.string().startsWith("stories/"),
|
||||
blurhash: z.string().max(100).nullable().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
@@ -64,6 +65,7 @@ export const storiesRouter = router({
|
||||
data: {
|
||||
petId: input.petId,
|
||||
storageKey: input.storageKey,
|
||||
blurhash: input.blurhash ?? null,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user