🎥 Make videos programmatically with React
refactor(tp2mg): extract image attachment logic to shared hook
ASchwadd6273ddeb171
diff --git a/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsxindex 2800aebf09..1551f54a75 100644--- a/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useRef, type ComponentType, type DragEvent, type ChangeEvent } from "react";+import { useState, type ComponentType } from "react";import { ArrowUp, Camera, X, Paperclip } from "lucide-react";import { Button } from "@/components/ui/button";import {@@ -11,9 +11,8 @@ import {SelectValue,} from "@/components/ui/select";import { type ModelId, MODELS } from "@/types/generation";-import { captureFrame, fileToBase64 } from "@/helpers/capture-frame";--const MAX_ATTACHED_IMAGES = 4;+import { captureFrame } from "@/helpers/capture-frame";+import { useImageAttachments } from "@/hooks/useImageAttachments";interface ChatInputProps {prompt: string;@@ -41,35 +40,27 @@ export function ChatInput({durationInFrames = 150,currentFrame = 0,}: ChatInputProps) {- const [attachedImages, setAttachedImages] = useState<string[]>([]);const [isCapturing, setIsCapturing] = useState(false);- const [isDragging, setIsDragging] = useState(false);- const fileInputRef = useRef<HTMLInputElement>(null);+ const {+ attachedImages,+ isDragging,+ fileInputRef,+ addImages,+ removeImage,+ clearImages,+ handleFileSelect,+ handlePaste,+ handleDragOver,+ handleDragLeave,+ handleDrop,+ canAddMore,+ } = useImageAttachments();const handleSubmit = (e: React.FormEvent) => {e.preventDefault();if (!prompt.trim()) return;onSubmit(attachedImages.length > 0 ? attachedImages : undefined);- setAttachedImages([]); // Clear after submit- };-- const addImages = (newImages: string[]) => {- setAttachedImages((prev) => {- const combined = [...prev, ...newImages];- return combined.slice(0, MAX_ATTACHED_IMAGES);- });- };-- const removeImage = (index: number) => {- setAttachedImages((prev) => prev.filter((_, i) => i !== index));- };-- const handleFileSelect = async (e: ChangeEvent<HTMLInputElement>) => {- const files = Array.from(e.target.files || []);- const imageFiles = files.filter((f) => f.type.startsWith("image/"));- const base64Images = await Promise.all(imageFiles.map(fileToBase64));- addImages(base64Images);- e.target.value = "";+ clearImages();};const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {@@ -81,7 +72,7 @@ export function ChatInput({};const handleCapture = async () => {- if (!Component || isCapturing || attachedImages.length >= MAX_ATTACHED_IMAGES) return;+ if (!Component || isCapturing || !canAddMore) return;setIsCapturing(true);try {@@ -99,40 +90,7 @@ export function ChatInput({}};- const handlePaste = async (e: React.ClipboardEvent) => {- const items = Array.from(e.clipboardData.items);- const imageItems = items.filter((item) => item.type.startsWith("image/"));- if (imageItems.length > 0) {- e.preventDefault();- const files = imageItems- .map((item) => item.getAsFile())- .filter((f): f is File => f !== null);- const base64Images = await Promise.all(files.map(fileToBase64));- addImages(base64Images);- }- };-- const handleDragOver = (e: DragEvent) => {- e.preventDefault();- setIsDragging(true);- };-- const handleDragLeave = (e: DragEvent) => {- e.preventDefault();- setIsDragging(false);- };-- const handleDrop = async (e: DragEvent) => {- e.preventDefault();- setIsDragging(false);-- const files = Array.from(e.dataTransfer.files);- const imageFiles = files.filter((f) => f.type.startsWith("image/"));- const base64Images = await Promise.all(imageFiles.map(fileToBase64));- addImages(base64Images);- };-- const canCapture = Component && !isLoading && !isCapturing && attachedImages.length < MAX_ATTACHED_IMAGES;+ const canCapture = Component && !isLoading && !isCapturing && canAddMore;return (<div className="p-4">@@ -218,7 +176,7 @@ export function ChatInput({variant="ghost"size="icon-sm"onClick={() => fileInputRef.current?.click()}- disabled={isLoading || attachedImages.length >= MAX_ATTACHED_IMAGES}+ disabled={isLoading || !canAddMore}className="text-muted-foreground hover:text-foreground h-7 w-7"title="Attach images">diff --git a/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsxindex 7515099596..7a7c691076 100644--- a/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useRef, type DragEvent, type ChangeEvent } from "react";+import { useState } from "react";import Link from "next/link";import {ArrowUp,@@ -14,7 +14,6 @@ import {Paperclip,type LucideIcon,} from "lucide-react";-import { fileToBase64 } from "@/helpers/capture-frame";import {Select,SelectContent,@@ -25,6 +24,7 @@ import {import { Button } from "@/components/ui/button";import { examplePrompts } from "@/examples/prompts";import { type ModelId, MODELS } from "@/types/generation";+import { useImageAttachments } from "@/hooks/useImageAttachments";const iconMap: Record<string, LucideIcon> = {Type,@@ -34,8 +34,6 @@ const iconMap: Record<string, LucideIcon> = {Disc,};-const MAX_ATTACHED_IMAGES = 4;-interface LandingPageInputProps {onNavigate: (prompt: string, model: ModelId, attachedImages?: string[]) => void;isNavigating?: boolean;@@ -49,9 +47,18 @@ export function LandingPageInput({}: LandingPageInputProps) {const [prompt, setPrompt] = useState("");const [model, setModel] = useState<ModelId>("gpt-5.2:low");- const [attachedImages, setAttachedImages] = useState<string[]>([]);- const [isDragging, setIsDragging] = useState(false);- const fileInputRef = useRef<HTMLInputElement>(null);+ const {+ attachedImages,+ isDragging,+ fileInputRef,+ removeImage,+ handleFileSelect,+ handlePaste,+ handleDragOver,+ handleDragLeave,+ handleDrop,+ canAddMore,+ } = useImageAttachments();const handleSubmit = (e: React.FormEvent) => {e.preventDefault();@@ -59,26 +66,6 @@ export function LandingPageInput({onNavigate(prompt, model, attachedImages.length > 0 ? attachedImages : undefined);};- const addImages = (newImages: string[]) => {- setAttachedImages((prev) => {- const combined = [...prev, ...newImages];- return combined.slice(0, MAX_ATTACHED_IMAGES);- });- };-- const removeImage = (index: number) => {- setAttachedImages((prev) => prev.filter((_, i) => i !== index));- };-- const handleFileSelect = async (e: ChangeEvent<HTMLInputElement>) => {- const files = Array.from(e.target.files || []);- const imageFiles = files.filter((f) => f.type.startsWith("image/"));- const base64Images = await Promise.all(imageFiles.map(fileToBase64));- addImages(base64Images);- // Reset input so same file can be selected again- e.target.value = "";- };-const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {// Submit on Enter (Shift+Enter for new line)if (e.key === "Enter" && !e.shiftKey) {@@ -87,39 +74,6 @@ export function LandingPageInput({}};- const handlePaste = async (e: React.ClipboardEvent) => {- const items = Array.from(e.clipboardData.items);- const imageItems = items.filter((item) => item.type.startsWith("image/"));- if (imageItems.length > 0) {- e.preventDefault();- const files = imageItems- .map((item) => item.getAsFile())- .filter((f): f is File => f !== null);- const base64Images = await Promise.all(files.map(fileToBase64));- addImages(base64Images);- }- };-- const handleDragOver = (e: DragEvent) => {- e.preventDefault();- setIsDragging(true);- };-- const handleDragLeave = (e: DragEvent) => {- e.preventDefault();- setIsDragging(false);- };-- const handleDrop = async (e: DragEvent) => {- e.preventDefault();- setIsDragging(false);-- const files = Array.from(e.dataTransfer.files);- const imageFiles = files.filter((f) => f.type.startsWith("image/"));- const base64Images = await Promise.all(imageFiles.map(fileToBase64));- addImages(base64Images);- };-return (<div className="flex flex-col items-center justify-center flex-1 px-4"><h1 className="text-5xl font-bold text-white mb-10 text-center">@@ -207,7 +161,7 @@ export function LandingPageInput({variant="ghost"size="icon-sm"onClick={() => fileInputRef.current?.click()}- disabled={isNavigating || attachedImages.length >= MAX_ATTACHED_IMAGES}+ disabled={isNavigating || !canAddMore}className="text-muted-foreground hover:text-foreground"title="Attach images">diff --git a/packages/template-prompt-to-motion-graphics/src/hooks/useImageAttachments.ts b/packages/template-prompt-to-motion-graphics/src/hooks/useImageAttachments.tsnew file mode 100644index 0000000000..2a3f9a0d9b--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/hooks/useImageAttachments.ts@@ -0,0 +1,97 @@+import { useState, useRef, useCallback, type ChangeEvent, type DragEvent, type ClipboardEvent } from "react";+import { fileToBase64 } from "@/helpers/capture-frame";++const MAX_ATTACHED_IMAGES = 4;++interface UseImageAttachmentsReturn {+ attachedImages: string[];+ isDragging: boolean;+ fileInputRef: React.RefObject<HTMLInputElement | null>;+ addImages: (newImages: string[]) => void;+ removeImage: (index: number) => void;+ clearImages: () => void;+ handleFileSelect: (e: ChangeEvent<HTMLInputElement>) => Promise<void>;+ handlePaste: (e: ClipboardEvent) => Promise<void>;+ handleDragOver: (e: DragEvent) => void;+ handleDragLeave: (e: DragEvent) => void;+ handleDrop: (e: DragEvent) => Promise<void>;+ canAddMore: boolean;+}++export function useImageAttachments(): UseImageAttachmentsReturn {+ const [attachedImages, setAttachedImages] = useState<string[]>([]);+ const [isDragging, setIsDragging] = useState(false);+ const fileInputRef = useRef<HTMLInputElement>(null);++ const addImages = useCallback((newImages: string[]) => {+ setAttachedImages((prev) => {+ const combined = [...prev, ...newImages];+ return combined.slice(0, MAX_ATTACHED_IMAGES);+ });+ }, []);++ const removeImage = useCallback((index: number) => {+ setAttachedImages((prev) => prev.filter((_, i) => i !== index));+ }, []);++ const clearImages = useCallback(() => {+ setAttachedImages([]);+ }, []);++ const handleFileSelect = useCallback(async (e: ChangeEvent<HTMLInputElement>) => {+ const files = Array.from(e.target.files || []);+ const imageFiles = files.filter((f) => f.type.startsWith("image/"));+ const base64Images = await Promise.all(imageFiles.map(fileToBase64));+ addImages(base64Images);+ // Reset input so same file can be selected again+ e.target.value = "";+ }, [addImages]);++ const handlePaste = useCallback(async (e: ClipboardEvent) => {+ const items = Array.from(e.clipboardData.items);+ const imageItems = items.filter((item) => item.type.startsWith("image/"));+ if (imageItems.length > 0) {+ e.preventDefault();+ const files = imageItems+ .map((item) => item.getAsFile())+ .filter((f): f is File => f !== null);+ const base64Images = await Promise.all(files.map(fileToBase64));+ addImages(base64Images);+ }+ }, [addImages]);++ const handleDragOver = useCallback((e: DragEvent) => {+ e.preventDefault();+ setIsDragging(true);+ }, []);++ const handleDragLeave = useCallback((e: DragEvent) => {+ e.preventDefault();+ setIsDragging(false);+ }, []);++ const handleDrop = useCallback(async (e: DragEvent) => {+ e.preventDefault();+ setIsDragging(false);++ const files = Array.from(e.dataTransfer.files);+ const imageFiles = files.filter((f) => f.type.startsWith("image/"));+ const base64Images = await Promise.all(imageFiles.map(fileToBase64));+ addImages(base64Images);+ }, [addImages]);++ return {+ attachedImages,+ isDragging,+ fileInputRef,+ addImages,+ removeImage,+ clearImages,+ handleFileSelect,+ handlePaste,+ handleDragOver,+ handleDragLeave,+ handleDrop,+ canAddMore: attachedImages.length < MAX_ATTACHED_IMAGES,+ };+}