Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

feat: enhance video upload and caching mechanisms, improve UI feedback in PhotoPickerPopover

CristianOlivera1d98fa18acff3
diff --git a/app/components/ui/PhotoPickerPopover.tsx b/app/components/ui/PhotoPickerPopover.tsx
index 6e545c6..06a5421 100644
--- a/app/components/ui/PhotoPickerPopover.tsx
+++ b/app/components/ui/PhotoPickerPopover.tsx
@@ -88,7 +88,7 @@ function MasonryGrid({
if (!photos.length) {
return (
- <div className="flex flex-col items-center justify-center py-20 text-muted-foreground/40 gap-3">
+ <div className="flex flex-col items-center justify-center py-20 text-muted-foreground/70 gap-3">
<Icon icon="ph:image-broken-duotone" width="48" className="opacity-50" />
<span className="text-xs font-medium tracking-wide">{emptyText}</span>
</div>
@@ -244,31 +244,31 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
</TooltipAction>
<PopoverContent side="right" align="start" sideOffset={12} className="w-115 p-0 border-0 shadow-2xl">
<div className="flex flex-col bg-popover dark:bg-black border border-border squircle-element-camera overflow-hidden shadow-2xl max-h-150">
- <div className="px-4 py-3 border-b border-border bg-muted shrink-0">
+ <div className="px-4 py-3 border-b border-border shrink-0">
<div className="flex items-center gap-2">
<Icon icon="ph:images-bold" width="13" className="text-muted-foreground" aria-hidden="true" />
<span className="text-[11px] font-medium uppercase tracking-[0.15em] text-muted-foreground">
{t("title")}
</span>
- <span className="ml-auto text-[11px] text-muted-foreground/40">
+ <span className="ml-auto text-[11px] text-muted-foreground/70">
{isSearchMode ? `"${activeQuery}"` : t("statusDiscovering")}
</span>
</div>
</div>
<div className="px-4 pt-3 pb-2 shrink-0">
- <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-muted border border-border focus-within:border-border transition-colors">
- <Icon icon="ph:magnifying-glass-bold" width="13" className="text-muted-foreground/40 shrink-0" aria-hidden="true" />
+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg border border-border focus-within:border-border transition-colors">
+ <Icon icon="ph:magnifying-glass-bold" width="13" className="text-muted-foreground/70 shrink-0" aria-hidden="true" />
<input
type="text"
value={inputValue}
onChange={handleInputChange}
onKeyDown={handleInputKeyDown}
placeholder={t("searchPlaceholder")}
- className="flex-1 bg-transparent text-[12px] text-foreground/80 placeholder:text-muted-foreground/40 outline-none"
+ className="flex-1 bg-transparent text-[12px] text-foreground/80 placeholder:text-muted-foreground/70 outline-none"
aria-label={t("searchPlaceholder")}
/>
{inputValue && (
- <button onClick={handleClear} className="text-muted-foreground/40 hover:text-muted-foreground transition-colors" aria-label="Clear search">
+ <button onClick={handleClear} className="text-muted-foreground/70 hover:text-muted-foreground transition-colors" aria-label="Clear search">
<Icon icon="mdi:close" width="13" aria-hidden="true" />
</button>
)}
@@ -300,12 +300,12 @@ export function PhotoPickerPopover({ onSelect }: PhotoPickerPopoverProps) {
<MasonryGrid photos={photos} onSelect={handleSelect} loading={loading && photos.length === 0} emptyText={t("noResults")} />
{loading && photos.length > 0 && (
<div className="flex justify-center py-3">
- <Icon icon="mdi:loading" className="text-muted-foreground/40 animate-spin" width="20" aria-hidden="true" />
+ <Icon icon="mdi:loading" className="text-muted-foreground/70 animate-spin" width="20" aria-hidden="true" />
</div>
)}
</div>
- <div className="px-4 py-2.5 border-t border-border bg-muted shrink-0">
- <span className="text-[11px] text-muted-foreground/40">
+ <div className="px-4 py-2.5 border-t border-border shrink-0">
+ <span className="text-[11px] text-muted-foreground/70">
{t("footerPhotosBy")}{" "}
<a
href="https://unsplash.com"
diff --git a/hooks/useScreenRecording.ts b/hooks/useScreenRecording.ts
index bffb74e..fa8c43c 100644
--- a/hooks/useScreenRecording.ts
+++ b/hooks/useScreenRecording.ts
@@ -6,7 +6,6 @@ import type { RecordingState, RecordingResult, VideoData, RecordingContextType }
import type { CameraConfig, RecordingSetupConfig } from "@/types/camera.types";
import { DEFAULT_RECORDING_SETUP, requestCameraStream, requestMicrophoneStream } from "@/types/camera.types";
import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";
-import { convertToMp4 } from "@/lib/video-conversion";
import { clearVideoTrack } from "@/lib/video-upload-cache";
import { clearVideoProjectAndAudios } from "@/lib/video-project-cache";
@@ -115,6 +114,22 @@ async function saveVideoToIndexedDB(
});
}
+let cachedLoadedVideo: {
+ videoId: string;
+ url: string;
+ cameraUrl: string | null;
+} | null = null;
+
+function releaseCachedLoadedVideo(): void {
+ if (cachedLoadedVideo) {
+ URL.revokeObjectURL(cachedLoadedVideo.url);
+ if (cachedLoadedVideo.cameraUrl) {
+ URL.revokeObjectURL(cachedLoadedVideo.cameraUrl);
+ }
+ cachedLoadedVideo = null;
+ }
+}
+
export async function loadVideoFromIndexedDB(): Promise<{
blob: Blob;
duration: number;
@@ -141,11 +156,29 @@ export async function loadVideoFromIndexedDB(): Promise<{
db.close();
const data = getRequest.result;
if (data) {
- const url = URL.createObjectURL(data.blob);
const videoId = data.videoId || `vid_${data.timestamp || Date.now()}`;
const timestamp = data.timestamp || Date.now();
const cameraBlob: Blob | null = data.cameraBlob ?? null;
+
+ if (cachedLoadedVideo && cachedLoadedVideo.videoId === videoId) {
+ resolve({
+ blob: data.blob,
+ duration: data.duration,
+ url: cachedLoadedVideo.url,
+ videoId,
+ timestamp,
+ isRecordedVideo: data.isRecordedVideo || false,
+ cameraBlob,
+ cameraUrl: cachedLoadedVideo.cameraUrl,
+ cameraConfig: data.cameraConfig ?? null,
+ });
+ return;
+ }
+
+ releaseCachedLoadedVideo();
+ const url = URL.createObjectURL(data.blob);
const cameraUrl = cameraBlob ? URL.createObjectURL(cameraBlob) : null;
+ cachedLoadedVideo = { videoId, url, cameraUrl };
resolve({
blob: data.blob,
duration: data.duration,
@@ -186,6 +219,7 @@ export async function deleteRecordedVideo(): Promise<void> {
const deleteRequest = store.delete("currentVideo");
deleteRequest.onsuccess = () => {
db.close();
+ releaseCachedLoadedVideo();
resolve();
};
deleteRequest.onerror = () => {
@@ -236,6 +270,7 @@ export function useScreenRecording() {
const stateRef = useRef<RecordingState>("idle");
const recordingTimerRef = useRef<NodeJS.Timeout | null>(null);
const cameraConfigRef = useRef<CameraConfig | null>(null);
+ const cancelledRef = useRef(false);
useEffect(() => {
stateRef.current = state;
@@ -321,6 +356,7 @@ export function useScreenRecording() {
const startRecording = useCallback(
(screenStream: MediaStream, camStream: MediaStream | null) => {
try {
+ cancelledRef.current = false;
screenChunksRef.current = [];
cameraChunksRef.current = [];
startTimeRef.current = Date.now();
@@ -378,14 +414,16 @@ export function useScreenRecording() {
let cameraBlob: Blob | null = null;
const finalize = async () => {
+ if (cancelledRef.current) {
+ return;
+ }
setState("processing");
const duration = (Date.now() - startTimeRef.current) / 1000;
cleanupStreams();
try {
const rawScreenBlob =
screenBlob || new Blob([], { type: screenMime || "video/webm" });
- const finalMp4Blob = await convertToMp4(rawScreenBlob);
- await saveVideoToIndexedDB(finalMp4Blob, duration, {
+ await saveVideoToIndexedDB(rawScreenBlob, duration, {
cameraBlob,
cameraConfig: cameraConfigRef.current,
});
@@ -397,7 +435,7 @@ export function useScreenRecording() {
router.push("/editor");
}
} catch (err) {
- console.error("Error processing video with Mediabunny:", err);
+ console.error("Error saving recording:", err);
setError("Error processing video");
setState("idle");
restoreOriginals();
@@ -562,6 +600,7 @@ export function useScreenRecording() {
);
const cancelRecording = useCallback(() => {
+ cancelledRef.current = true;
if (screenRecorderRef.current && screenRecorderRef.current.state !== "inactive") {
screenRecorderRef.current.stop();
}
diff --git a/hooks/useVideoUpload.ts b/hooks/useVideoUpload.ts
index ade6d3d..c23cc02 100644
--- a/hooks/useVideoUpload.ts
+++ b/hooks/useVideoUpload.ts
@@ -1,5 +1,5 @@
import { useCallback, useState } from "react";
-import { saveUploadedVideo, getUploadedVideo, deleteUploadedVideo } from "@/lib/video-upload-cache";
+import { saveUploadedVideo, getUploadedVideo, deleteUploadedVideo, ALLOWED_VIDEO_TYPES, MAX_VIDEO_SIZE, mapAspectRatio } from "@/lib/video-upload-cache";
import type { AspectRatio } from "@/types";
interface UploadedVideoData {
@@ -21,17 +21,12 @@ interface UseVideoUploadReturn {
uploadError: string | null;
}
-const MAX_VIDEO_SIZE = 500 * 1024 * 1024; // 500MB
-const ALLOWED_VIDEO_TYPES = ["video/mp4", "video/webm", "video/quicktime", "video/x-matroska"];
-
-function mapAspectRatio(ratio: string): AspectRatio {
- switch (ratio) {
- case "16:9": return "16:9";
- case "9:16": return "9:16";
- case "1:1": return "1:1";
- case "4:3": return "4:3";
- case "3:4": return "3:4";
- default: return "auto";
+let cachedLoadedUrl: { key: string; url: string } | null = null;
+
+function releaseCachedUploadedUrl(): void {
+ if (cachedLoadedUrl) {
+ URL.revokeObjectURL(cachedLoadedUrl.url);
+ cachedLoadedUrl = null;
}
}
@@ -54,7 +49,9 @@ export function useVideoUpload(): UseVideoUploadReturn {
const cachedVideo = await saveUploadedVideo(file);
+ releaseCachedUploadedUrl();
const url = URL.createObjectURL(cachedVideo.blob);
+ cachedLoadedUrl = { key: `${cachedVideo.uploadedAt}`, url };
const videoId = `uploaded-${cachedVideo.uploadedAt}`;
return {
@@ -85,7 +82,23 @@ export function useVideoUpload(): UseVideoUploadReturn {
return null;
}
+ const key = `${cachedVideo.uploadedAt}`;
+ if (cachedLoadedUrl && cachedLoadedUrl.key === key) {
+ return {
+ url: cachedLoadedUrl.url,
+ videoId: `uploaded-${cachedVideo.uploadedAt}`,
+ duration: cachedVideo.duration,
+ aspectRatio: mapAspectRatio(cachedVideo.aspectRatio),
+ fileName: cachedVideo.fileName,
+ width: cachedVideo.width,
+ height: cachedVideo.height,
+ timestamp: cachedVideo.uploadedAt,
+ };
+ }
+
+ releaseCachedUploadedUrl();
const url = URL.createObjectURL(cachedVideo.blob);
+ cachedLoadedUrl = { key, url };
const videoId = `uploaded-${cachedVideo.uploadedAt}`;
return {
@@ -106,6 +119,7 @@ export function useVideoUpload(): UseVideoUploadReturn {
const clearUploadedVideo = useCallback(async (): Promise<void> => {
try {
+ releaseCachedUploadedUrl();
await deleteUploadedVideo();
} catch (error) {
console.error("Error clearing uploaded video:", error);
diff --git a/lib/video-upload-cache.ts b/lib/video-upload-cache.ts
index bd39a4f..285e62b 100644
--- a/lib/video-upload-cache.ts
+++ b/lib/video-upload-cache.ts
@@ -1,3 +1,4 @@
+import { AspectRatio } from "@/types";
import { normalizeVideoFile } from "./video-conversion";
import type { VideoTrackClip } from "@/types/video-track.types";
@@ -248,4 +249,32 @@ export async function clearVideoTrack(): Promise<void> {
} catch (error) {
console.warn("Failed to clear video track:", error);
}
+}
+
+export const MAX_VIDEO_SIZE = 500 * 1024 * 1024; // 500MB
+export const ALLOWED_VIDEO_TYPES = ["video/mp4", "video/webm", "video/quicktime", "video/x-matroska"];
+
+export function mapAspectRatio(ratio: string): AspectRatio {
+ const parts = ratio.split(/[:\/]/).map(Number);
+ const w = parts[0];
+ const h = parts[1];
+ if (!w || !h) return "auto";
+ const value = w / h;
+ const targets: Array<[AspectRatio, number]> = [
+ ["16:9", 16 / 9],
+ ["9:16", 9 / 16],
+ ["1:1", 1],
+ ["4:3", 4 / 3],
+ ["3:4", 3 / 4],
+ ];
+ let best: AspectRatio = "auto";
+ let bestDiff = Infinity;
+ for (const [label, target] of targets) {
+ const diff = Math.abs(value - target);
+ if (diff < bestDiff) {
+ bestDiff = diff;
+ best = label;
+ }
+ }
+ return bestDiff / value < 0.02 ? best : "auto";
}
\ No newline at end of file
diff --git a/lib/videos-library.ts b/lib/videos-library.ts
index c7177d8..439c338 100644
--- a/lib/videos-library.ts
+++ b/lib/videos-library.ts
@@ -213,6 +213,7 @@ export interface AddVideoWithMetadataOptions {
width: number;
height: number;
hasAudio?: boolean;
+ skipNormalization?: boolean;
}
export async function addVideoToLibraryWithMetadata(
@@ -237,7 +238,13 @@ export async function addVideoToLibraryWithMetadata(
}
}
- const { blob: normalizedBlob, wasConverted } = await normalizeVideoFile(options.blob);
+ let normalizedBlob = options.blob;
+ let wasConverted = false;
+ if (!options.skipNormalization) {
+ const result = await normalizeVideoFile(options.blob);
+ normalizedBlob = result.blob;
+ wasConverted = result.wasConverted;
+ }
const fileName = wasConverted
? `${options.fileName.replace(/\.[^/.]+$/, "")}.mp4`
: options.fileName;
diff --git a/utils/supabase/middleware.ts b/utils/supabase/middleware.ts
index fd9871a..6cc537a 100644
--- a/utils/supabase/middleware.ts
+++ b/utils/supabase/middleware.ts
@@ -117,20 +117,6 @@ export function enforceAuthRoutes(
const pathname = request.nextUrl.pathname;
const { searchParams } = request.nextUrl;
- if (!user && isVideoEditorPath(pathname, searchParams)) {
- const url = request.nextUrl.clone();
- const redirectedFrom = `${pathname}${request.nextUrl.search}`;
-
- url.pathname = pathname.replace(/\/editor$/, "/login");
- url.search = "";
- url.searchParams.set("redirectedFrom", redirectedFrom);
-
- if (searchParams.get("autoupload") === "1") {
- url.searchParams.set("autoupload", "1");
- }
-
- return NextResponse.redirect(url);
- }
if (user && isLoginPath(pathname)) {
const fallback = pathname.replace(/\/login$/, "/editor");