Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat(editing-templates): add editing template categories and registry

Augustus Otua0a54526fd9d
diff --git a/apps/web/src/components/editor/AssetsPanel.tsx b/apps/web/src/components/editor/AssetsPanel.tsx
index df34ea77..899c4666 100644
--- a/apps/web/src/components/editor/AssetsPanel.tsx
+++ b/apps/web/src/components/editor/AssetsPanel.tsx
@@ -35,6 +35,7 @@ import { useUIStore } from "../../stores/ui-store";
import type { MediaItem } from "@openreel/core";
import { AspectRatioMatchDialog } from "./dialogs/AspectRatioMatchDialog";
import { AIGenTab } from "./AIGenTab";
+import { RecipesTab } from "./panels/RecipesTab";
import { TemplatesTab } from "./panels/TemplatesTab";
import { useTtsAudioStore } from "../../stores/tts-store";
import { toast } from "../../stores/notification-store";
@@ -47,6 +48,9 @@ import {
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
+ Tabs,
+ TabsList,
+ TabsTrigger,
} from "@openreel/ui";
import { KieAIImageDialog } from "./kieai/KieAIImageDialog";
import { loadMediaBlob } from "../../services/media-storage";
@@ -65,6 +69,44 @@ const formatDuration = (seconds: number): string => {
* Shows thumbnail with metadata below (not overlaid)
*/
type MediaViewMode = "large" | "small" | "list";
+type AssetsTab = "media" | "text" | "graphics" | "ai" | "recipes" | "templates";
+
+const ASSETS_TABS: ReadonlyArray<{
+ value: AssetsTab;
+ label: string;
+ description: string;
+}> = [
+ {
+ value: "media",
+ label: "Media",
+ description: "Import footage, audio, and stills.",
+ },
+ {
+ value: "text",
+ label: "Text",
+ description: "Add title presets and caption elements.",
+ },
+ {
+ value: "graphics",
+ label: "Graphics",
+ description: "Create shapes, arrows, and SVG overlays.",
+ },
+ {
+ value: "ai",
+ label: "AI Generate",
+ description: "Generate clips, captions, and assisted edits.",
+ },
+ {
+ value: "recipes",
+ label: "Recipes",
+ description: "Apply clip-scoped looks, overlays, and text stacks.",
+ },
+ {
+ value: "templates",
+ label: "Project Templates",
+ description: "Load full-project starter layouts and presets.",
+ },
+] as const;
const MediaThumbnail: React.FC<{
item: MediaItem;
@@ -522,12 +564,10 @@ const LoadingIndicator: React.FC<{ message: string }> = ({ message }) => (
export const AssetsPanel: React.FC = () => {
const fileInputRef = useRef<HTMLInputElement>(null);
const [searchQuery, setSearchQuery] = useState("");
- const [activeTab, setActiveTabRaw] = useState<
- "media" | "text" | "graphics" | "ai" | "templates"
- >("media");
+ const [activeTab, setActiveTabRaw] = useState<AssetsTab>("media");
const ttsHasUnsaved = useTtsAudioStore((s) => s.generatedAudio !== null && !s.isAudioSaved);
- const setActiveTab = useCallback((tab: "media" | "text" | "graphics" | "ai" | "templates") => {
+ const setActiveTab = useCallback((tab: AssetsTab) => {
if (activeTab === "ai" && tab !== "ai" && ttsHasUnsaved) {
toast.warning("Unsaved audio discarded", "Save to media or download next time to keep it.");
}
@@ -891,543 +931,359 @@ export const AssetsPanel: React.FC = () => {
retryTask(item.kieaiTaskId);
}, [retryTask, setKieAIItemState]);
- return (
- <div
- data-tour="assets"
- className="w-80 bg-background-secondary border-r border-border flex flex-col h-full relative"
- >
- {/* Loading overlay */}
- {isImporting && (
- <LoadingIndicator message={importProgress || "Importing media..."} />
- )}
- {/* Panel Header */}
- <div className="px-5 py-4 flex items-center justify-between">
- <span className="font-bold text-lg text-text-primary tracking-tight">
- Assets
- </span>
- <div className="flex gap-1">
- <IconButton
- icon={Plus}
- onClick={triggerFileInput}
- title="Import media"
- />
- <IconButton icon={Maximize2} title="Maximize panel" />
- <IconButton icon={X} title="Close panel" />
- </div>
- </div>
-
- {/* Tabs */}
- <div className="flex px-5 gap-6 border-b border-border text-xs font-medium text-text-muted mb-5">
- <button
- onClick={() => setActiveTab("media")}
- className={`pb-3 transition-all relative ${
- activeTab === "media"
- ? "text-text-primary"
- : "hover:text-text-secondary"
- }`}
- >
- Media
- {activeTab === "media" && (
- <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(34,197,94,0.5)]" />
- )}
- </button>
- <button
- onClick={() => setActiveTab("text")}
- className={`pb-3 transition-all relative ${
- activeTab === "text"
- ? "text-text-primary"
- : "hover:text-text-secondary"
- }`}
- >
- Text
- {activeTab === "text" && (
- <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(34,197,94,0.5)]" />
- )}
- </button>
- <button
- onClick={() => setActiveTab("graphics")}
- className={`pb-3 transition-all relative ${
- activeTab === "graphics"
- ? "text-text-primary"
- : "hover:text-text-secondary"
- }`}
- >
- Graphics
- {activeTab === "graphics" && (
- <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(34,197,94,0.5)]" />
- )}
- </button>
- <button
- onClick={() => setActiveTab("ai")}
- className={`pb-3 transition-all relative ${
- activeTab === "ai"
- ? "text-primary"
- : "text-primary/70 hover:text-primary"
- }`}
- >
- AI Gen
- {activeTab === "ai" && (
- <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(34,197,94,0.5)]" />
- )}
- </button>
- <button
- onClick={() => setActiveTab("templates")}
- className={`pb-3 transition-all relative ${
- activeTab === "templates"
- ? "text-text-primary"
- : "hover:text-text-secondary"
- }`}
- >
- Templates
- {activeTab === "templates" && (
- <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(34,197,94,0.5)]" />
- )}
- </button>
- </div>
-
- {/* Search & view toggle - only show for media tab */}
- {activeTab === "media" && (
- <div className="px-5 mb-3 flex items-center gap-2">
- <div className="relative flex-1">
- <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted z-10" />
- <Input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Search media"
- className="pl-9 text-xs bg-background-tertiary border-border text-text-primary h-9"
- />
- </div>
- <div className="flex items-center bg-background-tertiary border border-border rounded-lg p-0.5">
- {([
- { mode: "large" as const, icon: LayoutGrid, title: "Large icons" },
- { mode: "small" as const, icon: Grid2x2, title: "Small icons" },
- { mode: "list" as const, icon: List, title: "List view" },
- ]).map(({ mode, icon: ViewIcon, title }) => (
- <button
- key={mode}
- onClick={() => setMediaViewMode(mode)}
- title={title}
- className={`p-1.5 rounded transition-colors ${
- mediaViewMode === mode
- ? "bg-background-elevated text-text-primary"
- : "text-text-muted hover:text-text-secondary"
- }`}
- >
- <ViewIcon size={13} />
- </button>
- ))}
- </div>
- </div>
- )}
-
- {/* Missing Assets Filter and Badge */}
- {activeTab === "media" && missingAssetsCount > 0 && (
- <div className="px-5 mb-5 space-y-2">
- <button
- onClick={() => setShowOnlyMissing(!showOnlyMissing)}
- className={`w-full px-3 py-2 rounded-lg border text-xs font-medium transition-all flex items-center justify-between ${
- showOnlyMissing
- ? "bg-yellow-500/10 border-yellow-500 text-yellow-500"
- : "bg-background-tertiary border-border text-text-secondary hover:border-yellow-500/50"
- }`}
- >
- <div className="flex items-center gap-2">
- <AlertTriangle size={14} />
- <span>Show Only Missing Assets</span>
- </div>
- <div className="px-2 py-0.5 rounded-full bg-yellow-500 text-black text-[10px] font-bold">
- {missingAssetsCount}
- </div>
- </button>
- <button
- onClick={handleRelinkFromFolder}
- className="w-full px-3 py-2 rounded-lg border border-yellow-500/40 bg-yellow-500/5 text-yellow-500 text-xs font-medium transition-all hover:bg-yellow-500/15 flex items-center gap-2"
- >
- <RefreshCw size={14} />
- <span>Relink from Folder…</span>
- </button>
- </div>
- )}
-
- {/* Hidden file input */}
- <input
- ref={fileInputRef}
- type="file"
- multiple
- accept="video/*,audio/*,image/*"
- onChange={(e) => handleFileImport(e.target.files)}
- className="hidden"
- />
-
- {/* Content based on active tab */}
- {activeTab === "media" && (
- <ScrollArea
- className={`flex-1 ${isDragOver ? "bg-primary/5" : ""}`}
- onDrop={handleDrop}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- >
- <div className="px-5 pb-5">
- {filteredItems.length === 0 ? (
- <EmptyState onImport={triggerFileInput} />
- ) : (
- <div className={
- mediaViewMode === "list"
- ? "flex flex-col gap-1.5"
- : mediaViewMode === "small"
- ? "grid grid-cols-3 gap-2"
- : "grid grid-cols-2 gap-3"
- }>
- {filteredItems.map((item) => (
- <MediaThumbnail
- key={item.id}
- item={item}
- isSelected={isSelected(item.id)}
- viewMode={mediaViewMode}
- onSelect={() => handleSelectItem(item.id)}
- onDelete={() => handleDeleteItem(item.id)}
- onReplace={() => handleReplaceAsset(item.id)}
- onDragStart={(e) => handleItemDragStart(e, item)}
- onAddToTimeline={() => handleAddToTimeline(item)}
- onKieAI={item.type === "image" && !item.isPending && !item.kieaiError ? () => handleOpenKieAI(item) : undefined}
- onRetryKieAI={item.kieaiError && item.kieaiTaskId ? () => handleRetryKieAI(item) : undefined}
- />
- ))}
- {/* Add more media tile */}
- {mediaViewMode === "list" ? (
- <button
- onClick={triggerFileInput}
- className="flex items-center gap-3 px-2 py-1.5 rounded-lg border-2 border-dashed border-border hover:border-text-secondary cursor-pointer transition-all group"
- >
- <div className="w-12 h-8 rounded bg-background-tertiary flex items-center justify-center flex-shrink-0">
- <Upload size={14} className="text-text-muted group-hover:text-text-secondary transition-colors" />
- </div>
- <span className="text-[11px] text-text-muted group-hover:text-text-secondary transition-colors font-medium">Add media</span>
- </button>
- ) : (
- <div className="flex flex-col">
- <button
- onClick={triggerFileInput}
- className="aspect-video bg-background-tertiary rounded-lg border-2 border-dashed border-border hover:border-text-secondary relative flex items-center justify-center cursor-pointer transition-all overflow-hidden shadow-sm group"
- >
- <div className="flex flex-col items-center gap-1.5">
- <Upload size={mediaViewMode === "small" ? 16 : 20} className="text-text-muted group-hover:text-text-secondary transition-colors" />
- <span className="text-[10px] text-text-muted group-hover:text-text-secondary transition-colors">Add media</span>
- </div>
- </button>
- </div>
- )}
+ const renderSectionContent = (tab: AssetsTab): React.ReactNode => {
+ switch (tab) {
+ case "media":
+ return (
+ <div className="flex min-h-0 flex-1 flex-col border-t border-border/70">
+ <div className="px-4 pt-3 pb-3 flex items-center gap-2">
+ <div className="relative flex-1">
+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted z-10" />
+ <Input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search media"
+ className="pl-9 text-xs bg-background-tertiary border-border text-text-primary h-9"
+ />
</div>
- )}
-
- {/* Drop zone indicator */}
- {isDragOver && (
- <div className="absolute inset-4 border-2 border-dashed border-primary rounded-xl flex items-center justify-center bg-primary/5 pointer-events-none z-50 backdrop-blur-sm">
- <div className="text-primary text-sm font-bold bg-background-secondary px-4 py-2 rounded-full shadow-lg">
- Drop files to import
- </div>
- </div>
- )}
- </div>
- </ScrollArea>
- )}
-
- {/* Graphics Tab Content (Task 16) */}
- {activeTab === "graphics" && (
- <ScrollArea className="flex-1">
- <div className="px-5 pb-5">
- {/* Backgrounds Section */}
- <div className="mb-6">
- <div className="flex items-center justify-between mb-3">
- <h4 className="text-xs font-medium text-text-secondary flex items-center gap-1.5">
- <Palette size={12} />
- Backgrounds
- </h4>
- </div>
- <div className="flex gap-1.5 mb-3 flex-wrap">
- {(["all", "solid", "gradient", "mesh", "pattern"] as const).map(
- (cat) => (
+ <div className="flex items-center bg-background-tertiary border border-border rounded-lg p-0.5">
+ {([
+ { mode: "large" as const, icon: LayoutGrid, title: "Large icons" },
+ { mode: "small" as const, icon: Grid2x2, title: "Small icons" },
+ { mode: "list" as const, icon: List, title: "List view" },
+ ]).map(({ mode, icon: ViewIcon, title }) => (
<button
- key={cat}
- onClick={() => setBackgroundCategory(cat)}
- className={`px-2.5 py-1 text-[10px] rounded-md transition-all ${
- backgroundCategory === cat
- ? "bg-primary text-white"
- : "bg-background-tertiary text-text-muted hover:text-text-secondary"
+ key={mode}
+ onClick={() => setMediaViewMode(mode)}
+ title={title}
+ className={`p-1.5 rounded transition-colors ${
+ mediaViewMode === mode
+ ? "bg-background-elevated text-text-primary"
+ : "text-text-muted hover:text-text-secondary"
}`}
>
- {cat.charAt(0).toUpperCase() + cat.slice(1)}
+ <ViewIcon size={13} />
</button>
- ),
- )}
+ ))}
+ </div>
</div>
- <div className="grid grid-cols-4 gap-2">
- {filteredBackgrounds.map((preset) => (
+
+ {missingAssetsCount > 0 && (
+ <div className="px-4 pb-3 space-y-2">
<button
- key={preset.id}
- onClick={() => handleImportBackground(preset)}
- disabled={generatingBackground !== null}
- className="aspect-square rounded-lg border border-border hover:border-primary/50 transition-all overflow-hidden relative group disabled:opacity-50"
- title={preset.name}
- style={{ background: preset.thumbnail }}
+ onClick={() => setShowOnlyMissing(!showOnlyMissing)}
+ className={`w-full px-3 py-2 rounded-lg border text-xs font-medium transition-all flex items-center justify-between ${
+ showOnlyMissing
+ ? "bg-yellow-500/10 border-yellow-500 text-yellow-500"
+ : "bg-background-tertiary border-border text-text-secondary hover:border-yellow-500/50"
+ }`}
>
- {generatingBackground === preset.id && (
- <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
- <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
- </div>
- )}
- <div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-all flex items-center justify-center opacity-0 group-hover:opacity-100">
- <Plus size={16} className="text-white" />
+ <div className="flex items-center gap-2">
+ <AlertTriangle size={14} />
+ <span>Show Only Missing Assets</span>
+ </div>
+ <div className="px-2 py-0.5 rounded-full bg-yellow-500 text-black text-[10px] font-bold">
+ {missingAssetsCount}
</div>
- <span className="absolute bottom-0 left-0 right-0 text-[8px] text-white bg-black/60 py-0.5 px-1 truncate opacity-0 group-hover:opacity-100 transition-opacity">
- {preset.name}
- </span>
</button>
- ))}
- </div>
- </div>
-
- {/* Shapes Section */}
- <div className="mb-6">
- <h4 className="text-xs font-medium text-text-secondary mb-3">
- Shapes
- </h4>
- <div className="grid grid-cols-4 gap-2">
- {[
- {
- type: "rectangle" as ShapeType,
- icon: Square,
- label: "Rectangle",
- },
- { type: "circle" as ShapeType, icon: Circle, label: "Circle" },
- {
- type: "triangle" as ShapeType,
- icon: Triangle,
- label: "Triangle",
- },
- { type: "star" as ShapeType, icon: Star, label: "Star" },
- {
- type: "arrow" as ShapeType,
- icon: ArrowRight,
- label: "Arrow",
- },
- {
- type: "polygon" as ShapeType,
- icon: Hexagon,
- label: "Polygon",
- },
- ].map((shape) => (
<button
- key={shape.type}
- onClick={async () => {
- const state = useProjectStore.getState();
- const { createShapeClip, addTrack } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("graphics", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newGraphicsTrack = tracksAfter.find(
- (t) =>
- t.type === "graphics" &&
- !tracksBefore.some((bt) => bt.id === t.id),
- );
- if (newGraphicsTrack) {
- createShapeClip(newGraphicsTrack.id, 0, shape.type);
- }
- }}
- className="aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex flex-col items-center justify-center gap-1 group"
- title={shape.label}
+ onClick={handleRelinkFromFolder}
+ className="w-full px-3 py-2 rounded-lg border border-yellow-500/40 bg-yellow-500/5 text-yellow-500 text-xs font-medium transition-all hover:bg-yellow-500/15 flex items-center gap-2"
>
- <shape.icon
- size={20}
- className="text-text-secondary group-hover:text-primary transition-colors"
- />
- <span className="text-[9px] text-text-muted group-hover:text-text-secondary">
- {shape.label}
- </span>
+ <RefreshCw size={14} />
+ <span>Relink from Folder…</span>
</button>
- ))}
- </div>
- </div>
+ </div>
+ )}
- {/* SVG Import Section */}
- <div className="mb-6">
- <h4 className="text-xs font-medium text-text-secondary mb-3">
- SVG Import
- </h4>
- <button
- onClick={() => {
- const input = document.createElement("input");
- input.type = "file";
- input.accept = ".svg";
- input.onchange = async (e) => {
- const file = (e.target as HTMLInputElement).files?.[0];
- if (file) {
- const content = await file.text();
- const state = useProjectStore.getState();
- const { importSVG, addTrack } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("graphics", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newGraphicsTrack = tracksAfter.find(
- (t) =>
- t.type === "graphics" &&
- !tracksBefore.some((bt) => bt.id === t.id),
- );
- if (newGraphicsTrack) {
- importSVG(content, newGraphicsTrack.id, 0);
- }
- }
- };
- input.click();
- }}
- className="w-full py-3 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex items-center justify-center gap-2 group"
+ <ScrollArea
+ className={`min-h-0 flex-1 ${isDragOver ? "bg-primary/5" : ""}`}
+ onDrop={handleDrop}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
>
- <FileCode
- size={16}
- className="text-text-secondary group-hover:text-primary transition-colors"
- />
- <span className="text-xs text-text-secondary group-hover:text-text-primary">
- Import SVG File
- </span>
- </button>
+ <div className="px-4 pb-4 relative">
+ {filteredItems.length === 0 ? (
+ <EmptyState onImport={triggerFileInput} />
+ ) : (
+ <div className={
+ mediaViewMode === "list"
+ ? "flex flex-col gap-1.5"
+ : mediaViewMode === "small"
+ ? "grid grid-cols-3 gap-2"
+ : "grid grid-cols-2 gap-3"
+ }>
+ {filteredItems.map((item) => (
+ <MediaThumbnail
+ key={item.id}
+ item={item}
+ isSelected={isSelected(item.id)}
+ viewMode={mediaViewMode}
+ onSelect={() => handleSelectItem(item.id)}
+ onDelete={() => handleDeleteItem(item.id)}
+ onReplace={() => handleReplaceAsset(item.id)}
+ onDragStart={(e) => handleItemDragStart(e, item)}
+ onAddToTimeline={() => handleAddToTimeline(item)}
+ onKieAI={item.type === "image" && !item.isPending && !item.kieaiError ? () => handleOpenKieAI(item) : undefined}
+ onRetryKieAI={item.kieaiError && item.kieaiTaskId ? () => handleRetryKieAI(item) : undefined}
+ />
+ ))}
+ {mediaViewMode === "list" ? (
+ <button
+ onClick={triggerFileInput}
+ className="flex items-center gap-3 px-2 py-1.5 rounded-lg border-2 border-dashed border-border hover:border-text-secondary cursor-pointer transition-all group"
+ >
+ <div className="w-12 h-8 rounded bg-background-tertiary flex items-center justify-center flex-shrink-0">
+ <Upload size={14} className="text-text-muted group-hover:text-text-secondary transition-colors" />
+ </div>
+ <span className="text-[11px] text-text-muted group-hover:text-text-secondary transition-colors font-medium">Add media</span>
+ </button>
+ ) : (
+ <div className="flex flex-col">
+ <button
+ onClick={triggerFileInput}
+ className="aspect-video bg-background-tertiary rounded-lg border-2 border-dashed border-border hover:border-text-secondary relative flex items-center justify-center cursor-pointer transition-all overflow-hidden shadow-sm group"
+ >
+ <div className="flex flex-col items-center gap-1.5">
+ <Upload size={mediaViewMode === "small" ? 16 : 20} className="text-text-muted group-hover:text-text-secondary transition-colors" />
+ <span className="text-[10px] text-text-muted group-hover:text-text-secondary transition-colors">Add media</span>
+ </div>
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+
+ {isDragOver && (
+ <div className="absolute inset-4 border-2 border-dashed border-primary rounded-xl flex items-center justify-center bg-primary/5 pointer-events-none z-50 backdrop-blur-sm">
+ <div className="text-primary text-sm font-bold bg-background-secondary px-4 py-2 rounded-full shadow-lg">
+ Drop files to import
+ </div>
+ </div>
+ )}
+ </div>
+ </ScrollArea>
</div>
+ );
+ case "graphics":
+ return (
+ <div className="min-h-0 flex-1 border-t border-border/70">
+ <ScrollArea className="min-h-0 flex-1">
+ <div className="px-4 py-4">
+ <div className="mb-6">
+ <div className="flex items-center justify-between mb-3">
+ <h4 className="text-xs font-medium text-text-secondary flex items-center gap-1.5">
+ <Palette size={12} />
+ Backgrounds
+ </h4>
+ </div>
+ <div className="flex gap-1.5 mb-3 flex-wrap">
+ {(["all", "solid", "gradient", "mesh", "pattern"] as const).map(
+ (cat) => (
+ <button
+ key={cat}
+ onClick={() => setBackgroundCategory(cat)}
+ className={`px-2.5 py-1 text-[10px] rounded-md transition-all ${
+ backgroundCategory === cat
+ ? "bg-primary text-white"
+ : "bg-background-tertiary text-text-muted hover:text-text-secondary"
+ }`}
+ >
+ {cat.charAt(0).toUpperCase() + cat.slice(1)}
+ </button>
+ ),
+ )}
+ </div>
+ <div className="grid grid-cols-4 gap-2">
+ {filteredBackgrounds.map((preset) => (
+ <button
+ key={preset.id}
+ onClick={() => handleImportBackground(preset)}
+ disabled={generatingBackground !== null}
+ className="aspect-square rounded-lg border border-border hover:border-primary/50 transition-all overflow-hidden relative group disabled:opacity-50"
+ title={preset.name}
+ style={{ background: preset.thumbnail }}
+ >
+ {generatingBackground === preset.id && (
+ <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
+ <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
+ </div>
+ )}
+ <div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-all flex items-center justify-center opacity-0 group-hover:opacity-100">
+ <Plus size={16} className="text-white" />
+ </div>
+ <span className="absolute bottom-0 left-0 right-0 text-[8px] text-white bg-black/60 py-0.5 px-1 truncate opacity-0 group-hover:opacity-100 transition-opacity">
+ {preset.name}
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="mb-6">
+ <h4 className="text-xs font-medium text-text-secondary mb-3">
+ Shapes
+ </h4>
+ <div className="grid grid-cols-4 gap-2">
+ {[
+ {
+ type: "rectangle" as ShapeType,
+ icon: Square,
+ label: "Rectangle",
+ },
+ { type: "circle" as ShapeType, icon: Circle, label: "Circle" },
+ {
+ type: "triangle" as ShapeType,
+ icon: Triangle,
+ label: "Triangle",
+ },
+ { type: "star" as ShapeType, icon: Star, label: "Star" },
+ {
+ type: "arrow" as ShapeType,
+ icon: ArrowRight,
+ label: "Arrow",
+ },
+ {
+ type: "polygon" as ShapeType,
+ icon: Hexagon,
+ label: "Polygon",
+ },
+ ].map((shape) => (
+ <button
+ key={shape.type}
+ onClick={async () => {
+ const state = useProjectStore.getState();
+ const { createShapeClip, addTrack } = state;
+ const tracksBefore = state.project.timeline.tracks;
+ await addTrack("graphics", 0);
+ const tracksAfter =
+ useProjectStore.getState().project.timeline.tracks;
+ const newGraphicsTrack = tracksAfter.find(
+ (t) =>
+ t.type === "graphics" &&
+ !tracksBefore.some((bt) => bt.id === t.id),
+ );
+ if (newGraphicsTrack) {
+ createShapeClip(newGraphicsTrack.id, 0, shape.type);
+ }
+ }}
+ className="aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex flex-col items-center justify-center gap-1 group"
+ title={shape.label}
+ >
+ <shape.icon
+ size={20}
+ className="text-text-secondary group-hover:text-primary transition-colors"
+ />
+ <span className="text-[9px] text-text-muted group-hover:text-text-secondary">
+ {shape.label}
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
- {/* Stickers Section (placeholder) */}
- <div className="mb-6">
- <h4 className="text-xs font-medium text-text-secondary mb-3">
- Stickers & Emojis
- </h4>
- <div className="grid grid-cols-4 gap-2">
- {["😀", "🎉", "❤️", "⭐", "🔥", "👍", "🎬", "🎵"].map(
- (emoji, i) => (
+ <div className="mb-6">
+ <h4 className="text-xs font-medium text-text-secondary mb-3">
+ SVG Import
+ </h4>
<button
- key={i}
- onClick={async () => {
- const state = useProjectStore.getState();
- const { createStickerClip, addTrack } = state;
- const { stickerLibrary } = await import("@openreel/core");
-
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("graphics", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newGraphicsTrack = tracksAfter.find(
- (t) =>
- t.type === "graphics" &&
- !tracksBefore.some((bt) => bt.id === t.id),
- );
-
- if (newGraphicsTrack) {
- const emojiItem = {
- id: `emoji-${i}`,
- emoji,
- name: emoji,
- category: "emojis",
- };
- const clip = stickerLibrary.createEmojiClip(
- emojiItem,
- newGraphicsTrack.id,
- 0,
- 5,
- );
- createStickerClip(clip);
- }
+ onClick={() => {
+ const input = document.createElement("input");
+ input.type = "file";
+ input.accept = ".svg";
+ input.onchange = async (e) => {
+ const file = (e.target as HTMLInputElement).files?.[0];
+ if (file) {
+ const content = await file.text();
+ const state = useProjectStore.getState();
+ const { importSVG, addTrack } = state;
+ const tracksBefore = state.project.timeline.tracks;
+ await addTrack("graphics", 0);
+ const tracksAfter =
+ useProjectStore.getState().project.timeline.tracks;
+ const newGraphicsTrack = tracksAfter.find(
+ (t) =>
+ t.type === "graphics" &&
+ !tracksBefore.some((bt) => bt.id === t.id),
+ );
+ if (newGraphicsTrack) {
+ importSVG(content, newGraphicsTrack.id, 0);
+ }
+ }
+ };
+ input.click();
}}
- className="aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex items-center justify-center text-xl cursor-pointer"
+ className="w-full py-3 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex items-center justify-center gap-2 group"
>
- {emoji}
+ <FileCode
+ size={16}
+ className="text-text-secondary group-hover:text-primary transition-colors"
+ />
+ <span className="text-xs text-text-secondary group-hover:text-text-primary">
+ Import SVG File
+ </span>
</button>
- ),
- )}
- </div>
- </div>
- </div>
- </ScrollArea>
- )}
+ </div>
- {/* Text Tab Content */}
- {activeTab === "text" && (
- <ScrollArea className="flex-1">
- <div className="px-5 pb-5 space-y-3">
- <button
- onClick={async () => {
- const state = useProjectStore.getState();
- const { createTextClip, addTrack } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("text", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newTextTrack = tracksAfter.find(
- (t) =>
- t.type === "text" &&
- !tracksBefore.some((bt) => bt.id === t.id),
- );
- if (newTextTrack) {
- createTextClip(newTextTrack.id, 0, "New Title");
- }
- }}
- className="w-full py-4 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-center"
- >
- <span className="text-lg font-bold text-text-primary">
- Add Title
- </span>
- <p className="text-xs text-text-muted mt-1">
- Click to add text to timeline
- </p>
- </button>
- <div className="grid grid-cols-2 gap-2">
- {[
- {
- name: "Heading",
- text: "Heading",
- style: {
- fontSize: 72,
- fontWeight: 700 as const,
- textAlign: "center" as const,
- verticalAlign: "middle" as const,
- },
- },
- {
- name: "Subtitle",
- text: "Subtitle text",
- style: {
- fontSize: 36,
- fontWeight: 400 as const,
- textAlign: "center" as const,
- verticalAlign: "middle" as const,
- },
- },
- {
- name: "Lower Third",
- text: "Name Here",
- style: {
- fontSize: 32,
- fontWeight: 600 as const,
- textAlign: "left" as const,
- verticalAlign: "bottom" as const,
- backgroundColor: "rgba(0, 0, 0, 0.7)",
- },
- },
- {
- name: "Caption",
- text: "Caption text here",
- style: {
- fontSize: 24,
- fontWeight: 400 as const,
- textAlign: "center" as const,
- verticalAlign: "bottom" as const,
- shadowColor: "rgba(0, 0, 0, 0.8)",
- shadowBlur: 4,
- shadowOffsetX: 1,
- shadowOffsetY: 1,
- },
- },
- ].map((preset) => (
+ <div className="mb-6">
+ <h4 className="text-xs font-medium text-text-secondary mb-3">
+ Stickers & Emojis
+ </h4>
+ <div className="grid grid-cols-4 gap-2">
+ {["😀", "🎉", "❤️", "⭐", "🔥", "👍", "🎬", "🎵"].map(
+ (emoji, i) => (
+ <button
+ key={i}
+ onClick={async () => {
+ const state = useProjectStore.getState();
+ const { createStickerClip, addTrack } = state;
+ const { stickerLibrary } = await import("@openreel/core");
+
+ const tracksBefore = state.project.timeline.tracks;
+ await addTrack("graphics", 0);
+ const tracksAfter =
+ useProjectStore.getState().project.timeline.tracks;
+ const newGraphicsTrack = tracksAfter.find(
+ (t) =>
+ t.type === "graphics" &&
+ !tracksBefore.some((bt) => bt.id === t.id),
+ );
+
+ if (newGraphicsTrack) {
+ const emojiItem = {
+ id: `emoji-${i}`,
+ emoji,
+ name: emoji,
+ category: "emojis",
+ };
+ const clip = stickerLibrary.createEmojiClip(
+ emojiItem,
+ newGraphicsTrack.id,
+ 0,
+ 5,
+ );
+ createStickerClip(clip);
+ }
+ }}
+ className="aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex items-center justify-center text-xl cursor-pointer"
+ >
+ {emoji}
+ </button>
+ ),
+ )}
+ </div>
+ </div>
+ </div>
+ </ScrollArea>
+ </div>
+ );
+ case "text":
+ return (
+ <div className="min-h-0 flex-1 border-t border-border/70">
+ <ScrollArea className="min-h-0 flex-1">
+ <div className="px-4 py-4 space-y-3">
<button
- key={preset.name}
onClick={async () => {
const state = useProjectStore.getState();
const { createTextClip, addTrack } = state;
@@ -1441,34 +1297,193 @@ export const AssetsPanel: React.FC = () => {
!tracksBefore.some((bt) => bt.id === t.id),
);
if (newTextTrack) {
- createTextClip(
- newTextTrack.id,
- 0,
- preset.text,
- 5,
- preset.style,
- );
+ createTextClip(newTextTrack.id, 0, "New Title");
}
}}
- className="py-3 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-xs text-text-secondary hover:text-text-primary"
+ className="w-full py-4 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-center"
>
- {preset.name}
+ <span className="text-lg font-bold text-text-primary">
+ Add Title
+ </span>
+ <p className="text-xs text-text-muted mt-1">
+ Click to add text to timeline
+ </p>
</button>
- ))}
- </div>
+ <div className="grid grid-cols-2 gap-2">
+ {[
+ {
+ name: "Heading",
+ text: "Heading",
+ style: {
+ fontSize: 72,
+ fontWeight: 700 as const,
+ textAlign: "center" as const,
+ verticalAlign: "middle" as const,
+ },
+ },
+ {
+ name: "Subtitle",
+ text: "Subtitle text",
+ style: {
+ fontSize: 36,
+ fontWeight: 400 as const,
+ textAlign: "center" as const,
+ verticalAlign: "middle" as const,
+ },
+ },
+ {
+ name: "Lower Third",
+ text: "Name Here",
+ style: {
+ fontSize: 32,
+ fontWeight: 600 as const,
+ textAlign: "left" as const,
+ verticalAlign: "bottom" as const,
+ backgroundColor: "rgba(0, 0, 0, 0.7)",
+ },
+ },
+ {
+ name: "Caption",
+ text: "Caption text here",
+ style: {
+ fontSize: 24,
+ fontWeight: 400 as const,
+ textAlign: "center" as const,
+ verticalAlign: "bottom" as const,
+ shadowColor: "rgba(0, 0, 0, 0.8)",
+ shadowBlur: 4,
+ shadowOffsetX: 1,
+ shadowOffsetY: 1,
+ },
+ },
+ ].map((preset) => (
+ <button
+ key={preset.name}
+ onClick={async () => {
+ const state = useProjectStore.getState();
+ const { createTextClip, addTrack } = state;
+ const tracksBefore = state.project.timeline.tracks;
+ await addTrack("text", 0);
+ const tracksAfter =
+ useProjectStore.getState().project.timeline.tracks;
+ const newTextTrack = tracksAfter.find(
+ (t) =>
+ t.type === "text" &&
+ !tracksBefore.some((bt) => bt.id === t.id),
+ );
+ if (newTextTrack) {
+ createTextClip(
+ newTextTrack.id,
+ 0,
+ preset.text,
+ 5,
+ preset.style,
+ );
+ }
+ }}
+ className="py-3 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-xs text-text-secondary hover:text-text-primary"
+ >
+ {preset.name}
+ </button>
+ ))}
+ </div>
+ </div>
+ </ScrollArea>
+ </div>
+ );
+ case "ai":
+ return (
+ <div className="min-h-0 flex-1 border-t border-border/70">
+ <AIGenTab />
</div>
- </ScrollArea>
+ );
+ case "recipes":
+ return (
+ <div className="min-h-0 flex-1 border-t border-border/70">
+ <ScrollArea className="min-h-0 flex-1">
+ <RecipesTab />
+ </ScrollArea>
+ </div>
+ );
+ case "templates":
+ return (
+ <div className="min-h-0 flex-1 border-t border-border/70">
+ <ScrollArea className="min-h-0 flex-1">
+ <TemplatesTab />
+ </ScrollArea>
+ </div>
+ );
+ default:
+ return null;
+ }
+ };
+
+ return (
+ <div
+ data-tour="assets"
+ className="w-full min-w-0 bg-background-secondary border-r border-border flex flex-col h-full relative"
+ >
+ {/* Loading overlay */}
+ {isImporting && (
+ <LoadingIndicator message={importProgress || "Importing media..."} />
)}
+ {/* Panel Header */}
+ <div className="px-5 py-4 flex items-center justify-between">
+ <span className="font-bold text-lg text-text-primary tracking-tight">
+ Assets
+ </span>
+ <div className="flex gap-1">
+ <IconButton
+ icon={Plus}
+ onClick={triggerFileInput}
+ title="Import media"
+ />
+ <IconButton icon={Maximize2} title="Maximize panel" />
+ <IconButton icon={X} title="Close panel" />
+ </div>
+ </div>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept="video/*,audio/*,image/*"
+ onChange={(e) => handleFileImport(e.target.files)}
+ className="hidden"
+ />
- {/* AI Tab Content */}
- {activeTab === "ai" && <AIGenTab />}
+ <Tabs
+ value={activeTab}
+ onValueChange={(value) => setActiveTab(value as AssetsTab)}
+ className="flex-1 min-h-0 flex flex-col overflow-hidden"
+ >
+ <div className="px-4 pb-3">
+ <div className="overflow-x-auto">
+ <TabsList className="inline-flex min-w-max h-auto gap-1 rounded-xl border border-border bg-background-tertiary/80 p-1 shadow-sm">
+ {ASSETS_TABS.map((tab) => (
+ <TabsTrigger
+ key={tab.value}
+ value={tab.value}
+ title={tab.description}
+ className={`shrink-0 rounded-lg border border-transparent px-3 py-2 text-[11px] font-medium transition-colors data-[state=active]:border-border data-[state=active]:bg-background-secondary data-[state=active]:shadow-sm ${
+ tab.value === "ai"
+ ? "text-primary hover:text-primary"
+ : "text-text-secondary hover:text-text-primary"
+ }`}
+ >
+ {tab.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </div>
+ </div>
- {/* Templates Tab Content */}
- {activeTab === "templates" && (
- <ScrollArea className="flex-1">
- <TemplatesTab />
- </ScrollArea>
- )}
+ <div className="flex-1 overflow-hidden px-4 pb-4">
+ <div className="flex h-full min-h-0 flex-col overflow-hidden rounded-xl border border-border bg-background-secondary/70 shadow-sm">
+ {renderSectionContent(activeTab)}
+ </div>
+ </div>
+ </Tabs>
{aspectRatioDialogData && (
<AspectRatioMatchDialog
diff --git a/apps/web/src/components/editor/EditorInterface.tsx b/apps/web/src/components/editor/EditorInterface.tsx
index 7d3bdfbb..dd7a2bc3 100644
--- a/apps/web/src/components/editor/EditorInterface.tsx
+++ b/apps/web/src/components/editor/EditorInterface.tsx
@@ -35,6 +35,25 @@ import {
disposeTransitionBridge,
} from "../../bridges/transition-bridge";
+const DEFAULT_TIMELINE_HEIGHT = 320;
+const MIN_TIMELINE_HEIGHT = 220;
+const MIN_TOP_WORKSPACE_HEIGHT = 280;
+const DEFAULT_ASSETS_WIDTH = 320;
+const MIN_ASSETS_WIDTH = 240;
+const MAX_ASSETS_WIDTH = 520;
+const DEFAULT_INSPECTOR_WIDTH = 320;
+const MIN_INSPECTOR_WIDTH = 260;
+const MAX_INSPECTOR_WIDTH = 520;
+const MIN_PREVIEW_WIDTH = 420;
+const SIDE_RESIZE_HANDLE_WIDTH = 6;
+const HORIZONTAL_RESIZE_HANDLE_HEIGHT = 4;
+
+type ResizeTarget = "timeline" | "assets" | "inspector";
+
+const clamp = (value: number, min: number, max: number): number => {
+ return Math.min(Math.max(value, min), max);
+};
+
/**
* Auto-save initialization hook
*/
@@ -249,27 +268,182 @@ export const EditorInterface: React.FC = () => {
[]
);
- const [timelineHeight, setTimelineHeight] = useState(320);
- const isDraggingRef = useRef(false);
+ const editorBodyRef = useRef<HTMLDivElement>(null);
+ const workspaceRef = useRef<HTMLDivElement>(null);
+ const audioMixerRef = useRef<HTMLDivElement>(null);
+ const keyframePanelRef = useRef<HTMLDivElement>(null);
+ const resizeStateRef = useRef<ResizeTarget | null>(null);
+
+ const [timelineHeight, setTimelineHeight] = useState(DEFAULT_TIMELINE_HEIGHT);
+ const [assetsWidth, setAssetsWidth] = useState(DEFAULT_ASSETS_WIDTH);
+ const [inspectorWidth, setInspectorWidth] = useState(DEFAULT_INSPECTOR_WIDTH);
+
+ const timelineHeightRef = useRef(DEFAULT_TIMELINE_HEIGHT);
+ const assetsWidthRef = useRef(DEFAULT_ASSETS_WIDTH);
+ const inspectorWidthRef = useRef(DEFAULT_INSPECTOR_WIDTH);
+
+ useEffect(() => {
+ timelineHeightRef.current = timelineHeight;
+ }, [timelineHeight]);
+
+ useEffect(() => {
+ assetsWidthRef.current = assetsWidth;
+ }, [assetsWidth]);
+
+ useEffect(() => {
+ inspectorWidthRef.current = inspectorWidth;
+ }, [inspectorWidth]);
+
+ const beginResize = useCallback(
+ (target: ResizeTarget) => (e: React.MouseEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ resizeStateRef.current = target;
+ document.body.style.cursor =
+ target === "timeline" ? "row-resize" : "col-resize";
+ document.body.style.userSelect = "none";
+ },
+ [],
+ );
+
+ const clampLayout = useCallback(() => {
+ const workspaceRect = workspaceRef.current?.getBoundingClientRect();
+ if (workspaceRect) {
+ const keyframeWidth =
+ keyframePanelRef.current?.getBoundingClientRect().width ?? 0;
+ const maxResizableWidth =
+ workspaceRect.width -
+ keyframeWidth -
+ MIN_PREVIEW_WIDTH -
+ SIDE_RESIZE_HANDLE_WIDTH * 2;
+
+ const nextAssetsWidth = clamp(
+ assetsWidthRef.current,
+ MIN_ASSETS_WIDTH,
+ Math.max(
+ MIN_ASSETS_WIDTH,
+ Math.min(
+ MAX_ASSETS_WIDTH,
+ maxResizableWidth - inspectorWidthRef.current,
+ ),
+ ),
+ );
- const handleMouseDown = useCallback((e: React.MouseEvent) => {
- e.preventDefault();
- isDraggingRef.current = true;
- document.body.style.cursor = "row-resize";
- document.body.style.userSelect = "none";
+ const nextInspectorWidth = clamp(
+ inspectorWidthRef.current,
+ MIN_INSPECTOR_WIDTH,
+ Math.max(
+ MIN_INSPECTOR_WIDTH,
+ Math.min(
+ MAX_INSPECTOR_WIDTH,
+ maxResizableWidth - nextAssetsWidth,
+ ),
+ ),
+ );
+
+ if (nextAssetsWidth !== assetsWidthRef.current) {
+ setAssetsWidth(nextAssetsWidth);
+ }
+
+ if (nextInspectorWidth !== inspectorWidthRef.current) {
+ setInspectorWidth(nextInspectorWidth);
+ }
+ }
+
+ const bodyRect = editorBodyRef.current?.getBoundingClientRect();
+ if (bodyRect) {
+ const audioMixerHeight =
+ audioMixerRef.current?.getBoundingClientRect().height ?? 0;
+ const maxTimelineHeight = Math.max(
+ MIN_TIMELINE_HEIGHT,
+ bodyRect.height -
+ audioMixerHeight -
+ MIN_TOP_WORKSPACE_HEIGHT -
+ HORIZONTAL_RESIZE_HANDLE_HEIGHT,
+ );
+ const nextTimelineHeight = clamp(
+ timelineHeightRef.current,
+ MIN_TIMELINE_HEIGHT,
+ maxTimelineHeight,
+ );
+
+ if (nextTimelineHeight !== timelineHeightRef.current) {
+ setTimelineHeight(nextTimelineHeight);
+ }
+ }
}, []);
useEffect(() => {
const handleMouseMove = (e: MouseEvent) => {
- if (!isDraggingRef.current) return;
+ const resizeTarget = resizeStateRef.current;
+ if (!resizeTarget) return;
+
+ if (resizeTarget === "timeline") {
+ const bodyRect = editorBodyRef.current?.getBoundingClientRect();
+ if (!bodyRect) return;
+
+ const audioMixerHeight =
+ audioMixerRef.current?.getBoundingClientRect().height ?? 0;
+ const maxTimelineHeight = Math.max(
+ MIN_TIMELINE_HEIGHT,
+ bodyRect.height -
+ audioMixerHeight -
+ MIN_TOP_WORKSPACE_HEIGHT -
+ HORIZONTAL_RESIZE_HANDLE_HEIGHT,
+ );
+ const desiredTimelineHeight =
+ bodyRect.bottom - e.clientY - audioMixerHeight;
+
+ setTimelineHeight(
+ clamp(
+ desiredTimelineHeight,
+ MIN_TIMELINE_HEIGHT,
+ maxTimelineHeight,
+ ),
+ );
+ return;
+ }
- const newHeight = window.innerHeight - e.clientY;
- const maxHeight = window.innerHeight * 0.6;
- setTimelineHeight(Math.max(200, Math.min(newHeight, maxHeight)));
+ const workspaceRect = workspaceRef.current?.getBoundingClientRect();
+ if (!workspaceRect) return;
+
+ const keyframeWidth =
+ keyframePanelRef.current?.getBoundingClientRect().width ?? 0;
+ const maxResizableWidth =
+ workspaceRect.width -
+ keyframeWidth -
+ MIN_PREVIEW_WIDTH -
+ SIDE_RESIZE_HANDLE_WIDTH * 2;
+
+ if (resizeTarget === "assets") {
+ const maxAssetsWidth = Math.max(
+ MIN_ASSETS_WIDTH,
+ Math.min(
+ MAX_ASSETS_WIDTH,
+ maxResizableWidth - inspectorWidthRef.current,
+ ),
+ );
+ const desiredAssetsWidth = e.clientX - workspaceRect.left;
+ setAssetsWidth(
+ clamp(desiredAssetsWidth, MIN_ASSETS_WIDTH, maxAssetsWidth),
+ );
+ return;
+ }
+
+ const maxInspectorWidth = Math.max(
+ MIN_INSPECTOR_WIDTH,
+ Math.min(
+ MAX_INSPECTOR_WIDTH,
+ maxResizableWidth - assetsWidthRef.current,
+ ),
+ );
+ const desiredInspectorWidth = workspaceRect.right - e.clientX;
+ setInspectorWidth(
+ clamp(desiredInspectorWidth, MIN_INSPECTOR_WIDTH, maxInspectorWidth),
+ );
};
const handleMouseUp = () => {
- isDraggingRef.current = false;
+ resizeStateRef.current = null;
document.body.style.cursor = "";
document.body.style.userSelect = "";
};
@@ -283,6 +457,20 @@ export const EditorInterface: React.FC = () => {
};
}, []);
+ useEffect(() => {
+ clampLayout();
+
+ const handleResize = () => {
+ clampLayout();
+ };
+
+ window.addEventListener("resize", handleResize);
+
+ return () => {
+ window.removeEventListener("resize", handleResize);
+ };
+ }, [clampLayout, keyframeEditorOpen, panels.audioMixer?.visible]);
+
if (initializing || !initialized) {
return (
<div className="w-full h-full bg-background flex items-center justify-center">
@@ -303,63 +491,97 @@ export const EditorInterface: React.FC = () => {
{/* Main App Toolbar */}
<Toolbar />
- {/* Workspace Area */}
- <div className="flex-1 flex overflow-hidden">
- <PanelErrorBoundary name="Assets Panel">
- <AssetsPanel />
- </PanelErrorBoundary>
-
- <PanelErrorBoundary name="Preview">
- <Preview />
- </PanelErrorBoundary>
-
- <PanelErrorBoundary name="Inspector">
- <InspectorPanel />
- </PanelErrorBoundary>
-
- {keyframeEditorOpen && (
- <PanelErrorBoundary name="Keyframe Editor">
- <KeyframeEditorPanel
- clip={selectedClip}
- onClose={() => setKeyframeEditorOpen(false)}
- onUpdateKeyframe={handleUpdateKeyframe}
- onDeleteKeyframe={handleDeleteKeyframe}
- onCopyKeyframes={handleCopyKeyframes}
- onPasteKeyframes={handlePasteKeyframes}
- selectedKeyframeIds={selectedKeyframeIds}
- onSelectKeyframe={handleSelectKeyframe}
- copiedKeyframes={copiedKeyframes}
- />
- </PanelErrorBoundary>
- )}
- </div>
+ <div ref={editorBodyRef} className="min-h-0 flex-1 flex flex-col overflow-hidden">
+ <div ref={workspaceRef} className="min-h-0 flex-1 flex overflow-hidden">
+ <div
+ className="h-full shrink-0 min-w-0 overflow-hidden"
+ style={{ width: assetsWidth }}
+ >
+ <PanelErrorBoundary name="Assets Panel">
+ <AssetsPanel />
+ </PanelErrorBoundary>
+ </div>
+
+ <div
+ className="relative h-full shrink-0 cursor-col-resize bg-border/80 transition-colors hover:bg-primary/50"
+ style={{ width: SIDE_RESIZE_HANDLE_WIDTH }}
+ onMouseDown={beginResize("assets")}
+ >
+ <div className="absolute inset-y-0 -left-1 -right-1" />
+ </div>
+
+ <div className="min-h-0 min-w-0 flex-1 flex overflow-hidden">
+ <PanelErrorBoundary name="Preview">
+ <Preview />
+ </PanelErrorBoundary>
+ </div>
+
+ <div
+ className="relative h-full shrink-0 cursor-col-resize bg-border/80 transition-colors hover:bg-primary/50"
+ style={{ width: SIDE_RESIZE_HANDLE_WIDTH }}
+ onMouseDown={beginResize("inspector")}
+ >
+ <div className="absolute inset-y-0 -left-1 -right-1" />
+ </div>
+
+ <div
+ className="h-full shrink-0 min-w-0 overflow-hidden"
+ style={{ width: inspectorWidth }}
+ >
+ <PanelErrorBoundary name="Inspector">
+ <InspectorPanel />
+ </PanelErrorBoundary>
+ </div>
+
+ {keyframeEditorOpen && (
+ <div
+ ref={keyframePanelRef}
+ className="h-full shrink-0 min-w-0 overflow-hidden"
+ >
+ <PanelErrorBoundary name="Keyframe Editor">
+ <KeyframeEditorPanel
+ clip={selectedClip}
+ onClose={() => setKeyframeEditorOpen(false)}
+ onUpdateKeyframe={handleUpdateKeyframe}
+ onDeleteKeyframe={handleDeleteKeyframe}
+ onCopyKeyframes={handleCopyKeyframes}
+ onPasteKeyframes={handlePasteKeyframes}
+ selectedKeyframeIds={selectedKeyframeIds}
+ onSelectKeyframe={handleSelectKeyframe}
+ copiedKeyframes={copiedKeyframes}
+ />
+ </PanelErrorBoundary>
+ </div>
+ )}
+ </div>
- {/* Resizable Handle */}
- <div
- className="h-1 bg-border hover:bg-primary/50 cursor-row-resize transition-colors z-10 relative group"
- onMouseDown={handleMouseDown}
- >
- <div className="absolute inset-x-0 -top-1 -bottom-1 bg-transparent" />
- </div>
+ <div
+ className="shrink-0 bg-border transition-colors hover:bg-primary/50 cursor-row-resize z-10 relative"
+ style={{ height: HORIZONTAL_RESIZE_HANDLE_HEIGHT }}
+ onMouseDown={beginResize("timeline")}
+ >
+ <div className="absolute inset-x-0 -top-1 -bottom-1 bg-transparent" />
+ </div>
+
+ {panels.audioMixer?.visible && (
+ <div ref={audioMixerRef} className="shrink-0">
+ <PanelErrorBoundary name="Audio Mixer">
+ <AudioMixer
+ visible
+ onClose={() => setPanelVisible("audioMixer", false)}
+ />
+ </PanelErrorBoundary>
+ </div>
+ )}
- {/* Audio Mixer (when open) */}
- {panels.audioMixer?.visible && (
- <PanelErrorBoundary name="Audio Mixer">
- <AudioMixer
- visible
- onClose={() => setPanelVisible("audioMixer", false)}
- />
- </PanelErrorBoundary>
- )}
-
- {/* BOTTOM PANEL: Timeline */}
- <div
- style={{ height: timelineHeight }}
- className="shrink-0 flex flex-col"
- >
- <PanelErrorBoundary name="Timeline">
- <Timeline />
- </PanelErrorBoundary>
+ <div
+ style={{ height: timelineHeight }}
+ className="min-h-0 shrink-0 flex flex-col overflow-hidden"
+ >
+ <PanelErrorBoundary name="Timeline">
+ <Timeline />
+ </PanelErrorBoundary>
+ </div>
</div>
<KeyboardShortcutsOverlay
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsx
index 9a80d078..96ca2587 100644
--- a/apps/web/src/components/editor/InspectorPanel.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tsx
@@ -1,9 +1,9 @@
-import React, { useCallback, useMemo, useState } from "react";
-import { ChevronDown, Zap, Captions, Loader2 } from "lucide-react";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { ChevronDown, Zap, Captions, Loader2, Sparkles, Trash2 } from "lucide-react";
import { useProjectStore } from "../../stores/project-store";
import { useUIStore } from "../../stores/ui-store";
import { useEngineStore } from "../../stores/engine-store";
-import type { Transform, FitMode, Clip } from "@openreel/core";
+import type { Transform, FitMode, Clip, EditingTemplatePrimitive } from "@openreel/core";
import {
ChromaKeyEngine,
initializeTranscriptionService,
@@ -52,12 +52,17 @@ import {
import { OPENREEL_TRANSCRIBE_URL } from "../../config/api-endpoints";
import { AutoEditPanel } from "./panels/AutoEditPanel";
import { HighlightExtractorPanel } from "./panels/HighlightExtractorPanel";
+import {
+ EditingTemplateControls,
+ mergeEditingTemplateControlValues,
+} from "./panels/EditingTemplateControls";
import {
getAudioBridgeEffects,
initializeAudioBridgeEffects,
DEFAULT_EQ_BANDS,
DEFAULT_NOISE_REDUCTION,
} from "../../bridges/audio-bridge-effects";
+import { toast } from "../../stores/notification-store";
import {
Input,
LabeledSlider,
@@ -184,8 +189,16 @@ const ParticleEffectsSectionWrapper: React.FC<{
export const InspectorPanel: React.FC = () => {
// Stores
- const { getClip, getMediaItem, addSubtitle, updateSubtitle, getSubtitle } =
- useProjectStore();
+ const {
+ getClip,
+ getMediaItem,
+ addSubtitle,
+ updateSubtitle,
+ getSubtitle,
+ getEditingTemplate,
+ updateEditingTemplateApplication,
+ removeEditingTemplateApplication,
+ } = useProjectStore();
const project = useProjectStore((state) => state.project);
const { getSelectedClipIds } = useUIStore();
const selectedItems = useUIStore((state) => state.selectedItems);
@@ -200,6 +213,15 @@ export const InspectorPanel: React.FC = () => {
const [targetLanguage, setTargetLanguage] = useState("none");
const [defaultAnimationStyle, setDefaultAnimationStyle] =
useState<CaptionAnimationStyle>("word-highlight");
+ const [expandedRecipeApplicationId, setExpandedRecipeApplicationId] =
+ useState<string | null>(null);
+ const [recipeControlValues, setRecipeControlValues] = useState<
+ Record<string, Record<string, EditingTemplatePrimitive>>
+ >({});
+
+ useEffect(() => {
+ setExpandedRecipeApplicationId(null);
+ }, [selectedClipIds.join("|")]);
// Check if a subtitle is selected
const selectedSubtitleId = useMemo(() => {
@@ -214,6 +236,11 @@ export const InspectorPanel: React.FC = () => {
return getSubtitle(selectedSubtitleId) || null;
}, [selectedSubtitleId, getSubtitle, project.timeline.subtitles]);
+ const selectedTimelineClip = useMemo(() => {
+ if (selectedClipIds.length !== 1) return null;
+ return getClip(selectedClipIds[0]) || null;
+ }, [getClip, project.modifiedAt, selectedClipIds]);
+
// Get selected clip (check regular clips, text clips, and shape clips)
const selectedClip = useMemo(() => {
if (selectedClipIds.length !== 1) return null;
@@ -601,6 +628,97 @@ export const InspectorPanel: React.FC = () => {
const showTextSection = clipType === "text";
const showShapeSection = clipType === "shape";
const showSVGSection = clipType === "svg";
+ const appliedEditingTemplates =
+ selectedTimelineClip?.metadata?.appliedTemplates || [];
+ const handleRecipeControlChange = useCallback(
+ (
+ applicationId: string,
+ controlId: string,
+ value: EditingTemplatePrimitive,
+ ) => {
+ setRecipeControlValues((current) => ({
+ ...current,
+ [applicationId]: {
+ ...(current[applicationId] || {}),
+ [controlId]: value,
+ },
+ }));
+ },
+ [],
+ );
+ const handleToggleRecipeControls = useCallback(
+ (applicationId: string, templateId: string, controlValues?: Record<string, unknown>) => {
+ const template = getEditingTemplate(templateId);
+ if (!template || !template.controls || template.controls.length === 0) {
+ return;
+ }
+
+ setExpandedRecipeApplicationId((current) =>
+ current === applicationId ? null : applicationId,
+ );
+ setRecipeControlValues((current) =>
+ current[applicationId]
+ ? current
+ : {
+ ...current,
+ [applicationId]: mergeEditingTemplateControlValues(
+ template,
+ controlValues,
+ ),
+ },
+ );
+ },
+ [getEditingTemplate],
+ );
+ const handleResetRecipeControls = useCallback(
+ (applicationId: string, templateId: string, controlValues?: Record<string, unknown>) => {
+ const template = getEditingTemplate(templateId);
+ if (!template) {
+ return;
+ }
+
+ setRecipeControlValues((current) => ({
+ ...current,
+ [applicationId]: mergeEditingTemplateControlValues(template, controlValues),
+ }));
+ },
+ [getEditingTemplate],
+ );
+ const handleUpdateRecipeControls = useCallback(
+ (applicationId: string, templateId: string, controlValues?: Record<string, unknown>) => {
+ if (!selectedTimelineClip) {
+ return;
+ }
+
+ const template = getEditingTemplate(templateId);
+ if (!template) {
+ toast.error("Recipe unavailable", "This recipe definition is no longer available.");
+ return;
+ }
+
+ const nextControlValues =
+ recipeControlValues[applicationId] ||
+ mergeEditingTemplateControlValues(template, controlValues);
+ const updated = updateEditingTemplateApplication(
+ selectedTimelineClip.id,
+ applicationId,
+ nextControlValues,
+ );
+
+ if (!updated) {
+ toast.error("Could not update recipe", "The recipe controls could not be saved for this clip.");
+ return;
+ }
+
+ toast.success("Recipe updated", `${template.name} was updated on this clip.`);
+ },
+ [
+ getEditingTemplate,
+ recipeControlValues,
+ selectedTimelineClip,
+ updateEditingTemplateApplication,
+ ],
+ );
const showVideoControls = clipType === "video" || clipType === "image";
const showTransformControls =
clipType === "video" ||
@@ -613,7 +731,7 @@ export const InspectorPanel: React.FC = () => {
return (
<div
data-tour="inspector"
- className="w-80 bg-background-secondary border-l border-border flex flex-col overflow-y-auto h-full custom-scrollbar"
+ className="w-full min-w-0 bg-background-secondary border-l border-border flex flex-col overflow-y-auto h-full custom-scrollbar"
>
<div className="p-5">
<h3 className="text-sm font-bold text-text-primary mb-5 tracking-tight">
@@ -1134,6 +1252,156 @@ export const InspectorPanel: React.FC = () => {
</Section>
)}
+ {showVideoControls && selectedTimelineClip && (
+ <Section
+ title="Applied Recipes"
+ sectionId="applied-recipes"
+ defaultOpen={appliedEditingTemplates.length > 0}
+ >
+ {appliedEditingTemplates.length === 0 ? (
+ <div className="rounded-xl border border-dashed border-border bg-background-tertiary/60 px-4 py-5 text-center">
+ <div className="mx-auto mb-2 flex h-9 w-9 items-center justify-center rounded-xl bg-primary/10 text-primary">
+ <Sparkles size={15} />
+ </div>
+ <p className="text-[11px] font-medium text-text-primary">
+ No recipes applied
+ </p>
+ <p className="mt-1 text-[10px] leading-5 text-text-muted">
+ Open the Recipes tab in Assets to stack looks, overlays,
+ and text treatments onto this clip.
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {appliedEditingTemplates.map((application) => {
+ const template = getEditingTemplate(application.templateId);
+ const canEdit = Boolean(template?.controls?.length);
+ const isExpanded =
+ expandedRecipeApplicationId === application.applicationId;
+ const currentControlValues = template
+ ? recipeControlValues[application.applicationId] ||
+ mergeEditingTemplateControlValues(
+ template,
+ application.controlValues,
+ )
+ : undefined;
+
+ return (
+ <div
+ key={application.applicationId}
+ className="rounded-xl border border-border bg-background-tertiary/70 px-3 py-3"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <Sparkles size={12} className="text-primary" />
+ <p className="truncate text-[11px] font-semibold text-text-primary">
+ {application.name}
+ </p>
+ </div>
+ <p className="mt-1 text-[10px] capitalize text-text-muted">
+ {application.category
+ ? application.category.replace(/-/g, " ")
+ : "Recipe"}
+ </p>
+ </div>
+ <div className="flex shrink-0 gap-2">
+ {canEdit && (
+ <button
+ onClick={() =>
+ handleToggleRecipeControls(
+ application.applicationId,
+ application.templateId,
+ application.controlValues,
+ )
+ }
+ className={`inline-flex h-8 items-center rounded-lg border px-2 text-[10px] font-medium transition-colors ${
+ isExpanded
+ ? "border-primary bg-primary/10 text-primary"
+ : "border-border bg-background-secondary text-text-secondary hover:border-primary/40 hover:text-text-primary"
+ }`}
+ >
+ Controls
+ </button>
+ )}
+ <button
+ onClick={() => {
+ const removed = removeEditingTemplateApplication(
+ selectedTimelineClip.id,
+ application.applicationId,
+ );
+ if (!removed) {
+ toast.error("Could not remove recipe", "The recipe could not be removed from this clip.");
+ return;
+ }
+ setRecipeControlValues((current) => {
+ const next = { ...current };
+ delete next[application.applicationId];
+ return next;
+ });
+ if (
+ expandedRecipeApplicationId === application.applicationId
+ ) {
+ setExpandedRecipeApplicationId(null);
+ }
+ }}
+ className="inline-flex h-8 items-center gap-1 rounded-lg border border-border bg-background-secondary px-2 text-[10px] font-medium text-text-secondary transition-colors hover:border-red-500/40 hover:text-red-400"
+ >
+ <Trash2 size={11} />
+ Remove
+ </button>
+ </div>
+ </div>
+
+ {isExpanded && template && currentControlValues && (
+ <div className="mt-3 space-y-3 rounded-xl border border-border/80 bg-background-secondary/80 p-3">
+ <EditingTemplateControls
+ template={template}
+ values={currentControlValues}
+ onChange={(controlId, value) =>
+ handleRecipeControlChange(
+ application.applicationId,
+ controlId,
+ value,
+ )
+ }
+ />
+ <div className="flex justify-end gap-2">
+ <button
+ onClick={() =>
+ handleResetRecipeControls(
+ application.applicationId,
+ application.templateId,
+ application.controlValues,
+ )
+ }
+ className="inline-flex h-8 items-center rounded-lg border border-border bg-background-tertiary px-3 text-[10px] font-medium text-text-secondary transition-colors hover:border-primary/30 hover:text-text-primary"
+ >
+ Reset
+ </button>
+ <button
+ onClick={() =>
+ handleUpdateRecipeControls(
+ application.applicationId,
+ application.templateId,
+ application.controlValues,
+ )
+ }
+ className="inline-flex h-8 items-center rounded-lg bg-primary px-3 text-[10px] font-semibold text-black transition-colors hover:bg-primary/85"
+ >
+ Update
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </Section>
+ )}
+
{showVideoEffects && (
<Section title="Video Effects" sectionId="video-effects">
<VideoEffectsSection clipId={clipId} />
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index f8071fc8..e2533759 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -362,6 +362,7 @@ interface ClipWithPlaceholder {
export const Preview: React.FC = () => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
+ const videoAreaRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement>(null);
const animationRef = useRef<number | null>(null);
const renderBridgeInitialized = useRef<boolean>(false);
@@ -428,6 +429,7 @@ export const Preview: React.FC = () => {
const [isMuted, setIsMuted] = useState(false);
const [isRenderBridgeReady, setIsRenderBridgeReady] = useState(false);
const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });
+ const [videoAreaSize, setVideoAreaSize] = useState({ width: 0, height: 0 });
const [rendererType, setRendererType] = useState<string>("none");
const [isMaximized, setIsMaximized] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
@@ -586,6 +588,21 @@ export const Preview: React.FC = () => {
return () => resizeObserver.disconnect();
}, []);
+ useEffect(() => {
+ const videoArea = videoAreaRef.current;
+ if (!videoArea) return;
+
+ const resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ const { width, height } = entry.contentRect;
+ setVideoAreaSize({ width, height });
+ }
+ });
+
+ resizeObserver.observe(videoArea);
+ return () => resizeObserver.disconnect();
+ }, []);
+
// Project store - subscribe to the entire project to ensure re-renders
// when any part of the project changes (including clips)
const project = useProjectStore((state) => state.project);
@@ -624,6 +641,29 @@ export const Preview: React.FC = () => {
const timelineTracks = project.timeline.tracks;
const settings = project.settings;
+ const previewFrameSize = useMemo(() => {
+ if (videoAreaSize.width <= 0 || videoAreaSize.height <= 0) {
+ return { width: 0, height: 0 };
+ }
+
+ const aspectRatio = settings.width / settings.height;
+ const availableWidth = Math.min(videoAreaSize.width, 800);
+ const availableHeight = Math.min(videoAreaSize.height, 450);
+
+ let width = availableWidth;
+ let height = width / aspectRatio;
+
+ if (height > availableHeight) {
+ height = availableHeight;
+ width = height * aspectRatio;
+ }
+
+ return {
+ width: width * zoomLevel,
+ height: height * zoomLevel,
+ };
+ }, [settings.height, settings.width, videoAreaSize, zoomLevel]);
+
// Keep a ref to timelineTracks for use in playback effect without causing re-runs
const timelineTracksRef = useRef(timelineTracks);
useEffect(() => {
@@ -5407,7 +5447,7 @@ export const Preview: React.FC = () => {
<div
ref={containerRef}
data-tour="preview"
- className="flex-1 bg-background flex flex-col relative group overflow-hidden"
+ className="flex-1 min-h-0 min-w-0 bg-background flex flex-col relative group overflow-hidden"
>
{/* Crop Mode View - Full Screen Overlay */}
{shouldShowCropMode && (
@@ -5426,7 +5466,8 @@ export const Preview: React.FC = () => {
{/* Video Area */}
<div
- className={`flex-1 relative flex items-center justify-center bg-background-secondary/30 transition-all duration-300 ${
+ ref={videoAreaRef}
+ className={`flex-1 min-h-0 min-w-0 relative flex items-center justify-center bg-background-secondary/30 transition-all duration-300 ${
isMaximized || isFullscreen ? "p-0" : "p-4"
} ${zoomLevel > 1 ? "overflow-auto" : ""}`}
onMouseMove={interactionMode !== "none" ? handleMouseMove : undefined}
@@ -5447,9 +5488,10 @@ export const Preview: React.FC = () => {
maxWidth: "none",
}
: {
- height: `${450 * zoomLevel}px`,
- width: `calc(${450 * zoomLevel}px * ${settings.width} / ${settings.height})`,
- maxWidth: `${800 * zoomLevel}px`,
+ width: `${previewFrameSize.width}px`,
+ height: `${previewFrameSize.height}px`,
+ maxWidth: "100%",
+ maxHeight: "100%",
}
}
onMouseMove={!isPlaying ? handleGraphicsMouseMove : undefined}
diff --git a/apps/web/src/components/editor/panels/EditingTemplateControls.tsx b/apps/web/src/components/editor/panels/EditingTemplateControls.tsx
new file mode 100644
index 00000000..0eb90425
--- /dev/null
+++ b/apps/web/src/components/editor/panels/EditingTemplateControls.tsx
@@ -0,0 +1,182 @@
+import React from "react";
+import type { EditingTemplate, EditingTemplatePrimitive } from "@openreel/core";
+
+export const getEditingTemplateDefaultControlValues = (
+ template: EditingTemplate,
+): Record<string, EditingTemplatePrimitive> =>
+ (template.controls || []).reduce<Record<string, EditingTemplatePrimitive>>(
+ (values, control) => {
+ values[control.id] = control.defaultValue;
+ return values;
+ },
+ {},
+ );
+
+export const mergeEditingTemplateControlValues = (
+ template: EditingTemplate,
+ overrides: Readonly<Record<string, unknown>> | undefined,
+): Record<string, EditingTemplatePrimitive> => {
+ const values = getEditingTemplateDefaultControlValues(template);
+
+ for (const control of template.controls || []) {
+ const override = overrides?.[control.id];
+ if (
+ typeof override === "string" ||
+ typeof override === "number" ||
+ typeof override === "boolean"
+ ) {
+ values[control.id] = override;
+ }
+ }
+
+ return values;
+};
+
+interface EditingTemplateControlsProps {
+ template: EditingTemplate;
+ values: Record<string, EditingTemplatePrimitive>;
+ onChange: (controlId: string, value: EditingTemplatePrimitive) => void;
+ disabled?: boolean;
+ className?: string;
+}
+
+export const EditingTemplateControls: React.FC<EditingTemplateControlsProps> = ({
+ template,
+ values,
+ onChange,
+ disabled = false,
+ className,
+}) => {
+ if (!template.controls || template.controls.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className={className || "space-y-3"}>
+ {template.controls.map((control) => {
+ const value = values[control.id] ?? control.defaultValue;
+
+ if (control.type === "number") {
+ return (
+ <div key={control.id} className="space-y-2">
+ <div className="flex items-center justify-between gap-3">
+ <label className="text-[11px] font-medium text-text-primary">
+ {control.label}
+ </label>
+ <span className="rounded-full bg-background-tertiary px-2 py-0.5 text-[10px] text-text-secondary">
+ {value}
+ </span>
+ </div>
+ <input
+ type="range"
+ min={control.min ?? 0}
+ max={control.max ?? 100}
+ step={control.step ?? 1}
+ value={Number(value)}
+ disabled={disabled}
+ onChange={(event) => onChange(control.id, Number(event.target.value))}
+ className="w-full accent-[var(--color-primary,#22c55e)] disabled:cursor-not-allowed disabled:opacity-60"
+ />
+ </div>
+ );
+ }
+
+ if (control.type === "toggle") {
+ return (
+ <div key={control.id} className="flex items-center justify-between gap-3">
+ <label className="text-[11px] font-medium text-text-primary">
+ {control.label}
+ </label>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => onChange(control.id, !Boolean(value))}
+ className={`inline-flex h-7 w-12 items-center rounded-full px-1 transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${
+ Boolean(value)
+ ? "justify-end bg-primary"
+ : "justify-start bg-background-tertiary"
+ }`}
+ >
+ <span className="h-5 w-5 rounded-full bg-white shadow-sm" />
+ </button>
+ </div>
+ );
+ }
+
+ if (control.type === "select") {
+ const options = control.options || [];
+ const selectedIndex = Math.max(
+ 0,
+ options.findIndex((option) => option.value === value),
+ );
+
+ return (
+ <div key={control.id} className="space-y-2">
+ <label className="text-[11px] font-medium text-text-primary">
+ {control.label}
+ </label>
+ <select
+ value={`${selectedIndex}`}
+ disabled={disabled}
+ onChange={(event) => {
+ const option = options[Number(event.target.value)];
+ if (option) {
+ onChange(control.id, option.value);
+ }
+ }}
+ className="h-10 w-full rounded-xl border border-border bg-background-tertiary px-3 text-xs text-text-primary focus:border-primary/50 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {options.map((option, index) => (
+ <option key={option.label} value={`${index}`}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ );
+ }
+
+ if (control.type === "color") {
+ return (
+ <div key={control.id} className="space-y-2">
+ <label className="text-[11px] font-medium text-text-primary">
+ {control.label}
+ </label>
+ <div className="flex items-center gap-3">
+ <input
+ type="color"
+ value={String(value)}
+ disabled={disabled}
+ onChange={(event) => onChange(control.id, event.target.value)}
+ className="h-10 w-12 rounded-lg border border-border bg-transparent disabled:cursor-not-allowed disabled:opacity-60"
+ />
+ <input
+ type="text"
+ value={String(value)}
+ disabled={disabled}
+ onChange={(event) => onChange(control.id, event.target.value)}
+ className="h-10 flex-1 rounded-xl border border-border bg-background-tertiary px-3 text-xs text-text-primary placeholder:text-text-muted focus:border-primary/50 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
+ />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div key={control.id} className="space-y-2">
+ <label className="text-[11px] font-medium text-text-primary">
+ {control.label}
+ </label>
+ <input
+ type="text"
+ value={String(value)}
+ disabled={disabled}
+ onChange={(event) => onChange(control.id, event.target.value)}
+ className="h-10 w-full rounded-xl border border-border bg-background-tertiary px-3 text-xs text-text-primary placeholder:text-text-muted focus:border-primary/50 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
+ />
+ </div>
+ );
+ })}
+ </div>
+ );
+};
\ No newline at end of file
diff --git a/apps/web/src/components/editor/panels/RecipesTab.tsx b/apps/web/src/components/editor/panels/RecipesTab.tsx
new file mode 100644
index 00000000..5cd9c796
--- /dev/null
+++ b/apps/web/src/components/editor/panels/RecipesTab.tsx
@@ -0,0 +1,371 @@
+import React, { useEffect, useMemo, useState } from "react";
+import {
+ CheckCircle2,
+ Search,
+ SlidersHorizontal,
+ Sparkles,
+ Wand2,
+} from "lucide-react";
+import {
+ EDITING_TEMPLATE_CATEGORIES,
+ type EditingTemplate,
+ type EditingTemplateCategory,
+ type EditingTemplatePrimitive,
+} from "@openreel/core";
+import { useProjectStore } from "../../../stores/project-store";
+import { useUIStore } from "../../../stores/ui-store";
+import { toast } from "../../../stores/notification-store";
+import {
+ EditingTemplateControls,
+ getEditingTemplateDefaultControlValues,
+} from "./EditingTemplateControls";
+
+const formatCategoryLabel = (category: string): string =>
+ category.replace(/-/g, " ");
+
+export const RecipesTab: React.FC = () => {
+ const project = useProjectStore((state) => state.project);
+ const getClip = useProjectStore((state) => state.getClip);
+ const getMediaItem = useProjectStore((state) => state.getMediaItem);
+ const getEditingTemplates = useProjectStore((state) => state.getEditingTemplates);
+ const applyEditingTemplate = useProjectStore(
+ (state) => state.applyEditingTemplate,
+ );
+ const getSelectedClipIds = useUIStore((state) => state.getSelectedClipIds);
+
+ const [searchQuery, setSearchQuery] = useState("");
+ const [selectedCategory, setSelectedCategory] = useState<
+ "all" | EditingTemplateCategory
+ >("all");
+ const [expandedTemplateId, setExpandedTemplateId] = useState<string | null>(
+ null,
+ );
+ const [applyingTemplateId, setApplyingTemplateId] = useState<string | null>(
+ null,
+ );
+ const [controlValuesByTemplate, setControlValuesByTemplate] = useState<
+ Record<string, Record<string, EditingTemplatePrimitive>>
+ >({});
+
+ const selectedClipIds = getSelectedClipIds();
+ const templates = useMemo(() => getEditingTemplates(), [getEditingTemplates]);
+
+ const selectedClip = useMemo(() => {
+ if (selectedClipIds.length !== 1) {
+ return null;
+ }
+
+ return getClip(selectedClipIds[0]) || null;
+ }, [getClip, selectedClipIds, project.modifiedAt]);
+
+ const selectedTrack = useMemo(() => {
+ if (!selectedClip) {
+ return null;
+ }
+
+ return (
+ project.timeline.tracks.find((track) =>
+ track.clips.some((clip) => clip.id === selectedClip.id),
+ ) || null
+ );
+ }, [project.timeline.tracks, selectedClip]);
+
+ const selectedTargetType =
+ selectedTrack?.type === "image"
+ ? "image"
+ : selectedTrack?.type === "video"
+ ? "video"
+ : null;
+
+ const selectedMedia = selectedClip
+ ? getMediaItem(selectedClip.mediaId)
+ : undefined;
+ const appliedTemplates = selectedClip?.metadata?.appliedTemplates || [];
+
+ useEffect(() => {
+ if (!expandedTemplateId) {
+ return;
+ }
+
+ const expandedTemplate = templates.find(
+ (template) => template.id === expandedTemplateId,
+ );
+ if (!expandedTemplate || controlValuesByTemplate[expandedTemplateId]) {
+ return;
+ }
+
+ setControlValuesByTemplate((current) => ({
+ ...current,
+ [expandedTemplateId]: getEditingTemplateDefaultControlValues(expandedTemplate),
+ }));
+ }, [controlValuesByTemplate, expandedTemplateId, templates]);
+
+ const filteredTemplates = useMemo(() => {
+ return templates.filter((template) => {
+ if (
+ selectedTargetType &&
+ template.supportedTargets &&
+ !template.supportedTargets.includes(selectedTargetType)
+ ) {
+ return false;
+ }
+
+ if (selectedCategory !== "all" && template.category !== selectedCategory) {
+ return false;
+ }
+
+ if (!searchQuery.trim()) {
+ return true;
+ }
+
+ const query = searchQuery.trim().toLowerCase();
+ return (
+ template.name.toLowerCase().includes(query) ||
+ template.description.toLowerCase().includes(query) ||
+ template.tags.some((tag) => tag.toLowerCase().includes(query))
+ );
+ });
+ }, [searchQuery, selectedCategory, selectedTargetType, templates]);
+
+ const handleExpand = (template: EditingTemplate): void => {
+ setExpandedTemplateId((current) =>
+ current === template.id ? null : template.id,
+ );
+
+ if (!controlValuesByTemplate[template.id]) {
+ setControlValuesByTemplate((current) => ({
+ ...current,
+ [template.id]: getEditingTemplateDefaultControlValues(template),
+ }));
+ }
+ };
+
+ const handleControlChange = (
+ templateId: string,
+ controlId: string,
+ value: EditingTemplatePrimitive,
+ ): void => {
+ setControlValuesByTemplate((current) => ({
+ ...current,
+ [templateId]: {
+ ...(current[templateId] || {}),
+ [controlId]: value,
+ },
+ }));
+ };
+
+ const handleApply = async (template: EditingTemplate): Promise<void> => {
+ if (!selectedClip || !selectedTargetType) {
+ toast.warning(
+ "Select a clip",
+ "Recipes apply to one selected video or image clip.",
+ );
+ return;
+ }
+
+ setApplyingTemplateId(template.id);
+ try {
+ const applicationId = applyEditingTemplate(
+ template.id,
+ selectedClip.id,
+ controlValuesByTemplate[template.id] ||
+ getEditingTemplateDefaultControlValues(template),
+ );
+
+ if (!applicationId) {
+ toast.error(
+ "Could not apply recipe",
+ "This recipe could not be applied to the current clip.",
+ );
+ return;
+ }
+
+ toast.success(
+ "Recipe applied",
+ `${template.name} was added to ${selectedMedia?.name || "the selected clip"}.`,
+ );
+ } finally {
+ setApplyingTemplateId(null);
+ }
+ };
+
+ if (!selectedClip || !selectedTargetType) {
+ return (
+ <div className="px-5 py-6 space-y-4">
+ <div className="rounded-2xl border border-dashed border-border bg-background-tertiary/60 px-4 py-5 text-center">
+ <div className="mx-auto mb-3 flex h-11 w-11 items-center justify-center rounded-2xl bg-primary/10 text-primary">
+ <Sparkles size={18} />
+ </div>
+ <p className="text-sm font-semibold text-text-primary">
+ Choose a video or image clip
+ </p>
+ <p className="mt-2 text-xs leading-5 text-text-muted">
+ Recipes are clip-scoped. Select a single clip in the timeline, then
+ apply a look, caption treatment, or overlay stack without replacing
+ the rest of the project.
+ </p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="px-5 py-4 space-y-4">
+ <div className="rounded-2xl border border-border bg-background-tertiary/70 p-4 shadow-sm">
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-text-muted">
+ Target Clip
+ </p>
+ <p className="mt-1 text-sm font-semibold text-text-primary">
+ {selectedMedia?.name || selectedClip.id}
+ </p>
+ <p className="mt-1 text-xs text-text-muted">
+ {selectedTargetType === "video" ? "Video clip" : "Image clip"}
+ {` • ${selectedClip.duration.toFixed(2)}s`}
+ </p>
+ </div>
+ <div className="rounded-full border border-primary/30 bg-primary/10 px-2.5 py-1 text-[10px] font-medium text-primary">
+ {appliedTemplates.length} applied
+ </div>
+ </div>
+ </div>
+
+ <div className="relative">
+ <Search
+ size={14}
+ className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted"
+ />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(event) => setSearchQuery(event.target.value)}
+ placeholder="Search recipes"
+ className="h-10 w-full rounded-xl border border-border bg-background-secondary pl-9 pr-3 text-xs text-text-primary placeholder:text-text-muted transition-colors focus:border-primary/50 focus:outline-none"
+ />
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <button
+ onClick={() => setSelectedCategory("all")}
+ className={`rounded-full border px-3 py-1.5 text-[10px] font-medium capitalize transition-colors ${
+ selectedCategory === "all"
+ ? "border-primary bg-primary/12 text-primary"
+ : "border-border bg-background-tertiary text-text-muted hover:border-primary/30 hover:text-text-primary"
+ }`}
+ >
+ All Recipes
+ </button>
+ {EDITING_TEMPLATE_CATEGORIES.map((category) => (
+ <button
+ key={category.id}
+ onClick={() => setSelectedCategory(category.id)}
+ className={`rounded-full border px-3 py-1.5 text-[10px] font-medium capitalize transition-colors ${
+ selectedCategory === category.id
+ ? "border-primary bg-primary/12 text-primary"
+ : "border-border bg-background-tertiary text-text-muted hover:border-primary/30 hover:text-text-primary"
+ }`}
+ >
+ {category.name}
+ </button>
+ ))}
+ </div>
+
+ {filteredTemplates.length === 0 ? (
+ <div className="rounded-2xl border border-border bg-background-tertiary/60 px-4 py-8 text-center">
+ <p className="text-sm font-medium text-text-primary">No recipes match</p>
+ <p className="mt-2 text-xs text-text-muted">
+ Try a different search or category.
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-3 pb-4">
+ {filteredTemplates.map((template) => {
+ const currentValues =
+ controlValuesByTemplate[template.id] ||
+ getEditingTemplateDefaultControlValues(template);
+ const appliedCount = appliedTemplates.filter(
+ (appliedTemplate) => appliedTemplate.templateId === template.id,
+ ).length;
+ const isExpanded = expandedTemplateId === template.id;
+
+ return (
+ <div
+ key={template.id}
+ className="rounded-2xl border border-border bg-background-tertiary/70 p-4 shadow-sm transition-colors hover:border-primary/30"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <p className="truncate text-sm font-semibold text-text-primary">
+ {template.name}
+ </p>
+ {appliedCount > 0 && (
+ <span className="inline-flex items-center gap-1 rounded-full border border-primary/20 bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary">
+ <CheckCircle2 size={10} />
+ {appliedCount}x
+ </span>
+ )}
+ </div>
+ <p className="mt-1 text-xs leading-5 text-text-muted">
+ {template.description}
+ </p>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <span className="rounded-full border border-border bg-background-secondary px-2 py-1 text-[10px] font-medium text-text-secondary capitalize">
+ {formatCategoryLabel(template.category)}
+ </span>
+ {template.tags.slice(0, 3).map((tag) => (
+ <span
+ key={tag}
+ className="rounded-full bg-background-secondary px-2 py-1 text-[10px] text-text-muted"
+ >
+ {tag}
+ </span>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex shrink-0 gap-2">
+ {template.controls && template.controls.length > 0 && (
+ <button
+ onClick={() => handleExpand(template)}
+ className={`inline-flex h-10 items-center gap-2 rounded-xl border px-3 text-[11px] font-medium transition-colors ${
+ isExpanded
+ ? "border-primary bg-primary/12 text-primary"
+ : "border-border bg-background-secondary text-text-secondary hover:border-primary/30 hover:text-text-primary"
+ }`}
+ >
+ <SlidersHorizontal size={13} />
+ Controls
+ </button>
+ )}
+ <button
+ onClick={() => void handleApply(template)}
+ disabled={applyingTemplateId !== null}
+ className="inline-flex h-10 items-center gap-2 rounded-xl bg-primary px-3 text-[11px] font-semibold text-black transition-all hover:bg-primary/85 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <Wand2 size={13} />
+ {applyingTemplateId === template.id ? "Applying" : "Apply"}
+ </button>
+ </div>
+ </div>
+
+ {isExpanded && template.controls && template.controls.length > 0 && (
+ <div className="mt-4 space-y-3 rounded-2xl border border-border/80 bg-background-secondary/80 p-4">
+ <EditingTemplateControls
+ template={template}
+ values={currentValues}
+ onChange={(controlId, value) =>
+ handleControlChange(template.id, controlId, value)
+ }
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+};
\ No newline at end of file
diff --git a/apps/web/src/stores/project-store.test.ts b/apps/web/src/stores/project-store.test.ts
index 2de8428e..e9878961 100644
--- a/apps/web/src/stores/project-store.test.ts
+++ b/apps/web/src/stores/project-store.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { useProjectStore } from "./project-store";
+import { useEngineStore } from "./engine-store";
import type { Project, Clip, MediaItem, Transition } from "@openreel/core";
const {
@@ -723,6 +724,326 @@ describe("ProjectStore", () => {
});
});
+ describe("editing templates", () => {
+ const createProjectWithEditableClip = (): Project => {
+ const mediaItem: MediaItem = {
+ id: "video-media-1",
+ name: "hero-shot.mp4",
+ type: "video",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 10,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48000,
+ channels: 2,
+ fileSize: 1000000,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ };
+
+ const clip: Clip = {
+ id: "video-clip-1",
+ mediaId: mediaItem.id,
+ trackId: "video-track-1",
+ startTime: 0,
+ duration: 10,
+ inPoint: 0,
+ outPoint: 10,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0.5, y: 0.5 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ };
+
+ return {
+ id: "editing-template-project",
+ name: "Editing Template Project",
+ createdAt: Date.now(),
+ modifiedAt: Date.now(),
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48000,
+ channels: 2,
+ },
+ mediaLibrary: { items: [mediaItem] },
+ timeline: {
+ tracks: [
+ {
+ id: "video-track-1",
+ type: "video",
+ name: "Video",
+ clips: [clip],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ subtitles: [],
+ duration: 10,
+ markers: [],
+ },
+ };
+ };
+
+ beforeEach(() => {
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
+
+ titleEngine?.loadTextClips([]);
+ graphicsEngine?.loadShapeClips([]);
+ graphicsEngine?.loadSVGClips([]);
+ graphicsEngine?.loadStickerClips([]);
+ });
+
+ const getRecipeTextValues = (applicationId: string): string[] =>
+ (useEngineStore.getState().getTitleEngine()?.getAllTextClips() || [])
+ .filter(
+ (clip) => clip.metadata?.templateSource?.applicationId === applicationId,
+ )
+ .map((clip) => clip.text)
+ .sort();
+
+ it("applies a clip-scoped recipe and records metadata plus overlays", () => {
+ useProjectStore.getState().loadProject(createProjectWithEditableClip());
+
+ const applicationId = useProjectStore.getState().applyEditingTemplate(
+ "branding-lower-third",
+ "video-clip-1",
+ {
+ name: "Ada Lovelace",
+ role: "Director",
+ },
+ );
+
+ expect(applicationId).toBeTruthy();
+
+ const clip = useProjectStore.getState().getClip("video-clip-1");
+ expect(clip?.metadata?.appliedTemplates).toEqual([
+ expect.objectContaining({
+ templateId: "branding-lower-third",
+ applicationId,
+ controlValues: expect.objectContaining({
+ name: "Ada Lovelace",
+ role: "Director",
+ }),
+ }),
+ ]);
+ expect(
+ useProjectStore
+ .getState()
+ .project.timeline.tracks.map((track) => track.type),
+ ).toEqual(["video", "graphics", "text"]);
+ expect(
+ useEngineStore.getState().getGraphicsEngine()?.getAllShapeClips(),
+ ).toHaveLength(1);
+ expect(
+ useEngineStore.getState().getTitleEngine()?.getAllTextClips(),
+ ).toHaveLength(2);
+ });
+
+ it("removes a clip-scoped recipe and cleans up its generated tracks", () => {
+ useProjectStore.getState().loadProject(createProjectWithEditableClip());
+
+ const applicationId = useProjectStore.getState().applyEditingTemplate(
+ "branding-lower-third",
+ "video-clip-1",
+ );
+
+ expect(applicationId).toBeTruthy();
+ expect(
+ useProjectStore.getState().removeEditingTemplateApplication(
+ "video-clip-1",
+ applicationId!,
+ ),
+ ).toBe(true);
+
+ const clip = useProjectStore.getState().getClip("video-clip-1");
+ expect(clip?.metadata?.appliedTemplates || []).toHaveLength(0);
+ expect(
+ useProjectStore
+ .getState()
+ .project.timeline.tracks.map((track) => track.type),
+ ).toEqual(["video"]);
+ expect(
+ useEngineStore.getState().getGraphicsEngine()?.getAllShapeClips(),
+ ).toHaveLength(0);
+ expect(
+ useEngineStore.getState().getTitleEngine()?.getAllTextClips(),
+ ).toHaveLength(0);
+ });
+
+ it("updates an applied recipe in place and keeps its application id", () => {
+ useProjectStore.getState().loadProject(createProjectWithEditableClip());
+
+ const applicationId = useProjectStore.getState().applyEditingTemplate(
+ "branding-lower-third",
+ "video-clip-1",
+ {
+ name: "Ada Lovelace",
+ role: "Director",
+ },
+ );
+
+ expect(applicationId).toBeTruthy();
+ expect(
+ useProjectStore.getState().updateEditingTemplateApplication(
+ "video-clip-1",
+ applicationId!,
+ {
+ name: "Grace Hopper",
+ role: "Engineer",
+ },
+ ),
+ ).toBe(true);
+
+ const clip = useProjectStore.getState().getClip("video-clip-1");
+ expect(clip?.metadata?.appliedTemplates).toEqual([
+ expect.objectContaining({
+ applicationId,
+ controlValues: expect.objectContaining({
+ name: "Grace Hopper",
+ role: "Engineer",
+ }),
+ }),
+ ]);
+ expect(getRecipeTextValues(applicationId!)).toEqual([
+ "Engineer",
+ "Grace Hopper",
+ ]);
+ expect(
+ useEngineStore
+ .getState()
+ .getGraphicsEngine()
+ ?.getAllShapeClips()
+ .filter(
+ (clip) => clip.metadata?.templateSource?.applicationId === applicationId,
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("undos and redoes a recipe update between previous and current controls", async () => {
+ useProjectStore.getState().loadProject(createProjectWithEditableClip());
+
+ const applicationId = useProjectStore.getState().applyEditingTemplate(
+ "branding-lower-third",
+ "video-clip-1",
+ {
+ name: "Ada Lovelace",
+ role: "Director",
+ },
+ );
+
+ expect(applicationId).toBeTruthy();
+ expect(
+ useProjectStore.getState().updateEditingTemplateApplication(
+ "video-clip-1",
+ applicationId!,
+ {
+ name: "Grace Hopper",
+ role: "Engineer",
+ },
+ ),
+ ).toBe(true);
+ expect(getRecipeTextValues(applicationId!)).toEqual([
+ "Engineer",
+ "Grace Hopper",
+ ]);
+
+ await useProjectStore.getState().undo();
+ expect(getRecipeTextValues(applicationId!)).toEqual([
+ "Ada Lovelace",
+ "Director",
+ ]);
+ expect(
+ useProjectStore.getState().getClip("video-clip-1")?.metadata?.appliedTemplates,
+ ).toEqual([
+ expect.objectContaining({
+ applicationId,
+ controlValues: expect.objectContaining({
+ name: "Ada Lovelace",
+ role: "Director",
+ }),
+ }),
+ ]);
+
+ await useProjectStore.getState().redo();
+ expect(getRecipeTextValues(applicationId!)).toEqual([
+ "Engineer",
+ "Grace Hopper",
+ ]);
+ expect(
+ useProjectStore.getState().getClip("video-clip-1")?.metadata?.appliedTemplates,
+ ).toEqual([
+ expect.objectContaining({
+ applicationId,
+ controlValues: expect.objectContaining({
+ name: "Grace Hopper",
+ role: "Engineer",
+ }),
+ }),
+ ]);
+ });
+
+ it("undos newer timeline actions before undoing a recipe and can redo the recipe", async () => {
+ useProjectStore.getState().loadProject(createProjectWithEditableClip());
+
+ const applicationId = useProjectStore.getState().applyEditingTemplate(
+ "branding-lower-third",
+ "video-clip-1",
+ );
+
+ expect(applicationId).toBeTruthy();
+ expect(useProjectStore.getState().project.timeline.tracks).toHaveLength(3);
+
+ await useProjectStore.getState().addTrack("audio");
+ expect(useProjectStore.getState().project.timeline.tracks).toHaveLength(4);
+
+ await useProjectStore.getState().undo();
+ expect(useProjectStore.getState().project.timeline.tracks).toHaveLength(3);
+ expect(
+ useProjectStore.getState().getClip("video-clip-1")?.metadata?.appliedTemplates,
+ ).toHaveLength(1);
+
+ await useProjectStore.getState().undo();
+ expect(
+ useProjectStore.getState().getClip("video-clip-1")?.metadata?.appliedTemplates || [],
+ ).toHaveLength(0);
+ expect(
+ useEngineStore.getState().getGraphicsEngine()?.getAllShapeClips(),
+ ).toHaveLength(0);
+ expect(
+ useEngineStore.getState().getTitleEngine()?.getAllTextClips(),
+ ).toHaveLength(0);
+
+ await useProjectStore.getState().redo();
+ expect(
+ useProjectStore.getState().getClip("video-clip-1")?.metadata?.appliedTemplates,
+ ).toHaveLength(1);
+ expect(
+ useEngineStore.getState().getGraphicsEngine()?.getAllShapeClips(),
+ ).toHaveLength(1);
+ expect(
+ useEngineStore.getState().getTitleEngine()?.getAllTextClips(),
+ ).toHaveLength(2);
+ });
+ });
+
describe("clip transitions", () => {
const createProjectWithAdjacentClips = (): Project => ({
id: "transition-project",
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 6a3c1121..410faf9e 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -25,10 +25,18 @@ import type {
Effect,
Keyframe,
Transform,
+ AppliedEditingTemplate,
+ EditingTemplate,
+ EditingTemplateApplicationSource,
+ EditingTemplatePrimitive,
+ ResolvedEditingTemplateApplication,
} from "@openreel/core";
import {
ActionExecutor,
ActionHistory,
+ getBuiltInEditingTemplate,
+ getBuiltInEditingTemplates,
+ resolveEditingTemplate,
textAnimationEngine,
} from "@openreel/core";
import { v4 as uuidv4 } from "uuid";
@@ -49,7 +57,9 @@ import { getMediaBridge, initializeMediaBridge } from "../bridges/media-bridge";
import {
createEmptyProject,
calculateTimelineDuration,
+ type EditingTemplateApplicationState,
type ClipHistoryEntry,
+ type EditingTemplateHistoryEntry,
} from "./project/index";
import {
saveMediaBlob,
@@ -91,6 +101,8 @@ export interface ProjectState {
// Clip history for graphics/text clips (outside main timeline)
clipUndoStack: ClipHistoryEntry[];
clipRedoStack: ClipHistoryEntry[];
+ templateUndoStack: EditingTemplateHistoryEntry[];
+ templateRedoStack: EditingTemplateHistoryEntry[];
// Loading state
isLoading: boolean;
@@ -211,6 +223,23 @@ export interface ProjectState {
pasteEffects: (clipId: string) => Promise<ActionResult>;
copiedEffects: Effect[];
+ getEditingTemplates: () => EditingTemplate[];
+ getEditingTemplate: (templateId: string) => EditingTemplate | undefined;
+ applyEditingTemplate: (
+ templateId: string,
+ clipId: string,
+ overrides?: Record<string, EditingTemplatePrimitive>,
+ ) => string | null;
+ updateEditingTemplateApplication: (
+ clipId: string,
+ applicationId: string,
+ overrides?: Record<string, EditingTemplatePrimitive>,
+ ) => boolean;
+ removeEditingTemplateApplication: (
+ clipId: string,
+ applicationId: string,
+ ) => boolean;
+
// Text clip actions
createTextClip: (
trackId: string,
@@ -605,6 +634,811 @@ export const useProjectStore = create<ProjectState>()(
}
};
+ const buildEditingTemplateTrack = (
+ trackType: "text" | "graphics",
+ ): Track => ({
+ id: `track-${uuidv4()}`,
+ type: trackType,
+ name: trackType === "text" ? "Recipe Text" : "Recipe Graphics",
+ clips: [],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ });
+
+ const insertEditingTemplateTrack = (
+ project: Project,
+ snapshot: EditingTemplateHistoryEntry["trackSnapshots"][number],
+ ): Project => {
+ if (project.timeline.tracks.some((track) => track.id === snapshot.track.id)) {
+ return project;
+ }
+
+ const tracks = [...project.timeline.tracks];
+ const position = Math.max(0, Math.min(snapshot.position, tracks.length));
+ tracks.splice(position, 0, snapshot.track);
+
+ return {
+ ...project,
+ timeline: { ...project.timeline, tracks },
+ modifiedAt: Date.now(),
+ };
+ };
+
+ const removeTrackFromProjectState = (
+ project: Project,
+ trackId: string,
+ ): Project => {
+ const nextTracks = project.timeline.tracks.filter((track) => track.id !== trackId);
+
+ if (nextTracks.length === project.timeline.tracks.length) {
+ return project;
+ }
+
+ return {
+ ...project,
+ timeline: { ...project.timeline, tracks: nextTracks },
+ modifiedAt: Date.now(),
+ };
+ };
+
+ const trackHasAnyClips = (project: Project, trackId: string): boolean => {
+ const track = project.timeline.tracks.find((candidate) => candidate.id === trackId);
+ if (!track) {
+ return false;
+ }
+
+ if (track.clips.length > 0) {
+ return true;
+ }
+
+ if (track.type === "text") {
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ return titleEngine?.getAllTextClips().some((clip) => clip.trackId === trackId) ?? false;
+ }
+
+ if (track.type === "graphics") {
+ const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
+ if (!graphicsEngine) {
+ return false;
+ }
+
+ return [
+ ...graphicsEngine.getAllShapeClips(),
+ ...graphicsEngine.getAllSVGClips(),
+ ...graphicsEngine.getAllStickerClips(),
+ ].some((clip) => clip.trackId === trackId);
+ }
+
+ return false;
+ };
+
+ const buildEditingTemplateKeyframes = (
+ prefix: string,
+ keyframes: readonly {
+ time: number;
+ property: string;
+ value: unknown;
+ easing: Keyframe["easing"];
+ }[],
+ ): Keyframe[] =>
+ keyframes.map((keyframe, index) => ({
+ id: `${prefix}-keyframe-${index + 1}`,
+ time: keyframe.time,
+ property: keyframe.property,
+ value: keyframe.value,
+ easing: keyframe.easing,
+ }));
+
+ const buildEditingTemplateSource = (
+ templateId: string,
+ applicationId: string,
+ ownerClipId: string,
+ ownerTrackId: string,
+ controlValues: Record<string, unknown> | undefined,
+ ): EditingTemplateApplicationSource => ({
+ templateId,
+ applicationId,
+ ownerClipId,
+ ownerTrackId,
+ controlValues,
+ });
+
+ const buildAppliedEditingTemplate = (
+ resolvedTemplate: ResolvedEditingTemplateApplication,
+ applicationId: string,
+ appliedAt: number = Date.now(),
+ ): AppliedEditingTemplate => ({
+ templateId: resolvedTemplate.template.id,
+ applicationId,
+ name: resolvedTemplate.template.name,
+ category: resolvedTemplate.template.category,
+ appliedAt,
+ controlValues: resolvedTemplate.controlValues,
+ });
+
+ const getEditingTemplateApplicationState = (
+ entry: EditingTemplateHistoryEntry,
+ ): EditingTemplateApplicationState => ({
+ ownerClipId: entry.ownerClipId,
+ templateId: entry.templateId,
+ applicationId: entry.applicationId,
+ appliedTemplate: entry.appliedTemplate,
+ addedEffects: entry.addedEffects,
+ addedAudioEffects: entry.addedAudioEffects,
+ addedKeyframes: entry.addedKeyframes,
+ overlays: entry.overlays,
+ trackSnapshots: entry.trackSnapshots,
+ });
+
+ const getEditingTemplatePreferredTrackIds = (
+ applicationState: EditingTemplateApplicationState,
+ ): Partial<Record<"text" | "graphics", string>> =>
+ applicationState.overlays.reduce<Partial<Record<"text" | "graphics", string>>>(
+ (trackIds, placement) => {
+ trackIds[placement.overlay.trackType] = placement.trackId;
+ return trackIds;
+ },
+ {},
+ );
+
+ const findEditingTemplateHistoryEntry = (
+ clipId: string,
+ applicationId: string,
+ ): EditingTemplateHistoryEntry | undefined => {
+ const { templateUndoStack, templateRedoStack } = get();
+
+ return [...templateUndoStack, ...templateRedoStack]
+ .reverse()
+ .find(
+ (entry) =>
+ entry.ownerClipId === clipId && entry.applicationId === applicationId,
+ );
+ };
+
+ const applyEditingTemplateApplicationToProject = (
+ project: Project,
+ templateId: string,
+ clipId: string,
+ overrides: Record<string, EditingTemplatePrimitive> = {},
+ options: {
+ applicationId?: string;
+ appliedAt?: number;
+ preferredTrackIds?: Partial<Record<"text" | "graphics", string>>;
+ preservedTrackSnapshots?: EditingTemplateApplicationState["trackSnapshots"];
+ } = {},
+ ):
+ | {
+ project: Project;
+ applicationState: EditingTemplateApplicationState;
+ }
+ | null => {
+ const template = getBuiltInEditingTemplate(templateId);
+ if (!template) {
+ return null;
+ }
+
+ const track = project.timeline.tracks.find((candidate) =>
+ candidate.clips.some((clip) => clip.id === clipId),
+ );
+ const ownerClip = track?.clips.find((clip) => clip.id === clipId);
+
+ if (!track || !ownerClip) {
+ return null;
+ }
+
+ const targetType =
+ track.type === "image"
+ ? "image"
+ : track.type === "video"
+ ? "video"
+ : null;
+
+ if (!targetType) {
+ return null;
+ }
+
+ if (
+ template.supportedTargets &&
+ !template.supportedTargets.includes(targetType)
+ ) {
+ return null;
+ }
+
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
+ const needsTextTrack = template.recipe.overlays.some(
+ (overlay) => overlay.trackType === "text",
+ );
+ const needsGraphicsTrack = template.recipe.overlays.some(
+ (overlay) => overlay.trackType === "graphics",
+ );
+
+ if (
+ (needsTextTrack && !titleEngine) ||
+ (needsGraphicsTrack && !graphicsEngine)
+ ) {
+ return null;
+ }
+
+ const mediaItem = project.mediaLibrary.items.find(
+ (item) => item.id === ownerClip.mediaId,
+ );
+ const assetUrls = project.mediaLibrary.items.reduce<Record<string, string>>(
+ (urls, item) => {
+ const url = item.originalUrl ?? item.thumbnailUrl ?? undefined;
+ if (url) {
+ urls[item.id] = url;
+ }
+ return urls;
+ },
+ {},
+ );
+
+ const resolvedTemplate = resolveEditingTemplate(
+ template,
+ {
+ clip: {
+ id: ownerClip.id,
+ startTime: ownerClip.startTime,
+ duration: ownerClip.duration,
+ name: mediaItem?.name,
+ },
+ assetUrls,
+ },
+ overrides,
+ );
+
+ const applicationId = options.applicationId || `editing-template-${uuidv4()}`;
+ const appliedTemplate = buildAppliedEditingTemplate(
+ resolvedTemplate,
+ applicationId,
+ options.appliedAt,
+ );
+ const templateSource = buildEditingTemplateSource(
+ template.id,
+ applicationId,
+ ownerClip.id,
+ ownerClip.trackId,
+ appliedTemplate.controlValues,
+ );
+
+ const addedEffects = resolvedTemplate.effects.map((effect, index) => ({
+ id: `template-effect-${applicationId}-${index + 1}-${effect.id}`,
+ type: effect.type,
+ params: effect.params,
+ enabled: effect.enabled,
+ metadata: { templateSource },
+ }));
+ const addedAudioEffects = resolvedTemplate.audioEffects.map((effect, index) => ({
+ id: `template-audio-effect-${applicationId}-${index + 1}-${effect.id}`,
+ type: effect.type,
+ params: effect.params,
+ enabled: effect.enabled,
+ metadata: { templateSource },
+ }));
+ const addedKeyframes = [
+ ...resolvedTemplate.effects.flatMap((effect, index) =>
+ buildEditingTemplateKeyframes(
+ `template-keyframe-${applicationId}-video-${index + 1}`,
+ effect.keyframes,
+ ),
+ ),
+ ...resolvedTemplate.audioEffects.flatMap((effect, index) =>
+ buildEditingTemplateKeyframes(
+ `template-keyframe-${applicationId}-audio-${index + 1}`,
+ effect.keyframes,
+ ),
+ ),
+ ];
+
+ let updatedProject = project;
+ const trackSnapshots = [
+ ...((options.preservedTrackSnapshots || []).filter((snapshot) =>
+ updatedProject.timeline.tracks.some((track) => track.id === snapshot.track.id),
+ )),
+ ];
+ const resolvedTrackIds: Partial<Record<"text" | "graphics", string>> = {};
+
+ for (const snapshot of trackSnapshots) {
+ if (snapshot.track.type === "text" || snapshot.track.type === "graphics") {
+ resolvedTrackIds[snapshot.track.type] = snapshot.track.id;
+ }
+ }
+
+ const ensureOverlayTrack = (trackType: "text" | "graphics"): string => {
+ const existingTrackId = resolvedTrackIds[trackType];
+ if (
+ existingTrackId &&
+ updatedProject.timeline.tracks.some((track) => track.id === existingTrackId)
+ ) {
+ return existingTrackId;
+ }
+
+ const preferredTrackId = options.preferredTrackIds?.[trackType];
+ if (
+ preferredTrackId &&
+ updatedProject.timeline.tracks.some((track) => track.id === preferredTrackId)
+ ) {
+ resolvedTrackIds[trackType] = preferredTrackId;
+ return preferredTrackId;
+ }
+
+ const existingTrack = updatedProject.timeline.tracks.find(
+ (candidate) => candidate.type === trackType,
+ );
+ if (existingTrack) {
+ resolvedTrackIds[trackType] = existingTrack.id;
+ return existingTrack.id;
+ }
+
+ const snapshot = {
+ track: buildEditingTemplateTrack(trackType),
+ position: updatedProject.timeline.tracks.length,
+ };
+ trackSnapshots.push(snapshot);
+ updatedProject = insertEditingTemplateTrack(updatedProject, snapshot);
+ resolvedTrackIds[trackType] = snapshot.track.id;
+ return snapshot.track.id;
+ };
+
+ const overlays: EditingTemplateApplicationState["overlays"] =
+ resolvedTemplate.overlays.map((overlay, index) => ({
+ trackId: ensureOverlayTrack(overlay.trackType),
+ overlay: {
+ ...overlay,
+ id: `template-overlay-${applicationId}-${index + 1}-${overlay.id}`,
+ },
+ }));
+
+ const nextProject = updateProjectClip(updatedProject, clipId, (clip) => ({
+ ...clip,
+ effects: [...clip.effects, ...addedEffects],
+ audioEffects: [...clip.audioEffects, ...addedAudioEffects],
+ keyframes: [...clip.keyframes, ...addedKeyframes],
+ metadata: {
+ ...(clip.metadata || {}),
+ appliedTemplates: [
+ ...(clip.metadata?.appliedTemplates || []),
+ appliedTemplate,
+ ],
+ },
+ }));
+
+ if (!nextProject) {
+ return null;
+ }
+
+ updatedProject = nextProject;
+
+ for (const placement of overlays) {
+ if (!createEditingTemplateOverlay(placement, templateSource)) {
+ removeEditingTemplateApplicationFromProject(
+ updatedProject,
+ clipId,
+ applicationId,
+ trackSnapshots.map((snapshot) => snapshot.track.id),
+ );
+ return null;
+ }
+ }
+
+ syncClipEffectsBridge(updatedProject, clipId);
+
+ return {
+ project: {
+ ...updatedProject,
+ modifiedAt: Date.now(),
+ },
+ applicationState: {
+ ownerClipId: clipId,
+ templateId: template.id,
+ applicationId,
+ appliedTemplate,
+ addedEffects,
+ addedAudioEffects,
+ addedKeyframes,
+ overlays,
+ trackSnapshots,
+ },
+ };
+ };
+
+ const canRestoreEditingTemplateOverlays = (
+ overlays: EditingTemplateHistoryEntry["overlays"],
+ ): boolean => {
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
+
+ for (const placement of overlays) {
+ if (placement.overlay.type === "text" && !titleEngine) {
+ return false;
+ }
+
+ if (placement.overlay.type !== "text" && !graphicsEngine) {
+ return false;
+ }
+
+ if (placement.overlay.type === "image" && !placement.overlay.content.imageUrl) {
+ return false;
+ }
+ }
+
+ return true;
+ };
+
+ const createEditingTemplateOverlay = (
+ placement: EditingTemplateHistoryEntry["overlays"][number],
+ source: EditingTemplateApplicationSource,
+ ): boolean => {
+ const metadata = {
+ templateSource: source,
+ templateManaged: true,
+ templateTrackType: placement.overlay.trackType,
+ };
+
+ if (placement.overlay.type === "text") {
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ if (!titleEngine) {
+ return false;
+ }
+
+ if (titleEngine.getTextClip(placement.overlay.id)) {
+ return true;
+ }
+
+ titleEngine.createTextClip({
+ id: placement.overlay.id,
+ trackId: placement.trackId,
+ startTime: placement.overlay.timing.startTime,
+ duration: placement.overlay.timing.duration,
+ text: placement.overlay.content.text,
+ style: placement.overlay.content.style,
+ transform: placement.overlay.transform,
+ animation: placement.overlay.content.animation
+ ? {
+ preset: placement.overlay.content.animation.preset,
+ params: placement.overlay.content.animation.params || {},
+ inDuration: placement.overlay.content.animation.inDuration,
+ outDuration: placement.overlay.content.animation.outDuration,
+ stagger: placement.overlay.content.animation.stagger,
+ unit: placement.overlay.content.animation.unit,
+ }
+ : undefined,
+ metadata,
+ });
+
+ return Boolean(
+ titleEngine.updateTextClip(placement.overlay.id, {
+ keyframes: buildEditingTemplateKeyframes(
+ placement.overlay.id,
+ placement.overlay.keyframes,
+ ),
+ blendMode: placement.overlay.blendMode,
+ blendOpacity: placement.overlay.blendOpacity,
+ emphasisAnimation: placement.overlay.emphasisAnimation,
+ metadata,
+ }),
+ );
+ }
+
+ const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
+ if (!graphicsEngine) {
+ return false;
+ }
+
+ if (placement.overlay.type === "shape") {
+ if (graphicsEngine.getShapeClip(placement.overlay.id)) {
+ return true;
+ }
+
+ graphicsEngine.createShape(
+ {
+ id: placement.overlay.id,
+ shapeType: placement.overlay.content.shapeType,
+ width: placement.overlay.content.width,
+ height: placement.overlay.content.height,
+ style: placement.overlay.content.style,
+ metadata,
+ },
+ placement.trackId,
+ placement.overlay.timing.startTime,
+ placement.overlay.timing.duration,
+ );
+
+ return Boolean(
+ graphicsEngine.updateShapeClip(placement.overlay.id, {
+ transform: placement.overlay.transform,
+ keyframes: buildEditingTemplateKeyframes(
+ placement.overlay.id,
+ placement.overlay.keyframes,
+ ),
+ blendMode: placement.overlay.blendMode,
+ blendOpacity: placement.overlay.blendOpacity,
+ emphasisAnimation: placement.overlay.emphasisAnimation,
+ }),
+ );
+ }
+
+ if (graphicsEngine.getStickerClip(placement.overlay.id)) {
+ return true;
+ }
+
+ if (!placement.overlay.content.imageUrl) {
+ return false;
+ }
+
+ graphicsEngine.addStickerClip({
+ id: placement.overlay.id,
+ trackId: placement.trackId,
+ startTime: placement.overlay.timing.startTime,
+ duration: placement.overlay.timing.duration,
+ type: "sticker",
+ imageUrl: placement.overlay.content.imageUrl,
+ name: placement.overlay.content.name,
+ transform: placement.overlay.transform,
+ keyframes: buildEditingTemplateKeyframes(
+ placement.overlay.id,
+ placement.overlay.keyframes,
+ ),
+ blendMode: placement.overlay.blendMode,
+ blendOpacity: placement.overlay.blendOpacity,
+ emphasisAnimation: placement.overlay.emphasisAnimation,
+ metadata,
+ });
+
+ return true;
+ };
+
+ const hasEditingTemplateArtifacts = (
+ project: Project,
+ ownerClipId: string,
+ applicationId: string,
+ ): boolean => {
+ const ownerClip = project.timeline.tracks
+ .flatMap((track) => track.clips)
+ .find((clip) => clip.id === ownerClipId);
+
+ if (ownerClip) {
+ if ((ownerClip.metadata?.appliedTemplates || []).some(
+ (template) => template.applicationId === applicationId,
+ )) {
+ return true;
+ }
+
+ if (ownerClip.effects.some(
+ (effect) => effect.metadata?.templateSource?.applicationId === applicationId,
+ )) {
+ return true;
+ }
+
+ if (ownerClip.audioEffects.some(
+ (effect) => effect.metadata?.templateSource?.applicationId === applicationId,
+ )) {
+ return true;
+ }
+
+ if (ownerClip.keyframes.some(
+ (keyframe) => keyframe.id.startsWith(`template-keyframe-${applicationId}-`),
+ )) {
+ return true;
+ }
+ }
+
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ if (titleEngine?.getAllTextClips().some(
+ (clip) => clip.metadata?.templateSource?.applicationId === applicationId,
+ )) {
+ return true;
+ }
+
+ const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
+ if (!graphicsEngine) {
+ return false;
+ }
+
+ return [
+ ...graphicsEngine.getAllShapeClips(),
+ ...graphicsEngine.getAllSVGClips(),
+ ...graphicsEngine.getAllStickerClips(),
+ ].some((clip) => clip.metadata?.templateSource?.applicationId === applicationId);
+ };
+
+ const removeEditingTemplateApplicationFromProject = (
+ project: Project,
+ ownerClipId: string,
+ applicationId: string,
+ trackIdsToRemoveIfEmpty: string[] = [],
+ ): Project => {
+ let updatedProject = project;
+ const currentOwnerClip = project.timeline.tracks
+ .flatMap((track) => track.clips)
+ .find((clip) => clip.id === ownerClipId);
+
+ if (currentOwnerClip) {
+ const nextProject = updateProjectClip(project, ownerClipId, (clip) => {
+ const appliedTemplates = (clip.metadata?.appliedTemplates || []).filter(
+ (template) => template.applicationId !== applicationId,
+ );
+ const metadata: Record<string, unknown> = {
+ ...(clip.metadata || {}),
+ };
+
+ if (appliedTemplates.length > 0) {
+ metadata.appliedTemplates = appliedTemplates;
+ } else {
+ delete metadata.appliedTemplates;
+ }
+
+ return {
+ ...clip,
+ effects: clip.effects.filter(
+ (effect) => effect.metadata?.templateSource?.applicationId !== applicationId,
+ ),
+ audioEffects: clip.audioEffects.filter(
+ (effect) => effect.metadata?.templateSource?.applicationId !== applicationId,
+ ),
+ keyframes: clip.keyframes.filter(
+ (keyframe) => !keyframe.id.startsWith(`template-keyframe-${applicationId}-`),
+ ),
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
+ };
+ });
+
+ if (nextProject) {
+ updatedProject = nextProject;
+ }
+ }
+
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ for (const textClip of titleEngine?.getAllTextClips() || []) {
+ if (textClip.metadata?.templateSource?.applicationId === applicationId) {
+ titleEngine?.deleteTextClip(textClip.id);
+ }
+ }
+
+ const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
+ if (graphicsEngine) {
+ for (const shapeClip of graphicsEngine.getAllShapeClips()) {
+ if (shapeClip.metadata?.templateSource?.applicationId === applicationId) {
+ graphicsEngine.deleteShapeClip(shapeClip.id);
+ }
+ }
+
+ for (const svgClip of graphicsEngine.getAllSVGClips()) {
+ if (svgClip.metadata?.templateSource?.applicationId === applicationId) {
+ graphicsEngine.deleteSVGClip(svgClip.id);
+ }
+ }
+
+ for (const stickerClip of graphicsEngine.getAllStickerClips()) {
+ if (stickerClip.metadata?.templateSource?.applicationId === applicationId) {
+ graphicsEngine.deleteStickerClip(stickerClip.id);
+ }
+ }
+ }
+
+ for (const trackId of trackIdsToRemoveIfEmpty) {
+ if (!trackHasAnyClips(updatedProject, trackId)) {
+ updatedProject = removeTrackFromProjectState(updatedProject, trackId);
+ }
+ }
+
+ syncClipEffectsBridge(updatedProject, ownerClipId);
+
+ return {
+ ...updatedProject,
+ modifiedAt: Date.now(),
+ };
+ };
+
+ const removeEditingTemplateApplicationStateFromProject = (
+ project: Project,
+ applicationState: EditingTemplateApplicationState,
+ removeEmptyTracks: boolean = true,
+ ): Project =>
+ removeEditingTemplateApplicationFromProject(
+ project,
+ applicationState.ownerClipId,
+ applicationState.applicationId,
+ removeEmptyTracks
+ ? applicationState.trackSnapshots.map((snapshot) => snapshot.track.id)
+ : [],
+ );
+
+ const restoreEditingTemplateApplicationState = (
+ project: Project,
+ applicationState: EditingTemplateApplicationState,
+ ): Project | null => {
+ if (!canRestoreEditingTemplateOverlays(applicationState.overlays)) {
+ return null;
+ }
+
+ let updatedProject = project;
+ for (const snapshot of applicationState.trackSnapshots) {
+ updatedProject = insertEditingTemplateTrack(updatedProject, snapshot);
+ }
+
+ const ownerClip = updatedProject.timeline.tracks
+ .flatMap((track) => track.clips)
+ .find((clip) => clip.id === applicationState.ownerClipId);
+ if (!ownerClip) {
+ return null;
+ }
+
+ const templateSource = buildEditingTemplateSource(
+ applicationState.templateId,
+ applicationState.applicationId,
+ applicationState.ownerClipId,
+ ownerClip.trackId,
+ applicationState.appliedTemplate.controlValues,
+ );
+
+ const nextProject = updateProjectClip(
+ updatedProject,
+ applicationState.ownerClipId,
+ (clip) => {
+ const effectIds = new Set(clip.effects.map((effect) => effect.id));
+ const audioEffectIds = new Set(clip.audioEffects.map((effect) => effect.id));
+ const keyframeIds = new Set(clip.keyframes.map((keyframe) => keyframe.id));
+ const appliedTemplates = clip.metadata?.appliedTemplates || [];
+ const hasAppliedTemplate = appliedTemplates.some(
+ (template) =>
+ template.applicationId === applicationState.applicationId,
+ );
+
+ return {
+ ...clip,
+ effects: [
+ ...clip.effects,
+ ...applicationState.addedEffects.filter(
+ (effect) => !effectIds.has(effect.id),
+ ),
+ ],
+ audioEffects: [
+ ...clip.audioEffects,
+ ...applicationState.addedAudioEffects.filter(
+ (effect) => !audioEffectIds.has(effect.id),
+ ),
+ ],
+ keyframes: [
+ ...clip.keyframes,
+ ...applicationState.addedKeyframes.filter(
+ (keyframe) => !keyframeIds.has(keyframe.id),
+ ),
+ ],
+ metadata: {
+ ...(clip.metadata || {}),
+ appliedTemplates: hasAppliedTemplate
+ ? appliedTemplates
+ : [...appliedTemplates, applicationState.appliedTemplate],
+ },
+ };
+ },
+ );
+
+ if (!nextProject) {
+ return null;
+ }
+
+ updatedProject = nextProject;
+
+ for (const placement of applicationState.overlays) {
+ if (!createEditingTemplateOverlay(placement, templateSource)) {
+ return null;
+ }
+ }
+
+ syncClipEffectsBridge(updatedProject, applicationState.ownerClipId);
+
+ return {
+ ...updatedProject,
+ modifiedAt: Date.now(),
+ };
+ };
+
return {
// Initial state - create empty project (Requirement 1.1)
project: createEmptyProject(),
@@ -613,6 +1447,8 @@ export const useProjectStore = create<ProjectState>()(
actionHistory,
clipUndoStack: [] as ClipHistoryEntry[],
clipRedoStack: [] as ClipHistoryEntry[],
+ templateUndoStack: [] as EditingTemplateHistoryEntry[],
+ templateRedoStack: [] as EditingTemplateHistoryEntry[],
isLoading: false,
error: null,
clipboard: [] as Clip[],
@@ -636,6 +1472,8 @@ export const useProjectStore = create<ProjectState>()(
actionExecutor: newExecutor,
clipUndoStack: [],
clipRedoStack: [],
+ templateUndoStack: [],
+ templateRedoStack: [],
error: null,
});
},
@@ -679,6 +1517,8 @@ export const useProjectStore = create<ProjectState>()(
actionExecutor: newExecutor,
clipUndoStack: [],
clipRedoStack: [],
+ templateUndoStack: [],
+ templateRedoStack: [],
error: null,
});
@@ -2673,12 +3513,69 @@ export const useProjectStore = create<ProjectState>()(
// Undo/Redo
undo: async () => {
- const { project, actionExecutor, clipUndoStack, clipRedoStack } = get();
+ const {
+ project,
+ actionExecutor,
+ actionHistory,
+ clipUndoStack,
+ clipRedoStack,
+ templateUndoStack,
+ templateRedoStack,
+ } = get();
+
+ const latestActionTimestamp = actionHistory.peekUndo()?.timestamp ?? -1;
+ const latestClipTimestamp =
+ clipUndoStack.length > 0
+ ? clipUndoStack[clipUndoStack.length - 1].timestamp
+ : -1;
+ const latestTemplateTimestamp =
+ templateUndoStack.length > 0
+ ? templateUndoStack[templateUndoStack.length - 1].timestamp
+ : -1;
+
+ if (
+ latestTemplateTimestamp >= 0 &&
+ latestTemplateTimestamp >= latestClipTimestamp &&
+ latestTemplateTimestamp > latestActionTimestamp
+ ) {
+ const entry = templateUndoStack[templateUndoStack.length - 1];
+ const removedProject = removeEditingTemplateApplicationStateFromProject(
+ project,
+ getEditingTemplateApplicationState(entry),
+ );
+ const updatedProject = entry.previousState
+ ? restoreEditingTemplateApplicationState(
+ removedProject,
+ entry.previousState,
+ )
+ : removedProject;
+
+ if (!updatedProject) {
+ return {
+ success: false,
+ error: {
+ code: "INVALID_PARAMS",
+ message: "Failed to undo editing template update",
+ },
+ };
+ }
+
+ set({
+ project: updatedProject,
+ templateUndoStack: templateUndoStack.slice(0, -1),
+ templateRedoStack: [
+ ...templateRedoStack,
+ { ...entry, timestamp: Date.now() },
+ ],
+ });
+
+ return { success: true };
+ }
// Dual-stack undo/redo system: clipUndoStack handles graphics/text/svg/sticker clips created outside the main timeline
// This prevents those creations from being mixed with ActionHistory which handles timeline operations
- // Check clip undo stack first (higher priority than global action history)
- if (clipUndoStack.length > 0) {
+ // Compare clip undo entries against the latest timeline action so the newest operation wins.
+ if (latestClipTimestamp >= 0 && latestClipTimestamp > latestActionTimestamp) {
const entry = clipUndoStack[clipUndoStack.length - 1];
let deleted = false;
@@ -2716,7 +3613,14 @@ export const useProjectStore = create<ProjectState>()(
set({
project: { ...project, modifiedAt: Date.now() },
clipUndoStack: clipUndoStack.slice(0, -1),
- clipRedoStack: [...clipRedoStack, { ...entry, hadEmptyTrackUndo: false }],
+ clipRedoStack: [
+ ...clipRedoStack,
+ {
+ ...entry,
+ timestamp: Date.now(),
+ hadEmptyTrackUndo: false,
+ },
+ ],
});
// Check if the track is now empty and should also be undone
@@ -2796,7 +3700,49 @@ export const useProjectStore = create<ProjectState>()(
},
redo: async () => {
- const { project, actionExecutor, clipUndoStack, clipRedoStack } = get();
+ const {
+ project,
+ actionExecutor,
+ clipUndoStack,
+ clipRedoStack,
+ templateUndoStack,
+ templateRedoStack,
+ } = get();
+
+ if (templateRedoStack.length > 0) {
+ const entry = templateRedoStack[templateRedoStack.length - 1];
+ const cleanedProject = entry.previousState
+ ? removeEditingTemplateApplicationStateFromProject(
+ project,
+ entry.previousState,
+ )
+ : project;
+ const updatedProject = restoreEditingTemplateApplicationState(
+ cleanedProject,
+ getEditingTemplateApplicationState(entry),
+ );
+
+ if (!updatedProject) {
+ return {
+ success: false,
+ error: {
+ code: "INVALID_PARAMS",
+ message: "Failed to restore editing template application",
+ },
+ };
+ }
+
+ set({
+ project: updatedProject,
+ templateUndoStack: [
+ ...templateUndoStack,
+ { ...entry, timestamp: Date.now() },
+ ],
+ templateRedoStack: templateRedoStack.slice(0, -1),
+ });
+
+ return { success: true };
+ }
// Inverse of undo: restore clip from redo stack by recreating it with saved clipData
// Check clip redo stack first (graphics/text/svg/sticker clips previously undone)
@@ -2894,7 +3840,13 @@ export const useProjectStore = create<ProjectState>()(
// Move entry from redo back to undo stack, pop from redo
set({
project: { ...get().project, modifiedAt: Date.now() },
- clipUndoStack: [...clipUndoStack, updatedEntry],
+ clipUndoStack: [
+ ...clipUndoStack,
+ {
+ ...updatedEntry,
+ timestamp: Date.now(),
+ },
+ ],
clipRedoStack: clipRedoStack.slice(0, -1),
});
return { success: true };
@@ -2910,15 +3862,21 @@ export const useProjectStore = create<ProjectState>()(
},
canUndo: () => {
- const { actionHistory, clipUndoStack } = get();
- // Check both undo sources: clip-specific stack takes precedence, then global action history
- return clipUndoStack.length > 0 || actionHistory.canUndo();
+ const { actionHistory, clipUndoStack, templateUndoStack } = get();
+ return (
+ templateUndoStack.length > 0 ||
+ clipUndoStack.length > 0 ||
+ actionHistory.canUndo()
+ );
},
canRedo: () => {
- const { actionHistory, clipRedoStack } = get();
- // Check both redo sources: clip-specific stack takes precedence, then global action history
- return clipRedoStack.length > 0 || actionHistory.canRedo();
+ const { actionHistory, clipRedoStack, templateRedoStack } = get();
+ return (
+ templateRedoStack.length > 0 ||
+ clipRedoStack.length > 0 ||
+ actionHistory.canRedo()
+ );
},
// Execute arbitrary action
@@ -3016,6 +3974,8 @@ export const useProjectStore = create<ProjectState>()(
actionExecutor: newExecutor,
clipUndoStack: [],
clipRedoStack: [],
+ templateUndoStack: [],
+ templateRedoStack: [],
error: null,
});
@@ -3054,6 +4014,144 @@ export const useProjectStore = create<ProjectState>()(
};
},
+ getEditingTemplates: () => [...getBuiltInEditingTemplates()],
+
+ getEditingTemplate: (templateId: string) =>
+ getBuiltInEditingTemplate(templateId),
+
+ applyEditingTemplate: (
+ templateId: string,
+ clipId: string,
+ overrides: Record<string, EditingTemplatePrimitive> = {},
+ ) => {
+ const { project, templateUndoStack } = get();
+ const applied = applyEditingTemplateApplicationToProject(
+ project,
+ templateId,
+ clipId,
+ overrides,
+ );
+
+ if (!applied) {
+ return null;
+ }
+
+ const historyEntry: EditingTemplateHistoryEntry = {
+ type: "editing-template",
+ mode: "apply",
+ timestamp: Date.now(),
+ description: `Apply ${applied.applicationState.appliedTemplate.name}`,
+ ...applied.applicationState,
+ };
+
+ set({
+ project: applied.project,
+ templateUndoStack: [...templateUndoStack, historyEntry],
+ templateRedoStack: [],
+ });
+
+ return applied.applicationState.applicationId;
+ },
+
+ updateEditingTemplateApplication: (
+ clipId: string,
+ applicationId: string,
+ overrides: Record<string, EditingTemplatePrimitive> = {},
+ ) => {
+ const { project, templateUndoStack } = get();
+ const matchingEntry = findEditingTemplateHistoryEntry(clipId, applicationId);
+ if (!matchingEntry) {
+ return false;
+ }
+
+ const previousState = getEditingTemplateApplicationState(matchingEntry);
+ const projectWithoutCurrent = removeEditingTemplateApplicationStateFromProject(
+ project,
+ previousState,
+ false,
+ );
+ const updated = applyEditingTemplateApplicationToProject(
+ projectWithoutCurrent,
+ previousState.templateId,
+ clipId,
+ overrides,
+ {
+ applicationId,
+ appliedAt: previousState.appliedTemplate.appliedAt,
+ preferredTrackIds: getEditingTemplatePreferredTrackIds(previousState),
+ preservedTrackSnapshots: previousState.trackSnapshots,
+ },
+ );
+
+ if (!updated) {
+ const restoredProject = restoreEditingTemplateApplicationState(
+ projectWithoutCurrent,
+ previousState,
+ );
+
+ if (restoredProject) {
+ set({ project: restoredProject });
+ }
+
+ return false;
+ }
+
+ const historyEntry: EditingTemplateHistoryEntry = {
+ type: "editing-template",
+ mode: "update",
+ timestamp: Date.now(),
+ description: `Update ${updated.applicationState.appliedTemplate.name}`,
+ previousState,
+ ...updated.applicationState,
+ };
+
+ set({
+ project: updated.project,
+ templateUndoStack: [...templateUndoStack, historyEntry],
+ templateRedoStack: [],
+ });
+
+ return true;
+ },
+
+ removeEditingTemplateApplication: (
+ clipId: string,
+ applicationId: string,
+ ) => {
+ const {
+ project,
+ templateUndoStack,
+ templateRedoStack,
+ } = get();
+
+ if (!hasEditingTemplateArtifacts(project, clipId, applicationId)) {
+ return false;
+ }
+
+ const matchingEntry = findEditingTemplateHistoryEntry(clipId, applicationId);
+
+ const updatedProject = removeEditingTemplateApplicationFromProject(
+ project,
+ clipId,
+ applicationId,
+ matchingEntry?.trackSnapshots.map((snapshot) => snapshot.track.id) || [],
+ );
+
+ set({
+ project: updatedProject,
+ templateUndoStack: templateUndoStack.filter(
+ (entry) =>
+ !(entry.ownerClipId === clipId && entry.applicationId === applicationId),
+ ),
+ templateRedoStack: templateRedoStack.filter(
+ (entry) =>
+ !(entry.ownerClipId === clipId && entry.applicationId === applicationId),
+ ),
+ });
+
+ return true;
+ },
+
// Text clip actions
/**
@@ -3093,6 +4191,7 @@ export const useProjectStore = create<ProjectState>()(
const { clipUndoStack } = get();
const historyEntry: ClipHistoryEntry = {
type: "text",
+ timestamp: Date.now(),
clipId: textClip.id,
trackId,
clipData: { ...textClip }, // Store full clip data for redo reconstruction
@@ -3557,6 +4656,7 @@ export const useProjectStore = create<ProjectState>()(
const { clipUndoStack } = get();
const historyEntry: ClipHistoryEntry = {
type: "shape",
+ timestamp: Date.now(),
clipId: shapeClip.id,
trackId,
clipData: { ...shapeClip }, // Store full clip data for redo reconstruction
@@ -3704,6 +4804,7 @@ export const useProjectStore = create<ProjectState>()(
const { clipUndoStack } = get();
const historyEntry: ClipHistoryEntry = {
type: "svg",
+ timestamp: Date.now(),
clipId: svgClip.id,
trackId,
clipData: { ...svgClip }, // Store full SVG clip including svgContent for redo
diff --git a/apps/web/src/stores/project/types.ts b/apps/web/src/stores/project/types.ts
index 42deb61a..bb65d186 100644
--- a/apps/web/src/stores/project/types.ts
+++ b/apps/web/src/stores/project/types.ts
@@ -24,6 +24,10 @@ import type {
Keyframe,
Transform,
Subtitle,
+ AppliedEditingTemplate,
+ EditingTemplate,
+ EditingTemplatePrimitive,
+ ResolvedEditingTemplateOverlay,
} from "@openreel/core";
import { ActionExecutor, ActionHistory } from "@openreel/core";
import type {
@@ -37,6 +41,7 @@ export type ClipHistoryEntryType = "shape" | "text" | "svg" | "sticker";
export interface ClipHistoryEntry {
type: ClipHistoryEntryType;
+ timestamp: number;
clipId: string;
trackId: string;
clipData: ShapeClip | TextClip | SVGClip | StickerClip;
@@ -44,6 +49,37 @@ export interface ClipHistoryEntry {
trackType?: "video" | "audio" | "image" | "text" | "graphics";
}
+export interface EditingTemplateTrackSnapshot {
+ track: Track;
+ position: number;
+}
+
+export interface EditingTemplateOverlayPlacement {
+ trackId: string;
+ overlay: ResolvedEditingTemplateOverlay;
+}
+
+export interface EditingTemplateApplicationState {
+ ownerClipId: string;
+ templateId: string;
+ applicationId: string;
+ appliedTemplate: AppliedEditingTemplate;
+ addedEffects: Effect[];
+ addedAudioEffects: Effect[];
+ addedKeyframes: Keyframe[];
+ overlays: EditingTemplateOverlayPlacement[];
+ trackSnapshots: EditingTemplateTrackSnapshot[];
+}
+
+export interface EditingTemplateHistoryEntry
+ extends EditingTemplateApplicationState {
+ type: "editing-template";
+ mode: "apply" | "update";
+ timestamp: number;
+ description: string;
+ previousState?: EditingTemplateApplicationState;
+}
+
export interface ProjectState {
project: Project;
photoProjects: Map<string, PhotoProject>;
@@ -51,6 +87,8 @@ export interface ProjectState {
actionHistory: ActionHistory;
clipUndoStack: ClipHistoryEntry[];
clipRedoStack: ClipHistoryEntry[];
+ templateUndoStack: EditingTemplateHistoryEntry[];
+ templateRedoStack: EditingTemplateHistoryEntry[];
isLoading: boolean;
error: string | null;
clipboard: Clip[];
@@ -134,6 +172,23 @@ export interface ProjectState {
copyEffects: (clipId: string) => void;
pasteEffects: (clipId: string) => Promise<ActionResult>;
+ getEditingTemplates: () => EditingTemplate[];
+ getEditingTemplate: (templateId: string) => EditingTemplate | undefined;
+ applyEditingTemplate: (
+ templateId: string,
+ clipId: string,
+ overrides?: Record<string, EditingTemplatePrimitive>,
+ ) => string | null;
+ updateEditingTemplateApplication: (
+ clipId: string,
+ applicationId: string,
+ overrides?: Record<string, EditingTemplatePrimitive>,
+ ) => boolean;
+ removeEditingTemplateApplication: (
+ clipId: string,
+ applicationId: string,
+ ) => boolean;
+
createTextClip: (
trackId: string,
startTime: number,
diff --git a/packages/core/src/editing-templates/built-in-templates.ts b/packages/core/src/editing-templates/built-in-templates.ts
new file mode 100644
index 00000000..72a09982
--- /dev/null
+++ b/packages/core/src/editing-templates/built-in-templates.ts
@@ -0,0 +1,1023 @@
+import type {
+ EditingTemplate,
+ EditingTemplateBinding,
+ EditingTemplateOverlay,
+ EditingTemplateTransform,
+} from "./types";
+
+const full = "full" as const;
+
+const bind = (controlId: string): EditingTemplateBinding => ({ controlId });
+
+const transform = (
+ x: number,
+ y: number,
+ scaleX: number = 1,
+ scaleY: number = 1,
+ rotation: number = 0,
+ anchorX: number = 0.5,
+ anchorY: number = 0.5,
+): EditingTemplateTransform => ({
+ position: { x, y },
+ scale: { x: scaleX, y: scaleY },
+ rotation,
+ anchor: { x: anchorX, y: anchorY },
+ opacity: 1,
+});
+
+const textOverlay = (overlay: EditingTemplate["recipe"]["overlays"][number]): EditingTemplateOverlay => overlay;
+
+const shapeOverlay = (overlay: EditingTemplate["recipe"]["overlays"][number]): EditingTemplateOverlay => overlay;
+
+export const BUILT_IN_EDITING_TEMPLATES: readonly EditingTemplate[] = [
+ {
+ id: "cinema-letterbox",
+ name: "Cinematic Letterbox",
+ description: "Wide-screen bars with grain and vignette.",
+ category: "cinema",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["cinema", "letterbox", "grain"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "grainAmount", label: "Grain", type: "number", defaultValue: 0.3, min: 0, max: 1, step: 0.05 },
+ { id: "barOpacity", label: "Bar Opacity", type: "number", defaultValue: 1, min: 0, max: 1, step: 0.05 },
+ ],
+ recipe: {
+ effects: [
+ { type: "film-grain", params: { intensity: bind("grainAmount"), size: 1.5 } },
+ { type: "vignette", params: { intensity: 0.4, radius: 0.8 } },
+ ],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.05),
+ content: {
+ shapeType: "rectangle",
+ width: 1920,
+ height: 120,
+ style: { fill: { type: "solid", color: "#000000", opacity: bind("barOpacity") }, stroke: { color: "#000000", width: 0, opacity: 0 } },
+ },
+ }),
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.95),
+ content: {
+ shapeType: "rectangle",
+ width: 1920,
+ height: 120,
+ style: { fill: { type: "solid", color: "#000000", opacity: bind("barOpacity") }, stroke: { color: "#000000", width: 0, opacity: 0 } },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "cinema-light-frame",
+ name: "Light Frame",
+ description: "A subtle warm edge frame for cinematic shots.",
+ category: "cinema",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["cinema", "frame", "warm"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "frameOpacity", label: "Frame Opacity", type: "number", defaultValue: 0.22, min: 0, max: 0.8, step: 0.02 },
+ ],
+ recipe: {
+ effects: [
+ { type: "contrast", params: { value: 0.08 } },
+ { type: "brightness", params: { value: 0.03 } },
+ ],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ blendOpacity: bind("frameOpacity"),
+ content: {
+ shapeType: "rectangle",
+ width: 1820,
+ height: 980,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "#f8c89a", width: 8, opacity: 1 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "cinema-warm-fade",
+ name: "Warm Fade",
+ description: "Soft warm grade for lifestyle and travel cuts.",
+ category: "cinema",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["cinema", "warm", "travel"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "warmth", label: "Warmth", type: "number", defaultValue: 0.14, min: 0, max: 0.4, step: 0.01 },
+ ],
+ recipe: {
+ effects: [
+ { type: "brightness", params: { value: 0.02 } },
+ { type: "contrast", params: { value: 0.1 } },
+ { type: "saturation", params: { value: bind("warmth") } },
+ ],
+ overlays: [],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "glitch-digital",
+ name: "Digital Glitch",
+ description: "RGB drift with moving scanline accents.",
+ category: "glitch",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["glitch", "rgb", "scanline"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "glitchAmount", label: "Glitch", type: "number", defaultValue: 0.18, min: 0, max: 0.6, step: 0.02 },
+ ],
+ recipe: {
+ effects: [
+ { type: "chromatic-aberration", params: { intensity: 4 } },
+ { type: "film-grain", params: { intensity: bind("glitchAmount"), size: 2 } },
+ ],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.2),
+ keyframes: [
+ { time: 0, property: "position.y", value: 0.18 },
+ { time: 0.4, property: "position.y", value: 0.74 },
+ { time: 0.8, property: "position.y", value: 0.32 },
+ { time: 1, property: "position.y", value: 0.86 },
+ ],
+ content: {
+ shapeType: "rectangle",
+ width: 1920,
+ height: 32,
+ style: {
+ fill: { type: "solid", color: "rgba(0,255,255,0.12)", opacity: 1 },
+ stroke: { color: "rgba(0,255,255,0.12)", width: 0, opacity: 0 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "glitch-rgb-scan",
+ name: "RGB Scan",
+ description: "Thin scanlines and channel separation.",
+ category: "glitch",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["glitch", "scan", "rgb"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "chromatic-aberration", params: { intensity: 6 } },
+ { type: "contrast", params: { value: 0.08 } },
+ ],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ content: {
+ shapeType: "rectangle",
+ width: 1920,
+ height: 1020,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "rgba(255,0,128,0.25)", width: 2, opacity: 1 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "glitch-static-frame",
+ name: "Static Frame",
+ description: "Noisy border treatment with light distortion.",
+ category: "glitch",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["glitch", "static", "noise"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "film-grain", params: { intensity: 0.45, size: 2.3 } },
+ { type: "contrast", params: { value: 0.15 } },
+ ],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ content: {
+ shapeType: "rectangle",
+ width: 1860,
+ height: 1020,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "rgba(255,255,255,0.18)", width: 12, opacity: 1 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "retro-vhs",
+ name: "VHS Tape",
+ description: "Classic tape softness with transport text.",
+ category: "retro",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["retro", "vhs", "tape"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "chromatic-aberration", params: { intensity: 3 } },
+ { type: "film-grain", params: { intensity: 0.6, size: 2.5 } },
+ { type: "blur", params: { radius: 0.5 } },
+ { type: "vignette", params: { intensity: 0.45, radius: 0.7 } },
+ ],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: full,
+ transform: transform(0.08, 0.9, 1, 1, 0, 0, 0.5),
+ content: {
+ text: "PLAY >",
+ style: { fontFamily: "JetBrains Mono", fontSize: 28, color: "rgba(255,255,255,0.85)", fontWeight: 600, textAlign: "left", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 1 },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: full,
+ transform: transform(0.92, 0.9, 1, 1, 0, 1, 0.5),
+ content: {
+ text: "SP",
+ style: { fontFamily: "JetBrains Mono", fontSize: 22, color: "rgba(255,255,255,0.65)", fontWeight: 600, textAlign: "right", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 1 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "retro-crt-monitor",
+ name: "CRT Monitor",
+ description: "Soft corner frame and green terminal vibe.",
+ category: "retro",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["retro", "crt", "monitor"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "contrast", params: { value: 0.12 } },
+ { type: "brightness", params: { value: -0.04 } },
+ ],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ content: {
+ shapeType: "rectangle",
+ width: 1840,
+ height: 1000,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "rgba(105,255,173,0.25)", width: 6, opacity: 1 },
+ cornerRadius: 18,
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "retro-old-film",
+ name: "Old Film",
+ description: "High grain monochrome with gate marker text.",
+ category: "retro",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["retro", "film", "mono"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "film-grain", params: { intensity: 0.75, size: 2.8 } },
+ { type: "contrast", params: { value: 0.22 } },
+ { type: "brightness", params: { value: -0.08 } },
+ ],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 1.2 },
+ transform: transform(0.08, 0.08, 1, 1, 0, 0, 0.5),
+ content: {
+ text: "ROLL 04",
+ style: { fontFamily: "JetBrains Mono", fontSize: 22, color: "rgba(255,255,255,0.8)", fontWeight: 600, textAlign: "left", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 1 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "retro-sepia-drift",
+ name: "Sepia Drift",
+ description: "Subtle vintage warmth with a soft border.",
+ category: "retro",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["retro", "sepia", "vintage"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "brightness", params: { value: 0.04 } },
+ { type: "contrast", params: { value: 0.06 } },
+ { type: "saturation", params: { value: -0.08 } },
+ ],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ blendOpacity: 0.3,
+ content: {
+ shapeType: "rectangle",
+ width: 1860,
+ height: 1020,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "#7d5b39", width: 10, opacity: 1 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "social-recording",
+ name: "Recording Camera",
+ description: "Classic REC indicator, timer, and frame border.",
+ category: "social",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["social", "rec", "recording"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.06, 0.06),
+ emphasisAnimation: { type: "pulse", speed: 1, intensity: 0.55, loop: true },
+ content: {
+ shapeType: "circle",
+ width: 28,
+ height: 28,
+ style: {
+ fill: { type: "solid", color: "#ff4d4d", opacity: 1 },
+ stroke: { color: "#ff4d4d", width: 0, opacity: 0 },
+ },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: full,
+ transform: transform(0.1, 0.06, 1, 1, 0, 0, 0.5),
+ content: {
+ text: "REC",
+ style: { fontFamily: "Inter", fontSize: 20, color: "#ff4d4d", fontWeight: 700, textAlign: "left", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 1 },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: full,
+ transform: transform(0.94, 0.06, 1, 1, 0, 1, 0.5),
+ content: {
+ text: "00:00:00",
+ style: { fontFamily: "JetBrains Mono", fontSize: 18, color: "rgba(255,255,255,0.85)", fontWeight: 600, textAlign: "right", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 1 },
+ },
+ }),
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ content: {
+ shapeType: "rectangle",
+ width: 1760,
+ height: 920,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "rgba(255,255,255,0.32)", width: 4, opacity: 1 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "social-facecam-frame",
+ name: "Facecam Frame",
+ description: "Corner frame for reaction and gameplay clips.",
+ category: "social",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["social", "facecam", "reaction"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.78, 0.76),
+ content: {
+ shapeType: "rectangle",
+ width: 560,
+ height: 320,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "rgba(255,255,255,0.9)", width: 6, opacity: 1 },
+ cornerRadius: 22,
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "social-countdown-lead",
+ name: "Countdown Lead",
+ description: "Short intro count-in for tutorials and hooks.",
+ category: "social",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["social", "countdown", "hook"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 2 },
+ transform: transform(0.5, 0.18),
+ keyframes: [
+ { time: 0, property: "opacity", value: 0 },
+ { time: 0.2, property: "opacity", value: 1 },
+ { time: 0.8, property: "opacity", value: 1 },
+ { time: 1, property: "opacity", value: 0 },
+ ],
+ content: {
+ text: "3 2 1",
+ style: { fontFamily: "Inter", fontSize: 82, color: "#ffffff", fontWeight: 800, textAlign: "center", verticalAlign: "middle", lineHeight: 1, letterSpacing: 8 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "social-comment-pop",
+ name: "Comment Pop",
+ description: "Pinned comment bubble for social callouts.",
+ category: "social",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["social", "comment", "bubble"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: { kind: "intro", duration: 3 },
+ transform: transform(0.5, 0.15),
+ content: {
+ shapeType: "rectangle",
+ width: 1080,
+ height: 140,
+ style: {
+ fill: { type: "solid", color: "rgba(255,255,255,0.92)", opacity: 1 },
+ stroke: { color: "rgba(0,0,0,0.08)", width: 2, opacity: 1 },
+ cornerRadius: 999,
+ },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 3 },
+ transform: transform(0.5, 0.15),
+ content: {
+ text: "Pinned: Drop your best take below",
+ style: { fontFamily: "Inter", fontSize: 30, color: "#111111", fontWeight: 700, textAlign: "center", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 0 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "branding-watermark-drift",
+ name: "Watermark Drift",
+ description: "Soft moving corner watermark for brand protection.",
+ category: "branding",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["branding", "watermark", "corner"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "watermarkText", label: "Watermark", type: "text", defaultValue: "@openreel" },
+ { id: "watermarkOpacity", label: "Opacity", type: "number", defaultValue: 0.45, min: 0.1, max: 1, step: 0.05 },
+ ],
+ recipe: {
+ effects: [],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: full,
+ transform: transform(0.88, 0.92, 1, 1, 0, 1, 0.5),
+ keyframes: [
+ { time: 0, property: "position.x", value: 0.88 },
+ { time: 0.5, property: "position.x", value: 0.84 },
+ { time: 1, property: "position.x", value: 0.88 },
+ ],
+ blendOpacity: bind("watermarkOpacity"),
+ content: {
+ text: "{control.watermarkText}",
+ style: { fontFamily: "Inter", fontSize: 22, color: "rgba(255,255,255,0.92)", fontWeight: 600, textAlign: "right", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 0.5 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "branding-copyright",
+ name: "Moving Copyright",
+ description: "Full-width copyright crawl for delivered cuts.",
+ category: "branding",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["branding", "copyright", "crawl"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: full,
+ transform: transform(0.5, 0.95),
+ keyframes: [
+ { time: 0, property: "position.x", value: 1.2 },
+ { time: 0.1, property: "position.x", value: 0.5 },
+ { time: 0.9, property: "position.x", value: 0.5 },
+ { time: 1, property: "position.x", value: -0.2 },
+ ],
+ content: {
+ text: "Copyright {year} All Rights Reserved",
+ style: { fontFamily: "Inter", fontSize: 18, color: "rgba(255,255,255,0.7)", fontWeight: 500, textAlign: "center", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 0.5 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "branding-lower-third",
+ name: "Lower Third",
+ description: "Simple branded name tag.",
+ category: "branding",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["branding", "lower third", "name"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "name", label: "Name", type: "text", defaultValue: "Open Reel" },
+ { id: "role", label: "Role", type: "text", defaultValue: "Creator" },
+ { id: "accent", label: "Accent", type: "color", defaultValue: "#7bf1a8" },
+ ],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: { kind: "intro", duration: 4 },
+ transform: transform(0.18, 0.88, 1, 1, 0, 0, 0.5),
+ content: {
+ shapeType: "rectangle",
+ width: 520,
+ height: 124,
+ style: {
+ fill: { type: "solid", color: "rgba(7,7,10,0.76)", opacity: 1 },
+ stroke: { color: bind("accent"), width: 4, opacity: 1 },
+ cornerRadius: 18,
+ },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 4 },
+ transform: transform(0.11, 0.865, 1, 1, 0, 0, 0.5),
+ content: {
+ text: "{control.name}",
+ style: { fontFamily: "Inter", fontSize: 34, color: "#ffffff", fontWeight: 800, textAlign: "left", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 0 },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 4 },
+ transform: transform(0.11, 0.905, 1, 1, 0, 0, 0.5),
+ content: {
+ text: "{control.role}",
+ style: { fontFamily: "Inter", fontSize: 22, color: "rgba(255,255,255,0.72)", fontWeight: 500, textAlign: "left", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 0 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "branding-subscribe-tag",
+ name: "Subscribe Tag",
+ description: "End-card subscribe banner.",
+ category: "branding",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["branding", "subscribe", "end card"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: { kind: "outro", duration: 3.5 },
+ transform: transform(0.5, 0.88),
+ content: {
+ shapeType: "rectangle",
+ width: 760,
+ height: 110,
+ style: {
+ fill: { type: "solid", color: "#ff3b30", opacity: 1 },
+ stroke: { color: "#ff3b30", width: 0, opacity: 0 },
+ cornerRadius: 999,
+ },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "outro", duration: 3.5 },
+ transform: transform(0.5, 0.88),
+ content: {
+ text: "Subscribe for the next drop",
+ style: { fontFamily: "Inter", fontSize: 28, color: "#ffffff", fontWeight: 800, textAlign: "center", verticalAlign: "middle", lineHeight: 1.1, letterSpacing: 0.5 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "color-warm-pop",
+ name: "Warm Pop",
+ description: "Golden warmth with gentle contrast.",
+ category: "color",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["color", "warm", "pop"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "brightness", params: { value: 0.05 } },
+ { type: "contrast", params: { value: 0.12 } },
+ { type: "saturation", params: { value: 0.14 } },
+ ],
+ overlays: [],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "color-cool-bloom",
+ name: "Cool Bloom",
+ description: "Softer cooler palette for night and tech footage.",
+ category: "color",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["color", "cool", "tech"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "brightness", params: { value: -0.02 } },
+ { type: "contrast", params: { value: 0.08 } },
+ { type: "saturation", params: { value: -0.08 } },
+ ],
+ overlays: [],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "color-dramatic-noir",
+ name: "Dramatic Noir",
+ description: "High-contrast moody look.",
+ category: "color",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["color", "dramatic", "noir"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "contrast", params: { value: 0.2 } },
+ { type: "brightness", params: { value: -0.08 } },
+ { type: "vignette", params: { intensity: 0.55, radius: 0.72 } },
+ ],
+ overlays: [],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "color-vintage-wash",
+ name: "Vintage Wash",
+ description: "Low-contrast faded stock feel.",
+ category: "color",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["color", "vintage", "fade"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [
+ { type: "brightness", params: { value: 0.08 } },
+ { type: "contrast", params: { value: -0.05 } },
+ { type: "saturation", params: { value: -0.12 } },
+ ],
+ overlays: [],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "overlay-focus-frame",
+ name: "Focus Frame",
+ description: "Center guide frame with crosshair accents.",
+ category: "overlay",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["overlay", "focus", "frame"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ content: {
+ shapeType: "rectangle",
+ width: 1360,
+ height: 760,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "rgba(255,255,255,0.4)", width: 4, opacity: 1 },
+ },
+ },
+ }),
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ content: {
+ shapeType: "line",
+ width: 120,
+ height: 6,
+ style: {
+ fill: { type: "solid", color: "rgba(255,255,255,0.55)", opacity: 1 },
+ stroke: { color: "rgba(255,255,255,0.55)", width: 0, opacity: 0 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "overlay-soft-border",
+ name: "Soft Border",
+ description: "Thin elegant border for editorial framing.",
+ category: "overlay",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["overlay", "border", "editorial"],
+ supportedTargets: ["video", "image"],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: full,
+ transform: transform(0.5, 0.5),
+ content: {
+ shapeType: "rectangle",
+ width: 1840,
+ height: 1000,
+ style: {
+ fill: { type: "none", opacity: 0 },
+ stroke: { color: "rgba(255,255,255,0.24)", width: 5, opacity: 1 },
+ },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "overlay-spotlight-title",
+ name: "Spotlight Title",
+ description: "Headline treatment for hero moments.",
+ category: "text-effects",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["text", "headline", "hero"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "headline", label: "Headline", type: "text", defaultValue: "Headline" },
+ ],
+ recipe: {
+ effects: [],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 4 },
+ transform: transform(0.5, 0.18),
+ content: {
+ text: "{control.headline}",
+ style: { fontFamily: "Inter", fontSize: 88, color: "#ffffff", fontWeight: 800, textAlign: "center", verticalAlign: "middle", lineHeight: 0.95, letterSpacing: -1 },
+ animation: { preset: "slide-up", inDuration: 0.45, outDuration: 0.35, params: { easing: "easeOutCubic" } },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "text-kinetic-punch",
+ name: "Kinetic Punch",
+ description: "Bold text punch-in for transitions and hooks.",
+ category: "text-effects",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["text", "kinetic", "hook"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "caption", label: "Caption", type: "text", defaultValue: "Watch this" },
+ { id: "accent", label: "Accent", type: "color", defaultValue: "#ffb100" },
+ ],
+ recipe: {
+ effects: [],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 3 },
+ transform: transform(0.5, 0.82),
+ emphasisAnimation: { type: "bounce", speed: 1, intensity: 0.5, loop: true },
+ content: {
+ text: "{control.caption}",
+ style: { fontFamily: "Inter", fontSize: 56, color: bind("accent"), fontWeight: 900, textAlign: "center", verticalAlign: "middle", lineHeight: 1, letterSpacing: 0 },
+ animation: { preset: "pop", inDuration: 0.3, outDuration: 0.25, params: { easing: "easeOutBack" } },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "text-stamp-upper",
+ name: "Stamp Upper",
+ description: "Upper-third stamp for chapter labels.",
+ category: "text-effects",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["text", "stamp", "chapter"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "label", label: "Label", type: "text", defaultValue: "Chapter One" },
+ ],
+ recipe: {
+ effects: [],
+ overlays: [
+ shapeOverlay({
+ type: "shape",
+ trackType: "graphics",
+ timing: { kind: "intro", duration: 3.5 },
+ transform: transform(0.5, 0.12),
+ content: {
+ shapeType: "rectangle",
+ width: 720,
+ height: 92,
+ style: {
+ fill: { type: "solid", color: "rgba(255,255,255,0.08)", opacity: 1 },
+ stroke: { color: "rgba(255,255,255,0.42)", width: 2, opacity: 1 },
+ cornerRadius: 999,
+ },
+ },
+ }),
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: { kind: "intro", duration: 3.5 },
+ transform: transform(0.5, 0.12),
+ content: {
+ text: "{control.label}",
+ style: { fontFamily: "Inter", fontSize: 32, color: "#ffffff", fontWeight: 700, textAlign: "center", verticalAlign: "middle", lineHeight: 1, letterSpacing: 2 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+ {
+ id: "text-neon-tag",
+ name: "Neon Tag",
+ description: "Bright tag for music and nightlife content.",
+ category: "text-effects",
+ thumbnailUrl: null,
+ previewUrl: null,
+ tags: ["text", "neon", "music"],
+ supportedTargets: ["video", "image"],
+ controls: [
+ { id: "tag", label: "Tag", type: "text", defaultValue: "LIVE SET" },
+ ],
+ recipe: {
+ effects: [],
+ overlays: [
+ textOverlay({
+ type: "text",
+ trackType: "text",
+ timing: full,
+ transform: transform(0.13, 0.14, 1, 1, 0, 0, 0.5),
+ emphasisAnimation: { type: "glow", speed: 1, intensity: 0.6, loop: true },
+ content: {
+ text: "{control.tag}",
+ style: { fontFamily: "Inter", fontSize: 34, color: "#66f7ff", fontWeight: 800, textAlign: "left", verticalAlign: "middle", lineHeight: 1, letterSpacing: 1 },
+ },
+ }),
+ ],
+ audioEffects: [],
+ },
+ },
+] as const;
\ No newline at end of file
diff --git a/packages/core/src/editing-templates/categories.ts b/packages/core/src/editing-templates/categories.ts
new file mode 100644
index 00000000..61e17659
--- /dev/null
+++ b/packages/core/src/editing-templates/categories.ts
@@ -0,0 +1,58 @@
+import type { EditingTemplateCategoryDefinition } from "./types";
+
+export const EDITING_TEMPLATE_CATEGORIES: readonly EditingTemplateCategoryDefinition[] = [
+ {
+ id: "cinema",
+ name: "Cinema",
+ description: "Letterbox, grain, and dramatic finishing touches.",
+ icon: "clapperboard",
+ },
+ {
+ id: "glitch",
+ name: "Glitch",
+ description: "Digital breakup, scanlines, and signal drift.",
+ icon: "zap",
+ },
+ {
+ id: "retro",
+ name: "Retro",
+ description: "Tape, CRT, and old-film inspired looks.",
+ icon: "tv",
+ },
+ {
+ id: "social",
+ name: "Social",
+ description: "Recording overlays, countdowns, and creator framing.",
+ icon: "smartphone",
+ },
+ {
+ id: "branding",
+ name: "Branding",
+ description: "Watermarks, lower thirds, and copyright overlays.",
+ icon: "badge",
+ },
+ {
+ id: "color",
+ name: "Color",
+ description: "Fast mood changes through stacked correction presets.",
+ icon: "palette",
+ },
+ {
+ id: "overlay",
+ name: "Overlay",
+ description: "Frames, focus markers, and atmospheric graphic layers.",
+ icon: "layers",
+ },
+ {
+ id: "text-effects",
+ name: "Text Effects",
+ description: "Stylized motion captions and title accents.",
+ icon: "type",
+ },
+ {
+ id: "transitions",
+ name: "Transitions",
+ description: "Reserved for clip-to-clip recipe transitions.",
+ icon: "shuffle",
+ },
+] as const;
\ No newline at end of file
diff --git a/packages/core/src/editing-templates/index.ts b/packages/core/src/editing-templates/index.ts
new file mode 100644
index 00000000..b09d7535
--- /dev/null
+++ b/packages/core/src/editing-templates/index.ts
@@ -0,0 +1,5 @@
+export * from "./types";
+export * from "./categories";
+export * from "./built-in-templates";
+export * from "./registry";
+export * from "./resolver";
\ No newline at end of file
diff --git a/packages/core/src/editing-templates/registry.ts b/packages/core/src/editing-templates/registry.ts
new file mode 100644
index 00000000..1aa895b2
--- /dev/null
+++ b/packages/core/src/editing-templates/registry.ts
@@ -0,0 +1,24 @@
+import { BUILT_IN_EDITING_TEMPLATES } from "./built-in-templates";
+import type { EditingTemplate, EditingTemplateCategory } from "./types";
+
+const builtInTemplateMap = new Map(
+ BUILT_IN_EDITING_TEMPLATES.map((template) => [template.id, template]),
+);
+
+export function getBuiltInEditingTemplates(): readonly EditingTemplate[] {
+ return BUILT_IN_EDITING_TEMPLATES;
+}
+
+export function getBuiltInEditingTemplate(
+ templateId: string,
+): EditingTemplate | undefined {
+ return builtInTemplateMap.get(templateId);
+}
+
+export function getBuiltInEditingTemplatesByCategory(
+ category: EditingTemplateCategory,
+): readonly EditingTemplate[] {
+ return BUILT_IN_EDITING_TEMPLATES.filter(
+ (template) => template.category === category,
+ );
+}
\ No newline at end of file
diff --git a/packages/core/src/editing-templates/resolver.ts b/packages/core/src/editing-templates/resolver.ts
new file mode 100644
index 00000000..cbc34445
--- /dev/null
+++ b/packages/core/src/editing-templates/resolver.ts
@@ -0,0 +1,426 @@
+import type { ShapeStyle } from "../graphics/types";
+import type { TextStyle } from "../text/types";
+import type { Transform } from "../types/timeline";
+import type {
+ EditingTemplate,
+ EditingTemplateBinding,
+ EditingTemplateControlDefinition,
+ EditingTemplateEmphasisAnimation,
+ EditingTemplateKeyframe,
+ EditingTemplatePrimitive,
+ EditingTemplateRangeTiming,
+ EditingTemplateResolutionContext,
+ EditingTemplateTransform,
+ EditingTemplateValue,
+ ResolvedEditingTemplateApplication,
+ ResolvedEditingTemplateEffect,
+ ResolvedEditingTemplateKeyframe,
+ ResolvedEditingTemplateOverlay,
+ ResolvedEditingTemplateTiming,
+} from "./types";
+
+const DEFAULT_TRANSFORM: Transform = {
+ position: { x: 0.5, y: 0.5 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+};
+
+const VARIABLE_PATTERN = /\{([^}]+)\}/g;
+
+export function isEditingTemplateBinding(
+ value: EditingTemplateValue,
+): value is EditingTemplateBinding {
+ return typeof value === "object" && value !== null && "controlId" in value;
+}
+
+export function getEditingTemplateDefaultControlValues(
+ template: EditingTemplate,
+): Record<string, EditingTemplatePrimitive> {
+ return (template.controls || []).reduce<Record<string, EditingTemplatePrimitive>>(
+ (values, control) => {
+ values[control.id] = control.defaultValue;
+ return values;
+ },
+ {},
+ );
+}
+
+export function resolveEditingTemplateControlValues(
+ template: EditingTemplate,
+ overrides: Readonly<Record<string, EditingTemplatePrimitive>> = {},
+): Record<string, EditingTemplatePrimitive> {
+ return {
+ ...getEditingTemplateDefaultControlValues(template),
+ ...overrides,
+ };
+}
+
+export function resolveEditingTemplate(
+ template: EditingTemplate,
+ context: EditingTemplateResolutionContext,
+ overrides: Readonly<Record<string, EditingTemplatePrimitive>> = {},
+): ResolvedEditingTemplateApplication {
+ const controlValues = resolveEditingTemplateControlValues(template, overrides);
+
+ return {
+ template,
+ controlValues,
+ effects: template.recipe.effects.map((effect, index) =>
+ resolveEffect(effect, context, controlValues, index),
+ ),
+ audioEffects: template.recipe.audioEffects.map((effect, index) =>
+ resolveEffect(effect, context, controlValues, index),
+ ),
+ overlays: template.recipe.overlays.map((overlay, index) =>
+ resolveOverlay(overlay, context, controlValues, index),
+ ),
+ };
+}
+
+export function resolveTemplateVariables(
+ value: string,
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+): string {
+ const now = context.now ?? new Date();
+ const variableMap: Record<string, string> = {
+ year: `${now.getFullYear()}`,
+ date: now.toISOString().slice(0, 10),
+ datetime: now.toISOString(),
+ duration: `${context.clip.duration}`,
+ "clip.id": context.clip.id,
+ "clip.name": context.clip.name ?? "Clip",
+ };
+
+ return value.replace(VARIABLE_PATTERN, (_match, token) => {
+ if (token.startsWith("control.")) {
+ const controlId = token.slice("control.".length);
+ return `${controlValues[controlId] ?? ""}`;
+ }
+
+ return variableMap[token] ?? `{${token}}`;
+ });
+}
+
+export function resolveOverlayTiming(
+ timing: EditingTemplate["recipe"]["overlays"][number]["timing"],
+ context: EditingTemplateResolutionContext,
+): ResolvedEditingTemplateTiming {
+ if (timing === "full") {
+ return {
+ startTime: context.clip.startTime,
+ duration: context.clip.duration,
+ };
+ }
+
+ if (timing.kind === "intro") {
+ const duration = Math.max(0, Math.min(timing.duration, context.clip.duration));
+ return {
+ startTime: context.clip.startTime,
+ duration,
+ };
+ }
+
+ if (timing.kind === "outro") {
+ const duration = Math.max(0, Math.min(timing.duration, context.clip.duration));
+ return {
+ startTime: context.clip.startTime + Math.max(0, context.clip.duration - duration),
+ duration,
+ };
+ }
+
+ return resolveRangeTiming(timing, context);
+}
+
+function resolveRangeTiming(
+ timing: EditingTemplateRangeTiming,
+ context: EditingTemplateResolutionContext,
+): ResolvedEditingTemplateTiming {
+ const startOffset =
+ timing.unit === "fraction"
+ ? timing.start * context.clip.duration
+ : timing.start;
+ const endOffset =
+ timing.unit === "fraction" ? timing.end * context.clip.duration : timing.end;
+ const safeStart = clamp(startOffset, 0, context.clip.duration);
+ const safeEnd = clamp(endOffset, safeStart, context.clip.duration);
+
+ return {
+ startTime: context.clip.startTime + safeStart,
+ duration: safeEnd - safeStart,
+ };
+}
+
+function resolveEffect(
+ effect: EditingTemplate["recipe"]["effects"][number],
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+ index: number,
+): ResolvedEditingTemplateEffect {
+ return {
+ id: effect.id || `${effect.type}-${index + 1}`,
+ type: effect.type,
+ enabled: effect.enabled ?? true,
+ params: resolveRecord(effect.params, context, controlValues),
+ keyframes: resolveEffectKeyframes(
+ effect.keyframes || [],
+ context,
+ controlValues,
+ ),
+ };
+}
+
+function resolveOverlay(
+ overlay: EditingTemplate["recipe"]["overlays"][number],
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+ index: number,
+): ResolvedEditingTemplateOverlay {
+ const timing = resolveOverlayTiming(overlay.timing, context);
+ const resolvedTransform = resolveTransform(overlay.transform, context, controlValues);
+ const blendOpacity =
+ overlay.blendOpacity === undefined
+ ? undefined
+ : toNumber(resolveValue(overlay.blendOpacity, context, controlValues), 1);
+ const emphasisAnimation = resolveEmphasisAnimation(
+ overlay.emphasisAnimation,
+ context,
+ controlValues,
+ );
+ const keyframes = resolveOverlayKeyframes(
+ overlay.keyframes || [],
+ timing.duration,
+ context,
+ controlValues,
+ );
+ const id = overlay.id || `${overlay.type}-${index + 1}`;
+
+ if (overlay.type === "text") {
+ return {
+ id,
+ type: "text",
+ trackType: "text",
+ timing,
+ transform: resolvedTransform,
+ blendMode: overlay.blendMode,
+ blendOpacity,
+ emphasisAnimation,
+ keyframes,
+ content: {
+ text: resolveTemplateVariables(overlay.content.text, context, controlValues),
+ style: resolveRecord(
+ overlay.content.style || {},
+ context,
+ controlValues,
+ ) as Partial<TextStyle>,
+ animation: overlay.content.animation,
+ },
+ };
+ }
+
+ if (overlay.type === "shape") {
+ return {
+ id,
+ type: "shape",
+ trackType: "graphics",
+ timing,
+ transform: resolvedTransform,
+ blendMode: overlay.blendMode,
+ blendOpacity,
+ emphasisAnimation,
+ keyframes,
+ content: {
+ shapeType: overlay.content.shapeType,
+ width: toNumber(resolveValue(overlay.content.width, context, controlValues), 0),
+ height: toNumber(resolveValue(overlay.content.height, context, controlValues), 0),
+ style: resolveRecord(
+ overlay.content.style || {},
+ context,
+ controlValues,
+ ) as Partial<ShapeStyle>,
+ },
+ };
+ }
+
+ return {
+ id,
+ type: "image",
+ trackType: "graphics",
+ timing,
+ transform: resolvedTransform,
+ blendMode: overlay.blendMode,
+ blendOpacity,
+ emphasisAnimation,
+ keyframes,
+ content: {
+ assetId: overlay.content.assetId,
+ imageUrl: overlay.content.imageUrl
+ ? resolveTemplateVariables(overlay.content.imageUrl, context, controlValues)
+ : overlay.content.assetId
+ ? context.assetUrls?.[overlay.content.assetId]
+ : undefined,
+ name: overlay.content.name,
+ },
+ };
+}
+
+function resolveEffectKeyframes(
+ keyframes: readonly EditingTemplateKeyframe[],
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+): readonly ResolvedEditingTemplateKeyframe[] {
+ return keyframes.map((keyframe) => ({
+ time: clamp(keyframe.time, 0, 1) * context.clip.duration,
+ property: keyframe.property.startsWith("effect.")
+ ? keyframe.property
+ : `effect.${keyframe.property}`,
+ value: resolveValue(keyframe.value, context, controlValues),
+ easing: keyframe.easing || "linear",
+ }));
+}
+
+function resolveOverlayKeyframes(
+ keyframes: readonly EditingTemplateKeyframe[],
+ duration: number,
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+): readonly ResolvedEditingTemplateKeyframe[] {
+ return keyframes.map((keyframe) => ({
+ time: clamp(keyframe.time, 0, 1) * duration,
+ property: keyframe.property,
+ value: resolveValue(keyframe.value, context, controlValues),
+ easing: keyframe.easing || "linear",
+ }));
+}
+
+function resolveTransform(
+ transform: EditingTemplateTransform | undefined,
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+): Transform {
+ return {
+ position: {
+ x: toNumber(resolveNestedValue(transform?.position?.x, context, controlValues), DEFAULT_TRANSFORM.position.x),
+ y: toNumber(resolveNestedValue(transform?.position?.y, context, controlValues), DEFAULT_TRANSFORM.position.y),
+ },
+ scale: {
+ x: toNumber(resolveNestedValue(transform?.scale?.x, context, controlValues), DEFAULT_TRANSFORM.scale.x),
+ y: toNumber(resolveNestedValue(transform?.scale?.y, context, controlValues), DEFAULT_TRANSFORM.scale.y),
+ },
+ rotation: toNumber(resolveNestedValue(transform?.rotation, context, controlValues), DEFAULT_TRANSFORM.rotation),
+ anchor: {
+ x: toNumber(resolveNestedValue(transform?.anchor?.x, context, controlValues), DEFAULT_TRANSFORM.anchor.x),
+ y: toNumber(resolveNestedValue(transform?.anchor?.y, context, controlValues), DEFAULT_TRANSFORM.anchor.y),
+ },
+ opacity: toNumber(resolveNestedValue(transform?.opacity, context, controlValues), DEFAULT_TRANSFORM.opacity),
+ };
+}
+
+function resolveEmphasisAnimation(
+ animation: EditingTemplateEmphasisAnimation | undefined,
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+) {
+ if (!animation) {
+ return undefined;
+ }
+
+ return {
+ type: animation.type,
+ speed: toNumber(resolveValue(animation.speed, context, controlValues), 1),
+ intensity: toNumber(resolveValue(animation.intensity, context, controlValues), 1),
+ loop: animation.loop,
+ focusPoint: animation.focusPoint
+ ? {
+ x: toNumber(resolveValue(animation.focusPoint.x, context, controlValues), 0.5),
+ y: toNumber(resolveValue(animation.focusPoint.y, context, controlValues), 0.5),
+ }
+ : undefined,
+ zoomScale:
+ animation.zoomScale === undefined
+ ? undefined
+ : toNumber(resolveValue(animation.zoomScale, context, controlValues), 1),
+ holdDuration:
+ animation.holdDuration === undefined
+ ? undefined
+ : toNumber(resolveValue(animation.holdDuration, context, controlValues), 0),
+ startTime:
+ animation.startTime === undefined
+ ? undefined
+ : toNumber(resolveValue(animation.startTime, context, controlValues), 0),
+ animationDuration:
+ animation.animationDuration === undefined
+ ? undefined
+ : toNumber(
+ resolveValue(animation.animationDuration, context, controlValues),
+ 0,
+ ),
+ };
+}
+
+function resolveRecord(
+ record: Readonly<Record<string, EditingTemplateValue>>,
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+): Record<string, unknown> {
+ return Object.entries(record).reduce<Record<string, unknown>>((resolved, [key, value]) => {
+ resolved[key] = resolveValue(value, context, controlValues);
+ return resolved;
+ }, {});
+}
+
+function resolveNestedValue(
+ value: EditingTemplateValue | undefined,
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+): unknown {
+ if (value === undefined) {
+ return undefined;
+ }
+
+ return resolveValue(value, context, controlValues);
+}
+
+function resolveValue(
+ value: EditingTemplateValue,
+ context: EditingTemplateResolutionContext,
+ controlValues: Readonly<Record<string, EditingTemplatePrimitive>>,
+): unknown {
+ if (typeof value === "string") {
+ return resolveTemplateVariables(value, context, controlValues);
+ }
+
+ if (typeof value === "number" || typeof value === "boolean") {
+ return value;
+ }
+
+ if (Array.isArray(value)) {
+ return value.map((item) => resolveValue(item, context, controlValues));
+ }
+
+ if (isEditingTemplateBinding(value)) {
+ return controlValues[value.controlId];
+ }
+
+ return Object.entries(value).reduce<Record<string, unknown>>((resolved, [key, nestedValue]) => {
+ resolved[key] = resolveValue(nestedValue, context, controlValues);
+ return resolved;
+ }, {});
+}
+
+function toNumber(value: unknown, fallback: number): number {
+ return typeof value === "number" ? value : fallback;
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(Math.max(value, min), max);
+}
+
+export function getEditingTemplateControlDefinition(
+ template: EditingTemplate,
+ controlId: string,
+): EditingTemplateControlDefinition | undefined {
+ return template.controls?.find((control) => control.id === controlId);
+}
\ No newline at end of file
diff --git a/packages/core/src/editing-templates/types.ts b/packages/core/src/editing-templates/types.ts
new file mode 100644
index 00000000..0831b88c
--- /dev/null
+++ b/packages/core/src/editing-templates/types.ts
@@ -0,0 +1,301 @@
+import type { ShapeStyle, ShapeType } from "../graphics/types";
+import type { TextAnimation, TextStyle } from "../text/types";
+import type { LayerEffectType } from "../types/effects";
+import type { Clip, EasingType, Transform } from "../types/timeline";
+import type { BlendMode } from "../video/types";
+
+export type EditingTemplateCategory =
+ | "cinema"
+ | "glitch"
+ | "retro"
+ | "social"
+ | "branding"
+ | "color"
+ | "overlay"
+ | "text-effects"
+ | "transitions";
+
+export type EditingTemplateTargetType = "video" | "image";
+
+export type EditingTemplatePrimitive = number | string | boolean;
+
+export interface EditingTemplateBinding {
+ readonly controlId: string;
+}
+
+export type EditingTemplateValue =
+ | EditingTemplatePrimitive
+ | EditingTemplateBinding
+ | { readonly [key: string]: EditingTemplateValue }
+ | EditingTemplateValue[];
+
+export type EditingTemplateControlType =
+ | "number"
+ | "color"
+ | "text"
+ | "toggle"
+ | "select";
+
+export interface EditingTemplateControlOption {
+ readonly label: string;
+ readonly value: EditingTemplatePrimitive;
+}
+
+export interface EditingTemplateControlDefinition {
+ readonly id: string;
+ readonly label: string;
+ readonly type: EditingTemplateControlType;
+ readonly defaultValue: EditingTemplatePrimitive;
+ readonly min?: number;
+ readonly max?: number;
+ readonly step?: number;
+ readonly options?: readonly EditingTemplateControlOption[];
+}
+
+export interface EditingTemplateKeyframe {
+ readonly time: number;
+ readonly property: string;
+ readonly value: EditingTemplateValue;
+ readonly easing?: EasingType;
+}
+
+export interface EditingTemplateEffect {
+ readonly id?: string;
+ readonly type: LayerEffectType | string;
+ readonly enabled?: boolean;
+ readonly params: Readonly<Record<string, EditingTemplateValue>>;
+ readonly keyframes?: readonly EditingTemplateKeyframe[];
+}
+
+export interface EditingTemplateIntroTiming {
+ readonly kind: "intro";
+ readonly duration: number;
+}
+
+export interface EditingTemplateOutroTiming {
+ readonly kind: "outro";
+ readonly duration: number;
+}
+
+export interface EditingTemplateRangeTiming {
+ readonly kind: "range";
+ readonly start: number;
+ readonly end: number;
+ readonly unit?: "seconds" | "fraction";
+}
+
+export type EditingTemplateTiming =
+ | "full"
+ | EditingTemplateIntroTiming
+ | EditingTemplateOutroTiming
+ | EditingTemplateRangeTiming;
+
+export interface EditingTemplateVector2 {
+ readonly x: EditingTemplateValue;
+ readonly y: EditingTemplateValue;
+}
+
+export interface EditingTemplateTransform {
+ readonly position?: EditingTemplateVector2;
+ readonly scale?: EditingTemplateVector2;
+ readonly rotation?: EditingTemplateValue;
+ readonly anchor?: EditingTemplateVector2;
+ readonly opacity?: EditingTemplateValue;
+}
+
+export interface EditingTemplateTextAnimation {
+ readonly preset: TextAnimation["preset"];
+ readonly inDuration: number;
+ readonly outDuration: number;
+ readonly stagger?: number;
+ readonly unit?: TextAnimation["unit"];
+ readonly params?: Partial<TextAnimation["params"]>;
+}
+
+export interface EditingTemplateEmphasisAnimation {
+ readonly type: "none" | "pulse" | "shake" | "bounce" | "float" | "spin" | "flash" | "heartbeat" | "swing" | "wobble" | "jello" | "rubber-band" | "tada" | "vibrate" | "flicker" | "glow" | "breathe" | "wave" | "tilt" | "zoom-pulse" | "focus-zoom" | "pan-left" | "pan-right" | "pan-up" | "pan-down" | "ken-burns";
+ readonly speed: EditingTemplateValue;
+ readonly intensity: EditingTemplateValue;
+ readonly loop: boolean;
+ readonly focusPoint?: EditingTemplateVector2;
+ readonly zoomScale?: EditingTemplateValue;
+ readonly holdDuration?: EditingTemplateValue;
+ readonly startTime?: EditingTemplateValue;
+ readonly animationDuration?: EditingTemplateValue;
+}
+
+export interface EditingTemplateOverlayBase {
+ readonly id?: string;
+ readonly trackType: "text" | "graphics";
+ readonly timing: EditingTemplateTiming;
+ readonly transform?: EditingTemplateTransform;
+ readonly keyframes?: readonly EditingTemplateKeyframe[];
+ readonly blendMode?: BlendMode;
+ readonly blendOpacity?: EditingTemplateValue;
+ readonly emphasisAnimation?: EditingTemplateEmphasisAnimation;
+}
+
+export interface EditingTemplateTextOverlay extends EditingTemplateOverlayBase {
+ readonly type: "text";
+ readonly trackType: "text";
+ readonly content: {
+ readonly text: string;
+ readonly style?: Readonly<Record<string, EditingTemplateValue>>;
+ readonly animation?: EditingTemplateTextAnimation;
+ };
+}
+
+export interface EditingTemplateShapeOverlay extends EditingTemplateOverlayBase {
+ readonly type: "shape";
+ readonly trackType: "graphics";
+ readonly content: {
+ readonly shapeType: ShapeType;
+ readonly width: EditingTemplateValue;
+ readonly height: EditingTemplateValue;
+ readonly style?: Readonly<Record<string, EditingTemplateValue>>;
+ };
+}
+
+export interface EditingTemplateImageOverlay extends EditingTemplateOverlayBase {
+ readonly type: "image";
+ readonly trackType: "graphics";
+ readonly content: {
+ readonly assetId?: string;
+ readonly imageUrl?: string;
+ readonly name?: string;
+ };
+}
+
+export type EditingTemplateOverlay =
+ | EditingTemplateTextOverlay
+ | EditingTemplateShapeOverlay
+ | EditingTemplateImageOverlay;
+
+export interface EditingTemplateRecipe {
+ readonly effects: readonly EditingTemplateEffect[];
+ readonly overlays: readonly EditingTemplateOverlay[];
+ readonly audioEffects: readonly EditingTemplateEffect[];
+}
+
+export interface EditingTemplate {
+ readonly id: string;
+ readonly name: string;
+ readonly description: string;
+ readonly category: EditingTemplateCategory;
+ readonly thumbnailUrl: string | null;
+ readonly previewUrl?: string | null;
+ readonly tags: readonly string[];
+ readonly supportedTargets?: readonly EditingTemplateTargetType[];
+ readonly controls?: readonly EditingTemplateControlDefinition[];
+ readonly recipe: EditingTemplateRecipe;
+}
+
+export interface EditingTemplateCategoryDefinition {
+ readonly id: EditingTemplateCategory;
+ readonly name: string;
+ readonly description: string;
+ readonly icon: string;
+}
+
+export interface EditingTemplateResolutionContext {
+ readonly clip: Pick<Clip, "id" | "startTime" | "duration"> & {
+ readonly name?: string;
+ };
+ readonly now?: Date;
+ readonly assetUrls?: Readonly<Record<string, string>>;
+}
+
+export interface ResolvedEditingTemplateKeyframe {
+ readonly time: number;
+ readonly property: string;
+ readonly value: unknown;
+ readonly easing: EasingType;
+}
+
+export interface ResolvedEditingTemplateEffect {
+ readonly id: string;
+ readonly type: string;
+ readonly enabled: boolean;
+ readonly params: Record<string, unknown>;
+ readonly keyframes: readonly ResolvedEditingTemplateKeyframe[];
+}
+
+export interface ResolvedEditingTemplateTiming {
+ readonly startTime: number;
+ readonly duration: number;
+}
+
+export interface ResolvedEditingTemplateTextOverlay {
+ readonly id: string;
+ readonly type: "text";
+ readonly trackType: "text";
+ readonly timing: ResolvedEditingTemplateTiming;
+ readonly transform: Transform;
+ readonly blendMode?: BlendMode;
+ readonly blendOpacity?: number;
+ readonly keyframes: readonly ResolvedEditingTemplateKeyframe[];
+ readonly emphasisAnimation?: {
+ readonly type: EditingTemplateEmphasisAnimation["type"];
+ readonly speed: number;
+ readonly intensity: number;
+ readonly loop: boolean;
+ readonly focusPoint?: { x: number; y: number };
+ readonly zoomScale?: number;
+ readonly holdDuration?: number;
+ readonly startTime?: number;
+ readonly animationDuration?: number;
+ };
+ readonly content: {
+ readonly text: string;
+ readonly style: Partial<TextStyle>;
+ readonly animation?: EditingTemplateTextAnimation;
+ };
+}
+
+export interface ResolvedEditingTemplateShapeOverlay {
+ readonly id: string;
+ readonly type: "shape";
+ readonly trackType: "graphics";
+ readonly timing: ResolvedEditingTemplateTiming;
+ readonly transform: Transform;
+ readonly blendMode?: BlendMode;
+ readonly blendOpacity?: number;
+ readonly keyframes: readonly ResolvedEditingTemplateKeyframe[];
+ readonly emphasisAnimation?: ResolvedEditingTemplateTextOverlay["emphasisAnimation"];
+ readonly content: {
+ readonly shapeType: ShapeType;
+ readonly width: number;
+ readonly height: number;
+ readonly style: Partial<ShapeStyle>;
+ };
+}
+
+export interface ResolvedEditingTemplateImageOverlay {
+ readonly id: string;
+ readonly type: "image";
+ readonly trackType: "graphics";
+ readonly timing: ResolvedEditingTemplateTiming;
+ readonly transform: Transform;
+ readonly blendMode?: BlendMode;
+ readonly blendOpacity?: number;
+ readonly keyframes: readonly ResolvedEditingTemplateKeyframe[];
+ readonly emphasisAnimation?: ResolvedEditingTemplateTextOverlay["emphasisAnimation"];
+ readonly content: {
+ readonly assetId?: string;
+ readonly imageUrl?: string;
+ readonly name?: string;
+ };
+}
+
+export type ResolvedEditingTemplateOverlay =
+ | ResolvedEditingTemplateTextOverlay
+ | ResolvedEditingTemplateShapeOverlay
+ | ResolvedEditingTemplateImageOverlay;
+
+export interface ResolvedEditingTemplateApplication {
+ readonly template: EditingTemplate;
+ readonly controlValues: Record<string, EditingTemplatePrimitive>;
+ readonly effects: readonly ResolvedEditingTemplateEffect[];
+ readonly audioEffects: readonly ResolvedEditingTemplateEffect[];
+ readonly overlays: readonly ResolvedEditingTemplateOverlay[];
+}
\ No newline at end of file
diff --git a/packages/core/src/graphics/graphics-engine.ts b/packages/core/src/graphics/graphics-engine.ts
index 7c78ccfe..446a4e72 100644
--- a/packages/core/src/graphics/graphics-engine.ts
+++ b/packages/core/src/graphics/graphics-engine.ts
@@ -19,7 +19,7 @@ import type {
EmphasisAnimation,
} from "./types";
import { DEFAULT_SHAPE_STYLE, DEFAULT_GRAPHIC_TRANSFORM } from "./types";
-import type { Transform, Keyframe } from "../types/timeline";
+import type { Transform, Keyframe, ClipMetadata } from "../types/timeline";
import { AnimationEngine } from "../video/animation-engine";
interface AnimatedGraphicState {
@@ -78,7 +78,7 @@ export class GraphicsEngine {
startTime: number,
duration: number,
): ShapeClip {
- const id = this.generateId();
+ const id = params.id || this.generateId();
const style: ShapeStyle = {
...DEFAULT_SHAPE_STYLE,
...params.style,
@@ -97,6 +97,7 @@ export class GraphicsEngine {
transform: { ...DEFAULT_GRAPHIC_TRANSFORM },
keyframes: [],
points: params.points,
+ metadata: params.metadata,
};
this.shapeClips.set(id, shapeClip);
@@ -265,6 +266,7 @@ export class GraphicsEngine {
startTime?: number;
duration?: number;
transform?: Partial<Transform>;
+ keyframes?: Keyframe[];
blendMode?: import("../video/types").BlendMode;
blendOpacity?: number;
emphasisAnimation?: EmphasisAnimation;
@@ -280,6 +282,7 @@ export class GraphicsEngine {
transform: updates.transform
? { ...existing.transform, ...updates.transform }
: existing.transform,
+ keyframes: updates.keyframes ?? existing.keyframes,
blendMode: updates.blendMode ?? existing.blendMode,
blendOpacity: updates.blendOpacity ?? existing.blendOpacity,
emphasisAnimation:
@@ -322,9 +325,10 @@ export class GraphicsEngine {
trackId: string,
startTime: number,
duration: number,
+ options?: { id?: string; metadata?: ClipMetadata },
): SVGClip {
const parsed = this.parseSVG(svgContent);
- const id = this.generateId();
+ const id = options?.id || this.generateId();
const svgClip: SVGClip = {
id,
@@ -352,6 +356,7 @@ export class GraphicsEngine {
duration: 0.5,
easing: "ease-in",
},
+ metadata: options?.metadata,
};
this.svgClips.set(id, svgClip);
@@ -1793,6 +1798,7 @@ export class GraphicsEngine {
startTime?: number;
duration?: number;
transform?: Partial<Transform>;
+ keyframes?: Keyframe[];
entryAnimation?: GraphicAnimation;
exitAnimation?: GraphicAnimation;
colorStyle?: SVGColorStyle;
@@ -1814,6 +1820,7 @@ export class GraphicsEngine {
transform: updates.transform
? { ...existing.transform, ...updates.transform }
: existing.transform,
+ keyframes: updates.keyframes ?? existing.keyframes,
entryAnimation: updates.entryAnimation ?? existing.entryAnimation,
exitAnimation: updates.exitAnimation ?? existing.exitAnimation,
colorStyle: updates.colorStyle ?? existing.colorStyle,
@@ -1929,6 +1936,7 @@ export class GraphicsEngine {
startTime?: number;
duration?: number;
transform?: Partial<Transform>;
+ keyframes?: Keyframe[];
blendMode?: import("../video/types").BlendMode;
blendOpacity?: number;
emphasisAnimation?: EmphasisAnimation;
@@ -1947,6 +1955,7 @@ export class GraphicsEngine {
transform: updates.transform
? { ...existing.transform, ...updates.transform }
: existing.transform,
+ keyframes: updates.keyframes ?? existing.keyframes,
blendMode: updates.blendMode ?? existing.blendMode,
blendOpacity: updates.blendOpacity ?? existing.blendOpacity,
emphasisAnimation:
diff --git a/packages/core/src/graphics/types.ts b/packages/core/src/graphics/types.ts
index e3da95f0..41f2e3af 100644
--- a/packages/core/src/graphics/types.ts
+++ b/packages/core/src/graphics/types.ts
@@ -1,4 +1,4 @@
-import type { Transform, Keyframe } from "../types/timeline";
+import type { Transform, Keyframe, ClipMetadata } from "../types/timeline";
import type { Point2D } from "../video/transform-animator";
// Re-export Point2D for convenience
@@ -15,6 +15,7 @@ export interface GraphicClip {
readonly blendMode?: import("../video/types").BlendMode;
readonly blendOpacity?: number;
readonly emphasisAnimation?: EmphasisAnimation;
+ readonly metadata?: ClipMetadata;
}
export type GraphicType = "shape" | "svg" | "sticker" | "emoji";
@@ -261,12 +262,14 @@ export interface GraphicRenderResult {
}
export interface CreateShapeParams {
+ readonly id?: string;
readonly shapeType: ShapeType;
readonly width: number;
readonly height: number;
readonly style?: Partial<ShapeStyle>;
readonly arrowProps?: ArrowProperties;
readonly points?: Point2D[];
+ readonly metadata?: ClipMetadata;
}
export interface SVGImportResult {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5809ae77..17906759 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -10,6 +10,7 @@ export * from "./playback";
export * from "./text";
export * from "./graphics";
export * from "./photo";
+export * from "./editing-templates";
export * from "./template";
export * from "./ai";
export * from "./animation";
diff --git a/packages/core/src/text/title-engine.ts b/packages/core/src/text/title-engine.ts
index 0f4c7c1e..088ee2c5 100644
--- a/packages/core/src/text/title-engine.ts
+++ b/packages/core/src/text/title-engine.ts
@@ -1,4 +1,4 @@
-import type { Transform, Keyframe } from "../types/timeline";
+import type { Transform, Keyframe, ClipMetadata } from "../types/timeline";
import type {
TextClip,
TextStyle,
@@ -19,6 +19,7 @@ export interface CreateTextClipOptions {
style?: Partial<TextStyle>;
transform?: Partial<Transform>;
animation?: TextAnimation;
+ metadata?: ClipMetadata;
}
export interface UpdateTextClipOptions {
@@ -33,6 +34,7 @@ export interface UpdateTextClipOptions {
blendOpacity?: number;
emphasisAnimation?: import("../graphics/types").EmphasisAnimation;
behindSubject?: boolean;
+ metadata?: ClipMetadata;
}
export class TitleEngine {
@@ -79,6 +81,7 @@ export class TitleEngine {
transform,
animation: options.animation,
keyframes: [],
+ metadata: options.metadata,
};
this.textClips.set(id, textClip);
@@ -127,6 +130,7 @@ export class TitleEngine {
updates.emphasisAnimation ?? existing.emphasisAnimation,
behindSubject:
updates.behindSubject ?? existing.behindSubject,
+ metadata: updates.metadata ?? existing.metadata,
};
this.textClips.set(id, updatedClip);
diff --git a/packages/core/src/text/types.ts b/packages/core/src/text/types.ts
index 4c5654fc..87bd467d 100644
--- a/packages/core/src/text/types.ts
+++ b/packages/core/src/text/types.ts
@@ -1,4 +1,9 @@
-import type { Transform, Keyframe, EasingType } from "../types/timeline";
+import type {
+ Transform,
+ Keyframe,
+ EasingType,
+ ClipMetadata,
+} from "../types/timeline";
import type { EmphasisAnimation } from "../graphics/types";
export interface TextClip {
@@ -15,6 +20,7 @@ export interface TextClip {
readonly blendOpacity?: number;
readonly emphasisAnimation?: EmphasisAnimation;
readonly behindSubject?: boolean;
+ readonly metadata?: ClipMetadata;
}
export interface TextStyle {
diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.ts
index dc18339f..a2844283 100644
--- a/packages/core/src/types/timeline.ts
+++ b/packages/core/src/types/timeline.ts
@@ -37,6 +37,36 @@ export interface Track {
readonly solo: boolean;
}
+export interface EditingTemplateApplicationSource {
+ readonly templateId: string;
+ readonly applicationId: string;
+ readonly ownerClipId: string;
+ readonly ownerTrackId?: string;
+ readonly controlValues?: Record<string, unknown>;
+}
+
+export interface AppliedEditingTemplate {
+ readonly templateId: string;
+ readonly applicationId: string;
+ readonly name: string;
+ readonly category?: string;
+ readonly appliedAt: number;
+ readonly controlValues?: Record<string, unknown>;
+}
+
+export interface ClipMetadata {
+ readonly templateSource?: EditingTemplateApplicationSource;
+ readonly appliedTemplates?: AppliedEditingTemplate[];
+ readonly templateManaged?: boolean;
+ readonly templateTrackType?: "text" | "graphics";
+ readonly [key: string]: unknown;
+}
+
+export interface EffectMetadata {
+ readonly templateSource?: EditingTemplateApplicationSource;
+ readonly [key: string]: unknown;
+}
+
export interface Clip {
readonly id: string;
readonly mediaId: string;
@@ -73,6 +103,7 @@ export interface Clip {
/** Zero-based index of the audio track within the source media file to use for this clip.
* Undefined or 0 means the primary/first audio track. */
readonly audioTrackIndex?: number;
+ readonly metadata?: ClipMetadata;
}
export interface Effect {
@@ -80,6 +111,7 @@ export interface Effect {
readonly type: string;
readonly params: Record<string, unknown>;
readonly enabled: boolean;
+ readonly metadata?: EffectMetadata;
}
export type FitMode = "contain" | "cover" | "stretch" | "none";