Skip to content

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

feat: implement useUndoRedo hook for state management, add video cache utilities, and enhance video upload and export functionalities

CristianOlivera13153c8c72fdf
diff --git a/hooks/useScreenRecording.ts b/hooks/useScreenRecording.ts
index 4931211..b2cddda 100644
--- a/hooks/useScreenRecording.ts
+++ b/hooks/useScreenRecording.ts
@@ -5,21 +5,17 @@ import { useRouter } from "next/navigation";
import type { RecordingState, RecordingResult, VideoData } from "@/types";
import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";
-// Re-export tipos para compatibilidad
export type { RecordingState, RecordingResult, VideoData };
-/**
- * Generate a unique video ID
- */
function generateVideoId(): string {
return `vid_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}
async function getDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
- const dbName = "FreeshotDB";
+ const dbName = "openvidDB";
const storeName = "videos";
- const version = 1;
+ const version = 2;
const request = indexedDB.open(dbName, version);
@@ -30,12 +26,28 @@ async function getDB(): Promise<IDBDatabase> {
}
};
- request.onsuccess = () => resolve(request.result);
+ request.onsuccess = () => {
+ const db = request.result;
+ if (!db.objectStoreNames.contains(storeName)) {
+ db.close();
+ const retryRequest = indexedDB.open(dbName, version + 1);
+ retryRequest.onupgradeneeded = (e) => {
+ const retryDb = (e.target as IDBOpenDBRequest).result;
+ if (!retryDb.objectStoreNames.contains(storeName)) {
+ retryDb.createObjectStore(storeName);
+ }
+ };
+ retryRequest.onsuccess = () => resolve(retryRequest.result);
+ retryRequest.onerror = () => reject(retryRequest.error);
+ } else {
+ resolve(db);
+ }
+ };
request.onerror = () => reject(request.error);
});
}
+
async function saveVideoToIndexedDB(blob: Blob, duration: number): Promise<string> {
- // Clear old thumbnail cache before saving new video
try {
await clearAllThumbnailCache();
} catch (e) {
@@ -43,7 +55,7 @@ async function saveVideoToIndexedDB(blob: Blob, duration: number): Promise<strin
}
const videoId = generateVideoId();
- const db = await getDB(); // Pedimos la conexión a la base de datos
+ const db = await getDB();
return new Promise((resolve, reject) => {
const storeName = "videos";
@@ -71,13 +83,11 @@ async function saveVideoToIndexedDB(blob: Blob, duration: number): Promise<strin
});
}
-// 3. Refactorización de loadVideoFromIndexedDB
-export async function loadVideoFromIndexedDB(): Promise<{ blob: Blob; duration: number; url: string; videoId: string } | null> {
+export async function loadVideoFromIndexedDB(): Promise<{ blob: Blob; duration: number; url: string; videoId: string; timestamp: number } | null> {
try {
- const db = await getDB(); // Pedimos la conexión a la base de datos
+ const db = await getDB();
const storeName = "videos";
- // Verificación de seguridad por si acaso
if (!db.objectStoreNames.contains(storeName)) {
db.close();
return null;
@@ -91,12 +101,12 @@ export async function loadVideoFromIndexedDB(): Promise<{ blob: Blob; duration:
getRequest.onsuccess = () => {
db.close();
const data = getRequest.result;
-
+
if (data) {
const url = URL.createObjectURL(data.blob);
- // Generate videoId if not exists (for backwards compatibility)
const videoId = data.videoId || `vid_${data.timestamp || Date.now()}`;
- resolve({ blob: data.blob, duration: data.duration, url, videoId });
+ const timestamp = data.timestamp || Date.now();
+ resolve({ blob: data.blob, duration: data.duration, url, videoId, timestamp });
} else {
resolve(null);
}
@@ -109,11 +119,10 @@ export async function loadVideoFromIndexedDB(): Promise<{ blob: Blob; duration:
});
} catch (error) {
console.error("Error al cargar video desde la base de datos:", error);
- return null; // Devolvemos null de forma segura si la DB falla al abrirse
+ return null;
}
}
-// Función para eliminar el video grabado de IndexedDB
export async function deleteRecordedVideo(): Promise<void> {
try {
const db = await getDB();
@@ -143,14 +152,6 @@ export async function deleteRecordedVideo(): Promise<void> {
}
}
-// Favicons como data URLs para cambio dinámico
-const favicons = {
- idle: `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="14" fill="%230E0E12" stroke="%233B82F6" stroke-width="2"/><circle cx="16" cy="16" r="6" fill="%233B82F6"/></svg>`,
- countdown: `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="14" fill="%230E0E12" stroke="%23FBBF24" stroke-width="2"/><circle cx="16" cy="16" r="6" fill="%23FBBF24"/></svg>`,
- recording: `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="14" fill="%230E0E12" stroke="%23EF4444" stroke-width="2"/><circle cx="16" cy="16" r="6" fill="%23EF4444"><animate attributeName="opacity" values="1;0.4;1" dur="1s" repeatCount="indefinite"/></circle></svg>`,
- processing: `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="14" fill="%230E0E12" stroke="%2322C55E" stroke-width="2"/><circle cx="16" cy="16" r="6" fill="%2222C55E"/></svg>`,
-};
-
const titles = {
idle: "openvid - Crea tomas cinemáticas",
countdown: (count: number) => `Grabando en ${count}...`,
@@ -170,7 +171,6 @@ export function useScreenRecording() {
const chunksRef = useRef<Blob[]>([]);
const startTimeRef = useRef<number>(0);
const originalTitleRef = useRef<string>("");
- const faviconLinkRef = useRef<HTMLLinkElement | null>(null);
const stateRef = useRef<RecordingState>("idle");
const recordingTimerRef = useRef<NodeJS.Timeout | null>(null);
@@ -178,29 +178,14 @@ export function useScreenRecording() {
stateRef.current = state;
}, [state]);
- const setFavicon = useCallback((type: keyof typeof favicons) => {
- if (typeof document === "undefined") return;
-
- if (!faviconLinkRef.current) {
- faviconLinkRef.current = document.querySelector('link[rel="icon"]');
- if (!faviconLinkRef.current) {
- faviconLinkRef.current = document.createElement("link");
- faviconLinkRef.current.rel = "icon";
- document.head.appendChild(faviconLinkRef.current);
- }
- }
- faviconLinkRef.current.href = favicons[type];
- }, []);
-
const setTitle = useCallback((title: string) => {
if (typeof document === "undefined") return;
document.title = title;
}, []);
const restoreOriginals = useCallback(() => {
- setFavicon("idle");
setTitle(originalTitleRef.current || titles.idle);
- }, [setFavicon, setTitle]);
+ }, [setTitle]);
useEffect(() => {
if (typeof document !== "undefined") {
@@ -212,17 +197,14 @@ export function useScreenRecording() {
if (state === "idle") {
restoreOriginals();
} else if (state === "countdown") {
- setFavicon("countdown");
setTitle(titles.countdown(countdown));
} else if (state === "recording") {
- setFavicon("recording");
const timeStr = recordingTime.toString().padStart(2, '0');
setTitle(`Grabando ${timeStr}s`);
} else if (state === "processing") {
- setFavicon("processing");
setTitle(titles.processing);
}
- }, [state, countdown, recordingTime, setFavicon, setTitle, restoreOriginals]);
+ }, [state, countdown, recordingTime, setTitle, restoreOriginals]);
useEffect(() => {
if (state === "recording") {
@@ -253,7 +235,6 @@ export function useScreenRecording() {
}
}, []);
- // Iniciar la grabación real
const startRecording = useCallback((stream: MediaStream) => {
try {
chunksRef.current = [];
@@ -318,7 +299,6 @@ export function useScreenRecording() {
try {
await saveVideoToIndexedDB(blob, duration);
-
router.push("/editor");
} catch (error) {
console.error("Error al guardar video:", error);
@@ -423,4 +403,4 @@ export function useScreenRecording() {
isRecording: state === "recording",
isProcessing: state === "processing",
};
-}
+}
\ No newline at end of file
diff --git a/hooks/useUndoRedo.ts b/hooks/useUndoRedo.ts
new file mode 100644
index 0000000..058653e
--- /dev/null
+++ b/hooks/useUndoRedo.ts
@@ -0,0 +1,110 @@
+import { useState, useCallback } from "react";
+
+export interface HistoryState<T> {
+ past: T[];
+ present: T;
+ future: T[];
+}
+
+interface UseUndoRedoReturn<T> {
+ state: T;
+ setState: (newState: T | ((prev: T) => T), skipHistory?: boolean) => void;
+ undo: () => void;
+ redo: () => void;
+ canUndo: boolean;
+ canRedo: boolean;
+ clearHistory: () => void;
+}
+
+const MAX_HISTORY_SIZE = 50;
+
+export function useUndoRedo<T>(initialState: T): UseUndoRedoReturn<T> {
+ const [history, setHistory] = useState<HistoryState<T>>({
+ past: [],
+ present: initialState,
+ future: [],
+ });
+
+ const setState = useCallback((newState: T | ((prev: T) => T), skipHistory = false) => {
+ setHistory((currentHistory) => {
+ const resolvedState = typeof newState === "function"
+ ? (newState as (prev: T) => T)(currentHistory.present)
+ : newState;
+
+ if (JSON.stringify(resolvedState) === JSON.stringify(currentHistory.present)) {
+ return currentHistory;
+ }
+
+ if (skipHistory) {
+ return {
+ ...currentHistory,
+ present: resolvedState,
+ };
+ }
+
+ const newPast = [...currentHistory.past, currentHistory.present];
+
+ if (newPast.length > MAX_HISTORY_SIZE) {
+ newPast.shift();
+ }
+
+ return {
+ past: newPast,
+ present: resolvedState,
+ future: [],
+ };
+ });
+ }, []);
+
+ const undo = useCallback(() => {
+ setHistory((currentHistory) => {
+ if (currentHistory.past.length === 0) {
+ return currentHistory;
+ }
+
+ const previous = currentHistory.past[currentHistory.past.length - 1];
+ const newPast = currentHistory.past.slice(0, currentHistory.past.length - 1);
+
+ return {
+ past: newPast,
+ present: previous,
+ future: [currentHistory.present, ...currentHistory.future],
+ };
+ });
+ }, []);
+
+ const redo = useCallback(() => {
+ setHistory((currentHistory) => {
+ if (currentHistory.future.length === 0) {
+ return currentHistory;
+ }
+
+ const next = currentHistory.future[0];
+ const newFuture = currentHistory.future.slice(1);
+
+ return {
+ past: [...currentHistory.past, currentHistory.present],
+ present: next,
+ future: newFuture,
+ };
+ });
+ }, []);
+
+ const clearHistory = useCallback(() => {
+ setHistory((currentHistory) => ({
+ past: [],
+ present: currentHistory.present,
+ future: [],
+ }));
+ }, []);
+
+ return {
+ state: history.present,
+ setState,
+ undo,
+ redo,
+ canUndo: history.past.length > 0,
+ canRedo: history.future.length > 0,
+ clearHistory,
+ };
+}
diff --git a/hooks/useVideoExport.ts b/hooks/useVideoExport.ts
index d309c0c..1899728 100644
--- a/hooks/useVideoExport.ts
+++ b/hooks/useVideoExport.ts
@@ -138,9 +138,13 @@ export function useVideoExport(
exportCanvas.width = targetWidth;
exportCanvas.height = targetHeight;
- // Guardar posición actual del video
+ // Guardar posición actual del video y estado de audio
const originalTime = video.currentTime;
const wasPlaying = !video.paused;
+ const originalMuted = video.muted;
+
+ // Mutear el video durante la exportación para evitar audio entrecortado
+ video.muted = true;
// Determine trim range (use full video if no trim specified)
const trimStart = settings.trim?.start ?? 0;
@@ -197,6 +201,7 @@ export function useVideoExport(
exportCanvas.width = originalWidth;
exportCanvas.height = originalHeight;
video.currentTime = originalTime;
+ video.muted = originalMuted;
// Restaurar estado de reproducción
if (wasPlaying) {
@@ -668,16 +673,17 @@ async function exportWithMediabunnyAndAudio(
}
// Add audio tracks to mix
- for (const audioTrackFile of audioTracks) {
- const { track } = audioTrackFile;
- const trackVolume = track.volume * (settings.masterVolume ?? 1);
- const delayMs = Math.round(track.startTime * 1000);
-
- // Apply delay, duration limit, and volume
- filterComplex += `[${inputIndex}:a]adelay=${delayMs}|${delayMs},volume=${trackVolume}[a${inputIndex}];`;
- audioInputs.push(`[a${inputIndex}]`);
- inputIndex++;
- }
+ for (const audioTrackFile of audioTracks) {
+ const { track } = audioTrackFile;
+ const trackVolume = track.volume * (settings.masterVolume ?? 1);
+ const delayMs = Math.round(track.startTime * 1000);
+ const audioTrimStart = track.trimStart ?? 0; // ← nuevo
+ const audioTrimEnd = audioTrimStart + track.duration; // ← nuevo
+
+ filterComplex += `[${inputIndex}:a]atrim=${audioTrimStart}:${audioTrimEnd},asetpts=PTS-STARTPTS,adelay=${delayMs}|${delayMs},volume=${trackVolume}[a${inputIndex}];`;
+ audioInputs.push(`[a${inputIndex}]`);
+ inputIndex++;
+}
// Mix all audio streams
const totalAudioInputs = (hasSourceAudio ? 1 : 0) + audioTracks.length;
diff --git a/hooks/useVideoUpload.ts b/hooks/useVideoUpload.ts
index 75c9555..44719b5 100644
--- a/hooks/useVideoUpload.ts
+++ b/hooks/useVideoUpload.ts
@@ -10,6 +10,7 @@ interface UploadedVideoData {
fileName: string;
width: number;
height: number;
+ timestamp: number; // uploadedAt timestamp for comparison
}
interface UseVideoUploadReturn {
@@ -54,7 +55,7 @@ export function useVideoUpload(): UseVideoUploadReturn {
const cachedVideo = await saveUploadedVideo(file);
const url = URL.createObjectURL(cachedVideo.blob);
- const videoId = `uploaded-${Date.now()}`;
+ const videoId = `uploaded-${cachedVideo.uploadedAt}`;
return {
url,
@@ -64,6 +65,7 @@ export function useVideoUpload(): UseVideoUploadReturn {
fileName: cachedVideo.fileName,
width: cachedVideo.width,
height: cachedVideo.height,
+ timestamp: cachedVideo.uploadedAt,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Error al subir el video";
@@ -94,6 +96,7 @@ export function useVideoUpload(): UseVideoUploadReturn {
fileName: cachedVideo.fileName,
width: cachedVideo.width,
height: cachedVideo.height,
+ timestamp: cachedVideo.uploadedAt,
};
} catch (error) {
console.error("Error loading uploaded video:", error);
diff --git a/lib/canvas-elements.config.ts b/lib/canvas-elements.config.ts
index 12abcb8..17feb6b 100644
--- a/lib/canvas-elements.config.ts
+++ b/lib/canvas-elements.config.ts
@@ -16,7 +16,7 @@ function generateImageItems(
return {
id: id,
- name: `${prefix.charAt(0).toUpperCase() + prefix.slice(1)} ${num}`, // Ej: "Sticker 01"
+ name: `${prefix.charAt(0).toUpperCase() + prefix.slice(1)} ${num}`,
imagePath: `/elements/images/${folder}/${id}.${extension}`,
};
});
@@ -30,17 +30,32 @@ export const PINNED_SVG_ITEMS = [
{ id: "arrow-right", name: "Derecha", icon: "ph:arrow-right-bold" },
{ id: "star", name: "Estrella", icon: "ph:star-bold" },
{ id: "heart", name: "Corazón", icon: "ph:heart-bold" },
- { id: "hexagon", name: "Hexágono", icon: "ph:hexagon-bold" },
- { id: "lightning", name: "Rayo", icon: "ph:lightning-bold" },
- { id: "arrow-left", name: "Izquierda", icon: "ph:arrow-left-bold" },
- { id: "diamond", name: "Rombo", icon: "ph:diamond-bold" },
+ { id: "splash", name: "Salpicadura" },
+ { id: "scribble", name: "Garabato" },
+ { id: "blob", name: "Blob", icon: "tabler:blob-filled" },
+ { id: "blob-outline", name: "Blob outline", icon: "tabler:blob" },
{ id: "chat", name: "Bocadillo", icon: "ph:chat-circle-bold" },
];
// Elementos de imagen destacados que se muestran directamente (11 slots)
export const PINNED_IMAGE_ITEMS = [
- { id: "overlay-01", name: "Lighta curve", imagePath: "/elements/images/overlays/overlay-01.webp" },
- // Add more pinned images here (up to 11 total)
+ { id: "overlay-01", name: "Overlay 1", imagePath: "/elements/images/overlays/overlay-01.webp" },
+ { id: "overlay-11", name: "Overlay 11", imagePath: "/elements/images/overlays/overlay-11.webp" },
+ { id: "overlay-06", name: "Overlay 6", imagePath: "/elements/images/overlays/overlay-06.webp" },
+ { id: "overlay-04", name: "Overlay 4", imagePath: "/elements/images/overlays/overlay-04.webp" },
+ { id: "overlay-07", name: "Overlay 7", imagePath: "/elements/images/overlays/overlay-07.webp" },
+ { id: "overlay-09", name: "Overlay 9", imagePath: "/elements/images/overlays/overlay-09.webp" },
+ { id: "overlay-14", name: "Overlay 14", imagePath: "/elements/images/overlays/overlay-14.webp" },
+ { id: "asset-06", name: "Asset 6", imagePath: "/elements/images/assets/asset-06.webp" },
+ { id: "asset-07", name: "Asset 7", imagePath: "/elements/images/assets/asset-07.webp" },
+ { id: "sticker-01", name: "Sticker 1", imagePath: "/elements/images/stickers/sticker-01.webp" },
+ { id: "sticker-04", name: "Sticker 4", imagePath: "/elements/images/stickers/sticker-04.webp" },
+ { id: "sticker-03", name: "Sticker 3", imagePath: "/elements/images/stickers/sticker-03.webp" },
+ { id: "sticker-05", name: "Sticker 5", imagePath: "/elements/images/stickers/sticker-05.webp" },
+ { id: "sticker-11", name: "Sticker 11", imagePath: "/elements/images/stickers/sticker-11.webp" },
+ { id: "sticker-60", name: "Sticker 60", imagePath: "/elements/images/stickers/sticker-60.webp" },
+ { id: "sticker-62", name: "Sticker 62", imagePath: "/elements/images/stickers/sticker-62.webp" },
+ { id: "sticker-69", name: "Sticker 69", imagePath: "/elements/images/stickers/sticker-69.webp" },
];
export const SVG_CATEGORIES: SvgCategory[] = [
@@ -55,7 +70,7 @@ export const SVG_CATEGORIES: SvgCategory[] = [
{ id: "diamond", name: "Rombo", icon: "ph:diamond-bold" },
{ id: "square", name: "Cuadrado", icon: "ph:square-bold" },
{ id: "blob", name: "Blob", icon: "tabler:blob-filled" },
- { id: "blob-outline", name: "Blob outline", icon: "tabler:blob" },
+ { id: "blob-outline", name: "Blob outline", icon: "tabler:blob" },
]
},
{
@@ -81,32 +96,31 @@ export const SVG_CATEGORIES: SvgCategory[] = [
{ id: "chat", name: "Bocadillo", icon: "ph:chat-circle-bold" },
{ id: "seal", name: "Sello", icon: "ph:seal-bold" },
{ id: "drop", name: "Gota", icon: "ph:drop-bold" },
- { id: "splash", name: "Salpicadura"},
+ { id: "splash", name: "Salpicadura" },
]
}
];
export const IMAGE_CATEGORIES: ImageCategory[] = [
- {
- id: "stickers",
- title: "Stickers",
- items: [
- // Si también tienes stickers numerados (sticker-01 a sticker-15):
- ...generateImageItems("stickers", "sticker", 1)
- ]
- },
{
id: "overlays",
title: "Superposiciones",
items: [
- ...generateImageItems("overlays", "overlay", 1)
+ ...generateImageItems("overlays", "overlay", 14)
]
},
{
id: "assets",
title: "Recursos",
items: [
- ...generateImageItems("assets", "asset", 0)
+ ...generateImageItems("assets", "asset", 7)
]
- }
+ },
+ {
+ id: "stickers",
+ title: "Stickers",
+ items: [
+ ...generateImageItems("stickers", "sticker", 74)
+ ]
+ },
];
diff --git a/lib/constants.ts b/lib/constants.ts
index df20df4..d92d9aa 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -49,3 +49,12 @@ export const TIMELINE_ZOOM_SCALE: Record<number, number> = {
9: 2.35,
10: 2.5,
};
+
+// Mockups con header → solo esquinas INFERIORES del video redondeadas
+export const BOTTOM_ONLY_RADIUS_MOCKUPS = ["macos", "macos-glass", "macos-ghost", "macos-ghost-glass", "vscode", "macos-dark-ide", "macos-ghost-ide", "brave", "brave-glass", "browser-tab-glass", "chrome", "chrome-glass"];
+
+// Mockups glass → manejan su propia sombra, no necesitan el rect sólido previo
+export const SELF_SHADOWING_MOCKUPS = ["macos-glass", "macos-ghost-glass", "glass-ui-container", "macos-container-glass", "brave-glass", "browser-tab-glass", "chrome-glass"];
+
+// Z-index del video: elementos con zIndex < VIDEO_Z_INDEX se renderizan detrás del video
+export const VIDEO_Z_INDEX = 1000;
diff --git a/lib/photo-providers.ts b/lib/photo-providers.ts
new file mode 100644
index 0000000..ef9d0b7
--- /dev/null
+++ b/lib/photo-providers.ts
@@ -0,0 +1,249 @@
+import { env } from "@/app/config/env";
+
+export interface UnifiedPhoto {
+ id: string;
+ urls: {
+ regular: string;
+ small: string;
+ };
+ alt: string;
+ photographer: string;
+ color: string;
+ width: number;
+ height: number;
+}
+
+export type PhotoProvider = "unsplash" | "pexels" | "pixabay";
+
+let providerIndex = 0;
+const providers: PhotoProvider[] = ["unsplash", "pexels", "pixabay"];
+
+function getNextProvider(): PhotoProvider {
+ const provider = providers[providerIndex];
+ providerIndex = (providerIndex + 1) % providers.length;
+ return provider;
+}
+
+interface UnsplashPhoto {
+ id: string;
+ urls: { regular: string; small: string };
+ alt_description: string | null;
+ user: { name: string };
+ color: string;
+ width: number;
+ height: number;
+}
+
+async function fetchUnsplash(query: string, page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
+ const url = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=landscape`;
+ try {
+ const res = await fetch(url, {
+ headers: { Authorization: `Client-ID ${env.unsplash.accessKey}` },
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ const results: UnsplashPhoto[] = data.results ?? [];
+ return results.map((photo) => ({
+ id: `unsplash-${photo.id}`,
+ urls: {
+ regular: photo.urls.regular,
+ small: photo.urls.small,
+ },
+ alt: photo.alt_description ?? "",
+ photographer: photo.user.name,
+ color: photo.color,
+ width: photo.width,
+ height: photo.height,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+interface PexelsPhoto {
+ id: number;
+ width: number;
+ height: number;
+ photographer: string;
+ avg_color: string;
+ src: {
+ large: string;
+ medium: string;
+ };
+ alt: string;
+}
+
+async function fetchPexels(query: string, page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
+ const url = `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=landscape`;
+ try {
+ const res = await fetch(url, {
+ headers: { Authorization: env.pexels.apiKey },
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ const results: PexelsPhoto[] = data.photos ?? [];
+ return results.map((photo) => ({
+ id: `pexels-${photo.id}`,
+ urls: {
+ regular: photo.src.large,
+ small: photo.src.medium,
+ },
+ alt: photo.alt || "",
+ photographer: photo.photographer,
+ color: photo.avg_color,
+ width: photo.width,
+ height: photo.height,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+interface PixabayPhoto {
+ id: number;
+ imageWidth: number;
+ imageHeight: number;
+ user: string;
+ tags: string;
+ webformatURL: string;
+ largeImageURL: string;
+}
+
+async function fetchPixabay(query: string, page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
+ const url = `https://pixabay.com/api/?key=${env.pixabay.apiKey}&q=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=horizontal&image_type=photo`;
+ try {
+ const res = await fetch(url);
+ if (!res.ok) return [];
+ const data = await res.json();
+ const results: PixabayPhoto[] = data.hits ?? [];
+ return results.map((photo) => ({
+ id: `pixabay-${photo.id}`,
+ urls: {
+ regular: photo.largeImageURL,
+ small: photo.webformatURL,
+ },
+ alt: photo.tags,
+ photographer: photo.user,
+ color: "#1a1a1a",
+ width: photo.imageWidth,
+ height: photo.imageHeight,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+// Discovery mode - curated/random photos
+async function fetchUnsplashCurated(page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
+ const queries = [
+ "blur gradient", "mesh gradient", "dark minimal wallpaper", "neon city night",
+ "abstract wave dark", "geometric dark background",
+ "deep space stars",
+ "aurora sky", "minimal texture dark",
+ ];
+ const query = queries[Math.floor(Math.random() * queries.length)];
+ return fetchUnsplash(query, page, perPage);
+}
+
+async function fetchPexelsCurated(page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
+ const url = `https://api.pexels.com/v1/curated?page=${page}&per_page=${perPage}`;
+ try {
+ const res = await fetch(url, {
+ headers: { Authorization: env.pexels.apiKey },
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ const results: PexelsPhoto[] = data.photos ?? [];
+ return results
+ .filter((photo) => photo.width >= photo.height)
+ .map((photo) => ({
+ id: `pexels-${photo.id}`,
+ urls: {
+ regular: photo.src.large,
+ small: photo.src.medium,
+ },
+ alt: photo.alt || "",
+ photographer: photo.photographer,
+ color: photo.avg_color,
+ width: photo.width,
+ height: photo.height,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+async function fetchPixabayCurated(page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
+ const queries = ["blur gradient", "dark minimal", "city dark", "blurred", "night sky", "minimalist background", "wallpaper sky"];
+ const query = queries[Math.floor(Math.random() * queries.length)];
+ return fetchPixabay(query, page, perPage);
+}
+
+const discoveryCache: { photos: UnifiedPhoto[]; timestamp: number } = {
+ photos: [],
+ timestamp: 0,
+};
+const DISCOVERY_TTL = 5 * 60 * 1000;
+
+export async function fetchPhotos(
+ query: string,
+ page = 1,
+ perPage = 20
+): Promise<UnifiedPhoto[]> {
+ const provider = getNextProvider();
+
+ switch (provider) {
+ case "unsplash":
+ return fetchUnsplash(query, page, perPage);
+ case "pexels":
+ return fetchPexels(query, page, perPage);
+ case "pixabay":
+ return fetchPixabay(query, page, perPage);
+ default:
+ return [];
+ }
+}
+
+export async function fetchDiscoveryPhotos(): Promise<UnifiedPhoto[]> {
+ if (
+ discoveryCache.photos.length > 0 &&
+ Date.now() - discoveryCache.timestamp < DISCOVERY_TTL
+ ) {
+ return [...discoveryCache.photos].sort(() => Math.random() - 0.5);
+ }
+
+ const [unsplashPhotos, pexelsPhotos, pixabayPhotos] = await Promise.all([
+ fetchUnsplashCurated(1, 7).catch(() => []),
+ fetchPexelsCurated(1, 7).catch(() => []),
+ fetchPixabayCurated(1, 6).catch(() => []),
+ ]);
+
+ const allPhotos = [...unsplashPhotos, ...pexelsPhotos, ...pixabayPhotos];
+ const shuffled = allPhotos.sort(() => Math.random() - 0.5);
+
+ discoveryCache.photos = shuffled;
+ discoveryCache.timestamp = Date.now();
+
+ return shuffled;
+}
+
+const searchCache = new Map<string, { photos: UnifiedPhoto[]; timestamp: number }>();
+const SEARCH_TTL = 10 * 60 * 1000;
+
+export async function fetchPhotosWithCache(
+ query: string,
+ page = 1,
+ perPage = 20
+): Promise<UnifiedPhoto[]> {
+ const cacheKey = `${query}::${page}::${perPage}`;
+ const cached = searchCache.get(cacheKey);
+
+ if (cached && Date.now() - cached.timestamp < SEARCH_TTL) {
+ return cached.photos;
+ }
+
+ const photos = await fetchPhotos(query, page, perPage);
+ searchCache.set(cacheKey, { photos, timestamp: Date.now() });
+
+ return photos;
+}
diff --git a/lib/video-cache-utils.ts b/lib/video-cache-utils.ts
new file mode 100644
index 0000000..44a7985
--- /dev/null
+++ b/lib/video-cache-utils.ts
@@ -0,0 +1,67 @@
+/**
+ * Utility functions to check for any cached video (recorded or uploaded)
+ */
+
+import { getUploadedVideo } from "./video-upload-cache";
+
+/**
+ * Check if a recorded video exists in IndexedDB
+ */
+async function hasRecordedVideo(): Promise<boolean> {
+ try {
+ const dbName = "openvidDB";
+ const storeName = "videos";
+
+ return new Promise((resolve) => {
+ const request = indexedDB.open(dbName);
+
+ request.onsuccess = () => {
+ const db = request.result;
+
+ if (!db.objectStoreNames.contains(storeName)) {
+ db.close();
+ resolve(false);
+ return;
+ }
+
+ const transaction = db.transaction([storeName], "readonly");
+ const store = transaction.objectStore(storeName);
+ const getRequest = store.get("currentVideo");
+
+ getRequest.onsuccess = () => {
+ db.close();
+ resolve(!!getRequest.result);
+ };
+
+ getRequest.onerror = () => {
+ db.close();
+ resolve(false);
+ };
+ };
+
+ request.onerror = () => {
+ resolve(false);
+ };
+ });
+ } catch (error) {
+ console.error("Error checking recorded video:", error);
+ return false;
+ }
+}
+
+/**
+ * Check if any video exists (recorded OR uploaded)
+ */
+export async function hasAnyVideo(): Promise<boolean> {
+ try {
+ // Check uploaded videos first (faster)
+ const uploadedVideo = await getUploadedVideo();
+ if (uploadedVideo) return true;
+
+ // If no uploaded video, check recorded video
+ return await hasRecordedVideo();
+ } catch (error) {
+ console.error("Error checking for any video:", error);
+ return false;
+ }
+}