Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Introduce Layout segments in the editor (#905)
Richie McIlroy21568c8be53d
diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 000000000..89cdb7d8c--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,397 @@+# CLAUDE.md++This file provides comprehensive guidance to Claude Code when working with code in this repository.++## Project Overview++Cap is the open source alternative to Loom. It's a Turborepo monorepo with a Tauri v2 desktop app (Rust + SolidStart) and a Next.js web app. The Next.js app at `apps/web` is the main web application for sharing and management; the desktop app at `apps/desktop` is the cross‑platform recorder/editor (macOS and Windows).++### Product Context+- **Core Purpose**: Screen recording with instant sharing capabilities+- **Target Users**: Content creators, developers, product managers, support teams+- **Key Features**: Instant recording, studio mode, AI-generated captions, collaborative comments+- **Business Model**: Freemium SaaS with usage-based pricing++## File Location Patterns & Key Directories++### Core Applications+- `apps/web/` — Next.js web application (sharing, management, dashboard)+- `apps/desktop/` — Tauri desktop app (recording, editing)+- `apps/tasks/` — Background job processing service+- `apps/discord-bot/` — Discord integration bot+- `apps/storybook/` — UI component documentation++### Shared Packages+- `packages/database/` — Drizzle ORM, auth, email templates+- `packages/ui/` — React components for web app+- `packages/ui-solid/` — SolidJS components for desktop+- `packages/utils/` — Shared utilities, types, constants+- `packages/env/` — Environment variable validation+- `packages/web-*` — Effect-based web API layers++### Rust Crates+- `crates/media*/` — Video/audio processing pipeline+- `crates/recording/` — Core recording functionality+- `crates/rendering/` — Video rendering and effects+- `crates/camera*/` — Cross-platform camera handling+- `crates/scap-*/` — Screen capture implementations++### Important File Patterns+- `**/tauri.ts` — Auto-generated IPC bindings (DO NOT EDIT)+- `**/queries.ts` — Auto-generated query bindings (DO NOT EDIT)+- `apps/web/actions/**/*.ts` — Server Actions ("use server")+- `packages/database/schema.ts` — Database schema definitions+- `*.config.*` — Configuration files (Next.js, Tailwind, etc.)++## Key Commands++### Development+```bash+pnpm dev:web # Start Next.js dev server (apps/web only)+pnpm run dev:desktop # Start Tauri desktop dev (apps/desktop)+pnpm build # Build all packages/apps via Turbo+pnpm lint # Lint with Biome across the repo+pnpm format # Format with Biome+pnpm typecheck # TypeScript project references build+```++### Database Operations+```bash+pnpm db:generate # Generate Drizzle migrations+pnpm db:push # Push schema changes to MySQL+pnpm db:studio # Open Drizzle Studio+pnpm --dir packages/database db:check # Verify database schema+```++### App-Specific Commands+```bash+# Web app (apps/web)+cd apps/web && pnpm dev # Start Next.js dev server++# Desktop (apps/desktop)+cd apps/desktop && pnpm dev # Start SolidStart + Tauri dev+pnpm tauri:build # Build desktop app (release)+```++## Development Environment Guidelines++### Server Management+- Do not start additional development servers or localhost services unless explicitly asked. Assume the developer already has the environment running and focus on code changes.+- Prefer `pnpm dev:web` or `pnpm run dev:desktop` when you only need one app. Avoid starting multiple overlapping servers.+- Avoid running Docker or external services yourself unless requested; root workflows handle them as needed.+- **Database**: MySQL via Docker Compose; schema managed through Drizzle migrations+- **Storage**: S3-compatible (AWS, Cloudflare R2, etc.) for video/audio files++### Auto-generated Bindings (Desktop)+- **NEVER EDIT**: `tauri.ts`, `queries.ts` (auto-generated on app load)+- **NEVER EDIT**: Files under `apps/desktop/src-tauri/gen/`+- **Icons**: Auto-imported in desktop app; do not import manually+- **Regeneration**: These files update automatically when Rust types change++### Common Development Pain Points+- **Node Version**: Must use Node 20 (specified in package.json engines)+- **PNPM Version**: Locked to 10.5.2 for consistency+- **Turbo Cache**: May need clearing if builds behave unexpectedly (`rm -rf .turbo`)+- **Database Migrations**: Always run `pnpm db:generate` before `pnpm db:push`+- **Desktop Icons**: Use `unplugin-icons` auto-import instead of manual imports++## Architecture Overview++### Monorepo Structure+- `apps/web` — Next.js 14 (App Router) web application+- `apps/desktop` — Tauri v2 desktop app with SolidStart (SolidJS)+- `packages/database` — Drizzle ORM (MySQL) + auth utilities+- `packages/ui` — React UI components for the web+- `packages/ui-solid` — SolidJS UI components for desktop+- `packages/utils` — Shared utilities and types+- `packages/env` — Zod-validated build/server env modules+- `crates/*` — Rust crates for media, rendering, recording, camera, etc.++### Technology Stack+- **Package Manager**: pnpm (`[email protected]`)+- **Build System**: Turborepo+- **Frontend (Web)**: React 19 + Next.js 14.2.x (App Router)+- **Desktop**: Tauri v2, Rust 2024, SolidStart+- **Styling**: Tailwind CSS (web consumes `@cap/ui/tailwind`)+- **Server State**: TanStack Query v5 on web; `@tanstack/solid-query` on desktop+- **Database**: MySQL (PlanetScale) with Drizzle ORM+- **AI Integration**: Groq preferred, OpenAI fallback; invoked in Next.js Server Actions+- **Analytics**: PostHog+- **Payments**: Stripe++### Critical Architectural Decisions+1. **AI on the Server**: All Groq/OpenAI calls execute in Server Actions under `apps/web/actions`. Never call AI from client components.+2. **Authentication**: NextAuth with a custom Drizzle adapter. Session handling via NextAuth cookies; API keys are supported for certain endpoints.+3. **API Surface**: Prefer Server Actions. When routes are necessary, implement under `app/api/*` (Hono-based utilities present), set proper CORS, and revalidate precisely.+4. **Desktop IPC**: Use `tauri_specta` for strongly typed commands/events; do not modify generated bindings.++#### Desktop event pattern+Rust (emit):+```rust+use specta::Type;+use tauri_specta::Event;++#[derive(Serialize, Type, tauri_specta::Event, Debug, Clone)]+pub struct UploadProgress {+ progress: f64,+ message: String,+}++UploadProgress { progress: 0.0, message: "Starting upload...".to_string() }+ .emit(&app)+ .ok();+```++Frontend (listen; generated bindings):+```ts+import { events } from "./tauri"; // auto-generated+await events.uploadProgress.listen((event) => {+ // update UI with event.payload+});+```++## Development Workflow & Best Practices++### Code Organization Principles+1. **Follow Local Patterns**: Study neighboring files and shared packages first+2. **Database Changes**: Always `pnpm db:generate` → `pnpm db:push` → test+3. **Strict Typing**: Use existing types; validate config via `@cap/env`+4. **Component Consistency**: Use `@cap/ui` (React) or `@cap/ui-solid` (Solid)+5. **No Manual Edits**: Never touch auto-generated bindings or schemas++### Key Implementation Patterns++#### Server Actions (Web App)+```typescript+"use server";++import { db } from "@cap/database";+import { getCurrentUser } from "@cap/database/auth/session";++export async function updateVideo(data: FormData) {+ const user = await getCurrentUser();+ if (!user?.id) throw new Error("Unauthorized");++ // Database operations with Drizzle+ return await db().update(videos).set({ ... }).where(eq(videos.id, id));+}+```++#### Desktop IPC Commands+```rust+// Rust side - emit events+UploadProgress { progress: 0.5, message: "Uploading...".to_string() }+ .emit(&app)+ .ok();+```++```typescript+// Frontend side - listen to events (auto-generated)+import { events, commands } from "./tauri";++// Call commands+await commands.startRecording({ ... });++// Listen to events+await events.uploadProgress.listen((event) => {+ setProgress(event.payload.progress);+});+```++#### React Query Patterns+```typescript+// Queries with Server Actions+const { data, isLoading } = useQuery({+ queryKey: ["videos", userId],+ queryFn: () => getUserVideos(),+ staleTime: 5 * 60 * 1000,+});++// Mutations with cache updates+const updateMutation = useMutation({+ mutationFn: updateVideo,+ onSuccess: (updated) => {+ queryClient.setQueryData(["video", updated.id], updated);+ },+});+```++## Environment Variables++### Build/Client (selected)+- `NEXT_PUBLIC_WEB_URL`+- `NEXT_PUBLIC_CAP_AWS_BUCKET`, `NEXT_PUBLIC_CAP_AWS_REGION`+- `NEXT_PUBLIC_POSTHOG_KEY`, `NEXT_PUBLIC_POSTHOG_HOST`+- `NEXT_PUBLIC_DOCKER_BUILD` (enables Next.js standalone output)++### Server (selected)+- Core: `DATABASE_URL`, `WEB_URL`, `NEXTAUTH_SECRET`, `NEXTAUTH_URL`+- S3: `CAP_AWS_BUCKET`, `CAP_AWS_REGION`, `CAP_AWS_ACCESS_KEY`, `CAP_AWS_SECRET_KEY`, optional `CAP_AWS_ENDPOINT`, `CAP_AWS_BUCKET_URL`+- AI: `GROQ_API_KEY`, `OPENAI_API_KEY`+- Email/Analytics: `RESEND_API_KEY`, `RESEND_FROM_DOMAIN`, `POSTHOG_PERSONAL_API_KEY`, `DUB_API_KEY`, `DEEPGRAM_API_KEY`+- OAuth: `GOOGLE_CLIENT_ID/SECRET`, `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`+- Stripe: `STRIPE_SECRET_KEY_TEST`, `STRIPE_SECRET_KEY_LIVE`, `STRIPE_WEBHOOK_SECRET`+- CDN signing: `CLOUDFRONT_KEYPAIR_ID`, `CLOUDFRONT_KEYPAIR_PRIVATE_KEY`+- Optional S3 endpoints: `S3_PUBLIC_ENDPOINT`, `S3_INTERNAL_ENDPOINT`++## Testing & Build Optimization++### Testing Strategy+- **Package-Specific**: Check each `package.json` for test commands+- **Web App**: Uses Vitest for utilities, no comprehensive frontend tests yet+- **Desktop**: Vitest for SolidJS components in some packages+- **Tasks Service**: Jest for API endpoint testing+- **Rust**: Standard Cargo test framework for crates++### Build Performance+- **Turborepo Caching**: Aggressive caching across all packages+- **Cache Invalidation**: Prefer targeted `--filter` over global rebuilds+- **Docker Builds**: `NEXT_PUBLIC_DOCKER_BUILD=true` enables standalone output+- **Development**: Incremental builds via TypeScript project references++### Performance Monitoring+- **Bundle Analysis**: Check Next.js bundle size regularly+- **Database Queries**: Monitor with Drizzle Studio+- **S3 Operations**: Watch for excessive uploads/downloads+- **Desktop Memory**: Rust crates handle heavy media processing++## Troubleshooting Common Issues++### Build Failures+- **"Cannot find module"**: Check workspace dependencies in package.json+- **TypeScript errors**: Run `pnpm typecheck` to see project-wide issues+- **Turbo cache issues**: Clear with `rm -rf .turbo`+- **Node version mismatch**: Ensure Node 20 is active++### Database Issues+- **Migration failures**: Check `packages/database/migrations/meta/`+- **Connection errors**: Verify Docker containers are running+- **Schema drift**: Run `pnpm --dir packages/database db:check`++### Desktop App Issues+- **IPC binding errors**: Restart dev server to regenerate `tauri.ts`+- **Rust compile errors**: Check Cargo.toml dependencies+- **Permission issues**: macOS/Windows may require app permissions+- **Recording failures**: Verify screen capture permissions++### Web App Issues+- **Auth failures**: Check NextAuth configuration and database+- **S3 upload errors**: Verify AWS credentials and bucket policies+- **Server Action errors**: Check network tab for detailed error messages+- **Hot reload issues**: Restart Next.js dev server++## React/Next.js Coding Standards++### Data Fetching & Server State+- Use TanStack Query v5 for all client-side server state and fetching.+- Use Server Components for initial data when possible; pass `initialData` to client components and let React Query take over.+- Mutations should call Server Actions directly and perform precise cache updates (`setQueryData`/`setQueriesData`) rather than broad invalidations.++Basic query pattern:+```tsx+import { useQuery } from "@tanstack/react-query";++function Example() {+ const { data, isLoading, error } = useQuery({+ queryKey: ["items"],+ queryFn: fetchItems,+ staleTime: 5 * 60 * 1000,+ gcTime: 10 * 60 * 1000,+ });+ if (isLoading) return <Skeleton />;+ if (error) return <ErrorState onRetry={() => { /* refetch */ }} />;+ return <List items={data} />;+}+```++Server Action mutation with targeted cache updates:+```tsx+"use client";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { updateItem } from "@/actions/items"; // 'use server'++function useUpdateItem() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: updateItem,+ onSuccess: (updated) => {+ qc.setQueriesData({ queryKey: ["items"] }, (old: any[] | undefined) =>+ old?.map((it) => (it.id === updated.id ? { ...it, ...updated } : it))+ );+ qc.setQueryData(["item", updated.id], updated);+ },+ });+}+```++Minimize `useEffect` usage: compute during render, handle logic in event handlers, and ensure cleanups for any subscriptions/timers.++### Next.js App Router+- Prefer Server Components for SEO/initial rendering; hydrate interactivity in client components.+- Co-locate feature components, keep components focused, and use Suspense boundaries for long fetches.++### UI/UX Guidelines+- Styling: Tailwind CSS only; stay consistent with spacing and tokens.+- Loading: Use static skeletons that mirror content; no bouncing animations.+- Performance: Memoize expensive work; code-split naturally; use Next/Image for remote assets.++## Desktop (Solid + Tauri) Patterns+- Data fetching: `@tanstack/solid-query` for server state.+- IPC: Call generated `commands` and `events` from `tauri_specta`. Listen directly to generated events and prefer the typed interfaces.+- Windowing/permissions are handled in Rust; keep UI logic in Solid and avoid mixing IPC with rendering logic.++## Conventions+- No code comments: Never add inline, block, or docstring comments in any language. Code must be self-explanatory through naming, types, and structure. Use docs/READMEs for explanations when necessary.+- Directory naming: lower-case-dashed+- Components: PascalCase; hooks: camelCase starting with `use`+- Strict TypeScript; avoid `any`; leverage shared types+- Use Biome for linting/formatting; match existing formatting++## Security & Privacy Considerations++### Data Handling+- **Video Storage**: S3-compatible storage with signed URLs+- **Database**: MySQL with connection pooling via PlanetScale+- **Authentication**: NextAuth with custom Drizzle adapter+- **API Security**: CORS policies, rate limiting via Hono middleware++### Privacy Controls+- **Recording Permissions**: Platform-specific (macOS Screen Recording, Windows)+- **Data Retention**: User-controlled deletion of recordings+- **Sharing Controls**: Password protection, expiry dates on shared links+- **Analytics**: PostHog with privacy-focused configuration++## AI & Processing Pipeline++### AI Integration Points+- **Transcription**: Deepgram API for captions generation+- **Metadata Generation**: Groq (primary) + OpenAI (fallback) for titles/descriptions+- **Processing Location**: All AI calls in Next.js Server Actions only+- **Privacy**: Transcripts stored in database, audio sent to external APIs++### Media Processing Flow+```+Desktop Recording → Local Files → Upload to S3 →+Background Processing (tasks service) →+Transcription/AI Enhancement → Database Storage+```++## References & Documentation++### Core Technologies+- **TanStack Query**: https://tanstack.com/query/latest+- **React Patterns**: https://react.dev/learn/you-might-not-need-an-effect+- **Tauri v2**: https://github.com/tauri-apps/tauri+- **tauri_specta**: https://github.com/oscartbeaumont/tauri-specta+- **Drizzle ORM**: https://orm.drizzle.team/+- **SolidJS**: https://solidjs.com/++### Cap-Specific+- **Self-hosting**: https://cap.so/docs/self-hosting+- **API Documentation**: Generated from TypeScript contracts+- **Architecture Decisions**: See individual package READMEs++### Development Resources+- **Monorepo Guide**: Turborepo documentation+- **Effect System**: Used in web-backend packages+- **Media Processing**: FFmpeg documentation for Rust bindingsdiff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex a6842300d..5dcfb1b97 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -985,6 +985,7 @@ fn project_config_from_recording(} else {Vec::new()},+ layout_segments: Vec::new(),}),..default_config.unwrap_or_default()}diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsxindex 7bb77e0d2..13c7cbac0 100644--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx@@ -24,13 +24,14 @@ import {createRoot,createSignal,For,+ Index,on,onMount,Show,Suspense,type ValidComponent,} from "solid-js";-import { createStore, produce } from "solid-js/store";+import { createStore } from "solid-js/store";import { Dynamic } from "solid-js/web";import toast from "solid-toast";import colorBg from "~/assets/illustrations/color.webp";@@ -43,10 +44,12 @@ import {type BackgroundSource,type CameraShape,commands,+ type LayoutSegment,type StereoMode,type TimelineSegment,type ZoomSegment,} from "~/utils/tauri";+import IconLucideMonitor from "~icons/lucide/monitor";import IconLucideSparkles from "~icons/lucide/sparkles";import { CaptionsTab } from "./CaptionsTab";import { useEditorContext } from "./context";@@ -212,8 +215,15 @@ const TAB_IDS = {} as const;export function ConfigSidebar() {- const { project, setProject, editorInstance, editorState, meta } =- useEditorContext();+ const {+ project,+ setProject,+ setEditorState,+ projectActions,+ editorInstance,+ editorState,+ meta,+ } = useEditorContext();const [state, setState] = createStore({selectedTab: "background" as@@ -291,6 +301,9 @@ export function ConfigSidebar() {</KTabs.List><divref={scrollRef}+ style={{+ "--margin-top-scroll": "5px",+ }}class="p-4 custom-scroll overflow-x-hidden overflow-y-scroll text-[0.875rem] h-full"><BackgroundConfig scrollRef={scrollRef} />@@ -564,22 +577,112 @@ export function ConfigSidebar() {</div><Show when={editorState.timeline.selection}>{(selection) => (- <div class="absolute inset-0 p-[0.75rem] text-[0.875rem] space-y-4 bg-gray-1 dark:bg-gray-2 z-50 animate-in slide-in-from-bottom-2 fade-in">+ <div+ style={{+ "--margin-top-scroll": "5px",+ }}+ class="absolute custom-scroll p-5 inset-0 text-[0.875rem] space-y-4 bg-gray-1 dark:bg-gray-2 z-50 animate-in slide-in-from-bottom-2 fade-in"+ ><Suspense><Showwhen={(() => {const zoomSelection = selection();if (zoomSelection.type !== "zoom") return;+ const segments = zoomSelection.indices+ .map((index) => ({+ index,+ segment: project.timeline?.zoomSegments?.[index],+ }))+ .filter(+ (item): item is { index: number; segment: ZoomSegment } =>+ item.segment !== undefined,+ );++ if (segments.length === 0) {+ setEditorState("timeline", "selection", null);+ return;+ }+ return { selection: zoomSelection, segments };+ })()}+ >+ {(value) => (+ <div class="space-y-4">+ <div class="flex flex-row justify-between items-center">+ <div class="flex gap-2 items-center">+ <EditorButton+ onClick={() =>+ setEditorState("timeline", "selection", null)+ }+ leftIcon={<IconLucideCheck />}+ >+ Done+ </EditorButton>+ <span class="text-sm text-gray-10">+ {value().segments.length} zoom{" "}+ {value().segments.length === 1+ ? "segment"+ : "segments"}{" "}+ selected+ </span>+ </div>+ <EditorButton+ variant="danger"+ onClick={() => {+ projectActions.deleteZoomSegments(+ value().segments.map((s) => s.index),+ );+ }}+ leftIcon={<IconCapTrash />}+ >+ Delete+ </EditorButton>+ </div>+ <Show+ when={value().segments.length === 1}+ fallback={+ <div class="grid grid-cols-3 gap-4">+ <Index each={value().segments}>+ {(item, index) => (+ <div class="p-2.5 rounded-lg border border-gray-4 bg-gray-3">+ <ZoomSegmentPreview+ segment={item().segment}+ segmentIndex={index}+ />+ </div>+ )}+ </Index>+ </div>+ }+ >+ <For each={value().segments}>+ {(item) => (+ <div class="p-4 rounded-lg border border-gray-200">+ <ZoomSegmentConfig+ segment={item.segment}+ segmentIndex={item.index}+ />+ </div>+ )}+ </For>+ </Show>+ </div>+ )}+ </Show>+ <Show+ when={(() => {+ const layoutSelection = selection();+ if (layoutSelection.type !== "layout") return;+const segment =- project.timeline?.zoomSegments?.[zoomSelection.index];+ project.timeline?.layoutSegments?.[layoutSelection.index];if (!segment) return;- return { selection: zoomSelection, segment };+ return { selection: layoutSelection, segment };})()}>{(value) => (- <ZoomSegmentConfig+ <LayoutSegmentConfigsegment={value().segment}segmentIndex={value().selection.index}/>@@ -913,9 +1016,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) {) {const selectedWallpaper = wallpapers()?.find((w) =>(- project.background.source as {- path?: string;- }+ project.background.source as { path?: string }).path?.includes(w.id),);// Only use wallpaper URL if it exists@@ -1287,10 +1388,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) {createRoot((dispose) =>createEventListenerMap(window, {- mouseup: () => {- dispose();- resumeHistory();- },+ mouseup: () => dispose(),mousemove: (moveEvent) => {const rawNewAngle =Math.round(@@ -1514,7 +1612,7 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) {<RadioGroup.ItemInput class="peer" /><RadioGroup.ItemControlclass={cx(- "cursor-pointer size-6 shink-0 rounded-[0.375rem] bg-gray-5 absolute flex justify-center items-center ui-checked:bg-blue-9 focus-visible:outline peer-focus-visible:outline outline-2 outline-offset-2 outline-blue-9 transition-colors duration-100",+ "cursor-pointer size-6 shrink-0 rounded-[0.375rem] bg-gray-5 absolute flex justify-center items-center ui-checked:bg-blue-9 focus-visible:outline peer-focus-visible:outline outline-2 outline-blue-9 outline-offset-2 transition-colors duration-100",item.x === "left"? "left-2": item.x === "right"@@ -1705,6 +1803,125 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) {);}+function ZoomSegmentPreview(props: {+ segmentIndex: number;+ segment: ZoomSegment;+}) {+ const { project, editorInstance } = useEditorContext();++ const start = createMemo(() => props.segment.start);++ const segmentIndex = createMemo(() => {+ const st = start();+ const i = project.timeline?.segments.findIndex(+ (s) => s.start <= st && s.end > st,+ );+ if (i === undefined || i === -1) return 0;+ return i;+ });++ const relativeTime = createMemo(() => {+ const st = start();+ const segment = project.timeline?.segments[segmentIndex()];+ if (!segment) return 0;+ return Math.max(0, st - segment.start);+ });++ const video = document.createElement("video");+ createEffect(() => {+ const path = convertFileSrc(+ `${editorInstance.path}/content/segments/segment-${segmentIndex()}/display.mp4`,+ );+ video.src = path;+ video.preload = "auto";+ video.load();+ });++ createEffect(() => {+ const t = relativeTime();+ if (t === undefined) return;++ if (video.readyState >= 2) {+ video.currentTime = t;+ } else {+ const handleCanPlay = () => {+ video.currentTime = t;+ video.removeEventListener("canplay", handleCanPlay);+ };+ video.addEventListener("canplay", handleCanPlay);+ }+ });++ const render = () => {+ if (!canvasRef || video.readyState < 2) return;++ const ctx = canvasRef.getContext("2d");+ if (!ctx) return;++ ctx.imageSmoothingEnabled = false;+ ctx.clearRect(0, 0, canvasRef.width, canvasRef.height);++ const raw = editorInstance.recordings.segments[0].display;+ const croppedPosition = project.background.crop?.position || { x: 0, y: 0 };+ const croppedSize = project.background.crop?.size || {+ x: raw.width,+ y: raw.height,+ };++ ctx.drawImage(+ video,+ croppedPosition.x,+ croppedPosition.y,+ croppedSize.x,+ croppedSize.y,+ 0,+ 0,+ canvasRef.width,+ canvasRef.height,+ );+ };++ const [loaded, setLoaded] = createSignal(false);+ video.onloadeddata = () => {+ setLoaded(true);+ render();+ };+ video.onseeked = render;+ video.onerror = () => {+ setTimeout(() => video.load(), 100);+ };++ let canvasRef!: HTMLCanvasElement;++ return (+ <>+ <div class="space-y-1.5">+ <div class="text-xs font-medium text-center text-gray-12">+ Zoom {props.segmentIndex + 1}+ </div>+ <div class="overflow-hidden relative rounded border aspect-video border-gray-3 bg-gray-3">+ <canvas+ ref={canvasRef}+ width={160}+ height={90}+ data-loaded={loaded()}+ class="w-full h-full opacity-0 transition-opacity data-[loaded='true']:opacity-100 duration-200"+ />+ <Show when={!loaded()}>+ <p class="flex absolute inset-0 justify-center items-center text-xs text-gray-11">+ Loading...+ </p>+ </Show>+ </div>+ </div>+ <div class="flex gap-1 justify-center items-center mt-3 w-full text-xs text-center text-gray-11">+ <IconLucideSearch class="size-3" />+ <p>{props.segment.amount.toFixed(1)}x</p>+ </div>+ </>+ );+}+function ZoomSegmentConfig(props: {segmentIndex: number;segment: ZoomSegment;@@ -1716,7 +1933,6 @@ function ZoomSegmentConfig(props: {editorInstance,setEditorState,projectHistory,- projectActions,} = useEditorContext();const states = {@@ -1728,26 +1944,10 @@ function ZoomSegmentConfig(props: {return (<>- <div class="flex flex-row justify-between items-center">- <div class="flex gap-2 items-center">- <EditorButton- onClick={() => setEditorState("timeline", "selection", null)}- leftIcon={<IconLucideCheck />}- >- Done- </EditorButton>- </div>- <EditorButton- variant="danger"- onClick={() => {- projectActions.deleteZoomSegment(props.segmentIndex);- }}- leftIcon={<IconCapTrash />}- >- Delete- </EditorButton>- </div>- <Field name="Zoom Amount" icon={<IconLucideSearch />}>+ <Field+ name={`Zoom ${props.segmentIndex + 1}`}+ icon={<IconLucideSearch />}+ ><Slidervalue={[props.segment.amount]}onChange={(v) =>@@ -1802,12 +2002,14 @@ function ZoomSegmentConfig(props: {when={(() => {const m = props.segment.mode;if (m === "auto") return;+return m.manual;})()}>{(mode) => {const start = createMemo<number>((prev) => {if (projectHistory.isPaused()) return prev;+return props.segment.start;}, 0);@@ -1822,20 +2024,44 @@ function ZoomSegmentConfig(props: {return i;}, 0);+ // Calculate the time relative to the video segment+ const relativeTime = createMemo(() => {+ const st = start();+ const segment = project.timeline?.segments[segmentIndex()];+ if (!segment) return 0;+ // The time within the actual video file+ return Math.max(0, st - segment.start);+ });+const video = document.createElement("video");createEffect(() => {- video.src = convertFileSrc(+ const path = convertFileSrc(// TODO: this shouldn't be so hardcoded`${editorInstance.path}/content/segments/segment-${segmentIndex()}/display.mp4`,);+ video.src = path;+ video.preload = "auto";+ // Force reload if video fails to load+ video.load();});createEffect(() => {- const s = start();- if (s === undefined) return;- video.currentTime = s;+ const t = relativeTime();+ if (t === undefined) return;++ // Ensure video is ready before seeking+ if (video.readyState >= 2) {+ video.currentTime = t;+ } else {+ // Wait for video to be ready, then seek+ const handleCanPlay = () => {+ video.currentTime = t;+ video.removeEventListener("canplay", handleCanPlay);+ };+ video.addEventListener("canplay", handleCanPlay);+ }});createEffect(@@ -1845,15 +2071,24 @@ function ZoomSegmentConfig(props: {croppedSize();},() => {- render();+ if (loaded()) {+ render();+ }},),);const render = () => {+ if (!canvasRef || video.readyState < 2) return;+const ctx = canvasRef.getContext("2d");- ctx!.imageSmoothingEnabled = false;- ctx!.drawImage(+ if (!ctx) return;++ ctx.imageSmoothingEnabled = false;+ // Clear canvas first+ ctx.clearRect(0, 0, canvasRef.width, canvasRef.height);+ // Draw video frame+ ctx.drawImage(video,croppedPosition().x,croppedPosition().y,@@ -1873,6 +2108,15 @@ function ZoomSegmentConfig(props: {};video.onseeked = render;+ // Add error handling+ video.onerror = (e) => {+ console.error("Failed to load video for zoom preview:", e);+ // Try to reload after a short delay+ setTimeout(() => {+ video.load();+ }, 100);+ };+let canvasRef!: HTMLCanvasElement;const [ref, setRef] = createSignal<HTMLDivElement>();@@ -1910,7 +2154,7 @@ function ZoomSegmentConfig(props: {const bounds =downEvent.currentTarget.getBoundingClientRect();- createRoot((dispose) => {+ createRoot((dispose) =>createEventListenerMap(window, {mouseup: () => dispose(),mousemove: (moveEvent) => {@@ -1940,29 +2184,34 @@ function ZoomSegmentConfig(props: {},);},- });- });+ }),+ );}}><divclass="absolute z-10 w-6 h-6 rounded-full border border-gray-400 -translate-x-1/2 -translate-y-1/2 bg-gray-1"style={{- left: `calc(${mode().x * 100}% + ${- 2 + mode().x * -6- }px)`,- top: `calc(${mode().y * 100}% + ${- 2 + mode().y * -6- }px)`,+ left: `${mode().x * 100}%`,+ top: `${mode().y * 100}%`,}}- />- <div class="overflow-hidden rounded-lg border border-gray-3 bg-gray-2">+ >+ <div class="size-1.5 bg-gray-5 rounded-full" />+ </div>+ <div class="overflow-hidden relative rounded-lg border border-gray-3 bg-gray-2"><canvasref={canvasRef}width={croppedSize().x}height={croppedSize().y}data-loaded={loaded()}- class="z-10 bg-red-500 opacity-0 transition-opacity data-[loaded='true']:opacity-100 w-full h-full duration-200"+ class="z-10 bg-gray-3 opacity-0 transition-opacity data-[loaded='true']:opacity-100 w-full h-full duration-200"/>+ <Show when={!loaded()}>+ <div class="flex absolute inset-0 justify-center items-center bg-gray-2">+ <div class="text-sm text-gray-11">+ Loading preview...+ </div>+ </div>+ </Show></div></div>);@@ -2024,6 +2273,112 @@ function ClipSegmentConfig(props: {);}+function LayoutSegmentConfig(props: {+ segmentIndex: number;+ segment: LayoutSegment;+}) {+ const { setProject, setEditorState, projectActions } = useEditorContext();++ return (+ <>+ <div class="flex flex-row justify-between items-center">+ <div class="flex gap-2 items-center">+ <EditorButton+ onClick={() => setEditorState("timeline", "selection", null)}+ leftIcon={<IconLucideCheck />}+ >+ Done+ </EditorButton>+ </div>+ <EditorButton+ variant="danger"+ onClick={() => {+ projectActions.deleteLayoutSegment(props.segmentIndex);+ }}+ leftIcon={<IconCapTrash />}+ >+ Delete+ </EditorButton>+ </div>+ <Field name="Camera Layout" icon={<IconLucideLayout />}>+ <KTabs+ class="space-y-6"+ value={props.segment.mode || "default"}+ onChange={(v) => {+ setProject(+ "timeline",+ "layoutSegments",+ props.segmentIndex,+ "mode",+ v as "default" | "cameraOnly" | "hideCamera",+ );+ }}+ >+ <KTabs.List class="flex flex-col gap-3">+ <div class="flex flex-row items-center rounded-[0.5rem] relative border">+ <KTabs.Trigger+ value="default"+ class="z-10 flex-1 py-2.5 text-gray-11 transition-colors duration-100 outline-none ui-selected:text-gray-12 peer"+ >+ Default+ </KTabs.Trigger>+ <KTabs.Trigger+ value="cameraOnly"+ class="z-10 flex-1 py-2.5 text-gray-11 transition-colors duration-100 outline-none ui-selected:text-gray-12 peer"+ >+ Camera Only+ </KTabs.Trigger>+ <KTabs.Trigger+ value="hideCamera"+ class="z-10 flex-1 py-2.5 text-gray-11 transition-colors duration-100 outline-none ui-selected:text-gray-12 peer"+ >+ Hide Camera+ </KTabs.Trigger>+ <KTabs.Indicator class="absolute flex p-px inset-0 transition-transform peer-focus-visible:outline outline-2 outline-blue-9 outline-offset-2 rounded-[0.6rem] overflow-hidden">+ <div class="flex-1 bg-gray-3" />+ </KTabs.Indicator>+ </div>++ <div class="relative">+ <div+ class="absolute -top-3 w-px h-3 transition-all duration-200 bg-gray-3"+ style={{+ left:+ props.segment.mode === "cameraOnly"+ ? "50%"+ : props.segment.mode === "hideCamera"+ ? "83.33%"+ : "16.67%",+ }}+ />+ <div+ class="absolute -top-1 w-2 h-2 rounded-full transition-all duration-200 -translate-x-1/2 bg-gray-3"+ style={{+ left:+ props.segment.mode === "cameraOnly"+ ? "50%"+ : props.segment.mode === "hideCamera"+ ? "83.33%"+ : "16.67%",+ }}+ />+ <div class="p-2.5 rounded-md bg-gray-2 border border-gray-3">+ <div class="text-xs text-center text-gray-11">+ {props.segment.mode === "cameraOnly"+ ? "Shows only the camera feed"+ : props.segment.mode === "hideCamera"+ ? "Shows only the screen recording"+ : "Shows both screen and camera"}+ </div>+ </div>+ </div>+ </KTabs.List>+ </KTabs>+ </Field>+ </>+ );+}+function RgbInput(props: {value: [number, number, number];onChange: (value: [number, number, number]) => void;diff --git a/apps/desktop/src/routes/editor/ShadowSettings.tsx b/apps/desktop/src/routes/editor/ShadowSettings.tsxindex cbf0dcb85..cd67d95ae 100644--- a/apps/desktop/src/routes/editor/ShadowSettings.tsx+++ b/apps/desktop/src/routes/editor/ShadowSettings.tsx@@ -38,7 +38,7 @@ const ShadowSettings = (props: Props) => {<buttontype="button"onClick={handleToggle}- class="flex gap-1 items-center w-full font-medium text-left text-gray-12 hover:text-gray-700"+ class="flex gap-1 items-center w-full font-medium text-left transition duration-200 text-gray-12 hover:text-gray-10"><span>Advanced shadow settings</span><IconCapChevronDowndiff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsxindex 72728849f..ee132163d 100644--- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx+++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx@@ -58,7 +58,10 @@ function WaveformCanvas(props: {ctx.moveTo(0, h);- const norm = (w: number) => 1.0 - Math.max(w + gain, -60) / -60;+ const norm = (w: number) => {+ const ww = Number.isFinite(w) ? w : -60;+ return 1.0 - Math.max(ww + gain, -60) / -60;+ };for (let segmentTime = props.segment.start;@@ -68,13 +71,17 @@ function WaveformCanvas(props: {const index = Math.floor(segmentTime * 10);const xTime = index / 10;- const amplitude = norm(waveform[index]) * maxAmplitude;+ const currentDb =+ typeof waveform[index] === "number" ? waveform[index] : -60;+ const amplitude = norm(currentDb) * maxAmplitude;const x = (xTime - props.segment.start) / secsPerPixel();const y = h - amplitude;const prevX = (xTime - 0.1 - props.segment.start) / secsPerPixel();- const prevAmplitude = norm(waveform[index - 1]) * maxAmplitude;+ const prevDb =+ typeof waveform[index - 1] === "number" ? waveform[index - 1] : -60;+ const prevAmplitude = norm(prevDb) * maxAmplitude;const prevY = h - prevAmplitude;const cpX1 = prevX + step / 2;@@ -259,7 +266,7 @@ export function ClipTrack(})()}>{(marker) => (- <div class="h-7 -top-8 overflow-hidden rounded-full -translate-x-1/2 z-10">+ <div class="overflow-hidden -top-8 z-10 h-7 rounded-full -translate-x-1/2"><CutOffsetButtonvalue={(() => {const m = marker();@@ -297,7 +304,7 @@ export function ClipTrack({(marker) => {const markerValue = marker();return (- <div class="h-7 w-0 absolute -top-8 flex flex-row rounded-full">+ <div class="flex absolute -top-8 flex-row w-0 h-7 rounded-full"><CutOffsetButtonvalue={markerValue.type === "time"@@ -348,10 +355,21 @@ export function ClipTrack(createEventListener(e.currentTarget, "mouseup", (e) => {dispose();- setEditorState("timeline", "selection", {- type: "clip",- index: i(),- });+ // If there's only one segment, don't open the clip config panel+ // since there's nothing to configure - just let the normal click behavior happen+ const hasOnlyOneSegment = segments().length === 1;++ if (hasOnlyOneSegment) {+ // Clear any existing selection (zoom, layout, etc.) when clicking on a clip+ // This ensures the sidebar updates properly+ setEditorState("timeline", "selection", null);+ } else {+ // When there are multiple segments, show the clip configuration+ setEditorState("timeline", "selection", {+ type: "clip",+ index: i(),+ });+ }props.handleUpdatePlayhead(e);});});@@ -539,7 +557,7 @@ export function ClipTrack(}}><div class="w-[2px] bottom-0 -top-2 rounded-full from-red-300 to-transparent bg-gradient-to-b -translate-x-1/2" />- <div class="h-7 w-0 absolute -top-8 flex flex-row rounded-full">+ <div class="flex absolute -top-8 flex-row w-0 h-7 rounded-full"><CutOffsetButtonvalue={(() => {const m = marker();diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsxnew file mode 100644index 000000000..02d796fb8--- /dev/null+++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx@@ -0,0 +1,482 @@+import {+ createEventListener,+ createEventListenerMap,+} from "@solid-primitives/event-listener";+import { cx } from "cva";+import {+ batch,+ createEffect,+ createMemo,+ createRoot,+ createSignal,+ For,+ Show,+} from "solid-js";+import { produce } from "solid-js/store";+import IconLucideEyeOff from "~icons/lucide/eye-off";+import IconLucideMonitor from "~icons/lucide/monitor";+import IconLucideVideo from "~icons/lucide/video";+import { useEditorContext } from "../context";+import {+ useSegmentContext,+ useTimelineContext,+ useTrackContext,+} from "./context";+import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track";++export type LayoutSegmentDragState =+ | { type: "idle" }+ | { type: "movePending" }+ | { type: "moving" };++export function LayoutTrack(props: {+ onDragStateChanged: (v: LayoutSegmentDragState) => void;+ handleUpdatePlayhead: (e: MouseEvent) => void;+}) {+ const { project, setProject, projectHistory, setEditorState, editorState } =+ useEditorContext();++ const { duration, secsPerPixel } = useTimelineContext();++ const [hoveringSegment, setHoveringSegment] = createSignal(false);+ const [hoveredTime, setHoveredTime] = createSignal<number>();+ const [maxAvailableDuration, setMaxAvailableDuration] =+ createSignal<number>(3);++ // When we delete a segment that's being hovered, the onMouseLeave never fires+ // because the element gets removed from the DOM. This leaves hoveringSegment stuck+ // as true, which blocks the onMouseMove from setting hoveredTime, preventing+ // users from creating new segments. This effect ensures we reset the hover state+ // when all segments are deleted.+ createEffect(() => {+ const segments = project.timeline?.layoutSegments;+ if (!segments || segments.length === 0) {+ setHoveringSegment(false);+ }+ });++ const getLayoutIcon = (mode: string | undefined) => {+ switch (mode) {+ case "cameraOnly":+ return <IconLucideVideo class="size-3.5" />;+ case "hideCamera":+ return <IconLucideEyeOff class="size-3.5" />;+ default:+ return <IconLucideMonitor class="size-3.5" />;+ }+ };++ const getLayoutLabel = (mode: string | undefined) => {+ switch (mode) {+ case "cameraOnly":+ return "Camera Only";+ case "hideCamera":+ return "Hide Camera";+ default:+ return "Default";+ }+ };++ return (+ <TrackRoot+ onMouseMove={(e) => {+ if (hoveringSegment()) {+ setHoveredTime(undefined);+ return;+ }++ const bounds = e.target.getBoundingClientRect()!;++ let time =+ (e.clientX - bounds.left) * secsPerPixel() ++ editorState.timeline.transform.position;++ const segments = project.timeline?.layoutSegments || [];+ const nextSegmentIndex = segments.findIndex((s) => time < s.start);++ let maxDuration = 3; // Default duration++ if (nextSegmentIndex !== -1) {+ const nextSegment = segments[nextSegmentIndex];+ const prevSegmentIndex = nextSegmentIndex - 1;++ if (prevSegmentIndex >= 0) {+ const prevSegment = segments[prevSegmentIndex];+ const gapStart = prevSegment.end;+ const gapEnd = nextSegment.start;+ const availableSpace = gapEnd - gapStart;++ if (availableSpace < 0.5) {+ setHoveredTime(undefined);+ return;+ }++ if (time < gapStart) {+ time = gapStart;+ }++ maxDuration = Math.min(3, gapEnd - time);+ } else {+ // No previous segment, only next segment+ maxDuration = Math.min(3, nextSegment.start - time);+ }++ if (nextSegment.start - time < 0.5) {+ setHoveredTime(undefined);+ return;+ }+ } else if (segments.length > 0) {+ const lastSegment = segments[segments.length - 1];+ if (time < lastSegment.end) {+ time = lastSegment.end;+ }+ maxDuration = Math.min(3, duration() - time);+ } else {+ maxDuration = Math.min(3, duration() - time);+ }++ if (maxDuration < 0.5) {+ setHoveredTime(undefined);+ return;+ }++ setMaxAvailableDuration(maxDuration);+ setHoveredTime(Math.min(time, duration() - maxDuration));+ }}+ onMouseLeave={() => {+ setHoveredTime();+ setMaxAvailableDuration(3);+ }}+ onMouseDown={(e) => {+ createRoot((dispose) => {+ createEventListener(e.currentTarget, "mouseup", (e) => {+ dispose();++ const time = hoveredTime();+ const maxDuration = maxAvailableDuration();+ if (time === undefined) return;++ e.stopPropagation();+ batch(() => {+ setProject("timeline", "layoutSegments", (v) => v ?? []);+ setProject(+ "timeline",+ "layoutSegments",+ produce((layoutSegments) => {+ layoutSegments ??= [];++ let index = layoutSegments.length;++ for (let i = layoutSegments.length - 1; i >= 0; i--) {+ if (layoutSegments[i].start > time) {+ index = i;+ break;+ }+ }++ layoutSegments.splice(index, 0, {+ start: time,+ end: time + maxDuration,+ mode: "cameraOnly",+ });+ }),+ );+ });+ });+ });+ }}+ >+ <For+ each={project.timeline?.layoutSegments}+ fallback={+ <div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">+ <div>Click to add layout segment</div>+ <div class="text-[10px] text-[--text-tertiary]/40 mt-0.5">+ (Make the camera full screen, or hide it)+ </div>+ </div>+ }+ >+ {(segment, i) => {+ const { setTrackState } = useTrackContext();++ const layoutSegments = () => project.timeline!.layoutSegments!;++ function createMouseDownDrag<T>(+ setup: () => T,+ _update: (e: MouseEvent, v: T, initialMouseX: number) => void,+ ) {+ return (downEvent: MouseEvent) => {+ downEvent.stopPropagation();++ const initial = setup();++ let moved = false;+ let initialMouseX: null | number = null;++ setTrackState("draggingSegment", true);++ const resumeHistory = projectHistory.pause();++ props.onDragStateChanged({ type: "movePending" });++ function finish(e: MouseEvent) {+ resumeHistory();+ if (!moved) {+ e.stopPropagation();+ setEditorState("timeline", "selection", {+ type: "layout",+ index: i(),+ });+ props.handleUpdatePlayhead(e);+ } else {+ setEditorState("timeline", "selection", {+ type: "layout",+ index: i(),+ });+ }+ props.onDragStateChanged({ type: "idle" });+ setTrackState("draggingSegment", false);+ }++ function update(event: MouseEvent) {+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {+ if (!moved) {+ moved = true;+ initialMouseX = event.clientX;+ props.onDragStateChanged({+ type: "moving",+ });+ }+ }++ if (initialMouseX === null) return;++ _update(event, initial, initialMouseX);+ }++ createRoot((dispose) => {+ createEventListenerMap(window, {+ mousemove: (e) => {+ update(e);+ },+ mouseup: (e) => {+ update(e);+ finish(e);+ dispose();+ },+ });+ });+ };+ }++ const isSelected = createMemo(() => {+ const selection = editorState.timeline.selection;+ if (!selection || selection.type !== "layout") return false;++ const segmentIndex = project.timeline?.layoutSegments?.findIndex(+ (s) => s.start === segment.start && s.end === segment.end,+ );++ return segmentIndex === selection.index;+ });++ return (+ <SegmentRoot+ class={cx(+ "border transition-colors duration-200 hover:border-gray-12 group",+ `bg-gradient-to-r from-[#5C1BC4] via-[#975CFA] to-[#5C1BC4] shadow-[inset_0_8px_12px_3px_rgba(255,255,255,0.2)]`,+ isSelected()+ ? "wobble-wrapper border-gray-12"+ : "border-transparent",+ )}+ innerClass="ring-blue-5"+ segment={segment}+ onMouseEnter={() => {+ setHoveringSegment(true);+ }}+ onMouseLeave={() => {+ setHoveringSegment(false);+ }}+ >+ <SegmentHandle+ position="start"+ onMouseDown={createMouseDownDrag(+ () => {+ const start = segment.start;++ let minValue = 0;++ const maxValue = segment.end - 1;++ for (let i = layoutSegments().length - 1; i >= 0; i--) {+ const segment = layoutSegments()[i]!;+ if (segment.end <= start) {+ minValue = segment.end;+ break;+ }+ }++ return { start, minValue, maxValue };+ },+ (e, value, initialMouseX) => {+ const newStart =+ value.start ++ (e.clientX - initialMouseX) * secsPerPixel();++ setProject(+ "timeline",+ "layoutSegments",+ i(),+ "start",+ Math.min(+ value.maxValue,+ Math.max(value.minValue, newStart),+ ),+ );++ setProject(+ "timeline",+ "layoutSegments",+ produce((s) => {+ if (s) {+ s.sort((a, b) => a.start - b.start);+ }+ }),+ );+ },+ )}+ />+ <SegmentContent+ class="flex justify-center items-center cursor-grab"+ onMouseDown={createMouseDownDrag(+ () => {+ const original = { ...segment };++ const prevSegment = layoutSegments()[i() - 1];+ const nextSegment = layoutSegments()[i() + 1];++ const minStart = prevSegment?.end ?? 0;+ const maxEnd = nextSegment?.start ?? duration();++ return {+ original,+ minStart,+ maxEnd,+ };+ },+ (e, value, initialMouseX) => {+ const rawDelta =+ (e.clientX - initialMouseX) * secsPerPixel();++ const newStart = value.original.start + rawDelta;+ const newEnd = value.original.end + rawDelta;++ let delta = rawDelta;++ if (newStart < value.minStart)+ delta = value.minStart - value.original.start;+ else if (newEnd > value.maxEnd)+ delta = value.maxEnd - value.original.end;++ setProject("timeline", "layoutSegments", i(), {+ start: value.original.start + delta,+ end: value.original.end + delta,+ });+ },+ )}+ >+ {(() => {+ const ctx = useSegmentContext();++ return (+ <Show when={ctx.width() > 80}>+ <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in">+ <span class="opacity-70">Layout</span>+ <div class="flex gap-1 items-center text-md">+ {getLayoutIcon(segment.mode)}+ {ctx.width() > 120 && (+ <span class="text-xs">+ {getLayoutLabel(segment.mode)}+ </span>+ )}+ </div>+ </div>+ </Show>+ );+ })()}+ </SegmentContent>+ <SegmentHandle+ position="end"+ onMouseDown={createMouseDownDrag(+ () => {+ const end = segment.end;++ const minValue = segment.start + 1;++ let maxValue = duration();++ for (let i = 0; i < layoutSegments().length; i++) {+ const segment = layoutSegments()[i]!;+ if (segment.start > end) {+ maxValue = segment.start;+ break;+ }+ }++ return { end, minValue, maxValue };+ },+ (e, value, initialMouseX) => {+ const newEnd =+ value.end + (e.clientX - initialMouseX) * secsPerPixel();++ setProject(+ "timeline",+ "layoutSegments",+ i(),+ "end",+ Math.min(+ value.maxValue,+ Math.max(value.minValue, newEnd),+ ),+ );++ setProject(+ "timeline",+ "layoutSegments",+ produce((s) => {+ if (s) {+ s.sort((a, b) => a.start - b.start);+ }+ }),+ );+ },+ )}+ />+ </SegmentRoot>+ );+ }}+ </For>+ <Show+ when={!useTrackContext().trackState.draggingSegment && hoveredTime()}+ >+ {(time) => (+ <SegmentRoot+ class="pointer-events-none"+ innerClass="ring-blue-300"+ segment={{+ start: time(),+ end: time() + maxAvailableDuration(),+ }}+ >+ <SegmentContent class="bg-gradient-to-r hover:border duration-200 hover:border-gray-500 from-[#3B82F6] via-[#60A5FA] to-[#3B82F6] transition-colors group shadow-[inset_0_8px_12px_3px_rgba(255,255,255,0.2)]">+ <p class="w-full text-center text-gray-1 dark:text-gray-12 text-md text-primary">+ ++ </p>+ </SegmentContent>+ </SegmentRoot>+ )}+ </Show>+ </TrackRoot>+ );+}diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsxindex 3e16a3a88..d38b5f699 100644--- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx+++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx@@ -6,6 +6,7 @@ import { Menu } from "@tauri-apps/api/menu";import { cx } from "cva";import {batch,+ createEffect,createMemo,createRoot,createSignal,@@ -39,6 +40,19 @@ export function ZoomTrack(props: {const [hoveringSegment, setHoveringSegment] = createSignal(false);const [hoveredTime, setHoveredTime] = createSignal<number>();+ // When we delete a segment that's being hovered, the onMouseLeave never fires+ // because the element gets removed from the DOM. This leaves hoveringSegment stuck+ // as true, which blocks the onMouseMove from setting hoveredTime, preventing+ // users from creating new segments. This effect ensures we reset the hover state+ // when all segments are deleted.+ createEffect(() => {+ const segments = project.timeline?.zoomSegments;+ if (!segments || segments.length === 0) {+ setHoveringSegment(false);+ setHoveredTime(undefined);+ }+ });+const handleGenerateZoomSegments = async () => {try {const zoomSegments = await commands.generateZoomSegmentsFromClicks();@@ -72,7 +86,7 @@ export function ZoomTrack(props: {return;}- const bounds = e.target.getBoundingClientRect()!;+ const bounds = e.currentTarget.getBoundingClientRect()!;let time =(e.clientX - bounds.left) * secsPerPixel() +@@ -156,8 +170,11 @@ export function ZoomTrack(props: {<Foreach={project.timeline?.zoomSegments}fallback={- <div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-black-transparent-5 hover:opacity-30 transition-opacity rounded-xl">- Click to add zoom segment+ <div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">+ <div>Click to add zoom segment</div>+ <div class="text-[10px] text-[--text-tertiary]/40 mt-0.5">+ (Smoothly zoom in on important areas)+ </div></div>}>@@ -193,10 +210,45 @@ export function ZoomTrack(props: {resumeHistory();if (!moved) {e.stopPropagation();- setEditorState("timeline", "selection", {- type: "zoom",- index: i(),- });++ const currentSelection = editorState.timeline.selection;+ const segmentIndex = i();++ // Handle multi-selection with Ctrl/Cmd+click+ if (e.ctrlKey || e.metaKey) {+ if (currentSelection?.type === "zoom") {+ // Normalize to indices[] from either indices[] or legacy index+ const baseIndices =+ "indices" in currentSelection &&+ Array.isArray(currentSelection.indices)+ ? currentSelection.indices+ : "index" in currentSelection &&+ typeof currentSelection.index === "number"+ ? [currentSelection.index]+ : [];++ const exists = baseIndices.includes(segmentIndex);+ const newIndices = exists+ ? baseIndices.filter((idx) => idx !== segmentIndex)+ : [...baseIndices, segmentIndex];++ setEditorState("timeline", "selection", {+ type: "zoom",+ indices: newIndices,+ });+ } else {+ // Start new multi-selection+ setEditorState("timeline", "selection", {+ type: "zoom",+ indices: [segmentIndex],+ });+ }+ } else {+ setEditorState("timeline", "selection", {+ type: "zoom",+ indices: [segmentIndex],+ });+ }props.handleUpdatePlayhead(e);}props.onDragStateChanged({ type: "idle" });@@ -242,7 +294,21 @@ export function ZoomTrack(props: {(s) => s.start === segment.start && s.end === segment.end,);- return segmentIndex === selection.index;+ // Support both single selection (index) and multi-selection (indices)+ if (+ "indices" in selection &&+ Array.isArray(selection.indices) &&+ segmentIndex !== undefined+ ) {+ return selection.indices.includes(segmentIndex);+ } else if (+ "index" in selection &&+ typeof selection.index === "number"+ ) {+ return segmentIndex === selection.index;+ }++ return false;});return (@@ -350,18 +416,35 @@ export function ZoomTrack(props: {>{(() => {const ctx = useSegmentContext();+ const width = ctx.width();- return (- <Show when={ctx.width() > 100}>+ if (width < 40) {+ // Very small - just show icon+ return (+ <div class="flex justify-center items-center">+ <IconLucideSearch class="size-3.5 text-gray-1 dark:text-gray-12" />+ </div>+ );+ } else if (width < 100) {+ // Small - show icon and zoom amount+ return (+ <div class="flex gap-1 items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">+ <IconLucideSearch class="size-3" />+ <span>{zoomPercentage()}</span>+ </div>+ );+ } else {+ // Large - show full content+ return (<div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in"><span class="opacity-70">Zoom</span><div class="flex gap-1 items-center text-md">- <IconLucideSearch class="size-3.5" />{" "}- {zoomPercentage()}{" "}+ <IconLucideSearch class="size-3.5" />+ {zoomPercentage()}</div></div>- </Show>- );+ );+ }})()}</SegmentContent><SegmentHandlediff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsxindex 1aa632110..7c02b59c7 100644--- a/apps/desktop/src/routes/editor/Timeline/index.tsx+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx@@ -11,6 +11,7 @@ import { useEditorContext } from "../context";import { formatTime } from "../utils";import { ClipTrack } from "./ClipTrack";import { TimelineContextProvider, useTimelineContext } from "./context";+import { type LayoutSegmentDragState, LayoutTrack } from "./LayoutTrack";import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack";const TIMELINE_PADDING = 16;@@ -25,6 +26,7 @@ export function Timeline() {totalDuration,editorState,projectActions,+ meta,} = useEditorContext();const duration = () => editorInstance.recordingDuration;@@ -72,10 +74,14 @@ export function Timeline() {}let zoomSegmentDragState = { type: "idle" } as ZoomSegmentDragState;+ let layoutSegmentDragState = { type: "idle" } as LayoutSegmentDragState;async function handleUpdatePlayhead(e: MouseEvent) {const { left } = timelineBounds;- if (zoomSegmentDragState.type !== "moving") {+ if (+ zoomSegmentDragState.type !== "moving" &&+ layoutSegmentDragState.type !== "moving"+ ) {setEditorState("playbackTime",Math.min(@@ -93,14 +99,20 @@ export function Timeline() {const selection = editorState.timeline.selection;if (!selection) return;- if (selection.type === "zoom")- projectActions.deleteZoomSegment(selection.index);- else if (selection.type === "clip")+ if (selection.type === "zoom") {+ projectActions.deleteZoomSegments(selection.indices);+ } else if (selection.type === "clip") {projectActions.deleteClipSegment(selection.index);+ } else if (selection.type === "layout") {+ projectActions.deleteLayoutSegment(selection.index);+ }} else if (e.code === "KeyC" && hasNoModifiers) {if (!editorState.previewTime) return;projectActions.splitClipSegment(editorState.previewTime);+ } else if (e.code === "Escape" && hasNoModifiers) {+ // Deselect all selected segments+ setEditorState("timeline", "selection", null);}});@@ -229,6 +241,14 @@ export function Timeline() {}}handleUpdatePlayhead={handleUpdatePlayhead}/>+ <Show when={meta().hasCamera}>+ <LayoutTrack+ onDragStateChanged={(v) => {+ layoutSegmentDragState = v;+ }}+ handleUpdatePlayhead={handleUpdatePlayhead}+ />+ </Show></div></TimelineContextProvider>);@@ -254,7 +274,7 @@ function TimelineMarkings() {{(second) => (<Show when={second > 0}><div- class="absolute bottom-1 left-0 text-center rounded-full w-1 h-1 bg-current"+ class="absolute left-0 bottom-1 w-1 h-1 text-center bg-current rounded-full"style={{transform: `translateX(${(second - transform().position) / secsPerPixel() - 1diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.tsindex 56cb1493a..7a2c10dac 100644--- a/apps/desktop/src/routes/editor/context.ts+++ b/apps/desktop/src/routes/editor/context.ts@@ -122,20 +122,38 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider("segments",produce((s) => {if (!s) return;- return s.splice(segmentIndex, 1);+ s.splice(segmentIndex, 1);}),);setEditorState("timeline", "selection", null);});},- deleteZoomSegment: (segmentIndex: number) => {+ deleteZoomSegments: (segmentIndices: number[]) => {batch(() => {setProject("timeline","zoomSegments",produce((s) => {if (!s) return;- return s.splice(segmentIndex, 1);+ // Normalize: numbers only, in-bounds, deduped, then descending+ const sorted = [...new Set(segmentIndices)]+ .filter((i) => Number.isInteger(i) && i >= 0 && i < s.length)+ .sort((a, b) => b - a);+ if (sorted.length === 0) return;+ for (const i of sorted) s.splice(i, 1);+ }),+ );+ setEditorState("timeline", "selection", null);+ });+ },+ deleteLayoutSegment: (segmentIndex: number) => {+ batch(() => {+ setProject(+ "timeline",+ "layoutSegments",+ produce((s) => {+ if (!s) return;+ s.splice(segmentIndex, 1);}),);setEditorState("timeline", "selection", null);@@ -237,8 +255,9 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(interactMode: "seek" as "seek" | "split",selection: null as| null- | { type: "zoom"; index: number }- | { type: "clip"; index: number },+ | { type: "zoom"; indices: number[] }+ | { type: "clip"; index: number }+ | { type: "layout"; index: number },transform: {// visible secondszoom: zoomOutLimit(),diff --git a/apps/desktop/src/styles/theme.css b/apps/desktop/src/styles/theme.cssindex ce6f5ee6d..72a63df90 100644--- a/apps/desktop/src/styles/theme.css+++ b/apps/desktop/src/styles/theme.css@@ -151,6 +151,7 @@.custom-scroll {margin-right: 3px; /* Add margin to create space between scrollbar and window edge */overflow-y: scroll;+ margin-top: var(--margin-top-scroll);}.custom-scroll::-webkit-scrollbar {diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex e2cd307ab..84c1629a1 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -721,9 +721,16 @@ export type TargetUnderCursor = {window: WindowUnderCursor | null;screen: ScreenUnderCursor | null;};+export type LayoutSegment = {+ start: number;+ end: number;+ mode?: "default" | "cameraOnly" | "hideCamera";+};+export type TimelineConfiguration = {segments: TimelineSegment[];zoomSegments: ZoomSegment[];+ layoutSegments?: LayoutSegment[];};export type TimelineSegment = {recordingSegment?: number;diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rsindex 3202b1e5c..8caa77a93 100644--- a/crates/project/src/configuration.rs+++ b/crates/project/src/configuration.rs@@ -456,11 +456,31 @@ pub enum ZoomMode {Manual { x: f32, y: f32 },}+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default)]+#[serde(rename_all = "camelCase")]+pub enum LayoutMode {+ #[default]+ Default,+ CameraOnly,+ HideCamera,+}++#[derive(Type, Serialize, Deserialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct LayoutSegment {+ pub start: f64,+ pub end: f64,+ #[serde(default)]+ pub mode: LayoutMode,+}+#[derive(Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]pub struct TimelineConfiguration {pub segments: Vec<TimelineSegment>,pub zoom_segments: Vec<ZoomSegment>,+ #[serde(default)]+ pub layout_segments: Vec<LayoutSegment>,}impl TimelineConfiguration {diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rsindex 992246caa..e64811843 100644--- a/crates/rendering/src/composite_frame.rs+++ b/crates/rendering/src/composite_frame.rs@@ -8,7 +8,7 @@ pub struct CompositeVideoFramePipeline {pub render_pipeline: wgpu::RenderPipeline,}-#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]#[repr(C)]pub struct CompositeVideoFrameUniforms {pub crop_bounds: [f32; 4],@@ -25,9 +25,33 @@ pub struct CompositeVideoFrameUniforms {pub shadow_size: f32,pub shadow_opacity: f32,pub shadow_blur: f32,+ pub opacity: f32,pub _padding: [f32; 3],}+impl Default for CompositeVideoFrameUniforms {+ fn default() -> Self {+ Self {+ crop_bounds: Default::default(),+ target_bounds: Default::default(),+ output_size: Default::default(),+ frame_size: Default::default(),+ velocity_uv: Default::default(),+ target_size: Default::default(),+ rounding_px: Default::default(),+ mirror_x: Default::default(),+ motion_blur_amount: Default::default(),+ camera_motion_blur_amount: Default::default(),+ shadow: Default::default(),+ shadow_size: Default::default(),+ shadow_opacity: Default::default(),+ shadow_blur: Default::default(),+ opacity: 1.0,+ _padding: Default::default(),+ }+ }+}+impl CompositeVideoFrameUniforms {pub fn to_buffer(self, device: &wgpu::Device) -> wgpu::Buffer {device.create_buffer_init(diff --git a/crates/rendering/src/layout.rs b/crates/rendering/src/layout.rsnew file mode 100644index 000000000..03e6f1bfd--- /dev/null+++ b/crates/rendering/src/layout.rs@@ -0,0 +1,276 @@+use cap_project::{LayoutMode, LayoutSegment};++pub const LAYOUT_TRANSITION_DURATION: f64 = 0.3;++#[derive(Debug, Clone, Copy)]+pub struct LayoutSegmentsCursor<'a> {+ time: f64,+ segment: Option<&'a LayoutSegment>,+ prev_segment: Option<&'a LayoutSegment>,+ segments: &'a [LayoutSegment],+}++impl<'a> LayoutSegmentsCursor<'a> {+ pub fn new(time: f64, segments: &'a [LayoutSegment]) -> Self {+ match segments+ .iter()+ .position(|s| time >= s.start && time < s.end)+ {+ Some(segment_index) => LayoutSegmentsCursor {+ time,+ segment: Some(&segments[segment_index]),+ prev_segment: if segment_index > 0 {+ Some(&segments[segment_index - 1])+ } else {+ None+ },+ segments,+ },+ None => {+ let prev = segments+ .iter()+ .enumerate()+ .rev()+ .find(|(_, s)| s.end <= time);+ LayoutSegmentsCursor {+ time,+ segment: None,+ prev_segment: prev.map(|(_, s)| s),+ segments,+ }+ }+ }+ }++ pub fn next_segment(&self) -> Option<&'a LayoutSegment> {+ let current_time = self.time;+ self.segments.iter().find(|s| s.start > current_time)+ }+}++#[derive(Debug, Clone, Copy)]+pub struct InterpolatedLayout {+ pub camera_opacity: f64,+ pub screen_opacity: f64,+ pub camera_scale: f64,+ pub layout_mode: LayoutMode,+ pub transition_progress: f64,+ pub from_mode: LayoutMode,+ pub to_mode: LayoutMode,+ pub screen_blur: f64,+ pub camera_only_zoom: f64,+ pub camera_only_blur: f64,+}++impl InterpolatedLayout {+ pub fn new(cursor: LayoutSegmentsCursor) -> Self {+ let ease_in_out = bezier_easing::bezier_easing(0.42, 0.0, 0.58, 1.0).unwrap();++ let (current_mode, next_mode, transition_progress) = if let Some(segment) = cursor.segment {+ let transition_start = segment.start - LAYOUT_TRANSITION_DURATION;+ let transition_end = segment.end - LAYOUT_TRANSITION_DURATION;++ if cursor.time < segment.start && cursor.time >= transition_start {+ let prev_mode = cursor+ .prev_segment+ .map(|s| s.mode.clone())+ .unwrap_or(LayoutMode::Default);+ let progress = (cursor.time - transition_start) / LAYOUT_TRANSITION_DURATION;+ (+ prev_mode,+ segment.mode.clone(),+ ease_in_out(progress as f32) as f64,+ )+ } else if cursor.time >= transition_end && cursor.time < segment.end {+ if let Some(next_seg) = cursor.next_segment() {+ let progress = (cursor.time - transition_end) / LAYOUT_TRANSITION_DURATION;+ (+ segment.mode.clone(),+ next_seg.mode.clone(),+ ease_in_out(progress as f32) as f64,+ )+ } else {+ let progress = (cursor.time - transition_end) / LAYOUT_TRANSITION_DURATION;+ (+ segment.mode.clone(),+ LayoutMode::Default,+ ease_in_out(progress as f32) as f64,+ )+ }+ } else {+ (segment.mode.clone(), segment.mode.clone(), 1.0)+ }+ } else if let Some(next_segment) = cursor.next_segment() {+ let transition_start = next_segment.start - LAYOUT_TRANSITION_DURATION;+ if cursor.time >= transition_start {+ let prev_mode = cursor+ .prev_segment+ .map(|s| s.mode.clone())+ .unwrap_or(LayoutMode::Default);+ let progress = (cursor.time - transition_start) / LAYOUT_TRANSITION_DURATION;+ (+ prev_mode,+ next_segment.mode.clone(),+ ease_in_out(progress as f32) as f64,+ )+ } else if let Some(prev_segment) = cursor.prev_segment {+ if cursor.time < prev_segment.end + 0.05 {+ (prev_segment.mode.clone(), LayoutMode::Default, 1.0)+ } else {+ (LayoutMode::Default, LayoutMode::Default, 1.0)+ }+ } else {+ (LayoutMode::Default, LayoutMode::Default, 1.0)+ }+ } else {+ if let Some(prev_segment) = cursor.prev_segment {+ if cursor.time < prev_segment.end + 0.05 {+ (prev_segment.mode.clone(), LayoutMode::Default, 1.0)+ } else {+ (LayoutMode::Default, LayoutMode::Default, 1.0)+ }+ } else {+ (LayoutMode::Default, LayoutMode::Default, 1.0)+ }+ };++ let (start_camera_opacity, start_screen_opacity, start_camera_scale) =+ Self::get_layout_values(¤t_mode);+ let (end_camera_opacity, end_screen_opacity, end_camera_scale) =+ Self::get_layout_values(&next_mode);++ let camera_opacity = Self::lerp(+ start_camera_opacity,+ end_camera_opacity,+ transition_progress,+ );+ let screen_opacity = Self::lerp(+ start_screen_opacity,+ end_screen_opacity,+ transition_progress,+ );+ let camera_scale = Self::lerp(start_camera_scale, end_camera_scale, transition_progress);++ let screen_blur = if matches!(current_mode, LayoutMode::CameraOnly)+ || matches!(next_mode, LayoutMode::CameraOnly)+ {+ if matches!(current_mode, LayoutMode::CameraOnly)+ && !matches!(next_mode, LayoutMode::CameraOnly)+ {+ Self::lerp(1.0, 0.0, transition_progress)+ } else if !matches!(current_mode, LayoutMode::CameraOnly)+ && matches!(next_mode, LayoutMode::CameraOnly)+ {+ transition_progress+ } else {+ 0.0+ }+ } else {+ 0.0+ };++ let camera_only_zoom = if matches!(next_mode, LayoutMode::CameraOnly)+ && !matches!(current_mode, LayoutMode::CameraOnly)+ {+ Self::lerp(1.1, 1.0, transition_progress)+ } else if matches!(current_mode, LayoutMode::CameraOnly)+ && !matches!(next_mode, LayoutMode::CameraOnly)+ {+ Self::lerp(1.0, 1.1, transition_progress)+ } else {+ 1.0+ };++ let camera_only_blur = if matches!(next_mode, LayoutMode::CameraOnly)+ && !matches!(current_mode, LayoutMode::CameraOnly)+ {+ Self::lerp(1.0, 0.0, transition_progress)+ } else if matches!(current_mode, LayoutMode::CameraOnly)+ && !matches!(next_mode, LayoutMode::CameraOnly)+ {+ transition_progress+ } else {+ 0.0+ };++ InterpolatedLayout {+ camera_opacity,+ screen_opacity,+ camera_scale,+ layout_mode: if transition_progress > 0.5 {+ next_mode.clone()+ } else {+ current_mode.clone()+ },+ transition_progress,+ from_mode: current_mode,+ to_mode: next_mode,+ screen_blur,+ camera_only_zoom,+ camera_only_blur,+ }+ }++ fn get_layout_values(mode: &LayoutMode) -> (f64, f64, f64) {+ match mode {+ LayoutMode::Default => (1.0, 1.0, 1.0),+ LayoutMode::CameraOnly => (1.0, 1.0, 1.0),+ LayoutMode::HideCamera => (0.0, 1.0, 1.0),+ }+ }++ fn lerp(start: f64, end: f64, t: f64) -> f64 {+ start + (end - start) * t+ }++ pub fn should_render_camera(&self) -> bool {+ self.camera_opacity > 0.01+ }++ pub fn should_render_screen(&self) -> bool {+ true+ }++ pub fn is_transitioning_camera_only(&self) -> bool {+ matches!(self.from_mode, LayoutMode::CameraOnly)+ || matches!(self.to_mode, LayoutMode::CameraOnly)+ }++ pub fn camera_only_transition_opacity(&self) -> f64 {+ if matches!(self.from_mode, LayoutMode::CameraOnly)+ && !matches!(self.to_mode, LayoutMode::CameraOnly)+ {+ 1.0 - self.transition_progress+ } else if !matches!(self.from_mode, LayoutMode::CameraOnly)+ && matches!(self.to_mode, LayoutMode::CameraOnly)+ {+ self.transition_progress+ } else if matches!(self.from_mode, LayoutMode::CameraOnly)+ && matches!(self.to_mode, LayoutMode::CameraOnly)+ {+ 1.0+ } else {+ 0.0+ }+ }++ pub fn regular_camera_transition_opacity(&self) -> f64 {+ if matches!(self.to_mode, LayoutMode::CameraOnly)+ && !matches!(self.from_mode, LayoutMode::CameraOnly)+ {+ let fast_fade = (1.0 - self.transition_progress * 1.5).max(0.0);+ fast_fade * self.camera_opacity+ } else if matches!(self.from_mode, LayoutMode::CameraOnly)+ && !matches!(self.to_mode, LayoutMode::CameraOnly)+ {+ let fast_fade = (self.transition_progress * 1.5).min(1.0);+ fast_fade * self.camera_opacity+ } else if matches!(self.from_mode, LayoutMode::CameraOnly)+ && matches!(self.to_mode, LayoutMode::CameraOnly)+ {+ 0.0+ } else {+ self.camera_opacity+ }+ }+}diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex cbae60a98..2e539a319 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -26,6 +26,7 @@ mod cursor_interpolation;pub mod decoder;mod frame_pipeline;mod layers;+mod layout;mod project_recordings;mod spring_mass_damper;mod zoom;@@ -35,6 +36,7 @@ pub use decoder::DecodedFrame;pub use frame_pipeline::RenderedFrame;pub use project_recordings::{ProjectRecordingsMeta, SegmentRecordings};+use layout::*;use zoom::*;const STANDARD_CURSOR_HEIGHT: f32 = 75.0;@@ -192,7 +194,6 @@ pub async fn render_video_to_channel(let start_time = Instant::now();- // Get the duration from the timeline if it exists, otherwise use the longest source durationlet duration = get_duration(recordings, recording_meta, meta, project);let total_frames = (fps as f64 * duration).ceil() as u32;@@ -216,7 +217,6 @@ pub async fn render_video_to_channel(let segment = &segments[segment_i as usize];- // do this after all usages but before any 'continue' to handle frame skiplet frame_number = {let prev = frame_number;std::mem::replace(&mut frame_number, prev + 1)@@ -266,7 +266,6 @@ pub fn get_duration() -> f64 {let mut max_duration = recordings.duration();- // Check camera duration if it existsif let Some(camera_path) = meta.camera_path()&& let Ok(camera_duration) =recordings.get_source_duration(&recording_meta.path(&camera_path))@@ -276,18 +275,7 @@ pub fn get_duration(println!("New max duration after camera check: {max_duration}");}- // If there's a timeline, ensure all segments extend to the max durationif let Some(timeline) = &project.timeline {- // for (i, segment) in timeline.segments.iter().enumerate() {- // println!(- // "Segment {} - current end: {}, max_duration: {}",- // i, segment.end, max_duration- // );- // if segment.end < max_duration {- // segment.end = max_duration;- // println!("Extended segment {} to new end: {}", i, segment.end);- // }- // }timeline.duration()} else {println!("No timeline found, using max_duration: {max_duration}");@@ -353,9 +341,11 @@ pub struct ProjectUniforms {pub cursor_size: f32,display: CompositeVideoFrameUniforms,camera: Option<CompositeVideoFrameUniforms>,+ camera_only: Option<CompositeVideoFrameUniforms>,interpolated_cursor: Option<InterpolatedCursorPosition>,pub project: ProjectConfiguration,pub zoom: InterpolatedZoom,+ pub layout: InterpolatedLayout,pub resolution_base: XY<u32>,}@@ -458,8 +448,6 @@ impl ProjectUniforms {let scaled_width = ((base_width as f32 * scale) as u32 + 1) & !1;let scaled_height = ((base_height as f32 * scale) as u32 + 1) & !1;(scaled_width, scaled_height)-- // ((base_width + 1) & !1, (base_height + 1) & !1)}pub fn display_offset(@@ -491,7 +479,6 @@ impl ProjectUniforms {f64::max(output_size.x, output_size.y) * padding_factor};- // let padding = Self::get_padding(options, project);let is_height_constrained = cropped_aspect <= output_aspect;let available_size = output_size - 2.0 * padding;@@ -578,6 +565,15 @@ impl ProjectUniforms {.unwrap_or_else(|| Coord::new(XY::new(0.5, 0.5))),);+ let layout = InterpolatedLayout::new(LayoutSegmentsCursor::new(+ frame_time as f64,+ project+ .timeline+ .as_ref()+ .map(|t| t.layout_segments.as_slice())+ .unwrap_or(&[]),+ ));+let display = {let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);let size = [options.screen_size.x as f32, options.screen_size.y as f32];@@ -621,7 +617,7 @@ impl ProjectUniforms {rounding_px: (project.background.rounding / 100.0 * 0.5 * min_target_axis) as f32,mirror_x: 0.0,velocity_uv: velocity,- motion_blur_amount,+ motion_blur_amount: (motion_blur_amount + layout.screen_blur as f32 * 0.8).min(1.0),camera_motion_blur_amount: 0.0,shadow: project.background.shadow,shadow_size: project@@ -639,19 +635,19 @@ impl ProjectUniforms {.advanced_shadow.as_ref().map_or(50.0, |s| s.blur),+ opacity: layout.screen_opacity as f32,_padding: [0.0; 3],}};let camera = options.camera_size- .filter(|_| !project.camera.hide)+ .filter(|_| !project.camera.hide && layout.should_render_camera()).map(|camera_size| {let output_size = [output_size.0 as f32, output_size.1 as f32];let frame_size = [camera_size.x as f32, camera_size.y as f32];let min_axis = output_size[0].min(output_size[1]);- // Calculate camera size based on zoomlet base_size = project.camera.size / 100.0;let zoom_size = project.camera@@ -662,6 +658,8 @@ impl ProjectUniforms {let zoomed_size =(zoom.t as f32) * zoom_size * base_size + (1.0 - zoom.t as f32) * base_size;+ let zoomed_size = zoomed_size * layout.camera_scale as f32;+let aspect = frame_size[0] / frame_size[1];let size = match project.camera.shape {CameraShape::Source => {@@ -704,21 +702,22 @@ impl ProjectUniforms {position[1] + size[1],];- // Calculate camera motion blur based on zoom transitionlet camera_motion_blur = 0.0;+ let crop_bounds = match project.camera.shape {+ CameraShape::Source => [0.0, 0.0, frame_size[0], frame_size[1]],+ CameraShape::Square => [+ (frame_size[0] - frame_size[1]) / 2.0,+ 0.0,+ frame_size[0] - (frame_size[0] - frame_size[1]) / 2.0,+ frame_size[1],+ ],+ };+CompositeVideoFrameUniforms {output_size,frame_size,- crop_bounds: match project.camera.shape {- CameraShape::Source => [0.0, 0.0, frame_size[0], frame_size[1]],- CameraShape::Square => [- (frame_size[0] - frame_size[1]) / 2.0,- 0.0,- frame_size[0] - (frame_size[0] - frame_size[1]) / 2.0,- frame_size[1],- ],- },+ crop_bounds,target_bounds,target_size: [target_bounds[2] - target_bounds[0],@@ -745,6 +744,70 @@ impl ProjectUniforms {.advanced_shadow.as_ref().map_or(50.0, |s| s.blur),+ opacity: layout.regular_camera_transition_opacity() as f32,+ _padding: [0.0; 3],+ }+ });++ let camera_only = options+ .camera_size+ .filter(|_| !project.camera.hide && layout.is_transitioning_camera_only())+ .map(|camera_size| {+ let output_size = [output_size.0 as f32, output_size.1 as f32];+ let frame_size = [camera_size.x as f32, camera_size.y as f32];++ let aspect = frame_size[0] / frame_size[1];+ let output_aspect = output_size[0] / output_size[1];++ let zoom_factor = layout.camera_only_zoom as f32;+ let size = [output_size[0] * zoom_factor, output_size[1] * zoom_factor];++ let position = [+ (output_size[0] - size[0]) / 2.0,+ (output_size[1] - size[1]) / 2.0,+ ];++ let target_bounds = [+ position[0],+ position[1],+ position[0] + size[0],+ position[1] + size[1],+ ];++ // In camera-only mode, we ignore the camera shape setting (Square/Source)+ // and just apply the minimum crop needed to fill the output aspect ratio.+ // This prevents excessive zooming when shape is set to Square.+ let crop_bounds = if aspect > output_aspect {+ // Camera is wider than output - crop left and right+ let visible_width = frame_size[1] * output_aspect;+ let crop_x = (frame_size[0] - visible_width) / 2.0;+ [crop_x, 0.0, frame_size[0] - crop_x, frame_size[1]]+ } else {+ // Camera is taller than output - crop top and bottom+ let visible_height = frame_size[0] / output_aspect;+ let crop_y = (frame_size[1] - visible_height) / 2.0;+ [0.0, crop_y, frame_size[0], frame_size[1] - crop_y]+ };++ CompositeVideoFrameUniforms {+ output_size,+ frame_size,+ crop_bounds,+ target_bounds,+ target_size: [+ target_bounds[2] - target_bounds[0],+ target_bounds[3] - target_bounds[1],+ ],+ rounding_px: 0.0,+ mirror_x: if project.camera.mirror { 1.0 } else { 0.0 },+ velocity_uv: [0.0, 0.0],+ motion_blur_amount: 0.0,+ camera_motion_blur_amount: layout.camera_only_blur as f32 * 0.5,+ shadow: 0.0,+ shadow_size: 0.0,+ shadow_opacity: 0.0,+ shadow_blur: 0.0,+ opacity: layout.camera_only_transition_opacity() as f32,_padding: [0.0; 3],}});@@ -755,8 +818,10 @@ impl ProjectUniforms {resolution_base,display,camera,+ camera_only,project: project.clone(),zoom,+ layout,interpolated_cursor,}}@@ -821,6 +886,7 @@ pub struct RendererLayers {display: DisplayLayer,cursor: CursorLayer,camera: CameraLayer,+ camera_only: CameraLayer,#[allow(unused)]captions: CaptionsLayer,}@@ -833,6 +899,7 @@ impl RendererLayers {display: DisplayLayer::new(device),cursor: CursorLayer::new(device),camera: CameraLayer::new(device),+ camera_only: CameraLayer::new(device),captions: CaptionsLayer::new(device, queue),}}@@ -885,14 +952,17 @@ impl RendererLayers {})(),);- // if let Some(captions) = &uniforms.project.captions {- // self.captions.prepare(- // uniforms,- // segment_frames,- // uniforms.resolution_base,- // constants,- // );- // }+ self.camera_only.prepare(+ &constants.device,+ &constants.queue,+ (|| {+ Some((+ uniforms.camera_only?,+ constants.options.camera_size?,+ segment_frames.camera_frame.as_ref()?,+ ))+ })(),+ );Ok(())}@@ -902,6 +972,7 @@ impl RendererLayers {device: &wgpu::Device,encoder: &mut wgpu::CommandEncoder,session: &mut RenderSession,+ uniforms: &ProjectUniforms,) {macro_rules! render_pass {($view:expr, $load:expr) => {@@ -909,7 +980,6 @@ impl RendererLayers {label: Some("Render Pass"),color_attachments: &[Some(wgpu::RenderPassColorAttachment {view: $view,- // depth_slice: None,resolve_target: None,ops: wgpu::Operations {load: $load,@@ -939,25 +1009,29 @@ impl RendererLayers {session.swap_textures();}- {+ if uniforms.layout.should_render_screen() {let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);self.display.render(&mut pass);}- {+ if uniforms.layout.should_render_screen() {let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);self.cursor.render(&mut pass);}+ // Render camera-only layer when transitioning with CameraOnly mode+ if uniforms.layout.is_transitioning_camera_only() {+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);+ self.camera_only.render(&mut pass);+ }++ // Also render regular camera overlay during transitions when its opacity > 0+ if uniforms.layout.should_render_camera()+ && uniforms.layout.regular_camera_transition_opacity() > 0.01{let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);self.camera.render(&mut pass);}-- // {- // let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);- // self.captions.render(&mut pass);- // }}}@@ -1056,8 +1130,6 @@ impl RenderSession {}}-// TODO: reuse as many resources as possible-// https://github.com/gfx-rs/wgpu/wiki/Encapsulating-Graphics-Workasync fn produce_frame(constants: &RenderVideoConstants,segment_frames: DecodedSegmentFrames,@@ -1076,7 +1148,7 @@ async fn produce_frame(}),);- layers.render(&constants.device, &mut encoder, session);+ layers.render(&constants.device, &mut encoder, session, &uniforms);finish_encoder(session,@@ -1088,26 +1160,21 @@ async fn produce_frame(.await}-// Helper function to parse color components from hex stringsfn parse_color_component(hex_color: &str, index: usize) -> f32 {- // Remove # prefix if presentlet color = hex_color.trim_start_matches('#');- // Parse the color componentif color.len() == 6 {- // Standard hex color #RRGGBBlet start = index * 2;if let Ok(value) = u8::from_str_radix(&color[start..start + 2], 16) {return value as f32 / 255.0;}}- // Default fallback valuesmatch index {- 0 => 1.0, // Red default- 1 => 1.0, // Green default- 2 => 1.0, // Blue default- _ => 1.0, // Alpha default+ 0 => 1.0,+ 1 => 1.0,+ 2 => 1.0,+ _ => 1.0,}}@@ -1177,7 +1244,3 @@ fn srgb_to_linear(c: u16) -> f32 {((c + 0.055) / 1.055).powf(2.4)}}--// fn get_either<T>((a, b): (T, T), left: bool) -> T {-// if left { a } else { b }-// }diff --git a/crates/rendering/src/shaders/composite-video-frame.wgsl b/crates/rendering/src/shaders/composite-video-frame.wgslindex 2f76e3c12..4f47f4fb1 100644--- a/crates/rendering/src/shaders/composite-video-frame.wgsl+++ b/crates/rendering/src/shaders/composite-video-frame.wgsl@@ -13,6 +13,7 @@ struct Uniforms {shadow_size: f32,shadow_opacity: f32,shadow_blur: f32,+ opacity: f32,};@group(0) @binding(0) var<uniform> uniforms: Uniforms;@@ -96,6 +97,7 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {var base_color = sample_texture(target_uv, crop_bounds_uv);base_color = apply_rounded_corners(base_color, target_uv);+ base_color.a = base_color.a * uniforms.opacity;let blur_amount = select(uniforms.motion_blur_amount, uniforms.camera_motion_blur_amount, uniforms.camera_motion_blur_amount > 0.0);diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex 9c83adab7..054b44f3c 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -68,9 +68,11 @@ declare global {const IconLucideDatabase: typeof import("~icons/lucide/database.jsx")["default"];const IconLucideEdit: typeof import("~icons/lucide/edit.jsx")["default"];const IconLucideEye: typeof import("~icons/lucide/eye.jsx")["default"];+ const IconLucideEyeOff: typeof import("~icons/lucide/eye-off.jsx")["default"];const IconLucideFolder: typeof import("~icons/lucide/folder.jsx")["default"];const IconLucideGift: typeof import("~icons/lucide/gift.jsx")["default"];const IconLucideHardDrive: typeof import("~icons/lucide/hard-drive.jsx")["default"];+ const IconLucideLayout: typeof import("~icons/lucide/layout.jsx")["default"];const IconLucideLoaderCircle: typeof import("~icons/lucide/loader-circle.jsx")["default"];const IconLucideMessageSquarePlus: typeof import("~icons/lucide/message-square-plus.jsx")["default"];const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"];