diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000000..89cdb7d8cc5 --- /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 (`pnpm@10.5.2`) +- **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 ; + if (error) return { /* refetch */ }} />; + return ; +} +``` + +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 bindings diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs index a6842300dd5..5dcfb1b97f9 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.tsx index 7bb77e0d289..13c7cbac079 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() {
@@ -564,22 +577,112 @@ export function ConfigSidebar() {
{(selection) => ( -
+
{ 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) => ( +
+
+
+ + setEditorState("timeline", "selection", null) + } + leftIcon={} + > + Done + + + {value().segments.length} zoom{" "} + {value().segments.length === 1 + ? "segment" + : "segments"}{" "} + selected + +
+ { + projectActions.deleteZoomSegments( + value().segments.map((s) => s.index), + ); + }} + leftIcon={} + > + Delete + +
+ + + {(item, index) => ( +
+ +
+ )} +
+
+ } + > + + {(item) => ( +
+ +
+ )} +
+
+
+ )} + + { + 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) => ( - @@ -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 }) { 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 ( + <> +
+
+ Zoom {props.segmentIndex + 1} +
+
+ + +

+ Loading... +

+
+
+
+
+ +

{props.segment.amount.toFixed(1)}x

+
+ + ); +} + 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 ( <> -
-
- setEditorState("timeline", "selection", null)} - leftIcon={} - > - Done - -
- { - projectActions.deleteZoomSegment(props.segmentIndex); - }} - leftIcon={} - > - Delete - -
- }> + } + > @@ -1802,12 +2002,14 @@ function ZoomSegmentConfig(props: { when={(() => { const m = props.segment.mode; if (m === "auto") return; + return m.manual; })()} > {(mode) => { const start = createMemo((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(); @@ -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: { }, ); }, - }); - }); + }), + ); }} >
-
+ > +
+
+
+ +
+
+ Loading preview... +
+
+
); @@ -2024,6 +2273,112 @@ function ClipSegmentConfig(props: { ); } +function LayoutSegmentConfig(props: { + segmentIndex: number; + segment: LayoutSegment; +}) { + const { setProject, setEditorState, projectActions } = useEditorContext(); + + return ( + <> +
+
+ setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + +
+ { + projectActions.deleteLayoutSegment(props.segmentIndex); + }} + leftIcon={} + > + Delete + +
+ }> + { + setProject( + "timeline", + "layoutSegments", + props.segmentIndex, + "mode", + v as "default" | "cameraOnly" | "hideCamera", + ); + }} + > + +
+ + Default + + + Camera Only + + + Hide Camera + + +
+ +
+ +
+
+
+
+
+ {props.segment.mode === "cameraOnly" + ? "Shows only the camera feed" + : props.segment.mode === "hideCamera" + ? "Shows only the screen recording" + : "Shows both screen and camera"} +
+
+
+ + + + + ); +} + 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.tsx index cbf0dcb85cc..cd67d95ae94 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) => {