From 03b3c952c75b7642b537fa2499d081edd1a0a1e4 Mon Sep 17 00:00:00 2001 From: ahmedfahim21 Date: Sun, 13 Jul 2025 00:59:54 +0530 Subject: [PATCH 01/19] feat: click to add to timeline --- .../editor/media-panel/views/media.tsx | 2 + .../editor/media-panel/views/text.tsx | 35 +++++- apps/web/src/components/editor/timeline.tsx | 64 ++-------- apps/web/src/components/ui/draggable-item.tsx | 22 +++- apps/web/src/constants/timeline-constants.ts | 1 + apps/web/src/lib/timeline-utils.ts | 117 ++++++++++++++++++ 6 files changed, 179 insertions(+), 62 deletions(-) create mode 100644 apps/web/src/lib/timeline-utils.ts diff --git a/apps/web/src/components/editor/media-panel/views/media.tsx b/apps/web/src/components/editor/media-panel/views/media.tsx index 48e54961..36478667 100644 --- a/apps/web/src/components/editor/media-panel/views/media.tsx +++ b/apps/web/src/components/editor/media-panel/views/media.tsx @@ -24,6 +24,7 @@ import { } from "@/components/ui/select"; import { DraggableMediaItem } from "@/components/ui/draggable-item"; import { useProjectStore } from "@/stores/project-store"; +import { addMediaToTimeline } from "@/lib/timeline-utils"; export function MediaView() { const { mediaItems, addMediaItem, removeMediaItem } = useMediaStore(); @@ -288,6 +289,7 @@ export function MediaView() { name: item.name, }} showPlusOnDrag={false} + onAddToTimeline={(currentTime) => addMediaToTimeline(item, currentTime)} rounded={false} /> diff --git a/apps/web/src/components/editor/media-panel/views/text.tsx b/apps/web/src/components/editor/media-panel/views/text.tsx index bec32c85..fad79343 100644 --- a/apps/web/src/components/editor/media-panel/views/text.tsx +++ b/apps/web/src/components/editor/media-panel/views/text.tsx @@ -1,4 +1,30 @@ import { DraggableMediaItem } from "@/components/ui/draggable-item"; +import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; +import { addTextToTimeline } from "@/lib/timeline-utils"; +import { type TextElement } from "@/types/timeline"; + +let textData: TextElement = { + id: "default-text", + type: "text", + name: "Default text", + content: "Default text", + fontSize: 48, + fontFamily: "Arial", + color: "#ffffff", + backgroundColor: "transparent", + textAlign: "center" as const, + fontWeight: "normal" as const, + fontStyle: "normal" as const, + textDecoration: "none" as const, + x: 0, + y: 0, + rotation: 0, + opacity: 1, + duration: TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION, + startTime: 0, + trimStart: 0, + trimEnd: 0, +}; export function TextView() { return ( @@ -11,12 +37,13 @@ export function TextView() { } dragData={{ - id: "default-text", - type: "text", - name: "Default text", - content: "Default text", + id: textData.id, + type: textData.type, + name: textData.name, + content: textData.content, }} aspectRatio={1} + onAddToTimeline={(currentTime) => addTextToTimeline(textData, currentTime)} showLabel={false} /> diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index 71e2997b..0926e7ba 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -51,6 +51,7 @@ import { import { SelectionBox } from "./selection-box"; import { useSelectionBox } from "@/hooks/use-selection-box"; import type { DragData, TimelineTrack } from "@/types/timeline"; +import { addTextToNewTrack, addMediaToNewTrack } from "@/lib/timeline-utils"; import { getTrackHeight, getCumulativeHeightBefore, @@ -216,7 +217,7 @@ export function Timeline() { Math.min( duration, (mouseX + scrollLeft) / - (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) + (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) ) ); @@ -364,29 +365,7 @@ export function Timeline() { if (dragData.type === "text") { // Always create new text track to avoid overlaps - const newTrackId = addTrack("text"); - - addElementToTrack(newTrackId, { - type: "text", - name: dragData.name || "Text", - content: dragData.content || "Default Text", - duration: TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION, - startTime: 0, - trimStart: 0, - trimEnd: 0, - fontSize: 48, - fontFamily: "Arial", - color: "#ffffff", - backgroundColor: "transparent", - textAlign: "center", - fontWeight: "normal", - fontStyle: "normal", - textDecoration: "none", - x: 0, - y: 0, - rotation: 0, - opacity: 1, - }); + addTextToNewTrack(dragData); } else { // Handle media items const mediaItem = mediaItems.find((item) => item.id === dragData.id); @@ -395,19 +374,7 @@ export function Timeline() { return; } - const trackType = dragData.type === "audio" ? "audio" : "media"; - let targetTrack = tracks.find((t) => t.type === trackType); - const newTrackId = targetTrack ? targetTrack.id : addTrack(trackType); - - addElementToTrack(newTrackId, { - type: "media", - mediaId: mediaItem.id, - name: mediaItem.name, - duration: mediaItem.duration || 5, - startTime: 0, - trimStart: 0, - trimEnd: 0, - }); + addMediaToNewTrack(mediaItem); } } catch (error) { console.error("Error parsing dropped item data:", error); @@ -435,18 +402,7 @@ export function Timeline() { item.name === processedItem.name && item.url === processedItem.url ); if (addedItem) { - const trackType = - processedItem.type === "audio" ? "audio" : "media"; - const newTrackId = addTrack(trackType); - addElementToTrack(newTrackId, { - type: "media", - mediaId: addedItem.id, - name: addedItem.name, - duration: addedItem.duration || 5, - startTime: 0, - trimStart: 0, - trimEnd: 0, - }); + addMediaToNewTrack(addedItem); } } } catch (error) { @@ -891,21 +847,19 @@ export function Timeline() { return (
{(() => { const formatTime = (seconds: number) => { diff --git a/apps/web/src/components/ui/draggable-item.tsx b/apps/web/src/components/ui/draggable-item.tsx index 16518dde..c1f81e16 100644 --- a/apps/web/src/components/ui/draggable-item.tsx +++ b/apps/web/src/components/ui/draggable-item.tsx @@ -6,12 +6,14 @@ import { ReactNode, useState, useRef, useEffect } from "react"; import { createPortal } from "react-dom"; import { Plus } from "lucide-react"; import { cn } from "@/lib/utils"; +import { usePlaybackStore } from "@/stores/playback-store"; export interface DraggableMediaItemProps { name: string; preview: ReactNode; dragData: Record; onDragStart?: (e: React.DragEvent) => void; + onAddToTimeline?: (currentTime: number) => void; aspectRatio?: number; className?: string; showPlusOnDrag?: boolean; @@ -24,6 +26,7 @@ export function DraggableMediaItem({ preview, dragData, onDragStart, + onAddToTimeline, aspectRatio = 16 / 9, className = "", showPlusOnDrag = true, @@ -33,6 +36,11 @@ export function DraggableMediaItem({ const [isDragging, setIsDragging] = useState(false); const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 }); const dragRef = useRef(null); + const currentTime = usePlaybackStore((state) => state.currentTime); + + const handleAddToTimeline = () => { + onAddToTimeline?.(currentTime); + }; const emptyImg = new window.Image(); emptyImg.src = @@ -92,7 +100,10 @@ export function DraggableMediaItem({ > {preview} {!isDragging && ( - + )} {showLabel && ( @@ -128,7 +139,7 @@ export function DraggableMediaItem({
{preview}
- {showPlusOnDrag && } + {showPlusOnDrag && }
, @@ -138,11 +149,16 @@ export function DraggableMediaItem({ ); } -function PlusButton({ className }: { className?: string }) { +function PlusButton({ className, onClick }: { className?: string; onClick?: () => void }) { return ( diff --git a/apps/web/src/constants/timeline-constants.ts b/apps/web/src/constants/timeline-constants.ts index 92045c5e..8c76a2e8 100644 --- a/apps/web/src/constants/timeline-constants.ts +++ b/apps/web/src/constants/timeline-constants.ts @@ -74,6 +74,7 @@ export const TIMELINE_CONSTANTS = { PIXELS_PER_SECOND: 50, TRACK_HEIGHT: 60, // Default fallback DEFAULT_TEXT_DURATION: 5, + DEFAULT_IMAGE_DURATION: 5, ZOOM_LEVELS: [0.25, 0.5, 1, 1.5, 2, 3, 4], } as const; diff --git a/apps/web/src/lib/timeline-utils.ts b/apps/web/src/lib/timeline-utils.ts new file mode 100644 index 00000000..994cb314 --- /dev/null +++ b/apps/web/src/lib/timeline-utils.ts @@ -0,0 +1,117 @@ +import { useTimelineStore } from "@/stores/timeline-store"; +import { type MediaItem } from "@/stores/media-store"; +import { toast } from "sonner"; +import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; +import { DragData, TextElement } from "@/types/timeline"; + + +const findOrCreateTrack = (trackType: "media" | "audio" | "text") => { + const timelineStore = useTimelineStore.getState(); + + // Always create new text track to allow multiple text elements + if (trackType === "text") { + return timelineStore.addTrack(trackType); + } + + const existingTrack = timelineStore.tracks.find(track => track.type === trackType); + return existingTrack ? existingTrack.id : timelineStore.addTrack(trackType); +}; + + +const checkOverlap = (trackId: string, startTime: number, duration: number, excludeElementId?: string) => { + const timelineStore = useTimelineStore.getState(); + const targetTrack = timelineStore.tracks.find(track => track.id === trackId); + + if (!targetTrack) { + return true; + } + + const elementEnd = startTime + duration; + + return targetTrack.elements.some((existingElement) => { + if (excludeElementId && existingElement.id === excludeElementId) { + return false; + } + + const existingStart = existingElement.startTime; + const existingEnd = existingElement.startTime + + (existingElement.duration - existingElement.trimStart - existingElement.trimEnd); + + return startTime < existingEnd && elementEnd > existingStart; + }); +}; + +const addMediaElement = (trackId: string, item: MediaItem, startTime: number) => { + const timelineStore = useTimelineStore.getState(); + + timelineStore.addElementToTrack(trackId, { + type: "media", + mediaId: item.id, + name: item.name, + duration: item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION, + startTime, + trimStart: 0, + trimEnd: 0, + }); +}; + +const addTextElement = (trackId: string, item: TextElement | DragData, startTime: number) => { + const timelineStore = useTimelineStore.getState(); + + timelineStore.addElementToTrack(trackId, { + type: "text", + name: item.name, + content: ("content" in item ? item.content : "Default Text"), + duration: TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION, + startTime, + trimStart: ("trimStart" in item ? item.trimStart : 0), + trimEnd: ("trimEnd" in item ? item.trimEnd : 0), + fontSize: ("fontSize" in item ? item.fontSize : 48), + fontFamily: ("fontFamily" in item ? item.fontFamily : "Arial"), + color: ("color" in item ? item.color : "#ffffff"), + backgroundColor: ("backgroundColor" in item ? item.backgroundColor : "transparent"), + textAlign: ("textAlign" in item ? item.textAlign : "center"), + fontWeight: ("fontWeight" in item ? item.fontWeight : "normal"), + fontStyle: ("fontStyle" in item ? item.fontStyle : "normal"), + textDecoration: ("textDecoration" in item ? item.textDecoration : "none"), + x: ("x" in item ? item.x : 0), + y: ("y" in item ? item.y : 0), + rotation: ("rotation" in item ? item.rotation : 0), + opacity: ("opacity" in item && item.opacity !== undefined ? item.opacity : 1), + }); +}; + + +// Adds a media item to the timeline at the specified time +export const addMediaToTimeline = (item: MediaItem, currentTime: number = 0) => { + const trackType = item.type === "audio" ? "audio" : "media"; + const targetTrackId = findOrCreateTrack(trackType); + + const duration = item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION; + + if (checkOverlap(targetTrackId, currentTime, duration)) { + toast.error("Cannot place element here - it would overlap with existing elements"); + return; + } + + addMediaElement(targetTrackId, item, currentTime); +}; + +// Adds a text item to the timeline at the specified time +export const addTextToTimeline = (item: TextElement, currentTime: number = 0) => { + const targetTrackId = findOrCreateTrack("text"); + addTextElement(targetTrackId, item, currentTime); +}; + +// Adds a media item to timeline +export const addMediaToNewTrack = (item: MediaItem) => { + const trackType = item.type === "audio" ? "audio" : "media"; + const targetTrackId = findOrCreateTrack(trackType); + addMediaElement(targetTrackId, item, 0); +}; + +// Adds a text item to timeline +export const addTextToNewTrack = (item: TextElement | DragData) => { + const targetTrackId = findOrCreateTrack("text"); + addTextElement(targetTrackId, item, 0); +}; From 1e64bc4abd8464ae733f884de46ffa13760035cc Mon Sep 17 00:00:00 2001 From: Anwarul Islam Date: Mon, 14 Jul 2025 23:49:48 +0600 Subject: [PATCH 02/19] fix improve timeline element visual display --- apps/web/src/components/editor/timeline.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index 71e2997b..6c3d731d 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -192,7 +192,7 @@ export function Timeline() { let scrollLeft = 0; if (isRulerClick) { - // Calculate based on ruler position + // Calculate based on ruler position const rulerContent = rulerScrollRef.current?.querySelector( "[data-radix-scroll-area-viewport]" ) as HTMLElement; From c628b5a8ee6650b223cdc7aa5b6b000bc1e2466d Mon Sep 17 00:00:00 2001 From: Anwarul Islam Date: Mon, 14 Jul 2025 23:53:11 +0600 Subject: [PATCH 03/19] fix improve timeline element visual display by tiling repeating media thumbnails --- .../components/editor/timeline-element.tsx | 81 ++++++++++++++----- apps/web/src/components/editor/timeline.tsx | 2 +- apps/web/src/constants/timeline-constants.ts | 51 ++++++++++++ 3 files changed, 114 insertions(+), 20 deletions(-) diff --git a/apps/web/src/components/editor/timeline-element.tsx b/apps/web/src/components/editor/timeline-element.tsx index ee9445f3..2a704227 100644 --- a/apps/web/src/components/editor/timeline-element.tsx +++ b/apps/web/src/components/editor/timeline-element.tsx @@ -24,6 +24,8 @@ import { useTimelineElementResize } from "@/hooks/use-timeline-element-resize"; import { getTrackElementClasses, TIMELINE_CONSTANTS, + getTrackHeight, + calculateMediaTiling, } from "@/constants/timeline-constants"; import { DropdownMenu, @@ -268,34 +270,75 @@ export function TimelineElement({ } if (mediaItem.type === "image") { + // Use utility function to calculate optimal tiling + const tiling = calculateMediaTiling(elementWidth, track.type, "image"); + return ( -
-
- {mediaItem.name} +
+
+ {Array.from({ length: tiling.totalTiles }, (_, index) => { + const isPartialTile = + index === tiling.numCompleteTiles && tiling.showPartialTile; + const tileWidthToUse = isPartialTile + ? tiling.remainingWidth + : tiling.tileWidth; + + return ( +
+ {mediaItem.name} +
+ ); + })}
); } if (mediaItem.type === "video" && mediaItem.thumbnailUrl) { + // Use utility function to calculate optimal tiling + const tiling = calculateMediaTiling(elementWidth, track.type, "video"); + return ( -
-
- {mediaItem.name} +
+
+ {Array.from({ length: tiling.totalTiles }, (_, index) => { + const isPartialTile = + index === tiling.numCompleteTiles && tiling.showPartialTile; + const tileWidthToUse = isPartialTile + ? tiling.remainingWidth + : tiling.tileWidth; + + return ( +
+ {mediaItem.name} +
+ ); + })}
- - {element.name} - + {/* Show name overlay on the right if there's sufficient space */} + {tiling.canShowOverlay && ( +
+ {element.name} +
+ )}
); } diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index 6c3d731d..71e2997b 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -192,7 +192,7 @@ export function Timeline() { let scrollLeft = 0; if (isRulerClick) { - // Calculate based on ruler position + // Calculate based on ruler position const rulerContent = rulerScrollRef.current?.querySelector( "[data-radix-scroll-area-viewport]" ) as HTMLElement; diff --git a/apps/web/src/constants/timeline-constants.ts b/apps/web/src/constants/timeline-constants.ts index 92045c5e..44773b84 100644 --- a/apps/web/src/constants/timeline-constants.ts +++ b/apps/web/src/constants/timeline-constants.ts @@ -104,3 +104,54 @@ export function snapTimeToFrame(time: number, fps: number): number { export function getFrameDuration(fps: number): number { return 1 / fps; } + +// Media thumbnail tiling constants +export const MEDIA_THUMBNAIL_CONSTANTS = { + DEFAULT_ASPECT_RATIO: 16 / 9, + IMAGE_PADDING: 8, + VIDEO_PADDING: 16, + PARTIAL_TILE_THRESHOLD_IMAGE: 0.2, // Show partial tile if >20% visible for images + PARTIAL_TILE_THRESHOLD_VIDEO: 0.3, // Show partial tile if >30% visible for videos + MIN_OVERLAY_WIDTH_RATIO: 1.5, // Minimum width ratio to show name overlay +} as const; + +// Utility function to calculate media thumbnail tiling +export function calculateMediaTiling( + elementWidth: number, + trackType: TrackType, + mediaType: "image" | "video" +) { + const trackHeight = getTrackHeight(trackType); + const aspectRatio = MEDIA_THUMBNAIL_CONSTANTS.DEFAULT_ASPECT_RATIO; + const padding = + mediaType === "image" + ? MEDIA_THUMBNAIL_CONSTANTS.IMAGE_PADDING + : MEDIA_THUMBNAIL_CONSTANTS.VIDEO_PADDING; + + const tileHeight = trackHeight - padding; + const tileWidth = tileHeight * aspectRatio; + + // Calculate how many complete tiles we can fit + const numCompleteTiles = Math.floor(elementWidth / tileWidth); + const remainingWidth = elementWidth - numCompleteTiles * tileWidth; + + const threshold = + mediaType === "image" + ? MEDIA_THUMBNAIL_CONSTANTS.PARTIAL_TILE_THRESHOLD_IMAGE + : MEDIA_THUMBNAIL_CONSTANTS.PARTIAL_TILE_THRESHOLD_VIDEO; + + const showPartialTile = remainingWidth > tileWidth * threshold; + const totalTiles = numCompleteTiles + (showPartialTile ? 1 : 0); + + return { + tileWidth, + tileHeight, + numCompleteTiles, + remainingWidth, + showPartialTile, + totalTiles: Math.max(1, totalTiles), // Always show at least one tile + canShowOverlay: + elementWidth > + tileWidth * MEDIA_THUMBNAIL_CONSTANTS.MIN_OVERLAY_WIDTH_RATIO, + }; +} From 2c941b1585d9fea0207fd9eae68775475dc462c4 Mon Sep 17 00:00:00 2001 From: Anwarul Islam Date: Tue, 15 Jul 2025 00:12:01 +0600 Subject: [PATCH 04/19] fix: optimize media thumbnail display by removing tiling utility and using CSS background instead --- .../components/editor/timeline-element.tsx | 81 +++++++------------ apps/web/src/constants/timeline-constants.ts | 51 ------------ 2 files changed, 27 insertions(+), 105 deletions(-) diff --git a/apps/web/src/components/editor/timeline-element.tsx b/apps/web/src/components/editor/timeline-element.tsx index 2a704227..5f5a2c6d 100644 --- a/apps/web/src/components/editor/timeline-element.tsx +++ b/apps/web/src/components/editor/timeline-element.tsx @@ -25,7 +25,6 @@ import { getTrackElementClasses, TIMELINE_CONSTANTS, getTrackHeight, - calculateMediaTiling, } from "@/constants/timeline-constants"; import { DropdownMenu, @@ -270,71 +269,45 @@ export function TimelineElement({ } if (mediaItem.type === "image") { - // Use utility function to calculate optimal tiling - const tiling = calculateMediaTiling(elementWidth, track.type, "image"); + // Calculate tile size based on 16:9 aspect ratio + const trackHeight = getTrackHeight(track.type); + const tileHeight = trackHeight - 8; // Account for padding + const tileWidth = tileHeight * (16 / 9); return (
-
- {Array.from({ length: tiling.totalTiles }, (_, index) => { - const isPartialTile = - index === tiling.numCompleteTiles && tiling.showPartialTile; - const tileWidthToUse = isPartialTile - ? tiling.remainingWidth - : tiling.tileWidth; - - return ( -
- {mediaItem.name} -
- ); - })} -
+
); } if (mediaItem.type === "video" && mediaItem.thumbnailUrl) { - // Use utility function to calculate optimal tiling - const tiling = calculateMediaTiling(elementWidth, track.type, "video"); + // Calculate tile size based on 16:9 aspect ratio + const trackHeight = getTrackHeight(track.type); + const tileHeight = trackHeight - 16; // Account for padding + const tileWidth = tileHeight * (16 / 9); return (
-
- {Array.from({ length: tiling.totalTiles }, (_, index) => { - const isPartialTile = - index === tiling.numCompleteTiles && tiling.showPartialTile; - const tileWidthToUse = isPartialTile - ? tiling.remainingWidth - : tiling.tileWidth; - - return ( -
- {mediaItem.name} -
- ); - })} -
+
{/* Show name overlay on the right if there's sufficient space */} - {tiling.canShowOverlay && ( + {elementWidth > tileWidth * 1.5 && (
{element.name}
diff --git a/apps/web/src/constants/timeline-constants.ts b/apps/web/src/constants/timeline-constants.ts index 44773b84..92045c5e 100644 --- a/apps/web/src/constants/timeline-constants.ts +++ b/apps/web/src/constants/timeline-constants.ts @@ -104,54 +104,3 @@ export function snapTimeToFrame(time: number, fps: number): number { export function getFrameDuration(fps: number): number { return 1 / fps; } - -// Media thumbnail tiling constants -export const MEDIA_THUMBNAIL_CONSTANTS = { - DEFAULT_ASPECT_RATIO: 16 / 9, - IMAGE_PADDING: 8, - VIDEO_PADDING: 16, - PARTIAL_TILE_THRESHOLD_IMAGE: 0.2, // Show partial tile if >20% visible for images - PARTIAL_TILE_THRESHOLD_VIDEO: 0.3, // Show partial tile if >30% visible for videos - MIN_OVERLAY_WIDTH_RATIO: 1.5, // Minimum width ratio to show name overlay -} as const; - -// Utility function to calculate media thumbnail tiling -export function calculateMediaTiling( - elementWidth: number, - trackType: TrackType, - mediaType: "image" | "video" -) { - const trackHeight = getTrackHeight(trackType); - const aspectRatio = MEDIA_THUMBNAIL_CONSTANTS.DEFAULT_ASPECT_RATIO; - const padding = - mediaType === "image" - ? MEDIA_THUMBNAIL_CONSTANTS.IMAGE_PADDING - : MEDIA_THUMBNAIL_CONSTANTS.VIDEO_PADDING; - - const tileHeight = trackHeight - padding; - const tileWidth = tileHeight * aspectRatio; - - // Calculate how many complete tiles we can fit - const numCompleteTiles = Math.floor(elementWidth / tileWidth); - const remainingWidth = elementWidth - numCompleteTiles * tileWidth; - - const threshold = - mediaType === "image" - ? MEDIA_THUMBNAIL_CONSTANTS.PARTIAL_TILE_THRESHOLD_IMAGE - : MEDIA_THUMBNAIL_CONSTANTS.PARTIAL_TILE_THRESHOLD_VIDEO; - - const showPartialTile = remainingWidth > tileWidth * threshold; - const totalTiles = numCompleteTiles + (showPartialTile ? 1 : 0); - - return { - tileWidth, - tileHeight, - numCompleteTiles, - remainingWidth, - showPartialTile, - totalTiles: Math.max(1, totalTiles), // Always show at least one tile - canShowOverlay: - elementWidth > - tileWidth * MEDIA_THUMBNAIL_CONSTANTS.MIN_OVERLAY_WIDTH_RATIO, - }; -} From d53321ec366979512d5e5a8cccc56b00cd84c1cf Mon Sep 17 00:00:00 2001 From: Anwarul Islam Date: Tue, 15 Jul 2025 00:42:19 +0600 Subject: [PATCH 05/19] fix: enhance media tile display with aspect ratio adjustments and overlay borders --- .../components/editor/timeline-element.tsx | 88 ++++++++++++++----- 1 file changed, 65 insertions(+), 23 deletions(-) diff --git a/apps/web/src/components/editor/timeline-element.tsx b/apps/web/src/components/editor/timeline-element.tsx index 5f5a2c6d..ca229818 100644 --- a/apps/web/src/components/editor/timeline-element.tsx +++ b/apps/web/src/components/editor/timeline-element.tsx @@ -268,46 +268,88 @@ export function TimelineElement({ ); } + const TILE_ASPECT_RATIO = 16 / 9; + if (mediaItem.type === "image") { // Calculate tile size based on 16:9 aspect ratio const trackHeight = getTrackHeight(track.type); const tileHeight = trackHeight - 8; // Account for padding - const tileWidth = tileHeight * (16 / 9); + const tileWidth = tileHeight * TILE_ASPECT_RATIO; return (
-
+
+ {/* Background with tiled images */} +
+ {/* Overlay with vertical borders */} +
+
); } + const VIDEO_TILE_PADDING = 16; + const OVERLAY_SPACE_MULTIPLIER = 1.5; + if (mediaItem.type === "video" && mediaItem.thumbnailUrl) { - // Calculate tile size based on 16:9 aspect ratio const trackHeight = getTrackHeight(track.type); - const tileHeight = trackHeight - 16; // Account for padding - const tileWidth = tileHeight * (16 / 9); + const tileHeight = trackHeight - VIDEO_TILE_PADDING; + const tileWidth = tileHeight * TILE_ASPECT_RATIO; return (
-
+
+ {/* Background with tiled thumbnails */} +
+ {/* Overlay with vertical borders */} +
+
{/* Show name overlay on the right if there's sufficient space */} - {elementWidth > tileWidth * 1.5 && ( + {elementWidth > tileWidth * OVERLAY_SPACE_MULTIPLIER && (
{element.name}
From dc0e4783fbacad5c7eb3cf0d1141b0166960f809 Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Tue, 15 Jul 2025 16:55:04 +0200 Subject: [PATCH 06/19] cleanup --- .../editor/media-panel/views/media.tsx | 8 +- .../editor/media-panel/views/text.tsx | 6 +- apps/web/src/components/editor/timeline.tsx | 19 +- apps/web/src/lib/timeline-utils.ts | 117 ------------- apps/web/src/stores/timeline-store.ts | 164 +++++++++++++++++- 5 files changed, 183 insertions(+), 131 deletions(-) delete mode 100644 apps/web/src/lib/timeline-utils.ts diff --git a/apps/web/src/components/editor/media-panel/views/media.tsx b/apps/web/src/components/editor/media-panel/views/media.tsx index 17893156..393d72db 100644 --- a/apps/web/src/components/editor/media-panel/views/media.tsx +++ b/apps/web/src/components/editor/media-panel/views/media.tsx @@ -24,7 +24,7 @@ import { } from "@/components/ui/select"; import { DraggableMediaItem } from "@/components/ui/draggable-item"; import { useProjectStore } from "@/stores/project-store"; -import { addMediaToTimeline } from "@/lib/timeline-utils"; +import { useTimelineStore } from "@/stores/timeline-store"; export function MediaView() { const { mediaItems, addMediaItem, removeMediaItem } = useMediaStore(); @@ -289,7 +289,11 @@ export function MediaView() { name: item.name, }} showPlusOnDrag={false} - onAddToTimeline={(currentTime) => addMediaToTimeline(item, currentTime)} + onAddToTimeline={(currentTime) => + useTimelineStore + .getState() + .addMediaAtTime(item, currentTime) + } rounded={false} /> diff --git a/apps/web/src/components/editor/media-panel/views/text.tsx b/apps/web/src/components/editor/media-panel/views/text.tsx index fad79343..6d0d310b 100644 --- a/apps/web/src/components/editor/media-panel/views/text.tsx +++ b/apps/web/src/components/editor/media-panel/views/text.tsx @@ -1,6 +1,6 @@ import { DraggableMediaItem } from "@/components/ui/draggable-item"; import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; -import { addTextToTimeline } from "@/lib/timeline-utils"; +import { useTimelineStore } from "@/stores/timeline-store"; import { type TextElement } from "@/types/timeline"; let textData: TextElement = { @@ -43,7 +43,9 @@ export function TextView() { content: textData.content, }} aspectRatio={1} - onAddToTimeline={(currentTime) => addTextToTimeline(textData, currentTime)} + onAddToTimeline={(currentTime) => + useTimelineStore.getState().addTextAtTime(textData, currentTime) + } showLabel={false} />
diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index ff9e0694..c1603542 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -48,7 +48,6 @@ import { useSelectionBox } from "@/hooks/use-selection-box"; import { SnapIndicator } from "./snap-indicator"; import { SnapPoint } from "@/hooks/use-timeline-snapping"; import type { DragData, TimelineTrack } from "@/types/timeline"; -import { addTextToNewTrack, addMediaToNewTrack } from "@/lib/timeline-utils"; import { getTrackHeight, getCumulativeHeightBefore, @@ -229,7 +228,7 @@ export function Timeline() { Math.min( duration, (mouseX + scrollLeft) / - (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) + (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) ) ); @@ -377,7 +376,7 @@ export function Timeline() { if (dragData.type === "text") { // Always create new text track to avoid overlaps - addTextToNewTrack(dragData); + useTimelineStore.getState().addTextToNewTrack(dragData); } else { // Handle media items const mediaItem = mediaItems.find((item) => item.id === dragData.id); @@ -386,7 +385,7 @@ export function Timeline() { return; } - addMediaToNewTrack(mediaItem); + useTimelineStore.getState().addMediaToNewTrack(mediaItem); } } catch (error) { console.error("Error parsing dropped item data:", error); @@ -414,7 +413,7 @@ export function Timeline() { item.name === processedItem.name && item.url === processedItem.url ); if (addedItem) { - addMediaToNewTrack(addedItem); + useTimelineStore.getState().addMediaToNewTrack(addedItem); } } } catch (error) { @@ -902,19 +901,21 @@ export function Timeline() { return (
{(() => { const formatTime = (seconds: number) => { diff --git a/apps/web/src/lib/timeline-utils.ts b/apps/web/src/lib/timeline-utils.ts deleted file mode 100644 index 994cb314..00000000 --- a/apps/web/src/lib/timeline-utils.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { useTimelineStore } from "@/stores/timeline-store"; -import { type MediaItem } from "@/stores/media-store"; -import { toast } from "sonner"; -import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; -import { DragData, TextElement } from "@/types/timeline"; - - -const findOrCreateTrack = (trackType: "media" | "audio" | "text") => { - const timelineStore = useTimelineStore.getState(); - - // Always create new text track to allow multiple text elements - if (trackType === "text") { - return timelineStore.addTrack(trackType); - } - - const existingTrack = timelineStore.tracks.find(track => track.type === trackType); - return existingTrack ? existingTrack.id : timelineStore.addTrack(trackType); -}; - - -const checkOverlap = (trackId: string, startTime: number, duration: number, excludeElementId?: string) => { - const timelineStore = useTimelineStore.getState(); - const targetTrack = timelineStore.tracks.find(track => track.id === trackId); - - if (!targetTrack) { - return true; - } - - const elementEnd = startTime + duration; - - return targetTrack.elements.some((existingElement) => { - if (excludeElementId && existingElement.id === excludeElementId) { - return false; - } - - const existingStart = existingElement.startTime; - const existingEnd = existingElement.startTime + - (existingElement.duration - existingElement.trimStart - existingElement.trimEnd); - - return startTime < existingEnd && elementEnd > existingStart; - }); -}; - -const addMediaElement = (trackId: string, item: MediaItem, startTime: number) => { - const timelineStore = useTimelineStore.getState(); - - timelineStore.addElementToTrack(trackId, { - type: "media", - mediaId: item.id, - name: item.name, - duration: item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION, - startTime, - trimStart: 0, - trimEnd: 0, - }); -}; - -const addTextElement = (trackId: string, item: TextElement | DragData, startTime: number) => { - const timelineStore = useTimelineStore.getState(); - - timelineStore.addElementToTrack(trackId, { - type: "text", - name: item.name, - content: ("content" in item ? item.content : "Default Text"), - duration: TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION, - startTime, - trimStart: ("trimStart" in item ? item.trimStart : 0), - trimEnd: ("trimEnd" in item ? item.trimEnd : 0), - fontSize: ("fontSize" in item ? item.fontSize : 48), - fontFamily: ("fontFamily" in item ? item.fontFamily : "Arial"), - color: ("color" in item ? item.color : "#ffffff"), - backgroundColor: ("backgroundColor" in item ? item.backgroundColor : "transparent"), - textAlign: ("textAlign" in item ? item.textAlign : "center"), - fontWeight: ("fontWeight" in item ? item.fontWeight : "normal"), - fontStyle: ("fontStyle" in item ? item.fontStyle : "normal"), - textDecoration: ("textDecoration" in item ? item.textDecoration : "none"), - x: ("x" in item ? item.x : 0), - y: ("y" in item ? item.y : 0), - rotation: ("rotation" in item ? item.rotation : 0), - opacity: ("opacity" in item && item.opacity !== undefined ? item.opacity : 1), - }); -}; - - -// Adds a media item to the timeline at the specified time -export const addMediaToTimeline = (item: MediaItem, currentTime: number = 0) => { - const trackType = item.type === "audio" ? "audio" : "media"; - const targetTrackId = findOrCreateTrack(trackType); - - const duration = item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION; - - if (checkOverlap(targetTrackId, currentTime, duration)) { - toast.error("Cannot place element here - it would overlap with existing elements"); - return; - } - - addMediaElement(targetTrackId, item, currentTime); -}; - -// Adds a text item to the timeline at the specified time -export const addTextToTimeline = (item: TextElement, currentTime: number = 0) => { - const targetTrackId = findOrCreateTrack("text"); - addTextElement(targetTrackId, item, currentTime); -}; - -// Adds a media item to timeline -export const addMediaToNewTrack = (item: MediaItem) => { - const trackType = item.type === "audio" ? "audio" : "media"; - const targetTrackId = findOrCreateTrack(trackType); - addMediaElement(targetTrackId, item, 0); -}; - -// Adds a text item to timeline -export const addTextToNewTrack = (item: TextElement | DragData) => { - const targetTrackId = findOrCreateTrack("text"); - addTextElement(targetTrackId, item, 0); -}; diff --git a/apps/web/src/stores/timeline-store.ts b/apps/web/src/stores/timeline-store.ts index f6b9bfd8..9a2c7361 100644 --- a/apps/web/src/stores/timeline-store.ts +++ b/apps/web/src/stores/timeline-store.ts @@ -5,15 +5,22 @@ import { CreateTimelineElement, TimelineTrack, TextElement, + DragData, sortTracksByOrder, ensureMainTrack, validateElementTrackCompatibility, } from "@/types/timeline"; import { useEditorStore } from "./editor-store"; -import { useMediaStore, getMediaAspectRatio } from "./media-store"; +import { + useMediaStore, + getMediaAspectRatio, + type MediaItem, +} from "./media-store"; import { storageService } from "@/lib/storage/storage-service"; import { useProjectStore } from "./project-store"; import { generateUUID } from "@/lib/utils"; +import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; +import { toast } from "sonner"; // Helper function to manage element naming with suffixes const getElementNameWithSuffix = ( @@ -166,6 +173,17 @@ interface TimelineStore { > > ) => void; + checkElementOverlap: ( + trackId: string, + startTime: number, + duration: number, + excludeElementId?: string + ) => boolean; + findOrCreateTrack: (trackType: TrackType) => string; + addMediaAtTime: (item: MediaItem, currentTime?: number) => boolean; + addTextAtTime: (item: TextElement, currentTime?: number) => boolean; + addMediaToNewTrack: (item: MediaItem) => boolean; + addTextToNewTrack: (item: TextElement | DragData) => boolean; } export const useTimelineStore = create((set, get) => { @@ -963,5 +981,149 @@ export const useTimelineStore = create((set, get) => { toggleSnapping: () => { set((state) => ({ snappingEnabled: !state.snappingEnabled })); }, + + checkElementOverlap: (trackId, startTime, duration, excludeElementId) => { + const track = get()._tracks.find((t) => t.id === trackId); + if (!track) return false; + + const overlap = track.elements.some((element) => { + const elementEnd = + element.startTime + + element.duration - + element.trimStart - + element.trimEnd; + + if (element.id === excludeElementId) { + return false; + } + + return ( + (startTime >= element.startTime && startTime < elementEnd) || + (startTime + duration > element.startTime && + startTime + duration <= elementEnd) || + (startTime < element.startTime && startTime + duration > elementEnd) + ); + }); + return overlap; + }, + + findOrCreateTrack: (trackType) => { + // Always create new text track to allow multiple text elements + if (trackType === "text") { + return get().addTrack(trackType); + } + + const existingTrack = get()._tracks.find((t) => t.type === trackType); + if (existingTrack) { + return existingTrack.id; + } + + return get().addTrack(trackType); + }, + + addMediaAtTime: (item, currentTime = 0) => { + const trackType = item.type === "audio" ? "audio" : "media"; + const targetTrackId = get().findOrCreateTrack(trackType); + + const duration = + item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION; + + if (get().checkElementOverlap(targetTrackId, currentTime, duration)) { + toast.error( + "Cannot place element here - it would overlap with existing elements" + ); + return false; + } + + get().addElementToTrack(targetTrackId, { + type: "media", + mediaId: item.id, + name: item.name, + duration, + startTime: currentTime, + trimStart: 0, + trimEnd: 0, + }); + return true; + }, + + addTextAtTime: (item, currentTime = 0) => { + const targetTrackId = get().addTrack("text"); // Always create new text track to allow multiple text elements + + get().addElementToTrack(targetTrackId, { + type: "text", + name: item.name || "Text", + content: item.content || "Default Text", + duration: item.duration || TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION, + startTime: currentTime, + trimStart: 0, + trimEnd: 0, + fontSize: item.fontSize || 48, + fontFamily: item.fontFamily || "Arial", + color: item.color || "#ffffff", + backgroundColor: item.backgroundColor || "transparent", + textAlign: item.textAlign || "center", + fontWeight: item.fontWeight || "normal", + fontStyle: item.fontStyle || "normal", + textDecoration: item.textDecoration || "none", + x: item.x || 0, + y: item.y || 0, + rotation: item.rotation || 0, + opacity: item.opacity !== undefined ? item.opacity : 1, + }); + return true; + }, + + addMediaToNewTrack: (item) => { + const trackType = item.type === "audio" ? "audio" : "media"; + const targetTrackId = get().findOrCreateTrack(trackType); + + get().addElementToTrack(targetTrackId, { + type: "media", + mediaId: item.id, + name: item.name, + duration: item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION, + startTime: 0, + trimStart: 0, + trimEnd: 0, + }); + return true; + }, + + addTextToNewTrack: (item) => { + const targetTrackId = get().addTrack("text"); // Always create new text track to allow multiple text elements + + get().addElementToTrack(targetTrackId, { + type: "text", + name: item.name || "Text", + content: + ("content" in item ? item.content : "Default Text") || "Default Text", + duration: TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION, + startTime: 0, + trimStart: 0, + trimEnd: 0, + fontSize: ("fontSize" in item ? item.fontSize : 48) || 48, + fontFamily: + ("fontFamily" in item ? item.fontFamily : "Arial") || "Arial", + color: ("color" in item ? item.color : "#ffffff") || "#ffffff", + backgroundColor: + ("backgroundColor" in item ? item.backgroundColor : "transparent") || + "transparent", + textAlign: + ("textAlign" in item ? item.textAlign : "center") || "center", + fontWeight: + ("fontWeight" in item ? item.fontWeight : "normal") || "normal", + fontStyle: + ("fontStyle" in item ? item.fontStyle : "normal") || "normal", + textDecoration: + ("textDecoration" in item ? item.textDecoration : "none") || "none", + x: ("x" in item ? item.x : 0) || 0, + y: ("y" in item ? item.y : 0) || 0, + rotation: ("rotation" in item ? item.rotation : 0) || 0, + opacity: + "opacity" in item && item.opacity !== undefined ? item.opacity : 1, + }); + return true; + }, }; }); From 7a725ecd0962fa0c37c78dc22827eb9e08c903f3 Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Tue, 15 Jul 2025 17:29:28 +0200 Subject: [PATCH 07/19] cleanup --- .../components/editor/timeline-element.tsx | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/editor/timeline-element.tsx b/apps/web/src/components/editor/timeline-element.tsx index ca229818..8cccd0e4 100644 --- a/apps/web/src/components/editor/timeline-element.tsx +++ b/apps/web/src/components/editor/timeline-element.tsx @@ -277,11 +277,11 @@ export function TimelineElement({ const tileWidth = tileHeight * TILE_ASPECT_RATIO; return ( -
-
+
+
{/* Background with tiled images */}
{/* Overlay with vertical borders */}
-
+
+
{/* Background with tiled thumbnails */}
{/* Overlay with vertical borders */}
- {/* Show name overlay on the right if there's sufficient space */} - {elementWidth > tileWidth * OVERLAY_SPACE_MULTIPLIER && ( + {elementWidth > tileWidth * OVERLAY_SPACE_MULTIPLIER ? (
{element.name}
+ ) : ( + + {element.name} + )}
); From fd2aa00074db0fd157bd41c0b6ddf061452f3aaa Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Tue, 15 Jul 2025 17:40:19 +0200 Subject: [PATCH 08/19] style: tooltip --- apps/web/src/components/ui/tooltip.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 0da023e6..4971e262 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -20,7 +20,7 @@ const TooltipContent = React.forwardRef< ref={ref} sideOffset={sideOffset} className={cn( - "z-50 overflow-hidden rounded-md bg-foreground/10 px-3 py-1.5 text-xs text-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", + "z-50 overflow-hidden rounded-md bg-foreground px-3 py-1.5 text-xs text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} From 3a8d57921e48b9ca1055644482ad39753c077ff4 Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Tue, 15 Jul 2025 17:41:10 +0200 Subject: [PATCH 09/19] feat: add lock icon toggle for snapping functionality --- apps/web/src/components/editor/timeline.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index c1603542..4a770627 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -17,6 +17,7 @@ import { TypeIcon, Magnet, Lock, + LockOpen, } from "lucide-react"; import { Tooltip, @@ -808,7 +809,11 @@ export function Timeline() { Auto snapping From 6df492b661539bd447c6855932be6bbfec6f205c Mon Sep 17 00:00:00 2001 From: Simon Orzel Date: Tue, 15 Jul 2025 23:25:09 +0200 Subject: [PATCH 10/19] fix(web): #268 multiple new projects bug --- apps/web/src/app/editor/[project_id]/page.tsx | 39 ++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/apps/web/src/app/editor/[project_id]/page.tsx b/apps/web/src/app/editor/[project_id]/page.tsx index 315e0764..65667106 100644 --- a/apps/web/src/app/editor/[project_id]/page.tsx +++ b/apps/web/src/app/editor/[project_id]/page.tsx @@ -1,7 +1,7 @@ "use client"; -import { useEffect } from "react"; -import { useParams } from "next/navigation"; +import { useEffect, useRef } from "react"; +import { useParams, useRouter } from "next/navigation"; import { ResizablePanelGroup, ResizablePanel, @@ -33,25 +33,38 @@ export default function Editor() { const { activeProject, loadProject, createNewProject } = useProjectStore(); const params = useParams(); + const router = useRouter(); const projectId = params.project_id as string; + const handledProjectIds = useRef>(new Set()); usePlaybackControls(); useEffect(() => { - const initializeProject = async () => { - if (projectId && (!activeProject || activeProject.id !== projectId)) { - try { - await loadProject(projectId); - } catch (error) { - console.error("Failed to load project:", error); - // If project doesn't exist, create a new one - await createNewProject("Untitled Project"); - } + const initProject = async () => { + + if (!projectId) return; + + if (activeProject?.id === projectId) { + return; + } + + if (handledProjectIds.current.has(projectId)) { + return; + } + + try { + await loadProject(projectId); + } catch (error) { + handledProjectIds.current.add(projectId); + + const newProjectId = await createNewProject("Untitled Project"); + router.replace(`/editor/${newProjectId}`); + return; } }; - initializeProject(); - }, [projectId, activeProject, loadProject, createNewProject]); + initProject(); + }, [projectId, activeProject?.id, loadProject, createNewProject, router]); return ( From 83d65bdd15946c4307a38af9f5c43b4c51e906fb Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Tue, 15 Jul 2025 23:26:04 +0200 Subject: [PATCH 11/19] feat: remove waitlist count due to bots --- apps/web/src/app/page.tsx | 8 +------- apps/web/src/components/landing/hero.tsx | 18 +----------------- 2 files changed, 2 insertions(+), 24 deletions(-) diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 74308470..74961549 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -1,18 +1,12 @@ import { Hero } from "@/components/landing/hero"; import { Header } from "@/components/header"; import { Footer } from "@/components/footer"; -import { getWaitlistCount } from "@/lib/waitlist"; - -// Force dynamic rendering so waitlist count updates in real-time -export const dynamic = "force-dynamic"; export default async function Home() { - const signupCount = await getWaitlistCount(); - return (
- +
); diff --git a/apps/web/src/components/landing/hero.tsx b/apps/web/src/components/landing/hero.tsx index 01ad7e7e..462e3ba7 100644 --- a/apps/web/src/components/landing/hero.tsx +++ b/apps/web/src/components/landing/hero.tsx @@ -10,11 +10,7 @@ import { toast } from "sonner"; import Image from "next/image"; import { Handlebars } from "./handlebars"; -interface HeroProps { - signupCount: number; -} - -export function Hero({ signupCount }: HeroProps) { +export function Hero() { const [email, setEmail] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); @@ -131,18 +127,6 @@ export function Hero({ signupCount }: HeroProps) { - - {signupCount > 0 && ( - -
- {signupCount.toLocaleString()} people already joined - - )}
); From f76169ada15cff51dbf9ce3af148a78c46ed36c6 Mon Sep 17 00:00:00 2001 From: Simon Orzel Date: Wed, 16 Jul 2025 00:48:00 +0200 Subject: [PATCH 12/19] feat: refactors media drag overlay and media tab --- .../editor/media-panel/views/media.tsx | 77 +++++++++--------- apps/web/src/components/ui/drag-overlay.tsx | 78 +++++++++++++++++-- 2 files changed, 108 insertions(+), 47 deletions(-) diff --git a/apps/web/src/components/editor/media-panel/views/media.tsx b/apps/web/src/components/editor/media-panel/views/media.tsx index 5438737f..f8cbb639 100644 --- a/apps/web/src/components/editor/media-panel/views/media.tsx +++ b/apps/web/src/components/editor/media-panel/views/media.tsx @@ -3,7 +3,7 @@ import { useDragDrop } from "@/hooks/use-drag-drop"; import { processMediaFiles } from "@/lib/media-processing"; import { useMediaStore, type MediaItem } from "@/stores/media-store"; -import { Image, Music, Plus, Upload, Video } from "lucide-react"; +import { Image, Loader2, Music, Plus, Upload, Video } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; @@ -203,9 +203,6 @@ export function MediaView() { className={`h-full flex flex-col gap-1 transition-colors relative ${isDragOver ? "bg-accent/30" : ""}`} {...dragProps} > - {/* Show overlay when dragging files over the panel */} - -
{/* Search and filter controls */}
@@ -227,47 +224,45 @@ export function MediaView() { value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} /> +
- {/* Show message if no media, otherwise show media grid */} - {filteredMediaItems.length === 0 ? ( -
-
- -
-

- No media in project -

-

- Drag files here or use the button below -

- -
+ {(isDragOver || filteredMediaItems.length === 0) ? ( + ) : (
void; + isEmptyState?: boolean; } export function DragOverlay({ isVisible, title = "Drop files here", description = "Images, videos, and audio files", + isProcessing = false, + progress = 0, + onClick, + isEmptyState = false, }: DragOverlayProps) { if (!isVisible) return null; + const handleClick = (e: React.MouseEvent) => { + if (isProcessing || !onClick) return; + e.preventDefault(); + e.stopPropagation(); + onClick(); + }; + return ( -
-
- -

{title}

-

{description}

+
+
+ {isProcessing ? ( + + ) : isEmptyState ? ( + + ) : ( + + )}
+ +
+

+ {isProcessing ? "Processing files..." : title} +

+

+ {isProcessing + ? `Processing your files (${progress}%)` + : description + } +

+
+ + {!isProcessing && ( +
+ +

+ {isEmptyState + ? "Supports images, videos, and audio files" + : "Or drop your files here" + } +

+
+ )} + + {isProcessing && ( +
+
+
+
+
+ )}
); } From 5178732c4c1205698d1846dd82896d9342558ac6 Mon Sep 17 00:00:00 2001 From: Ahmet Kilinc Date: Wed, 16 Jul 2025 00:44:42 +0100 Subject: [PATCH 13/19] csrf token and browser detection --- apps/web/src/app/api/waitlist/route.ts | 173 ++++++++++++++++--- apps/web/src/app/api/waitlist/token/route.ts | 47 +++++ apps/web/src/components/landing/hero.tsx | 71 ++++---- apps/web/src/lib/rate-limit.ts | 1 + 4 files changed, 235 insertions(+), 57 deletions(-) create mode 100644 apps/web/src/app/api/waitlist/token/route.ts diff --git a/apps/web/src/app/api/waitlist/route.ts b/apps/web/src/app/api/waitlist/route.ts index f6f81103..4d64be77 100644 --- a/apps/web/src/app/api/waitlist/route.ts +++ b/apps/web/src/app/api/waitlist/route.ts @@ -4,51 +4,179 @@ import { waitlist } from "@opencut/db/schema"; import { nanoid } from "nanoid"; import { waitlistRateLimit } from "@/lib/rate-limit"; import { z } from "zod"; +import { env } from "@/env"; +import { cookies } from "next/headers"; +import crypto from "crypto"; const waitlistSchema = z.object({ email: z.string().email("Invalid email format").min(1, "Email is required"), }); +const CSRF_TOKEN_NAME = "waitlist-csrf"; +const TOKEN_EXPIRY = 60 * 60 * 1000; + +function validateBrowserRequest(request: NextRequest): boolean { + const origin = request.headers.get("origin"); + const referer = request.headers.get("referer"); + const userAgent = request.headers.get("user-agent") || ""; + const secFetchSite = request.headers.get("sec-fetch-site"); + const secFetchMode = request.headers.get("sec-fetch-mode"); + const secFetchDest = request.headers.get("sec-fetch-dest"); + const contentType = request.headers.get("content-type"); + const accept = request.headers.get("accept"); + + if (env.NODE_ENV === "development") { + console.log("=== Validating Browser Request ==="); + console.log("Origin:", origin); + console.log("Referer:", referer); + console.log("User-Agent:", userAgent); + console.log("Sec-Fetch-Site:", secFetchSite); + console.log("Sec-Fetch-Mode:", secFetchMode); + console.log("Sec-Fetch-Dest:", secFetchDest); + console.log("Content-Type:", contentType); + console.log("Accept:", accept); + } + + const allowedOrigins = + env.NODE_ENV === "development" ? ["http://localhost:3000", "http://127.0.0.1:3000"] : ["https://opencut.app", "https://www.opencut.app"]; + + if (!origin || !allowedOrigins.includes(origin)) { + console.log("Failed: Invalid origin"); + return false; + } + + if (!referer || !referer.startsWith(origin)) { + console.log("Failed: Invalid referer"); + return false; + } + + const suspiciousUserAgents = [ + "curl", + "wget", + "postman", + "insomnia", + "thunder client", + "httpie", + "python-requests", + "node-fetch", + "axios", + "scrapy", + "httpclient", + "okhttp", + "libwww-perl", + "python-urllib", + "go-http-client", + "java/", + "apache-httpclient", + ]; + + const lowerUserAgent = userAgent.toLowerCase(); + if (!userAgent || suspiciousUserAgents.some((agent) => lowerUserAgent.includes(agent))) { + console.log("Failed: Suspicious user agent"); + return false; + } + + const hasBrowserIndicators = + lowerUserAgent.includes("mozilla/") || + lowerUserAgent.includes("chrome/") || + lowerUserAgent.includes("safari/") || + lowerUserAgent.includes("firefox/") || + lowerUserAgent.includes("edge/"); + + if (!hasBrowserIndicators) { + console.log("Failed: No browser indicators in user agent"); + return false; + } + + if (secFetchSite && secFetchSite !== "same-origin") { + console.log("Failed: Invalid Sec-Fetch-Site:", secFetchSite); + return false; + } + + if (secFetchMode && secFetchMode !== "cors") { + console.log("Failed: Invalid Sec-Fetch-Mode:", secFetchMode); + return false; + } + + if (secFetchDest && secFetchDest !== "empty") { + console.log("Failed: Invalid Sec-Fetch-Dest:", secFetchDest); + return false; + } + + if (!contentType || !contentType.includes("application/json")) { + console.log("Failed: Invalid Content-Type"); + return false; + } + + if (!accept || (!accept.includes("application/json") && !accept.includes("*/*"))) { + console.log("Failed: Invalid Accept header"); + return false; + } + + console.log("Browser validation passed!"); + return true; +} + +async function validateCSRFToken(request: NextRequest): Promise { + const clientToken = request.headers.get("x-csrf-token"); + if (!clientToken) return false; + + const cookieStore = await cookies(); + const cookieValue = cookieStore.get(CSRF_TOKEN_NAME)?.value; + if (!cookieValue) return false; + + const [token, timestamp, signature] = cookieValue.split(":"); + if (!token || !timestamp || !signature) return false; + + if (clientToken !== token) return false; + + const now = Date.now(); + const tokenTime = parseInt(timestamp); + if (now - tokenTime > TOKEN_EXPIRY) return false; + + const expectedSignature = crypto + .createHmac("sha256", env.BETTER_AUTH_SECRET || "fallback-secret") + .update(`${token}:${timestamp}`) + .digest("hex"); + + return signature === expectedSignature; +} + export async function POST(request: NextRequest) { - // Rate limit check const identifier = request.headers.get("x-forwarded-for") ?? "127.0.0.1"; const { success } = await waitlistRateLimit.limit(identifier); if (!success) { - return NextResponse.json( - { error: "Too many requests. Please try again later." }, - { status: 429 } - ); + return NextResponse.json({ error: "Too many requests. Please try again later." }, { status: 429 }); + } + + if (!validateBrowserRequest(request)) { + await new Promise((resolve) => setTimeout(resolve, Math.random() * 2000 + 1000)); + + return NextResponse.json({ error: "Invalid request" }, { status: 403 }); + } + + const isValidToken = await validateCSRFToken(request); + if (!isValidToken) { + return NextResponse.json({ error: "Invalid security token" }, { status: 403 }); } try { const body = await request.json(); const { email } = waitlistSchema.parse(body); - // Check if email already exists - const existingEmail = await db - .select() - .from(waitlist) - .where(eq(waitlist.email, email.toLowerCase())) - .limit(1); + const existingEmail = await db.select().from(waitlist).where(eq(waitlist.email, email.toLowerCase())).limit(1); if (existingEmail.length > 0) { - return NextResponse.json( - { error: "Email already registered" }, - { status: 409 } - ); + return NextResponse.json({ error: "Email already registered" }, { status: 409 }); } - // Add to waitlist await db.insert(waitlist).values({ id: nanoid(), email: email.toLowerCase(), }); - return NextResponse.json( - { message: "Successfully joined waitlist!" }, - { status: 201 } - ); + return NextResponse.json({ message: "Successfully joined waitlist!" }, { status: 201 }); } catch (error) { if (error instanceof z.ZodError) { const firstError = error.errors[0]; @@ -56,9 +184,6 @@ export async function POST(request: NextRequest) { } console.error("Waitlist signup error:", error); - return NextResponse.json( - { error: "Internal server error" }, - { status: 500 } - ); + return NextResponse.json({ error: "Internal server error" }, { status: 500 }); } } diff --git a/apps/web/src/app/api/waitlist/token/route.ts b/apps/web/src/app/api/waitlist/token/route.ts new file mode 100644 index 00000000..76622fc5 --- /dev/null +++ b/apps/web/src/app/api/waitlist/token/route.ts @@ -0,0 +1,47 @@ +import { NextRequest, NextResponse } from "next/server"; +import { cookies } from "next/headers"; +import crypto from "crypto"; +import { env } from "@/env"; + +const CSRF_TOKEN_NAME = "waitlist-csrf"; +const TOKEN_EXPIRY = 60 * 60 * 1000; + +export async function GET(request: NextRequest) { + const referer = request.headers.get("referer"); + const host = request.headers.get("host"); + + if (referer) { + const refererUrl = new URL(referer); + const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"]; + + if (!allowedHosts.some((allowed) => refererUrl.host === allowed || refererUrl.host.endsWith(allowed))) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + } else if (host) { + const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"]; + + if (!allowedHosts.some((allowed) => host === allowed || host.endsWith(allowed))) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + } else { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + + const token = crypto.randomBytes(32).toString("hex"); + const timestamp = Date.now(); + const signature = crypto + .createHmac("sha256", env.BETTER_AUTH_SECRET || "fallback-secret") + .update(`${token}:${timestamp}`) + .digest("hex"); + + const cookieStore = await cookies(); + cookieStore.set(CSRF_TOKEN_NAME, `${token}:${timestamp}:${signature}`, { + httpOnly: true, + secure: env.NODE_ENV === "production", + sameSite: "strict", + maxAge: TOKEN_EXPIRY / 1000, + path: "/", + }); + + return NextResponse.json({ token }); +} diff --git a/apps/web/src/components/landing/hero.tsx b/apps/web/src/components/landing/hero.tsx index 462e3ba7..54aba300 100644 --- a/apps/web/src/components/landing/hero.tsx +++ b/apps/web/src/components/landing/hero.tsx @@ -4,7 +4,7 @@ import { motion } from "motion/react"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { ArrowRight } from "lucide-react"; -import { useState } from "react"; +import { useState, useEffect } from "react"; import { toast } from "sonner"; import Image from "next/image"; @@ -13,6 +13,20 @@ import { Handlebars } from "./handlebars"; export function Hero() { const [email, setEmail] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); + const [csrfToken, setCsrfToken] = useState(null); + + useEffect(() => { + fetch("/api/waitlist/token", { + credentials: "include", + }) + .then((res) => res.json()) + .then((data) => { + if (data.token) { + setCsrfToken(data.token); + } + }) + .catch((err) => console.error("Failed to fetch CSRF token:", err)); + }, []); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); @@ -24,6 +38,13 @@ export function Hero() { return; } + if (!csrfToken) { + toast.error("Security error", { + description: "Please refresh the page and try again.", + }); + return; + } + setIsSubmitting(true); try { @@ -31,7 +52,9 @@ export function Hero() { method: "POST", headers: { "Content-Type": "application/json", + "X-CSRF-Token": csrfToken, }, + credentials: "include", body: JSON.stringify({ email: email.trim() }), }); @@ -42,11 +65,15 @@ export function Hero() { description: "You'll be notified when we launch.", }); setEmail(""); + + fetch("/api/waitlist/token", { credentials: "include" }) + .then((res) => res.json()) + .then((data) => { + if (data.token) setCsrfToken(data.token); + }); } else { toast.error("Oops!", { - description: - (data as { error: string }).error || - "Something went wrong. Please try again.", + description: (data as { error: string }).error || "Something went wrong. Please try again.", }); } } catch (error) { @@ -60,13 +87,7 @@ export function Hero() { return (
- landing-page.bg + landing-page.bg - A simple but powerful video editor that gets the job done. Works on - any platform. + A simple but powerful video editor that gets the job done. Works on any platform. - -
+ +
setEmail(e.target.value)} - disabled={isSubmitting} + disabled={isSubmitting || !csrfToken} required />
- diff --git a/apps/web/src/lib/rate-limit.ts b/apps/web/src/lib/rate-limit.ts index 92e78e74..ac63a64c 100644 --- a/apps/web/src/lib/rate-limit.ts +++ b/apps/web/src/lib/rate-limit.ts @@ -12,4 +12,5 @@ export const waitlistRateLimit = new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(5, "1 m"), // 5 requests per minute analytics: true, + prefix: "waitlist-rate-limit", }); From eb49500592e5c50c5637c09ea585b065545f2135 Mon Sep 17 00:00:00 2001 From: Ahmet Kilinc Date: Wed, 16 Jul 2025 01:00:40 +0100 Subject: [PATCH 14/19] adds Vercel BotId --- apps/web/next.config.ts | 3 ++- apps/web/package.json | 1 + apps/web/src/app/api/waitlist/route.ts | 7 +++++++ apps/web/src/app/layout.tsx | 11 +++++++++++ bun.lock | 3 +++ 5 files changed, 24 insertions(+), 1 deletion(-) diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index a0a0d31b..02261068 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -1,4 +1,5 @@ import type { NextConfig } from "next"; +import { withBotId } from "botid/next/config"; const nextConfig: NextConfig = { compiler: { @@ -21,4 +22,4 @@ const nextConfig: NextConfig = { }, }; -export default nextConfig; +export default withBotId(nextConfig); diff --git a/apps/web/package.json b/apps/web/package.json index 07b36dcb..193eb244 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -27,6 +27,7 @@ "@upstash/redis": "^1.35.0", "@vercel/analytics": "^1.4.1", "better-auth": "^1.2.7", + "botid": "^1.4.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.0.0", diff --git a/apps/web/src/app/api/waitlist/route.ts b/apps/web/src/app/api/waitlist/route.ts index 4d64be77..031ebd5a 100644 --- a/apps/web/src/app/api/waitlist/route.ts +++ b/apps/web/src/app/api/waitlist/route.ts @@ -1,6 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; import { db, eq } from "@opencut/db"; import { waitlist } from "@opencut/db/schema"; +import { checkBotId } from "botid/server"; import { nanoid } from "nanoid"; import { waitlistRateLimit } from "@/lib/rate-limit"; import { z } from "zod"; @@ -143,6 +144,12 @@ async function validateCSRFToken(request: NextRequest): Promise { } export async function POST(request: NextRequest) { + const verification = await checkBotId(); + + if (verification.isBot) { + return NextResponse.json({ error: "Access denied" }, { status: 403 }); + } + const identifier = request.headers.get("x-forwarded-for") ?? "127.0.0.1"; const { success } = await waitlistRateLimit.limit(identifier); diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx index 9ac54262..1cbc3f2e 100644 --- a/apps/web/src/app/layout.tsx +++ b/apps/web/src/app/layout.tsx @@ -7,9 +7,17 @@ import { TooltipProvider } from "../components/ui/tooltip"; import { StorageProvider } from "../components/storage-provider"; import { baseMetaData } from "./metadata"; import { defaultFont } from "../lib/font-config"; +import { BotIdClient } from "botid/client"; export const metadata = baseMetaData; +const protectedRoutes = [ + { + path: "/api/waitlist", + method: "POST", + }, +]; + export default function RootLayout({ children, }: Readonly<{ @@ -17,6 +25,9 @@ export default function RootLayout({ }>) { return ( + + + diff --git a/bun.lock b/bun.lock index 0e22ec75..7102ca46 100644 --- a/bun.lock +++ b/bun.lock @@ -28,6 +28,7 @@ "@upstash/redis": "^1.35.0", "@vercel/analytics": "^1.4.1", "better-auth": "^1.2.7", + "botid": "^1.4.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.0.0", @@ -507,6 +508,8 @@ "binary-extensions": ["binary-extensions@2.3.0", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="], + "botid": ["botid@1.4.2", "", { "peerDependencies": { "next": "*", "react": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["next"] }, "sha512-yiRWEdxXa5QhxzJW4lTk0lRZkbqPsVWdGrhnHLLihZf0xBEtsTUGtxLqK++IY80FX/Ye/rNMnGqBp2pl4yYU8w=="], + "brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], From ece9c78b16acd683f09b0fcd7c7b515c64da52f9 Mon Sep 17 00:00:00 2001 From: Ahmet Kilinc Date: Wed, 16 Jul 2025 01:05:42 +0100 Subject: [PATCH 15/19] coderabbit comments --- apps/web/src/app/api/waitlist/route.ts | 5 +---- apps/web/src/app/api/waitlist/token/route.ts | 13 ++++++------- apps/web/src/components/landing/hero.tsx | 15 +++++++++++++-- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/apps/web/src/app/api/waitlist/route.ts b/apps/web/src/app/api/waitlist/route.ts index 031ebd5a..076dd228 100644 --- a/apps/web/src/app/api/waitlist/route.ts +++ b/apps/web/src/app/api/waitlist/route.ts @@ -135,10 +135,7 @@ async function validateCSRFToken(request: NextRequest): Promise { const tokenTime = parseInt(timestamp); if (now - tokenTime > TOKEN_EXPIRY) return false; - const expectedSignature = crypto - .createHmac("sha256", env.BETTER_AUTH_SECRET || "fallback-secret") - .update(`${token}:${timestamp}`) - .digest("hex"); + const expectedSignature = crypto.createHmac("sha256", env.BETTER_AUTH_SECRET).update(`${token}:${timestamp}`).digest("hex"); return signature === expectedSignature; } diff --git a/apps/web/src/app/api/waitlist/token/route.ts b/apps/web/src/app/api/waitlist/token/route.ts index 76622fc5..4c7695fa 100644 --- a/apps/web/src/app/api/waitlist/token/route.ts +++ b/apps/web/src/app/api/waitlist/token/route.ts @@ -5,6 +5,7 @@ import { env } from "@/env"; const CSRF_TOKEN_NAME = "waitlist-csrf"; const TOKEN_EXPIRY = 60 * 60 * 1000; +const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"]; export async function GET(request: NextRequest) { const referer = request.headers.get("referer"); @@ -12,14 +13,11 @@ export async function GET(request: NextRequest) { if (referer) { const refererUrl = new URL(referer); - const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"]; if (!allowedHosts.some((allowed) => refererUrl.host === allowed || refererUrl.host.endsWith(allowed))) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } } else if (host) { - const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"]; - if (!allowedHosts.some((allowed) => host === allowed || host.endsWith(allowed))) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } @@ -27,12 +25,13 @@ export async function GET(request: NextRequest) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } + if (!env.BETTER_AUTH_SECRET) { + throw new Error("BETTER_AUTH_SECRET must be configured"); + } + const token = crypto.randomBytes(32).toString("hex"); const timestamp = Date.now(); - const signature = crypto - .createHmac("sha256", env.BETTER_AUTH_SECRET || "fallback-secret") - .update(`${token}:${timestamp}`) - .digest("hex"); + const signature = crypto.createHmac("sha256", env.BETTER_AUTH_SECRET).update(`${token}:${timestamp}`).digest("hex"); const cookieStore = await cookies(); cookieStore.set(CSRF_TOKEN_NAME, `${token}:${timestamp}:${signature}`, { diff --git a/apps/web/src/components/landing/hero.tsx b/apps/web/src/components/landing/hero.tsx index 54aba300..b1910dc5 100644 --- a/apps/web/src/components/landing/hero.tsx +++ b/apps/web/src/components/landing/hero.tsx @@ -16,16 +16,24 @@ export function Hero() { const [csrfToken, setCsrfToken] = useState(null); useEffect(() => { + let isMounted = true; fetch("/api/waitlist/token", { credentials: "include", }) .then((res) => res.json()) .then((data) => { - if (data.token) { + if (isMounted && data.token) { setCsrfToken(data.token); } }) - .catch((err) => console.error("Failed to fetch CSRF token:", err)); + .catch((err) => { + console.error("Failed to fetch CSRF token:", err); + if (isMounted) { + toast.error("Security initialization failed", { + description: "Please refresh the page to continue.", + }); + } + }); }, []); const handleSubmit = async (e: React.FormEvent) => { @@ -70,6 +78,9 @@ export function Hero() { .then((res) => res.json()) .then((data) => { if (data.token) setCsrfToken(data.token); + }) + .catch((err) => { + console.error("Failed to refresh CSRF token:", err); }); } else { toast.error("Oops!", { From 79f6c680f394ec4a9970124cfe915b05c1b969df Mon Sep 17 00:00:00 2001 From: Ahmet Kilinc Date: Wed, 16 Jul 2025 01:23:06 +0100 Subject: [PATCH 16/19] remove browser check --- apps/web/src/app/api/waitlist/route.ts | 109 ------------------------- 1 file changed, 109 deletions(-) diff --git a/apps/web/src/app/api/waitlist/route.ts b/apps/web/src/app/api/waitlist/route.ts index 076dd228..f62e24e9 100644 --- a/apps/web/src/app/api/waitlist/route.ts +++ b/apps/web/src/app/api/waitlist/route.ts @@ -16,108 +16,6 @@ const waitlistSchema = z.object({ const CSRF_TOKEN_NAME = "waitlist-csrf"; const TOKEN_EXPIRY = 60 * 60 * 1000; -function validateBrowserRequest(request: NextRequest): boolean { - const origin = request.headers.get("origin"); - const referer = request.headers.get("referer"); - const userAgent = request.headers.get("user-agent") || ""; - const secFetchSite = request.headers.get("sec-fetch-site"); - const secFetchMode = request.headers.get("sec-fetch-mode"); - const secFetchDest = request.headers.get("sec-fetch-dest"); - const contentType = request.headers.get("content-type"); - const accept = request.headers.get("accept"); - - if (env.NODE_ENV === "development") { - console.log("=== Validating Browser Request ==="); - console.log("Origin:", origin); - console.log("Referer:", referer); - console.log("User-Agent:", userAgent); - console.log("Sec-Fetch-Site:", secFetchSite); - console.log("Sec-Fetch-Mode:", secFetchMode); - console.log("Sec-Fetch-Dest:", secFetchDest); - console.log("Content-Type:", contentType); - console.log("Accept:", accept); - } - - const allowedOrigins = - env.NODE_ENV === "development" ? ["http://localhost:3000", "http://127.0.0.1:3000"] : ["https://opencut.app", "https://www.opencut.app"]; - - if (!origin || !allowedOrigins.includes(origin)) { - console.log("Failed: Invalid origin"); - return false; - } - - if (!referer || !referer.startsWith(origin)) { - console.log("Failed: Invalid referer"); - return false; - } - - const suspiciousUserAgents = [ - "curl", - "wget", - "postman", - "insomnia", - "thunder client", - "httpie", - "python-requests", - "node-fetch", - "axios", - "scrapy", - "httpclient", - "okhttp", - "libwww-perl", - "python-urllib", - "go-http-client", - "java/", - "apache-httpclient", - ]; - - const lowerUserAgent = userAgent.toLowerCase(); - if (!userAgent || suspiciousUserAgents.some((agent) => lowerUserAgent.includes(agent))) { - console.log("Failed: Suspicious user agent"); - return false; - } - - const hasBrowserIndicators = - lowerUserAgent.includes("mozilla/") || - lowerUserAgent.includes("chrome/") || - lowerUserAgent.includes("safari/") || - lowerUserAgent.includes("firefox/") || - lowerUserAgent.includes("edge/"); - - if (!hasBrowserIndicators) { - console.log("Failed: No browser indicators in user agent"); - return false; - } - - if (secFetchSite && secFetchSite !== "same-origin") { - console.log("Failed: Invalid Sec-Fetch-Site:", secFetchSite); - return false; - } - - if (secFetchMode && secFetchMode !== "cors") { - console.log("Failed: Invalid Sec-Fetch-Mode:", secFetchMode); - return false; - } - - if (secFetchDest && secFetchDest !== "empty") { - console.log("Failed: Invalid Sec-Fetch-Dest:", secFetchDest); - return false; - } - - if (!contentType || !contentType.includes("application/json")) { - console.log("Failed: Invalid Content-Type"); - return false; - } - - if (!accept || (!accept.includes("application/json") && !accept.includes("*/*"))) { - console.log("Failed: Invalid Accept header"); - return false; - } - - console.log("Browser validation passed!"); - return true; -} - async function validateCSRFToken(request: NextRequest): Promise { const clientToken = request.headers.get("x-csrf-token"); if (!clientToken) return false; @@ -153,13 +51,6 @@ export async function POST(request: NextRequest) { if (!success) { return NextResponse.json({ error: "Too many requests. Please try again later." }, { status: 429 }); } - - if (!validateBrowserRequest(request)) { - await new Promise((resolve) => setTimeout(resolve, Math.random() * 2000 + 1000)); - - return NextResponse.json({ error: "Invalid request" }, { status: 403 }); - } - const isValidToken = await validateCSRFToken(request); if (!isValidToken) { return NextResponse.json({ error: "Invalid security token" }, { status: 403 }); From 7c6b2e4f499a9878b641bac5692f5a2ee884d125 Mon Sep 17 00:00:00 2001 From: enkeii64 Date: Wed, 16 Jul 2025 18:49:11 +1000 Subject: [PATCH 17/19] feat: display all contributors --- apps/web/src/app/contributors/page.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/app/contributors/page.tsx b/apps/web/src/app/contributors/page.tsx index fcf96e11..5613f1f9 100644 --- a/apps/web/src/app/contributors/page.tsx +++ b/apps/web/src/app/contributors/page.tsx @@ -32,7 +32,7 @@ interface Contributor { async function getContributors(): Promise { try { const response = await fetch( - "https://api.github.com/repos/OpenCut-app/OpenCut/contributors", + "https://api.github.com/repos/OpenCut-app/OpenCut/contributors?per_page=100", { headers: { Accept: "application/vnd.github.v3+json", From 446745a33ce06273e78b9147e832434df458ef66 Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Wed, 16 Jul 2025 12:03:44 +0200 Subject: [PATCH 18/19] cleanup --- apps/web/src/components/editor/media-panel/views/media.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/editor/media-panel/views/media.tsx b/apps/web/src/components/editor/media-panel/views/media.tsx index f8cbb639..198f28de 100644 --- a/apps/web/src/components/editor/media-panel/views/media.tsx +++ b/apps/web/src/components/editor/media-panel/views/media.tsx @@ -3,7 +3,7 @@ import { useDragDrop } from "@/hooks/use-drag-drop"; import { processMediaFiles } from "@/lib/media-processing"; import { useMediaStore, type MediaItem } from "@/stores/media-store"; -import { Image, Loader2, Music, Plus, Upload, Video } from "lucide-react"; +import { Image, Loader2, Music, Plus, Video } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; From a7e23ec714faabbeaa3b6a673e7e2d86825944bd Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Wed, 16 Jul 2025 12:22:09 +0200 Subject: [PATCH 19/19] media drag overlay cleanup --- .../editor/media-panel/drag-overlay.tsx | 57 ++++++++++++ .../editor/media-panel/views/media.tsx | 20 +--- apps/web/src/components/ui/drag-overlay.tsx | 91 ------------------- 3 files changed, 60 insertions(+), 108 deletions(-) create mode 100644 apps/web/src/components/editor/media-panel/drag-overlay.tsx delete mode 100644 apps/web/src/components/ui/drag-overlay.tsx diff --git a/apps/web/src/components/editor/media-panel/drag-overlay.tsx b/apps/web/src/components/editor/media-panel/drag-overlay.tsx new file mode 100644 index 00000000..3f3820db --- /dev/null +++ b/apps/web/src/components/editor/media-panel/drag-overlay.tsx @@ -0,0 +1,57 @@ +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/views/media.tsx b/apps/web/src/components/editor/media-panel/views/media.tsx index e532e540..631fe39a 100644 --- a/apps/web/src/components/editor/media-panel/views/media.tsx +++ b/apps/web/src/components/editor/media-panel/views/media.tsx @@ -7,7 +7,7 @@ import { Image, Loader2, Music, Plus, Video } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; -import { DragOverlay } from "@/components/ui/drag-overlay"; +import { MediaDragOverlay } from "@/components/editor/media-panel/drag-overlay"; import { ContextMenu, ContextMenuContent, @@ -242,23 +242,9 @@ export function MediaView() {
- {(isDragOver || filteredMediaItems.length === 0) ? ( - void; - isEmptyState?: boolean; -} - -export function DragOverlay({ - isVisible, - title = "Drop files here", - description = "Images, videos, and audio files", - isProcessing = false, - progress = 0, - onClick, - isEmptyState = false, -}: DragOverlayProps) { - if (!isVisible) return null; - - const handleClick = (e: React.MouseEvent) => { - if (isProcessing || !onClick) return; - e.preventDefault(); - e.stopPropagation(); - onClick(); - }; - - return ( -
-
- {isProcessing ? ( - - ) : isEmptyState ? ( - - ) : ( - - )} -
- -
-

- {isProcessing ? "Processing files..." : title} -

-

- {isProcessing - ? `Processing your files (${progress}%)` - : description - } -

-
- - {!isProcessing && ( -
- -

- {isEmptyState - ? "Supports images, videos, and audio files" - : "Or drop your files here" - } -

-
- )} - - {isProcessing && ( -
-
-
-
-
- )} -
- ); -}