From 7bf0984698e43b9aa2dd879f65951318ed410390 Mon Sep 17 00:00:00 2001 From: Maze <167211895+mazeincoding@users.noreply.github.com> Date: Sat, 31 Jan 2026 00:20:04 +0100 Subject: codebase overhaul (#697) --- .../components/editor/media-panel/drag-overlay.tsx | 57 -- .../src/components/editor/media-panel/index.tsx | 52 -- .../web/src/components/editor/media-panel/store.ts | 86 --- .../src/components/editor/media-panel/tabbar.tsx | 99 ---- .../editor/media-panel/views/captions.tsx | 303 ---------- .../components/editor/media-panel/views/media.tsx | 545 ------------------ .../editor/media-panel/views/settings.tsx | 332 ----------- .../components/editor/media-panel/views/sounds.tsx | 562 ------------------- .../editor/media-panel/views/stickers.tsx | 612 --------------------- .../components/editor/media-panel/views/text.tsx | 36 -- 10 files changed, 2684 deletions(-) delete mode 100644 apps/web/src/components/editor/media-panel/drag-overlay.tsx delete mode 100644 apps/web/src/components/editor/media-panel/index.tsx delete mode 100644 apps/web/src/components/editor/media-panel/store.ts delete mode 100644 apps/web/src/components/editor/media-panel/tabbar.tsx delete mode 100644 apps/web/src/components/editor/media-panel/views/captions.tsx delete mode 100644 apps/web/src/components/editor/media-panel/views/media.tsx delete mode 100644 apps/web/src/components/editor/media-panel/views/settings.tsx delete mode 100644 apps/web/src/components/editor/media-panel/views/sounds.tsx delete mode 100644 apps/web/src/components/editor/media-panel/views/stickers.tsx delete mode 100644 apps/web/src/components/editor/media-panel/views/text.tsx (limited to 'apps/web/src/components/editor/media-panel') diff --git a/apps/web/src/components/editor/media-panel/drag-overlay.tsx b/apps/web/src/components/editor/media-panel/drag-overlay.tsx deleted file mode 100644 index e1fd257e..00000000 --- a/apps/web/src/components/editor/media-panel/drag-overlay.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { Upload, Plus, Image } from "lucide-react"; -import { Button } from "@/components/ui/button"; - -interface MediaDragOverlayProps { - isVisible: boolean; - isProcessing?: boolean; - progress?: number; - onClick?: () => void; - isEmptyState?: boolean; -} - -export function MediaDragOverlay({ - isVisible, - isProcessing = false, - progress = 0, - onClick, - isEmptyState = false, -}: MediaDragOverlayProps) { - if (!isVisible) return null; - - const handleClick = (e: React.MouseEvent) => { - if (isProcessing || !onClick) return; - e.preventDefault(); - e.stopPropagation(); - onClick(); - }; - - return ( -
-
- -
- -
-

- {isProcessing - ? `Processing your files (${progress}%)` - : "Drag and drop videos, photos, and audio files here"} -

-
- - {isProcessing && ( -
-
-
-
-
- )} -
- ); -} diff --git a/apps/web/src/components/editor/media-panel/index.tsx b/apps/web/src/components/editor/media-panel/index.tsx deleted file mode 100644 index 89b53b64..00000000 --- a/apps/web/src/components/editor/media-panel/index.tsx +++ /dev/null @@ -1,52 +0,0 @@ -"use client"; - -import { TabBar } from "./tabbar"; -import { MediaView } from "./views/media"; -import { useMediaPanelStore, Tab } from "./store"; -import { TextView } from "./views/text"; -import { SoundsView } from "./views/sounds"; -import { StickersView } from "./views/stickers"; -import { Separator } from "@/components/ui/separator"; -import { SettingsView } from "./views/settings"; -import { Captions } from "./views/captions"; - -export function MediaPanel() { - const { activeTab } = useMediaPanelStore(); - - const viewMap: Record = { - media: , - sounds: , - text: , - stickers: , - effects: ( -
- Effects view coming soon... -
- ), - transitions: ( -
- Transitions view coming soon... -
- ), - captions: , - filters: ( -
- Filters view coming soon... -
- ), - adjustment: ( -
- Adjustment view coming soon... -
- ), - settings: , - }; - - return ( -
- - -
{viewMap[activeTab]}
-
- ); -} diff --git a/apps/web/src/components/editor/media-panel/store.ts b/apps/web/src/components/editor/media-panel/store.ts deleted file mode 100644 index eb645ec3..00000000 --- a/apps/web/src/components/editor/media-panel/store.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - CaptionsIcon, - ArrowLeftRightIcon, - SparklesIcon, - StickerIcon, - MusicIcon, - VideoIcon, - BlendIcon, - SlidersHorizontalIcon, - LucideIcon, - TypeIcon, - SettingsIcon, -} from "lucide-react"; -import { create } from "zustand"; - -export type Tab = - | "media" - | "sounds" - | "text" - | "stickers" - | "effects" - | "transitions" - | "captions" - | "filters" - | "adjustment" - | "settings"; - -export const tabs: { [key in Tab]: { icon: LucideIcon; label: string } } = { - media: { - icon: VideoIcon, - label: "Media", - }, - sounds: { - icon: MusicIcon, - label: "Sounds", - }, - text: { - icon: TypeIcon, - label: "Text", - }, - stickers: { - icon: StickerIcon, - label: "Stickers", - }, - effects: { - icon: SparklesIcon, - label: "Effects", - }, - transitions: { - icon: ArrowLeftRightIcon, - label: "Transitions", - }, - captions: { - icon: CaptionsIcon, - label: "Captions", - }, - filters: { - icon: BlendIcon, - label: "Filters", - }, - adjustment: { - icon: SlidersHorizontalIcon, - label: "Adjustment", - }, - settings: { - icon: SettingsIcon, - label: "Settings", - }, -}; - -interface MediaPanelStore { - activeTab: Tab; - setActiveTab: (tab: Tab) => void; - highlightMediaId: string | null; - requestRevealMedia: (mediaId: string) => void; - clearHighlight: () => void; -} - -export const useMediaPanelStore = create((set) => ({ - activeTab: "media", - setActiveTab: (tab) => set({ activeTab: tab }), - highlightMediaId: null, - requestRevealMedia: (mediaId) => - set({ activeTab: "media", highlightMediaId: mediaId }), - clearHighlight: () => set({ highlightMediaId: null }), -})); diff --git a/apps/web/src/components/editor/media-panel/tabbar.tsx b/apps/web/src/components/editor/media-panel/tabbar.tsx deleted file mode 100644 index e2bfdff7..00000000 --- a/apps/web/src/components/editor/media-panel/tabbar.tsx +++ /dev/null @@ -1,99 +0,0 @@ -"use client"; - -import { cn } from "@/lib/utils"; -import { Tab, tabs, useMediaPanelStore } from "./store"; -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip"; -import { useEffect, useRef, useState } from "react"; - -export function TabBar() { - const { activeTab, setActiveTab } = useMediaPanelStore(); - const scrollRef = useRef(null); - const [showTopFade, setShowTopFade] = useState(false); - const [showBottomFade, setShowBottomFade] = useState(false); - - const checkScrollPosition = () => { - const element = scrollRef.current; - if (!element) return; - - const { scrollTop, scrollHeight, clientHeight } = element; - setShowTopFade(scrollTop > 0); - setShowBottomFade(scrollTop < scrollHeight - clientHeight - 1); - }; - - useEffect(() => { - const element = scrollRef.current; - if (!element) return; - - checkScrollPosition(); - element.addEventListener("scroll", checkScrollPosition); - - const resizeObserver = new ResizeObserver(checkScrollPosition); - resizeObserver.observe(element); - - return () => { - element.removeEventListener("scroll", checkScrollPosition); - resizeObserver.disconnect(); - }; - }, []); - - return ( -
-
- {(Object.keys(tabs) as Tab[]).map((tabKey) => { - const tab = tabs[tabKey]; - return ( -
setActiveTab(tabKey)} - key={tabKey} - > - - - - - -
- {tab.label} -
-
-
-
- ); - })} -
- - - -
- ); -} - -function FadeOverlay({ direction, show }: { direction: "top" | "bottom", show: boolean }) { - return ( -
- ); -} \ No newline at end of file diff --git a/apps/web/src/components/editor/media-panel/views/captions.tsx b/apps/web/src/components/editor/media-panel/views/captions.tsx deleted file mode 100644 index fbe5b418..00000000 --- a/apps/web/src/components/editor/media-panel/views/captions.tsx +++ /dev/null @@ -1,303 +0,0 @@ -import { Button } from "@/components/ui/button"; -import { PropertyGroup } from "../../properties-panel/property-item"; -import { PanelBaseView as BaseView } from "@/components/editor/panel-base-view"; -import { Language, LanguageSelect } from "@/components/language-select"; -import { useState, useRef, useEffect } from "react"; -import { extractTimelineAudio } from "@/lib/mediabunny-utils"; -import { encryptWithRandomKey, arrayBufferToBase64 } from "@/lib/zk-encryption"; -import { useTimelineStore } from "@/stores/timeline-store"; -import { DEFAULT_TEXT_ELEMENT } from "@/constants/text-constants"; -import { Loader2, Shield, Trash2, Upload } from "lucide-react"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { TextElement } from "@/types/timeline"; - -export const languages: Language[] = [ - { code: "US", name: "English" }, - { code: "ES", name: "Spanish" }, - { code: "IT", name: "Italian" }, - { code: "FR", name: "French" }, - { code: "DE", name: "German" }, - { code: "PT", name: "Portuguese" }, - { code: "RU", name: "Russian" }, - { code: "JP", name: "Japanese" }, - { code: "CN", name: "Chinese" }, -]; - -const PRIVACY_DIALOG_KEY = "opencut-transcription-privacy-accepted"; - -export function Captions() { - const [selectedCountry, setSelectedCountry] = useState("auto"); - const [isProcessing, setIsProcessing] = useState(false); - const [processingStep, setProcessingStep] = useState(""); - const [error, setError] = useState(null); - const [showPrivacyDialog, setShowPrivacyDialog] = useState(false); - const [hasAcceptedPrivacy, setHasAcceptedPrivacy] = useState(false); - const containerRef = useRef(null); - const { insertTrackAt, addElementToTrack } = useTimelineStore(); - - // Check if user has already accepted privacy on mount - useEffect(() => { - const hasAccepted = localStorage.getItem(PRIVACY_DIALOG_KEY) === "true"; - setHasAcceptedPrivacy(hasAccepted); - }, []); - - const handleGenerateTranscript = async () => { - try { - setIsProcessing(true); - setError(null); - setProcessingStep("Extracting audio..."); - - const audioBlob = await extractTimelineAudio(); - - setProcessingStep("Encrypting audio..."); - - // Encrypt the audio with a random key (zero-knowledge) - const audioBuffer = await audioBlob.arrayBuffer(); - const encryptionResult = await encryptWithRandomKey(audioBuffer); - - // Convert encrypted data to blob for upload - const encryptedBlob = new Blob([encryptionResult.encryptedData]); - - setProcessingStep("Uploading..."); - const uploadResponse = await fetch("/api/get-upload-url", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ fileExtension: "wav" }), - }); - - if (!uploadResponse.ok) { - const error = await uploadResponse.json(); - throw new Error(error.message || "Failed to get upload URL"); - } - - const { uploadUrl, fileName } = await uploadResponse.json(); - - // Upload to R2 - await fetch(uploadUrl, { - method: "PUT", - body: encryptedBlob, - }); - - setProcessingStep("Transcribing..."); - - // Call Modal transcription API with encryption parameters - const transcriptionResponse = await fetch("/api/transcribe", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - filename: fileName, - language: - selectedCountry === "auto" ? "auto" : selectedCountry.toLowerCase(), - // Send the raw encryption key and IV (zero-knowledge) - decryptionKey: arrayBufferToBase64(encryptionResult.key), - iv: arrayBufferToBase64(encryptionResult.iv), - }), - }); - - if (!transcriptionResponse.ok) { - const error = await transcriptionResponse.json(); - throw new Error(error.message || "Transcription failed"); - } - - const { text, segments } = await transcriptionResponse.json(); - - console.log("Transcription completed:", { text, segments }); - - const shortCaptions: Array<{ - text: string; - startTime: number; - duration: number; - }> = []; - - let globalEndTime = 0; // Track the end time of the last caption globally - - segments.forEach((segment: any) => { - const words = segment.text.trim().split(/\s+/); - const segmentDuration = segment.end - segment.start; - const wordsPerSecond = words.length / segmentDuration; - - // Split into chunks of 2-4 words - const chunks: string[] = []; - for (let i = 0; i < words.length; i += 3) { - chunks.push(words.slice(i, i + 3).join(" ")); - } - - // Calculate timing for each chunk to place them sequentially - let chunkStartTime = segment.start; - chunks.forEach((chunk) => { - const chunkWords = chunk.split(/\s+/).length; - const chunkDuration = Math.max(0.8, chunkWords / wordsPerSecond); // Minimum 0.8s per chunk - - let adjustedStartTime = chunkStartTime; - - // Prevent overlapping: if this caption would start before the last one ends, - // start it right after the last one ends - if (adjustedStartTime < globalEndTime) { - adjustedStartTime = globalEndTime; - } - - shortCaptions.push({ - text: chunk, - startTime: adjustedStartTime, - duration: chunkDuration, - }); - - // Update global end time - globalEndTime = adjustedStartTime + chunkDuration; - - // Next chunk starts when this one ends (for within-segment timing) - chunkStartTime += chunkDuration; - }); - }); - - // Create a single track for all captions - const captionTrackId = insertTrackAt("text", 0); - - // Add all caption elements to the same track - shortCaptions.forEach((caption, index) => { - addElementToTrack(captionTrackId, { - ...DEFAULT_TEXT_ELEMENT, - name: `Caption ${index + 1}`, - content: caption.text, - duration: caption.duration, - startTime: caption.startTime, - fontSize: 65, // Larger for captions - fontWeight: "bold", // Bold for captions - } as TextElement); - }); - - console.log( - `✅ ${shortCaptions.length} short-form caption chunks added to timeline!` - ); - } catch (error) { - console.error("Transcription failed:", error); - setError( - error instanceof Error ? error.message : "An unexpected error occurred" - ); - } finally { - setIsProcessing(false); - setProcessingStep(""); - } - }; - - return ( - - - - - -
- {error && ( -
-

{error}

-
- )} - - - - - - - - - Audio Processing Notice - - -

- To generate captions, we need to process your timeline audio - using speech-to-text technology. -

- -
-
- - - Zero-knowledge encryption - we cannot decrypt your files - even if we wanted to - -
- -
- - - Encryption keys generated randomly in your browser, never - stored anywhere - -
- -
- - - Audio encrypted before upload - raw audio never leaves - your device - -
- -
- - - Everything permanently deleted within seconds after - transcription - -
-
- -

- True zero-knowledge privacy: Encryption keys - are generated randomly in your browser and never stored - anywhere. It's cryptographically impossible for us, our cloud - providers, or anyone else to decrypt your audio files. -

-
-
- - - - -
-
-
-
- ); -} diff --git a/apps/web/src/components/editor/media-panel/views/media.tsx b/apps/web/src/components/editor/media-panel/views/media.tsx deleted file mode 100644 index 07a44a7c..00000000 --- a/apps/web/src/components/editor/media-panel/views/media.tsx +++ /dev/null @@ -1,545 +0,0 @@ -"use client"; - -import { useDragDrop } from "@/hooks/use-drag-drop"; -import { processMediaFiles } from "@/lib/media-processing"; -import { useMediaStore } from "@/stores/media-store"; -import { MediaFile } from "@/types/media"; -import { - ArrowDown01, - CloudUpload, - Grid2X2, - Image, - List, - Loader2, - Music, - Video, -} from "lucide-react"; -import { useRef, useState, useMemo } from "react"; -import { useHighlightScroll } from "@/hooks/use-highlight-scroll"; -import { toast } from "sonner"; -import { Button } from "@/components/ui/button"; -import { MediaDragOverlay } from "@/components/editor/media-panel/drag-overlay"; -import { - ContextMenu, - ContextMenuContent, - ContextMenuItem, - ContextMenuTrigger, -} from "@/components/ui/context-menu"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { DraggableMediaItem } from "@/components/ui/draggable-item"; -import { useProjectStore } from "@/stores/project-store"; -import { useTimelineStore } from "@/stores/timeline-store"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; -import { usePanelStore } from "@/stores/panel-store"; -import { useMediaPanelStore } from "../store"; - -function MediaItemWithContextMenu({ - item, - children, - onRemove, -}: { - item: MediaFile; - children: React.ReactNode; - onRemove: (e: React.MouseEvent, id: string) => Promise; -}) { - return ( - - {children} - - Export clips - onRemove(e, item.id)} - > - Delete - - - - ); -} - -export function MediaView() { - const { mediaFiles, addMediaFile, removeMediaFile } = useMediaStore(); - const { activeProject } = useProjectStore(); - const { mediaViewMode, setMediaViewMode } = usePanelStore(); - const fileInputRef = useRef(null); - const [isProcessing, setIsProcessing] = useState(false); - const [progress, setProgress] = useState(0); - const [sortBy, setSortBy] = useState<"name" | "type" | "duration" | "size">( - "name" - ); - const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc"); - const { highlightMediaId, clearHighlight } = useMediaPanelStore(); - const { highlightedId, registerElement } = useHighlightScroll( - highlightMediaId, - clearHighlight - ); - - const processFiles = async (files: FileList | File[]) => { - if (!files || files.length === 0) return; - if (!activeProject) { - toast.error("No active project"); - return; - } - - setIsProcessing(true); - setProgress(0); - try { - const processedItems = await processMediaFiles(files, (p) => - setProgress(p) - ); - for (const item of processedItems) { - await addMediaFile(activeProject.id, item); - } - } catch (error) { - console.error("Error processing files:", error); - toast.error("Failed to process files"); - } finally { - setIsProcessing(false); - setProgress(0); - } - }; - - const { isDragOver, dragProps } = useDragDrop({ - // When files are dropped, process them - onDrop: processFiles, - }); - - const handleFileSelect = () => fileInputRef.current?.click(); // Open file picker - - const handleFileChange = (e: React.ChangeEvent) => { - if (e.target.files) processFiles(e.target.files); - e.target.value = ""; // Reset input - }; - - const handleRemove = async (e: React.MouseEvent, id: string) => { - e.stopPropagation(); - - if (!activeProject) { - toast.error("No active project"); - return; - } - - await removeMediaFile(activeProject.id, id); - }; - - const formatDuration = (duration: number) => { - // Format seconds as mm:ss - const min = Math.floor(duration / 60); - const sec = Math.floor(duration % 60); - return `${min}:${sec.toString().padStart(2, "0")}`; - }; - - const filteredMediaItems = useMemo(() => { - let filtered = mediaFiles.filter((item) => { - if (item.ephemeral) return false; - return true; - }); - - filtered.sort((a, b) => { - let valueA: string | number; - let valueB: string | number; - - switch (sortBy) { - case "name": - valueA = a.name.toLowerCase(); - valueB = b.name.toLowerCase(); - break; - case "type": - valueA = a.type; - valueB = b.type; - break; - case "duration": - valueA = a.duration || 0; - valueB = b.duration || 0; - break; - case "size": - valueA = a.file.size; - valueB = b.file.size; - break; - default: - return 0; - } - - if (valueA < valueB) return sortOrder === "asc" ? -1 : 1; - if (valueA > valueB) return sortOrder === "asc" ? 1 : -1; - return 0; - }); - - return filtered; - }, [mediaFiles, sortBy, sortOrder]); - - const previewComponents = useMemo(() => { - const previews = new Map(); - - filteredMediaItems.forEach((item) => { - let preview: React.ReactNode; - - if (item.type === "image") { - preview = ( -
- {item.name} -
- ); - } else if (item.type === "video") { - if (item.thumbnailUrl) { - preview = ( -
- {item.name} -
-
- {item.duration && ( -
- {formatDuration(item.duration)} -
- )} -
- ); - } else { - preview = ( -
-
- ); - } - } else if (item.type === "audio") { - preview = ( -
- - Audio - {item.duration && ( - - {formatDuration(item.duration)} - - )} -
- ); - } else { - preview = ( -
- - Unknown -
- ); - } - - previews.set(item.id, preview); - }); - - return previews; - }, [filteredMediaItems]); - - const renderPreview = (item: MediaFile) => previewComponents.get(item.id); - - return ( - <> - {/* Hidden file input for uploading media */} - - -
-
- {/* Search and filter controls */} -
- -
- - - - - - -

- {mediaViewMode === "grid" - ? "Switch to list view" - : "Switch to grid view"} -

-
- - - - - - - - - { - if (sortBy === "name") { - setSortOrder( - sortOrder === "asc" ? "desc" : "asc" - ); - } else { - setSortBy("name"); - setSortOrder("asc"); - } - }} - > - Name{" "} - {sortBy === "name" && - (sortOrder === "asc" ? "↑" : "↓")} - - { - if (sortBy === "type") { - setSortOrder( - sortOrder === "asc" ? "desc" : "asc" - ); - } else { - setSortBy("type"); - setSortOrder("asc"); - } - }} - > - Type{" "} - {sortBy === "type" && - (sortOrder === "asc" ? "↑" : "↓")} - - { - if (sortBy === "duration") { - setSortOrder( - sortOrder === "asc" ? "desc" : "asc" - ); - } else { - setSortBy("duration"); - setSortOrder("asc"); - } - }} - > - Duration{" "} - {sortBy === "duration" && - (sortOrder === "asc" ? "↑" : "↓")} - - { - if (sortBy === "size") { - setSortOrder( - sortOrder === "asc" ? "desc" : "asc" - ); - } else { - setSortBy("size"); - setSortOrder("asc"); - } - }} - > - File Size{" "} - {sortBy === "size" && - (sortOrder === "asc" ? "↑" : "↓")} - - - - -

- Sort by {sortBy} ( - {sortOrder === "asc" ? "ascending" : "descending"}) -

-
-
-
-
-
-
-
- -
-
- {isDragOver || filteredMediaItems.length === 0 ? ( - - ) : mediaViewMode === "grid" ? ( - - ) : ( - - )} -
-
-
- - ); -} - -function GridView({ - filteredMediaItems, - renderPreview, - handleRemove, - highlightedId, - registerElement, -}: { - filteredMediaItems: MediaFile[]; - renderPreview: (item: MediaFile) => React.ReactNode; - handleRemove: (e: React.MouseEvent, id: string) => Promise; - highlightedId: string | null; - registerElement: (id: string, element: HTMLElement | null) => void; -}) { - const { addElementAtTime } = useTimelineStore(); - - return ( -
- {filteredMediaItems.map((item) => ( -
registerElement(item.id, el)}> - - - addElementAtTime(item, currentTime) - } - rounded={false} - variant="card" - isHighlighted={highlightedId === item.id} - /> - -
- ))} -
- ); -} - -function ListView({ - filteredMediaItems, - renderPreview, - handleRemove, - highlightedId, - registerElement, -}: { - filteredMediaItems: MediaFile[]; - renderPreview: (item: MediaFile) => React.ReactNode; - handleRemove: (e: React.MouseEvent, id: string) => Promise; - highlightedId: string | null; - registerElement: (id: string, element: HTMLElement | null) => void; -}) { - const { addElementAtTime } = useTimelineStore(); - - return ( -
- {filteredMediaItems.map((item) => ( -
registerElement(item.id, el)}> - - - addElementAtTime(item, currentTime) - } - variant="compact" - isHighlighted={highlightedId === item.id} - /> - -
- ))} -
- ); -} diff --git a/apps/web/src/components/editor/media-panel/views/settings.tsx b/apps/web/src/components/editor/media-panel/views/settings.tsx deleted file mode 100644 index be54a9c4..00000000 --- a/apps/web/src/components/editor/media-panel/views/settings.tsx +++ /dev/null @@ -1,332 +0,0 @@ -"use client"; - -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import { PanelBaseView as BaseView } from "@/components/editor/panel-base-view"; -import { - PropertyItem, - PropertyItemLabel, - PropertyItemValue, - PropertyGroup, -} from "../../properties-panel/property-item"; -import { FPS_PRESETS } from "@/constants/timeline-constants"; -import { useProjectStore } from "@/stores/project-store"; -import type { BlurIntensity } from "@/types/project"; -import { useEditorStore } from "@/stores/editor-store"; -import { useAspectRatio } from "@/hooks/use-aspect-ratio"; -import Image from "next/image"; -import { cn } from "@/lib/utils"; -import { colors } from "@/data/colors/solid"; -import { patternCraftGradients } from "@/data/colors/pattern-craft"; -import { PipetteIcon, PlusIcon } from "lucide-react"; -import { useMemo, memo, useCallback } from "react"; -import { syntaxUIGradients } from "@/data/colors/syntax-ui"; -import { Button } from "@/components/ui/button"; -import { Separator } from "@/components/ui/separator"; - -export function SettingsView() { - return ; -} - -function ProjectSettingsTabs() { - return ( - - -
- ), - }, - { - value: "background", - label: "Background", - content: ( -
-
- -
-
- - -
- - {/* Another UI, looks so beautiful i don't wanna remove it */} - {/*
- -
*/} -
- ), - }, - ]} - className="flex flex-col justify-between h-full p-0" - /> - ); -} - -function ProjectInfoView() { - const { activeProject, updateProjectFps, updateCanvasSize } = - useProjectStore(); - const { canvasPresets } = useEditorStore(); - const { getDisplayName } = useAspectRatio(); - - const handleAspectRatioChange = (value: string) => { - const preset = canvasPresets.find((p) => p.name === value); - if (preset) { - updateCanvasSize( - { width: preset.width, height: preset.height }, - "preset" - ); - } - }; - - const handleFpsChange = (value: string) => { - const fps = parseFloat(value); - updateProjectFps(fps); - }; - - return ( -
- - Name - - {activeProject?.name || "Untitled project"} - - - - - Aspect ratio - - - - - - - Frame rate - - - - -
- ); -} - -const BlurPreview = memo( - ({ - blur, - isSelected, - onSelect, - }: { - blur: { label: string; value: number }; - isSelected: boolean; - onSelect: () => void; - }) => ( -
- {`Blur -
- - {blur.label} - -
-
- ) -); - -BlurPreview.displayName = "BlurPreview"; - -const BackgroundPreviews = memo( - ({ - backgrounds, - currentBackgroundColor, - isColorBackground, - handleColorSelect, - useBackgroundColor = false, - }: { - backgrounds: string[]; - currentBackgroundColor: string; - isColorBackground: boolean; - handleColorSelect: (bg: string) => void; - useBackgroundColor?: boolean; - }) => { - return useMemo( - () => - backgrounds.map((bg, index) => ( -
handleColorSelect(bg)} - /> - )), - [ - backgrounds, - isColorBackground, - currentBackgroundColor, - handleColorSelect, - useBackgroundColor, - ] - ); - } -); - -BackgroundPreviews.displayName = "BackgroundPreviews"; - -function BackgroundView() { - const { activeProject, updateBackgroundType } = useProjectStore(); - - const blurLevels = useMemo>( - () => [ - { label: "Light", value: 4 }, - { label: "Medium", value: 8 }, - { label: "Heavy", value: 18 }, - ], - [] - ); - - const handleBlurSelect = useCallback( - async (blurIntensity: BlurIntensity) => { - await updateBackgroundType("blur", { blurIntensity }); - }, - [updateBackgroundType] - ); - - const handleColorSelect = useCallback( - async (color: string) => { - await updateBackgroundType("color", { backgroundColor: color }); - }, - [updateBackgroundType] - ); - - const currentBlurIntensity = activeProject?.blurIntensity || 8; - const isBlurBackground = activeProject?.backgroundType === "blur"; - const currentBackgroundColor = activeProject?.backgroundColor || "#000000"; - const isColorBackground = activeProject?.backgroundType === "color"; - - const blurPreviews = useMemo( - () => - blurLevels.map((blur) => ( - handleBlurSelect(blur.value)} - /> - )), - [blurLevels, isBlurBackground, currentBlurIntensity, handleBlurSelect] - ); - - return ( -
- -
{blurPreviews}
-
- - -
-
- -
- -
-
- - -
- -
-
- - -
- -
-
-
- ); -} diff --git a/apps/web/src/components/editor/media-panel/views/sounds.tsx b/apps/web/src/components/editor/media-panel/views/sounds.tsx deleted file mode 100644 index 700eaea7..00000000 --- a/apps/web/src/components/editor/media-panel/views/sounds.tsx +++ /dev/null @@ -1,562 +0,0 @@ -"use client"; - -import { Input } from "@/components/ui/input"; -import { useState, useMemo, useEffect } from "react"; -import { Separator } from "@/components/ui/separator"; -import { ScrollArea } from "@/components/ui/scroll-area"; -import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; -import { - PlayIcon, - PauseIcon, - HeartIcon, - PlusIcon, - ListFilter, -} from "lucide-react"; -import { useSoundsStore } from "@/stores/sounds-store"; -import { useSoundSearch } from "@/hooks/use-sound-search"; -import type { SoundEffect, SavedSound } from "@/types/sounds"; -import { Button } from "@/components/ui/button"; -import { - DropdownMenu, - DropdownMenuTrigger, - DropdownMenuContent, - DropdownMenuCheckboxItem, -} from "@/components/ui/dropdown-menu"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; -import { cn } from "@/lib/utils"; -import { useInfiniteScroll } from "@/hooks/use-infinite-scroll"; - -export function SoundsView() { - return ( -
- -
- - Sound effects - Songs - Saved - -
- - - - - - - - - - -
-
- ); -} - -function SoundEffectsView() { - const { - topSoundEffects, - isLoading, - searchQuery, - setSearchQuery, - scrollPosition, - setScrollPosition, - loadSavedSounds, - isSoundSaved, - toggleSavedSound, - showCommercialOnly, - toggleCommercialFilter, - hasLoaded, - setTopSoundEffects, - setLoading, - setError, - setHasLoaded, - setCurrentPage, - setHasNextPage, - setTotalCount, - } = useSoundsStore(); - const { - results: searchResults, - isLoading: isSearching, - loadMore, - hasNextPage, - isLoadingMore, - } = useSoundSearch(searchQuery, showCommercialOnly); - - // Audio playback state - const [playingId, setPlayingId] = useState(null); - const [audioElement, setAudioElement] = useState( - null - ); - - const { scrollAreaRef, handleScroll } = useInfiniteScroll({ - onLoadMore: loadMore, - hasMore: hasNextPage, - isLoading: isLoadingMore || isSearching, - }); - - useEffect(() => { - loadSavedSounds(); - - if (!hasLoaded) { - let ignore = false; - - const fetchTopSounds = async () => { - try { - if (!ignore) { - setLoading(true); - setError(null); - } - - const response = await fetch( - "/api/sounds/search?page_size=50&sort=downloads" - ); - - if (!ignore) { - if (!response.ok) { - throw new Error(`Failed to fetch: ${response.status}`); - } - - const data = await response.json(); - setTopSoundEffects(data.results); - setHasLoaded(true); - - setCurrentPage(1); - setHasNextPage(!!data.next); - setTotalCount(data.count); - } - } catch (error) { - if (!ignore) { - console.error("Failed to fetch top sounds:", error); - setError( - error instanceof Error ? error.message : "Failed to load sounds" - ); - } - } finally { - if (!ignore) { - setLoading(false); - } - } - }; - - const timeoutId = setTimeout(fetchTopSounds, 100); - - return () => { - clearTimeout(timeoutId); - ignore = true; - }; - } - - if (scrollAreaRef.current && scrollPosition > 0) { - const timeoutId = setTimeout(() => { - scrollAreaRef.current?.scrollTo({ top: scrollPosition }); - }, 100); - - return () => clearTimeout(timeoutId); - } - }, [ - hasLoaded, - setTopSoundEffects, - setLoading, - setError, - setHasLoaded, - setCurrentPage, - setHasNextPage, - setTotalCount, - ]); - - const handleScrollWithPosition = (event: React.UIEvent) => { - const { scrollTop } = event.currentTarget; - setScrollPosition(scrollTop); - handleScroll(event); - }; - - const displayedSounds = useMemo(() => { - const sounds = searchQuery ? searchResults : topSoundEffects; - return sounds; - }, [searchQuery, searchResults, topSoundEffects]); - - const playSound = (sound: SoundEffect) => { - if (playingId === sound.id) { - audioElement?.pause(); - setPlayingId(null); - return; - } - - // Stop previous sound - audioElement?.pause(); - - if (sound.previewUrl) { - const audio = new Audio(sound.previewUrl); - audio.addEventListener("ended", () => { - setPlayingId(null); - }); - audio.addEventListener("error", (e) => { - setPlayingId(null); - }); - audio.play().catch((error) => { - setPlayingId(null); - }); - - setAudioElement(audio); - setPlayingId(sound.id); - } - }; - - return ( -
-
- setSearchQuery(e.target.value)} - showClearIcon - onClear={() => setSearchQuery("")} - /> - - - - - - - Show only commercially licensed - -
- {showCommercialOnly - ? "Only showing sounds licensed for commercial use" - : "Showing all sounds regardless of license"} -
-
-
-
- -
- -
- {isLoading && !searchQuery && ( -
- Loading sounds... -
- )} - {isSearching && searchQuery && ( -
Searching...
- )} - {displayedSounds.map((sound) => ( - playSound(sound)} - isSaved={isSoundSaved(sound.id)} - onToggleSaved={() => toggleSavedSound(sound)} - /> - ))} - {!isLoading && !isSearching && displayedSounds.length === 0 && ( -
- {searchQuery ? "No sounds found" : "No sounds available"} -
- )} - {isLoadingMore && ( -
- Loading more sounds... -
- )} -
-
-
-
- ); -} - -function SavedSoundsView() { - const { - savedSounds, - isLoadingSavedSounds, - savedSoundsError, - loadSavedSounds, - isSoundSaved, - toggleSavedSound, - clearSavedSounds, - } = useSoundsStore(); - - // Audio playback state - const [playingId, setPlayingId] = useState(null); - const [audioElement, setAudioElement] = useState( - null - ); - - // Clear confirmation dialog state - const [showClearDialog, setShowClearDialog] = useState(false); - - // Load saved sounds when tab becomes active - useEffect(() => { - loadSavedSounds(); - }, [loadSavedSounds]); - - const playSound = (sound: SavedSound) => { - if (playingId === sound.id) { - audioElement?.pause(); - setPlayingId(null); - return; - } - - // Stop previous sound - audioElement?.pause(); - - if (sound.previewUrl) { - const audio = new Audio(sound.previewUrl); - audio.addEventListener("ended", () => { - setPlayingId(null); - }); - audio.addEventListener("error", (e) => { - setPlayingId(null); - }); - audio.play().catch((error) => { - setPlayingId(null); - }); - - setAudioElement(audio); - setPlayingId(sound.id); - } - }; - - // Convert SavedSound to SoundEffect for compatibility with AudioItem - const convertToSoundEffect = (savedSound: SavedSound): SoundEffect => ({ - id: savedSound.id, - name: savedSound.name, - description: "", - url: "", - previewUrl: savedSound.previewUrl, - downloadUrl: savedSound.downloadUrl, - duration: savedSound.duration, - filesize: 0, - type: "audio", - channels: 0, - bitrate: 0, - bitdepth: 0, - samplerate: 0, - username: savedSound.username, - tags: savedSound.tags, - license: savedSound.license, - created: savedSound.savedAt, - downloads: 0, - rating: 0, - ratingCount: 0, - }); - - if (isLoadingSavedSounds) { - return ( -
-
- Loading saved sounds... -
-
- ); - } - - if (savedSoundsError) { - return ( -
-
- Error: {savedSoundsError} -
-
- ); - } - - if (savedSounds.length === 0) { - return ( -
- -
-

No saved sounds

-

- Click the heart icon on any sound to save it here -

-
-
- ); - } - - return ( -
-
-

- {savedSounds.length} saved{" "} - {savedSounds.length === 1 ? "sound" : "sounds"} -

- - - - - - - Clear all saved sounds? - - This will permanently remove all {savedSounds.length} saved - sounds from your collection. This action cannot be undone. - - - - - - - - -
- -
- -
- {savedSounds.map((sound) => ( - playSound(sound)} - isSaved={isSoundSaved(sound.id)} - onToggleSaved={() => - toggleSavedSound(convertToSoundEffect(sound)) - } - /> - ))} -
-
-
-
- ); -} - -function SongsView() { - return
Songs
; -} - -interface AudioItemProps { - sound: SoundEffect; - isPlaying: boolean; - onPlay: () => void; - isSaved: boolean; - onToggleSaved: () => void; -} - -function AudioItem({ - sound, - isPlaying, - onPlay, - isSaved, - onToggleSaved, -}: AudioItemProps) { - const { addSoundToTimeline } = useSoundsStore(); - - const handleClick = () => { - onPlay(); - }; - - const handleSaveClick = (e: React.MouseEvent) => { - e.stopPropagation(); - onToggleSaved(); - }; - - const handleAddToTimeline = async (e: React.MouseEvent) => { - e.stopPropagation(); - await addSoundToTimeline(sound); - }; - - return ( -
-
-
- {isPlaying ? ( - - ) : ( - - )} -
- -
-

{sound.name}

- - {sound.username} - -
- -
- - -
-
- ); -} diff --git a/apps/web/src/components/editor/media-panel/views/stickers.tsx b/apps/web/src/components/editor/media-panel/views/stickers.tsx deleted file mode 100644 index f67450cc..00000000 --- a/apps/web/src/components/editor/media-panel/views/stickers.tsx +++ /dev/null @@ -1,612 +0,0 @@ -"use client"; - -import { useEffect, useState, useMemo } from "react"; -import { useStickersStore } from "@/stores/stickers-store"; -import { useMediaStore } from "@/stores/media-store"; -import { useProjectStore } from "@/stores/project-store"; -import { useTimelineStore } from "@/stores/timeline-store"; -import { usePlaybackStore } from "@/stores/playback-store"; -import { - Loader2, - Grid3X3, - Hash, - Smile, - Clock, - X, - Sparkles, - ArrowRight, - StickerIcon, -} from "lucide-react"; -import { toast } from "sonner"; -import { Button } from "@/components/ui/button"; -import { ScrollArea } from "@/components/ui/scroll-area"; -import { PanelBaseView as BaseView } from "@/components/editor/panel-base-view"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; - -import { - getIconSvgUrl, - buildIconSvgUrl, - ICONIFY_HOSTS, - POPULAR_COLLECTIONS, -} from "@/lib/iconify-api"; -import { cn } from "@/lib/utils"; -import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; -import Image from "next/image"; -import type { MediaFile } from "@/types/media"; -import { DraggableMediaItem } from "@/components/ui/draggable-item"; -import { InputWithBack } from "@/components/ui/input-with-back"; -import { StickerCategory } from "@/stores/stickers-store"; -import { useInfiniteScroll } from "@/hooks/use-infinite-scroll"; - -export function StickersView() { - const { selectedCategory, setSelectedCategory } = useStickersStore(); - - return ( - { - if (["all", "general", "brands", "emoji"].includes(v)) { - setSelectedCategory(v as StickerCategory); - } - }} - tabs={[ - { - value: "all", - label: "All", - icon: , - content: , - }, - { - value: "general", - label: "Icons", - icon: , - content: , - }, - { - value: "brands", - label: "Brands", - icon: , - content: , - }, - { - value: "emoji", - label: "Emoji", - icon: , - content: , - }, - ]} - className="flex flex-col h-full p-0 overflow-hidden" - /> - ); -} - -function StickerGrid({ - icons, - onAdd, - addingSticker, - capSize = false, -}: { - icons: string[]; - onAdd: (iconName: string) => void; - addingSticker: string | null; - capSize?: boolean; -}) { - return ( -
- {icons.map((iconName) => ( - - ))} -
- ); -} - -function CollectionGrid({ - collections, - onSelectCollection, -}: { - collections: Array<{ - prefix: string; - name: string; - total: number; - category?: string; - }>; - onSelectCollection: (prefix: string) => void; -}) { - return ( -
- {collections.map((collection) => ( - onSelectCollection(collection.prefix)} - /> - ))} -
- ); -} - -function EmptyView({ message }: { message: string }) { - return ( -
- -
-

No stickers found

-

{message}

-
-
- ); -} - -function StickersContentView({ category }: { category: StickerCategory }) { - const { activeProject } = useProjectStore(); - const { addElementAtTime } = useTimelineStore(); - const { currentTime } = usePlaybackStore(); - const { addMediaFile } = useMediaStore(); - const { - searchQuery, - selectedCollection, - viewMode, - collections, - currentCollection, - searchResults, - recentStickers, - isLoadingCollections, - isLoadingCollection, - isSearching, - setSearchQuery, - setSelectedCollection, - loadCollections, - searchStickers, - addStickerToTimeline, - clearRecentStickers, - setSelectedCategory, - addingSticker, - } = useStickersStore(); - - const [localSearchQuery, setLocalSearchQuery] = useState(searchQuery); - const [collectionsToShow, setCollectionsToShow] = useState(20); - const [showCollectionItems, setShowCollectionItems] = useState(false); - - const filteredCollections = useMemo(() => { - if (category === "all") { - return Object.entries(collections).map(([prefix, collection]) => ({ - prefix, - name: collection.name, - total: collection.total, - category: collection.category, - })); - } - - const collectionList = - POPULAR_COLLECTIONS[category as keyof typeof POPULAR_COLLECTIONS]; - if (!collectionList) return []; - - return collectionList - .map((c) => { - const collection = collections[c.prefix]; - return collection - ? { - prefix: c.prefix, - name: c.name, - total: collection.total, - } - : null; - }) - .filter(Boolean) as Array<{ - prefix: string; - name: string; - total: number; - }>; - }, [collections, category]); - - const { scrollAreaRef, handleScroll } = useInfiniteScroll({ - onLoadMore: () => setCollectionsToShow((prev) => prev + 20), - hasMore: filteredCollections.length > collectionsToShow, - isLoading: isLoadingCollections, - enabled: viewMode === "browse" && !selectedCollection && category === "all", - }); - - useEffect(() => { - if (Object.keys(collections).length === 0) { - loadCollections(); - } - }, []); - - useEffect(() => { - const timer = setTimeout(() => { - if (localSearchQuery !== searchQuery) { - setSearchQuery(localSearchQuery); - if (localSearchQuery.trim()) { - searchStickers(localSearchQuery); - } - } - }, 500); - - return () => clearTimeout(timer); - }, [localSearchQuery]); - - const handleAddSticker = async (iconName: string) => { - try { - await addStickerToTimeline(iconName); - } catch (error) { - console.error("Failed to add sticker:", error); - toast.error("Failed to add sticker to timeline"); - } - }; - - const iconsToDisplay = useMemo(() => { - if (viewMode === "search" && searchResults) { - return searchResults.icons; - } - - if (viewMode === "collection" && currentCollection) { - const icons: string[] = []; - - if (currentCollection.uncategorized) { - icons.push( - ...currentCollection.uncategorized.map( - (name) => `${currentCollection.prefix}:${name}` - ) - ); - } - - if (currentCollection.categories) { - Object.values(currentCollection.categories).forEach((categoryIcons) => { - icons.push( - ...categoryIcons.map( - (name) => `${currentCollection.prefix}:${name}` - ) - ); - }); - } - - return icons.slice(0, 100); - } - - return []; - }, [viewMode, searchResults, currentCollection]); - - const isInCollection = viewMode === "collection" && !!selectedCollection; - - useEffect(() => { - if (isInCollection) { - setShowCollectionItems(false); - const timer = setTimeout(() => setShowCollectionItems(true), 350); - return () => clearTimeout(timer); - } else { - setShowCollectionItems(false); - } - }, [isInCollection]); - - return ( -
-
- { - if (!expanded && isInCollection) { - setSelectedCollection(null); - } - }} - placeholder={ - category === "all" - ? "Search all stickers" - : category === "general" - ? "Search icons" - : category === "brands" - ? "Search brands" - : "Search Emojis" - } - value={localSearchQuery} - onChange={setLocalSearchQuery} - disableAnimation={true} - /> -
- -
- -
- {recentStickers.length > 0 && viewMode === "browse" && ( -
-
- - Recent - - - - - - -

Clear recent stickers

-
-
-
-
- -
- )} - - {viewMode === "collection" && selectedCollection && ( -
- {isLoadingCollection ? ( -
- -
- ) : showCollectionItems ? ( - - ) : ( -
- -
- )} -
- )} - - {viewMode === "search" && ( -
- {isSearching ? ( -
- -
- ) : searchResults?.icons.length ? ( - <> -
- - {searchResults.total} results - -
- - - ) : searchQuery ? ( -
- - {category !== "all" && ( - - )} -
- ) : null} -
- )} - - {viewMode === "browse" && !selectedCollection && ( -
- {isLoadingCollections ? ( -
- -
- ) : ( - <> - {category !== "all" && ( -
-

- Popular{" "} - {category === "general" - ? "Icon Sets" - : category === "brands" - ? "Brand Icons" - : "Emoji Sets"} -

- -
- )} - - {category === "all" && filteredCollections.length > 0 && ( -
- -
- )} - - )} -
- )} -
-
-
-
- ); -} - -interface CollectionItemProps { - title: string; - subtitle: string; - onClick: () => void; -} - -function CollectionItem({ title, subtitle, onClick }: CollectionItemProps) { - return ( - - ); -} - -interface StickerItemProps { - iconName: string; - onAdd: (iconName: string) => void; - isAdding?: boolean; - capSize?: boolean; -} - -function StickerItem({ - iconName, - onAdd, - isAdding, - capSize = false, -}: StickerItemProps) { - const [imageError, setImageError] = useState(false); - const [hostIndex, setHostIndex] = useState(0); - - useEffect(() => { - setImageError(false); - setHostIndex(0); - }, [iconName]); - - const displayName = iconName.split(":")[1] || iconName; - const collectionPrefix = iconName.split(":")[0]; - - const preview = imageError ? ( -
- - {displayName} - -
- ) : ( -
- {displayName} { - const next = hostIndex + 1; - if (next < ICONIFY_HOSTS.length) { - setHostIndex(next); - } else { - setImageError(true); - } - }} - loading="lazy" - unoptimized - /> -
- ); - - return ( - - -
- onAdd(iconName)} - aspectRatio={1} - showLabel={false} - rounded={true} - variant="card" - className="" - containerClassName="w-full" - isDraggable={false} - /> - {isAdding && ( -
- -
- )} -
-
- -
-

{displayName}

-

{collectionPrefix}

-
-
-
- ); -} diff --git a/apps/web/src/components/editor/media-panel/views/text.tsx b/apps/web/src/components/editor/media-panel/views/text.tsx deleted file mode 100644 index 22fc2413..00000000 --- a/apps/web/src/components/editor/media-panel/views/text.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { DraggableMediaItem } from "@/components/ui/draggable-item"; -import { PanelBaseView as BaseView } from "@/components/editor/panel-base-view"; -import { useTimelineStore } from "@/stores/timeline-store"; -import { DEFAULT_TEXT_ELEMENT } from "@/constants/text-constants"; - -export function TextView() { - return ( - - - Default text -
- } - dragData={{ - id: "temp-text-id", - type: DEFAULT_TEXT_ELEMENT.type, - name: DEFAULT_TEXT_ELEMENT.name, - content: DEFAULT_TEXT_ELEMENT.content, - }} - aspectRatio={1} - onAddToTimeline={(currentTime) => - useTimelineStore.getState().addElementAtTime( - { - ...DEFAULT_TEXT_ELEMENT, - id: "temp-text-id", - }, - currentTime - ) - } - showLabel={false} - /> - - ); -} -- cgit v1.3.1