From cc5c4879ec460eb1d788100d49f5d8a241be1458 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 20:39:19 +0100 Subject: [PATCH 01/25] wip: Layout builder --- CLAUDE.md | 396 ++++++ apps/desktop/src-tauri/src/recording.rs | 1 + .../src/routes/editor/ConfigSidebar.tsx | 101 ++ .../src/routes/editor/Timeline/ClipTrack.tsx | 1228 +++++++++-------- .../routes/editor/Timeline/LayoutTrack.tsx | 454 ++++++ .../src/routes/editor/Timeline/ZoomTrack.tsx | 44 +- .../src/routes/editor/Timeline/index.tsx | 10 + apps/desktop/src/routes/editor/context.ts | 20 +- crates/project/src/configuration.rs | 18 + crates/rendering/src/composite_frame.rs | 1 + crates/rendering/src/layout.rs | 202 +++ crates/rendering/src/lib.rs | 181 ++- .../src/shaders/composite-video-frame.wgsl | 4 +- packages/ui-solid/src/auto-imports.d.ts | 168 +-- 14 files changed, 2063 insertions(+), 765 deletions(-) create mode 100644 CLAUDE.md create mode 100644 apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx create mode 100644 crates/rendering/src/layout.rs diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000000..27a2faf2ab7 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,396 @@ +# 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 +- 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..4689f64b516 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -48,6 +48,7 @@ import { type ZoomSegment, } from "~/utils/tauri"; import IconLucideSparkles from "~icons/lucide/sparkles"; +import IconLucideMonitor from "~icons/lucide/monitor"; import { CaptionsTab } from "./CaptionsTab"; import { useEditorContext } from "./context"; import { @@ -585,6 +586,25 @@ export function ConfigSidebar() { /> )} + { + const layoutSelection = selection(); + if (layoutSelection.type !== "layout") return; + + const segment = + project.timeline?.layoutSegments?.[layoutSelection.index]; + if (!segment) return; + + return { selection: layoutSelection, segment }; + })()} + > + {(value) => ( + + )} + { const clipSegment = selection(); @@ -2077,6 +2097,87 @@ function RgbInput(props: { ); } +interface LayoutSegment { + start: number; + end: number; + mode?: "default" | "cameraOnly" | "hideCamera"; +} + +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, + ); + }} + > + + + Default + + + Camera Only + + + Hide Camera + + +
+ + + + +
+

• Default: Shows both screen and camera

+

• Camera Only: Shows only the camera feed

+

• Hide Camera: Shows only the screen recording

+
+ + ); +} + function rgbToHex(rgb: [number, number, number]) { return `#${rgb .map((c) => c.toString(16).padStart(2, "0")) diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx index 72728849f84..e5dd2ff6067 100644 --- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx @@ -1,18 +1,18 @@ import { - createEventListener, - createEventListenerMap, + createEventListener, + createEventListenerMap, } from "@solid-primitives/event-listener"; import { cx } from "cva"; import { - type ComponentProps, - createEffect, - createMemo, - createRoot, - For, - Match, - mergeProps, - Show, - Switch, + type ComponentProps, + createEffect, + createMemo, + createRoot, + For, + Match, + mergeProps, + Show, + Switch, } from "solid-js"; import { produce } from "solid-js/store"; @@ -21,622 +21,632 @@ import { useEditorContext } from "../context"; import { useSegmentContext, useTimelineContext } from "./context"; import { getSectionMarker } from "./sectionMarker"; import { - SegmentContent, - SegmentHandle, - SegmentRoot, - TrackRoot, - useSegmentTranslateX, - useSegmentWidth, + SegmentContent, + SegmentHandle, + SegmentRoot, + TrackRoot, + useSegmentTranslateX, + useSegmentWidth, } from "./Track"; function WaveformCanvas(props: { - systemWaveform?: number[]; - micWaveform?: number[]; - segment: { start: number; end: number }; - secsPerPixel: number; + systemWaveform?: number[]; + micWaveform?: number[]; + segment: { start: number; end: number }; + secsPerPixel: number; }) { - const { project } = useEditorContext(); - - let canvas: HTMLCanvasElement | undefined; - const { width } = useSegmentContext(); - const { secsPerPixel } = useTimelineContext(); - - const render = ( - ctx: CanvasRenderingContext2D, - h: number, - waveform: number[], - color: string, - gain = 0, - ) => { - const maxAmplitude = h; - - // yellow please - ctx.fillStyle = color; - ctx.beginPath(); - - const step = 0.05 / secsPerPixel(); - - ctx.moveTo(0, h); - - const norm = (w: number) => 1.0 - Math.max(w + gain, -60) / -60; - - for ( - let segmentTime = props.segment.start; - segmentTime <= props.segment.end + 0.1; - segmentTime += 0.1 - ) { - const index = Math.floor(segmentTime * 10); - const xTime = index / 10; - - const amplitude = norm(waveform[index]) * 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 prevY = h - prevAmplitude; - - const cpX1 = prevX + step / 2; - const cpX2 = x - step / 2; - - ctx.bezierCurveTo(cpX1, prevY, cpX2, y, x, y); - } - - ctx.lineTo( - (props.segment.end + 0.3 - props.segment.start) / secsPerPixel(), - h, - ); - - ctx.closePath(); - ctx.fill(); - }; - - function renderWaveforms() { - if (!canvas) return; - const ctx = canvas.getContext("2d"); - if (!ctx) return; - - const w = width(); - if (w <= 0) return; - - const h = canvas.height; - canvas.width = w; - ctx.clearRect(0, 0, w, h); - - if (props.micWaveform) - render( - ctx, - h, - props.micWaveform, - "rgba(255,255,255,0.4)", - project.audio.micVolumeDb, - ); - - if (props.systemWaveform) - render( - ctx, - h, - props.systemWaveform, - "rgba(255,150,0,0.5)", - project.audio.systemVolumeDb, - ); - } - - createEffect(() => { - renderWaveforms(); - }); - - return ( - { - canvas = el; - renderWaveforms(); - }} - class="absolute inset-0 w-full h-full pointer-events-none" - height={52} - /> - ); + const { project } = useEditorContext(); + + let canvas: HTMLCanvasElement | undefined; + const { width } = useSegmentContext(); + const { secsPerPixel } = useTimelineContext(); + + const render = ( + ctx: CanvasRenderingContext2D, + h: number, + waveform: number[], + color: string, + gain = 0 + ) => { + const maxAmplitude = h; + + // yellow please + ctx.fillStyle = color; + ctx.beginPath(); + + const step = 0.05 / secsPerPixel(); + + ctx.moveTo(0, h); + + const norm = (w: number) => 1.0 - Math.max(w + gain, -60) / -60; + + for ( + let segmentTime = props.segment.start; + segmentTime <= props.segment.end + 0.1; + segmentTime += 0.1 + ) { + const index = Math.floor(segmentTime * 10); + const xTime = index / 10; + + const amplitude = norm(waveform[index]) * 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 prevY = h - prevAmplitude; + + const cpX1 = prevX + step / 2; + const cpX2 = x - step / 2; + + ctx.bezierCurveTo(cpX1, prevY, cpX2, y, x, y); + } + + ctx.lineTo( + (props.segment.end + 0.3 - props.segment.start) / secsPerPixel(), + h + ); + + ctx.closePath(); + ctx.fill(); + }; + + function renderWaveforms() { + if (!canvas) return; + const ctx = canvas.getContext("2d"); + if (!ctx) return; + + const w = width(); + if (w <= 0) return; + + const h = canvas.height; + canvas.width = w; + ctx.clearRect(0, 0, w, h); + + if (props.micWaveform) + render( + ctx, + h, + props.micWaveform, + "rgba(255,255,255,0.4)", + project.audio.micVolumeDb + ); + + if (props.systemWaveform) + render( + ctx, + h, + props.systemWaveform, + "rgba(255,150,0,0.5)", + project.audio.systemVolumeDb + ); + } + + createEffect(() => { + renderWaveforms(); + }); + + return ( + { + canvas = el; + renderWaveforms(); + }} + class="absolute inset-0 w-full h-full pointer-events-none" + height={52} + /> + ); } export function ClipTrack( - props: Pick, "ref"> & { - handleUpdatePlayhead: (e: MouseEvent) => void; - }, + props: Pick, "ref"> & { + handleUpdatePlayhead: (e: MouseEvent) => void; + } ) { - const { - project, - setProject, - projectActions, - editorInstance, - projectHistory, - editorState, - setEditorState, - totalDuration, - micWaveforms, - systemAudioWaveforms, - metaQuery, - } = useEditorContext(); - - const { secsPerPixel, duration } = useTimelineContext(); - - const segments = (): Array => - project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }]; - - function onHandleReleased() { - const { transform } = editorState.timeline; - - if (transform.position + transform.zoom > totalDuration() + 4) { - transform.updateZoom(totalDuration(), editorState.previewTime!); - } - } - - const hasMultipleRecordingSegments = () => - editorInstance.recordings.segments.length > 1; - - return ( - - - {(segment, i) => { - const prevDuration = () => - segments() - .slice(0, i()) - .reduce((t, s) => t + (s.end - s.start) / s.timescale, 0); - - const relativeSegment = mergeProps(segment, () => ({ - start: prevDuration(), - end: segment.end - segment.start + prevDuration(), - })); - - const segmentX = useSegmentTranslateX(() => relativeSegment); - const segmentWidth = useSegmentWidth(() => relativeSegment); - - const segmentRecording = (s = i()) => - editorInstance.recordings.segments[ - segments()[s].recordingSegment ?? 0 - ]; - - const marker = useSectionMarker(() => ({ - segments: segments(), - i: i(), - position: "left", - })); - - const endMarker = useSectionMarker(() => ({ - segments: segments(), - i: i(), - position: "right", - })); - - const isSelected = createMemo(() => { - const selection = editorState.timeline.selection; - if (!selection || selection.type !== "clip") return false; - - const segmentIndex = project.timeline?.segments?.findIndex( - (s) => s.start === segment.start && s.end === segment.end, - ); - - return segmentIndex === selection.index; - }); - - const micWaveform = () => { - if (project.audio.micVolumeDb && project.audio.micVolumeDb < -30) - return; - - const idx = segment.recordingSegment ?? i(); - return micWaveforms()?.[idx] ?? []; - }; - - const systemAudioWaveform = () => { - if ( - project.audio.systemVolumeDb && - project.audio.systemVolumeDb <= -30 - ) - return; - - const idx = segment.recordingSegment ?? i(); - return systemAudioWaveforms()?.[idx] ?? []; - }; - - return ( - <> - - {(marker) => ( -
-
- - { - const m = marker(); - if (m.type === "single") return m.value; - })()} - > - {(marker) => ( -
- { - const m = marker(); - return m.type === "time" ? m.time : 0; - })()} - onClick={() => { - setProject( - "timeline", - "segments", - produce((s) => { - if (marker().type === "reset") { - s[i() - 1].end = s[i()].end; - s.splice(i(), 1); - } else { - s[i() - 1].end = s[i()].start; - } - }), - ); - }} - /> -
- )} -
- { - const m = marker(); - if ( - m.type === "dual" && - m.right && - m.right.type === "time" - ) - return m.right; - })()} - > - {(marker) => { - const markerValue = marker(); - return ( -
- { - setProject( - "timeline", - "segments", - i(), - "start", - 0, - ); - }} - /> -
- ); - }} -
-
-
- )} - - { - e.stopPropagation(); - - if (editorState.timeline.interactMode === "split") { - const rect = e.currentTarget.getBoundingClientRect(); - const fraction = (e.clientX - rect.left) / rect.width; - - const splitTime = fraction * (segment.end - segment.start); - - projectActions.splitClipSegment(prevDuration() + splitTime); - } else { - createRoot((dispose) => { - createEventListener(e.currentTarget, "mouseup", (e) => { - dispose(); - - setEditorState("timeline", "selection", { - type: "clip", - index: i(), - }); - props.handleUpdatePlayhead(e); - }); - }); - } - }} - > - - - - - { - const start = segment.start; - - const maxSegmentDuration = - editorInstance.recordings.segments[ - segment.recordingSegment ?? 0 - ].display.duration; - - const availableTimelineDuration = - editorInstance.recordingDuration - - segments().reduce( - (acc, segment, segmentI) => - segmentI === i() - ? acc - : acc + - (segment.end - segment.start) / segment.timescale, - 0, - ); - - const maxDuration = Math.min( - maxSegmentDuration, - availableTimelineDuration, - ); - - const prevSegment = segments()[i() - 1]; - const prevSegmentIsSameClip = - prevSegment?.recordingSegment !== undefined - ? prevSegment.recordingSegment === - segment.recordingSegment - : false; - - function update(event: MouseEvent) { - const newStart = - start + - (event.clientX - downEvent.clientX) * secsPerPixel(); - - setProject( - "timeline", - "segments", - i(), - "start", - Math.min( - Math.max( - newStart, - prevSegmentIsSameClip ? prevSegment.end : 0, - segment.end - maxDuration, - ), - segment.end - 1, - ), - ); - } - - const resumeHistory = projectHistory.pause(); - createRoot((dispose) => { - createEventListenerMap(window, { - mousemove: update, - mouseup: (e) => { - dispose(); - resumeHistory(); - update(e); - onHandleReleased(); - }, - }); - }); - }} - /> - - {(() => { - const ctx = useSegmentContext(); - - return ( - 100}> -
- - {hasMultipleRecordingSegments() - ? `Clip ${segment.recordingSegment}` - : "Clip"} - -
- {" "} - {(segment.end - segment.start).toFixed(1)}s -
-
-
- ); - })()} -
- { - const end = segment.end; - - const maxSegmentDuration = - editorInstance.recordings.segments[ - segment.recordingSegment ?? 0 - ].display.duration; - - const availableTimelineDuration = - editorInstance.recordingDuration - - segments().reduce( - (acc, segment, segmentI) => - segmentI === i() - ? acc - : acc + - (segment.end - segment.start) / segment.timescale, - 0, - ); - - const nextSegment = segments()[i() + 1]; - const nextSegmentIsSameClip = - nextSegment?.recordingSegment !== undefined - ? nextSegment.recordingSegment === - segment.recordingSegment - : false; - - function update(event: MouseEvent) { - const newEnd = - end + - (event.clientX - downEvent.clientX) * secsPerPixel(); - - setProject( - "timeline", - "segments", - i(), - "end", - Math.max( - Math.min( - newEnd, - segment.end + availableTimelineDuration, - nextSegmentIsSameClip - ? nextSegment.start - : maxSegmentDuration, - ), - segment.start + 1, - ), - ); - } - - const resumeHistory = projectHistory.pause(); - createRoot((dispose) => { - createEventListenerMap(window, { - mousemove: update, - mouseup: (e) => { - dispose(); - resumeHistory(); - update(e); - onHandleReleased(); - }, - }); - }); - }} - /> -
- { - const m = endMarker(); - if (m?.type === "dual" && m.left && m.left.type === "time") - return m.left; - })()} - > - {(marker) => ( -
-
-
- { - const m = marker(); - return m.type === "time" ? m.time : 0; - })()} - class="-right-px absolute rounded-l-full !pr-1.5 rounded-tr-full" - onClick={() => { - setProject( - "timeline", - "segments", - i(), - "end", - segmentRecording().display.duration, - ); - }} - /> -
-
- )} - - - ); - }} - - - ); + const { + project, + setProject, + projectActions, + editorInstance, + projectHistory, + editorState, + setEditorState, + totalDuration, + micWaveforms, + systemAudioWaveforms, + metaQuery, + } = useEditorContext(); + + const { secsPerPixel, duration } = useTimelineContext(); + + const segments = (): Array => + project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }]; + + function onHandleReleased() { + const { transform } = editorState.timeline; + + if (transform.position + transform.zoom > totalDuration() + 4) { + transform.updateZoom(totalDuration(), editorState.previewTime!); + } + } + + const hasMultipleRecordingSegments = () => + editorInstance.recordings.segments.length > 1; + + return ( + + + {(segment, i) => { + const prevDuration = () => + segments() + .slice(0, i()) + .reduce((t, s) => t + (s.end - s.start) / s.timescale, 0); + + const relativeSegment = mergeProps(segment, () => ({ + start: prevDuration(), + end: segment.end - segment.start + prevDuration(), + })); + + const segmentX = useSegmentTranslateX(() => relativeSegment); + const segmentWidth = useSegmentWidth(() => relativeSegment); + + const segmentRecording = (s = i()) => + editorInstance.recordings.segments[ + segments()[s].recordingSegment ?? 0 + ]; + + const marker = useSectionMarker(() => ({ + segments: segments(), + i: i(), + position: "left", + })); + + const endMarker = useSectionMarker(() => ({ + segments: segments(), + i: i(), + position: "right", + })); + + const isSelected = createMemo(() => { + const selection = editorState.timeline.selection; + if (!selection || selection.type !== "clip") return false; + + const segmentIndex = project.timeline?.segments?.findIndex( + (s) => s.start === segment.start && s.end === segment.end + ); + + return segmentIndex === selection.index; + }); + + const micWaveform = () => { + if (project.audio.micVolumeDb && project.audio.micVolumeDb < -30) + return; + + const idx = segment.recordingSegment ?? i(); + return micWaveforms()?.[idx] ?? []; + }; + + const systemAudioWaveform = () => { + if ( + project.audio.systemVolumeDb && + project.audio.systemVolumeDb <= -30 + ) + return; + + const idx = segment.recordingSegment ?? i(); + return systemAudioWaveforms()?.[idx] ?? []; + }; + + return ( + <> + + {(marker) => ( +
+
+ + { + const m = marker(); + if (m.type === "single") return m.value; + })()} + > + {(marker) => ( +
+ { + const m = marker(); + return m.type === "time" ? m.time : 0; + })()} + onClick={() => { + setProject( + "timeline", + "segments", + produce((s) => { + if (marker().type === "reset") { + s[i() - 1].end = s[i()].end; + s.splice(i(), 1); + } else { + s[i() - 1].end = s[i()].start; + } + }) + ); + }} + /> +
+ )} +
+ { + const m = marker(); + if ( + m.type === "dual" && + m.right && + m.right.type === "time" + ) + return m.right; + })()} + > + {(marker) => { + const markerValue = marker(); + return ( +
+ { + setProject( + "timeline", + "segments", + i(), + "start", + 0 + ); + }} + /> +
+ ); + }} +
+
+
+ )} + + { + e.stopPropagation(); + + if (editorState.timeline.interactMode === "split") { + const rect = e.currentTarget.getBoundingClientRect(); + const fraction = (e.clientX - rect.left) / rect.width; + + const splitTime = fraction * (segment.end - segment.start); + + projectActions.splitClipSegment(prevDuration() + splitTime); + } else { + createRoot((dispose) => { + createEventListener(e.currentTarget, "mouseup", (e) => { + dispose(); + + // 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) { + // Skip opening clip config for single segments + // The user probably just wants to interact with the timeline normally + } else { + // When there are multiple segments, show the clip configuration + setEditorState("timeline", "selection", { + type: "clip", + index: i(), + }); + } + props.handleUpdatePlayhead(e); + }); + }); + } + }} + > + + + + + { + const start = segment.start; + + const maxSegmentDuration = + editorInstance.recordings.segments[ + segment.recordingSegment ?? 0 + ].display.duration; + + const availableTimelineDuration = + editorInstance.recordingDuration - + segments().reduce( + (acc, segment, segmentI) => + segmentI === i() + ? acc + : acc + + (segment.end - segment.start) / segment.timescale, + 0 + ); + + const maxDuration = Math.min( + maxSegmentDuration, + availableTimelineDuration + ); + + const prevSegment = segments()[i() - 1]; + const prevSegmentIsSameClip = + prevSegment?.recordingSegment !== undefined + ? prevSegment.recordingSegment === + segment.recordingSegment + : false; + + function update(event: MouseEvent) { + const newStart = + start + + (event.clientX - downEvent.clientX) * secsPerPixel(); + + setProject( + "timeline", + "segments", + i(), + "start", + Math.min( + Math.max( + newStart, + prevSegmentIsSameClip ? prevSegment.end : 0, + segment.end - maxDuration + ), + segment.end - 1 + ) + ); + } + + const resumeHistory = projectHistory.pause(); + createRoot((dispose) => { + createEventListenerMap(window, { + mousemove: update, + mouseup: (e) => { + dispose(); + resumeHistory(); + update(e); + onHandleReleased(); + }, + }); + }); + }} + /> + + {(() => { + const ctx = useSegmentContext(); + + return ( + 100}> +
+ + {hasMultipleRecordingSegments() + ? `Clip ${segment.recordingSegment}` + : "Clip"} + +
+ {" "} + {(segment.end - segment.start).toFixed(1)}s +
+
+
+ ); + })()} +
+ { + const end = segment.end; + + const maxSegmentDuration = + editorInstance.recordings.segments[ + segment.recordingSegment ?? 0 + ].display.duration; + + const availableTimelineDuration = + editorInstance.recordingDuration - + segments().reduce( + (acc, segment, segmentI) => + segmentI === i() + ? acc + : acc + + (segment.end - segment.start) / segment.timescale, + 0 + ); + + const nextSegment = segments()[i() + 1]; + const nextSegmentIsSameClip = + nextSegment?.recordingSegment !== undefined + ? nextSegment.recordingSegment === + segment.recordingSegment + : false; + + function update(event: MouseEvent) { + const newEnd = + end + + (event.clientX - downEvent.clientX) * secsPerPixel(); + + setProject( + "timeline", + "segments", + i(), + "end", + Math.max( + Math.min( + newEnd, + segment.end + availableTimelineDuration, + nextSegmentIsSameClip + ? nextSegment.start + : maxSegmentDuration + ), + segment.start + 1 + ) + ); + } + + const resumeHistory = projectHistory.pause(); + createRoot((dispose) => { + createEventListenerMap(window, { + mousemove: update, + mouseup: (e) => { + dispose(); + resumeHistory(); + update(e); + onHandleReleased(); + }, + }); + }); + }} + /> +
+ { + const m = endMarker(); + if (m?.type === "dual" && m.left && m.left.type === "time") + return m.left; + })()} + > + {(marker) => ( +
+
+
+ { + const m = marker(); + return m.type === "time" ? m.time : 0; + })()} + class="-right-px absolute rounded-l-full !pr-1.5 rounded-tr-full" + onClick={() => { + setProject( + "timeline", + "segments", + i(), + "end", + segmentRecording().display.duration + ); + }} + /> +
+
+ )} + + + ); + }} + + + ); } function Markings(props: { segment: TimelineSegment; prevDuration: number }) { - const { editorState } = useEditorContext(); - const { secsPerPixel, markingResolution } = useTimelineContext(); - - const markings = () => { - const resolution = markingResolution(); - - const { transform } = editorState.timeline; - const visibleMin = - transform.position - props.prevDuration + props.segment.start; - const visibleMax = visibleMin + transform.zoom; - - const start = Math.floor(visibleMin / resolution); - - return Array.from( - { length: Math.ceil(visibleMax / resolution) - start }, - (_, i) => (start + i) * resolution, - ); - }; - - return ( - - {(marking) => ( -
- )} - - ); + const { editorState } = useEditorContext(); + const { secsPerPixel, markingResolution } = useTimelineContext(); + + const markings = () => { + const resolution = markingResolution(); + + const { transform } = editorState.timeline; + const visibleMin = + transform.position - props.prevDuration + props.segment.start; + const visibleMax = visibleMin + transform.zoom; + + const start = Math.floor(visibleMin / resolution); + + return Array.from( + { length: Math.ceil(visibleMax / resolution) - start }, + (_, i) => (start + i) * resolution + ); + }; + + return ( + + {(marking) => ( +
+ )} + + ); } function CutOffsetButton(props: { - value: number; - class?: string; - onClick?(): void; + value: number; + class?: string; + onClick?(): void; }) { - const formatTime = (t: number) => - t < 1 ? Math.round(t * 10) / 10 : Math.round(t); - - return ( - - ); + const formatTime = (t: number) => + t < 1 ? Math.round(t * 10) / 10 : Math.round(t); + + return ( + + ); } function useSectionMarker( - props: () => { - segments: TimelineSegment[]; - i: number; - position: "left" | "right"; - }, + props: () => { + segments: TimelineSegment[]; + i: number; + position: "left" | "right"; + } ) { - const { editorInstance } = useEditorContext(); + const { editorInstance } = useEditorContext(); - return () => getSectionMarker(props(), editorInstance.recordings.segments); + return () => getSectionMarker(props(), editorInstance.recordings.segments); } diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx new file mode 100644 index 00000000000..4d1135911ce --- /dev/null +++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx @@ -0,0 +1,454 @@ +import { + createEventListener, + createEventListenerMap, +} from "@solid-primitives/event-listener"; +import { Menu } from "@tauri-apps/api/menu"; +import { cx } from "cva"; +import { + batch, + createEffect, + createMemo, + createRoot, + createSignal, + For, + Show, +} from "solid-js"; +import { produce } from "solid-js/store"; +import { useEditorContext } from "../context"; +import { + useSegmentContext, + useTimelineContext, + useTrackContext, +} from "./context"; +import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track"; +import IconLucideMonitor from "~icons/lucide/monitor"; +import IconLucideVideo from "~icons/lucide/video"; +import IconLucideEyeOff from "~icons/lucide/eye-off"; + +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(); + + // 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) => { + switch (mode) { + case "cameraOnly": + return ; + case "hideCamera": + return ; + default: + return ; + } + }; + + const getLayoutLabel = (mode: string) => { + switch (mode) { + case "cameraOnly": + return "Camera Only"; + case "hideCamera": + return "Hide Camera"; + default: + return "Default"; + } + }; + + return ( + { + if (hoveringSegment()) { + setHoveredTime(undefined); + return; + } + + const bounds = e.target.getBoundingClientRect()!; + + let time = + (e.clientX - bounds.left) * secsPerPixel() + + editorState.timeline.transform.position; + + const nextSegmentIndex = project.timeline?.layoutSegments?.findIndex( + (s) => time < s.start, + ); + + if (nextSegmentIndex !== undefined) { + const prevSegmentIndex = nextSegmentIndex - 1; + + if (prevSegmentIndex === undefined) return; + + const nextSegment = + project.timeline?.layoutSegments?.[nextSegmentIndex]; + + if (prevSegmentIndex !== undefined && nextSegment) { + const prevSegment = + project.timeline?.layoutSegments?.[prevSegmentIndex]; + + if (prevSegment) { + const availableTime = nextSegment?.start - prevSegment?.end; + + if (availableTime < 1) return; + } + } + + if (nextSegment && nextSegment.start - time < 1) { + time = nextSegment.start - 1; + } + } + + setHoveredTime(Math.min(time, duration() - 1)); + }} + onMouseLeave={() => setHoveredTime()} + onMouseDown={(e) => { + createRoot((dispose) => { + createEventListener(e.currentTarget, "mouseup", (e) => { + dispose(); + + const time = hoveredTime(); + 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 + 3, + mode: "default", + }); + }), + ); + }); + }); + }); + }} + > + + Click to add layout segment +
+ } + > + {(segment, i) => { + const { setTrackState } = useTrackContext(); + + const layoutSegments = () => project.timeline!.layoutSegments!; + + function createMouseDownDrag( + 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); + } + 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; + }); + + const segmentColor = () => { + switch (segment.mode) { + case "cameraOnly": + return "from-[#3B82F6] via-[#60A5FA] to-[#3B82F6]"; + case "hideCamera": + return "from-[#EF4444] via-[#F87171] to-[#EF4444]"; + default: + return "from-[#10B981] via-[#34D399] to-[#10B981]"; + } + }; + + return ( + { + setHoveringSegment(true); + }} + onMouseLeave={() => { + setHoveringSegment(false); + }} + > + { + 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) => { + s.sort((a, b) => a.start - b.start); + }), + ); + }, + )} + /> + { + 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 ( + 80}> +
+ Layout +
+ {getLayoutIcon(segment.mode)} + {ctx.width() > 120 && ( + + {getLayoutLabel(segment.mode)} + + )} +
+
+
+ ); + })()} +
+ { + 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) => { + s.sort((a, b) => a.start - b.start); + }), + ); + }, + )} + /> +
+ ); + }} +
+ + {(time) => ( + + +

+ + +

+
+
+ )} +
+ + ); +} \ No newline at end of file diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx index 3e16a3a8874..8d509d6a1b0 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,18 @@ export function ZoomTrack(props: { const [hoveringSegment, setHoveringSegment] = createSignal(false); const [hoveredTime, setHoveredTime] = createSignal(); + // 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); + } + }); + const handleGenerateZoomSegments = async () => { try { const zoomSegments = await commands.generateZoomSegmentsFromClicks(); @@ -156,7 +169,7 @@ export function ZoomTrack(props: { +
Click to add zoom segment
} @@ -350,18 +363,35 @@ export function ZoomTrack(props: { > {(() => { const ctx = useSegmentContext(); + const width = ctx.width(); - return ( - 100}> + if (width < 40) { + // Very small - just show icon + return ( +
+ +
+ ); + } else if (width < 100) { + // Small - show icon and zoom amount + return ( +
+ + {zoomPercentage()} +
+ ); + } else { + // Large - show full content + return (
Zoom
- {" "} - {zoomPercentage()}{" "} + + {zoomPercentage()}
-
- ); + ); + } })()} + { + layoutSegmentDragState = v; + }} + handleUpdatePlayhead={handleUpdatePlayhead} + />
); diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts index 56cb1493a21..ad431e23d0a 100644 --- a/apps/desktop/src/routes/editor/context.ts +++ b/apps/desktop/src/routes/editor/context.ts @@ -122,7 +122,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( "segments", produce((s) => { if (!s) return; - return s.splice(segmentIndex, 1); + s.splice(segmentIndex, 1); }), ); setEditorState("timeline", "selection", null); @@ -135,7 +135,20 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( "zoomSegments", produce((s) => { if (!s) return; - return s.splice(segmentIndex, 1); + s.splice(segmentIndex, 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); @@ -238,7 +251,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( selection: null as | null | { type: "zoom"; index: number } - | { type: "clip"; index: number }, + | { type: "clip"; index: number } + | { type: "layout"; index: number }, transform: { // visible seconds zoom: zoomOutLimit(), diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs index 3202b1e5c77..b8f9ff83880 100644 --- a/crates/project/src/configuration.rs +++ b/crates/project/src/configuration.rs @@ -456,11 +456,29 @@ pub enum ZoomMode { Manual { x: f32, y: f32 }, } +#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug)] +#[serde(rename_all = "camelCase")] +pub enum LayoutMode { + Default, + CameraOnly, + HideCamera, +} + +#[derive(Type, Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct LayoutSegment { + pub start: f64, + pub end: f64, + pub mode: LayoutMode, +} + #[derive(Type, Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct TimelineConfiguration { pub segments: Vec, pub zoom_segments: Vec, + #[serde(default)] + pub layout_segments: Vec, } impl TimelineConfiguration { diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rs index 992246caaa8..06529d35a7b 100644 --- a/crates/rendering/src/composite_frame.rs +++ b/crates/rendering/src/composite_frame.rs @@ -25,6 +25,7 @@ pub struct CompositeVideoFrameUniforms { pub shadow_size: f32, pub shadow_opacity: f32, pub shadow_blur: f32, + pub opacity: f32, pub _padding: [f32; 3], } diff --git a/crates/rendering/src/layout.rs b/crates/rendering/src/layout.rs new file mode 100644 index 00000000000..0d47a7a7ee9 --- /dev/null +++ b/crates/rendering/src/layout.rs @@ -0,0 +1,202 @@ +use cap_project::{LayoutMode, LayoutSegment}; + +pub const LAYOUT_TRANSITION_DURATION: f64 = 0.5; + +#[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, +} + +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; + 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 { + (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 { + let transition_end = prev_segment.end + LAYOUT_TRANSITION_DURATION; + if cursor.time <= transition_end { + let progress = (cursor.time - prev_segment.end) / LAYOUT_TRANSITION_DURATION; + ( + prev_segment.mode.clone(), + LayoutMode::Default, + ease_in_out(progress as f32) as f64, + ) + } else { + (LayoutMode::Default, LayoutMode::Default, 1.0) + } + } else { + (LayoutMode::Default, LayoutMode::Default, 1.0) + } + } else { + if let Some(prev_segment) = cursor.prev_segment { + let transition_end = prev_segment.end + LAYOUT_TRANSITION_DURATION; + if cursor.time <= transition_end { + let progress = (cursor.time - prev_segment.end) / LAYOUT_TRANSITION_DURATION; + ( + prev_segment.mode.clone(), + LayoutMode::Default, + ease_in_out(progress as f32) as f64, + ) + } 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); + + 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, + } + } + + fn get_layout_values(mode: &LayoutMode) -> (f64, f64, f64) { + match mode { + LayoutMode::Default => (1.0, 1.0, 1.0), + LayoutMode::CameraOnly => (1.0, 0.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 { + self.screen_opacity > 0.01 + } + + 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 + } + } +} diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs index cbae60a986b..45f16a6b2f3 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 duration let 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 skip let 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 exists if 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 duration if 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, + camera_only: Option, interpolated_cursor: Option, pub project: ProjectConfiguration, pub zoom: InterpolatedZoom, + pub layout: InterpolatedLayout, pub resolution_base: XY, } @@ -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]; @@ -639,19 +635,22 @@ 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 + && !matches!(layout.layout_mode, cap_project::LayoutMode::CameraOnly) + }) .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 zoom let base_size = project.camera.size / 100.0; let zoom_size = project .camera @@ -662,6 +661,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 +705,22 @@ impl ProjectUniforms { position[1] + size[1], ]; - // Calculate camera motion blur based on zoom transition let 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 +747,67 @@ impl ProjectUniforms { .advanced_shadow .as_ref() .map_or(50.0, |s| s.blur), + opacity: layout.camera_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]; + + // Always fill the entire output + let size = output_size; + + let position = [0.0, 0.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: 0.0, + 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,25 @@ 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); } - { + if uniforms.layout.should_render_camera() { 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); - // } + 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); + } } } @@ -1056,8 +1126,6 @@ impl RenderSession { } } -// TODO: reuse as many resources as possible -// https://github.com/gfx-rs/wgpu/wiki/Encapsulating-Graphics-Work async fn produce_frame( constants: &RenderVideoConstants, segment_frames: DecodedSegmentFrames, @@ -1076,7 +1144,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 +1156,21 @@ async fn produce_frame( .await } -// Helper function to parse color components from hex strings fn parse_color_component(hex_color: &str, index: usize) -> f32 { - // Remove # prefix if present let color = hex_color.trim_start_matches('#'); - // Parse the color component if color.len() == 6 { - // Standard hex color #RRGGBB let start = index * 2; if let Ok(value) = u8::from_str_radix(&color[start..start + 2], 16) { return value as f32 / 255.0; } } - // Default fallback values match 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 +1240,3 @@ fn srgb_to_linear(c: u16) -> f32 { ((c + 0.055) / 1.055).powf(2.4) } } - -// fn get_either((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.wgsl index 2f76e3c120f..ca4cc06f2b7 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 uniforms: Uniforms; @@ -96,6 +97,7 @@ fn fs_main(@builtin(position) frag_coord: vec4) -> @location(0) vec4 { 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); @@ -146,7 +148,7 @@ fn fs_main(@builtin(position) frag_coord: vec4) -> @location(0) vec4 { } let final_color = accum / weight_sum; - let blurred = vec4(final_color.rgb, base_color.a); + let blurred = vec4(final_color.rgb, base_color.a * uniforms.opacity); return mix(shadow_color, blurred, blurred.a); } diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts index 7c165f2b98f..b6b6f3d663d 100644 --- a/packages/ui-solid/src/auto-imports.d.ts +++ b/packages/ui-solid/src/auto-imports.d.ts @@ -4,89 +4,89 @@ // noinspection JSUnusedGlobalSymbols // Generated by unplugin-auto-import // biome-ignore lint: disable -export {}; +export {} declare global { - const IconCapArrows: typeof import("~icons/cap/arrows.jsx")["default"]; - const IconCapAudioOn: typeof import("~icons/cap/audio-on.jsx")["default"]; - const IconCapBgBlur: typeof import("~icons/cap/bg-blur.jsx")["default"]; - const IconCapCamera: typeof import("~icons/cap/camera.jsx")["default"]; - const IconCapCaptions: typeof import("~icons/cap/captions.jsx")["default"]; - const IconCapChevronDown: typeof import("~icons/cap/chevron-down.jsx")["default"]; - const IconCapCircle: typeof import("~icons/cap/circle.jsx")["default"]; - const IconCapCircleCheck: typeof import("~icons/cap/circle-check.jsx")["default"]; - const IconCapCirclePlus: typeof import("~icons/cap/circle-plus.jsx")["default"]; - const IconCapCircleX: typeof import("~icons/cap/circle-x.jsx")["default"]; - const IconCapCopy: typeof import("~icons/cap/copy.jsx")["default"]; - const IconCapCorners: typeof import("~icons/cap/corners.jsx")["default"]; - const IconCapCrop: typeof import("~icons/cap/crop.jsx")["default"]; - const IconCapCursor: typeof import("~icons/cap/cursor.jsx")["default"]; - const IconCapEditor: typeof import("~icons/cap/editor.jsx")["default"]; - const IconCapEnlarge: typeof import("~icons/cap/enlarge.jsx")["default"]; - const IconCapFile: typeof import("~icons/cap/file.jsx")["default"]; - const IconCapFilmCut: typeof import("~icons/cap/film-cut.jsx")["default"]; - const IconCapGauge: typeof import("~icons/cap/gauge.jsx")["default"]; - const IconCapHotkeys: typeof import("~icons/cap/hotkeys.jsx")["default"]; - const IconCapImage: typeof import("~icons/cap/image.jsx")["default"]; - const IconCapInfo: typeof import("~icons/cap/info.jsx")["default"]; - const IconCapInstant: typeof import("~icons/cap/instant.jsx")["default"]; - const IconCapLayout: typeof import("~icons/cap/layout.jsx")["default"]; - const IconCapLink: typeof import("~icons/cap/link.jsx")["default"]; - const IconCapLogo: typeof import("~icons/cap/logo.jsx")["default"]; - const IconCapLogoFull: typeof import("~icons/cap/logo-full.jsx")["default"]; - const IconCapLogoFullDark: typeof import("~icons/cap/logo-full-dark.jsx")["default"]; - const IconCapMessageBubble: typeof import("~icons/cap/message-bubble.jsx")["default"]; - const IconCapMicrophone: typeof import("~icons/cap/microphone.jsx")["default"]; - const IconCapMoreVertical: typeof import("~icons/cap/more-vertical.jsx")["default"]; - const IconCapNext: typeof import("~icons/cap/next.jsx")["default"]; - const IconCapPadding: typeof import("~icons/cap/padding.jsx")["default"]; - const IconCapPause: typeof import("~icons/cap/pause.jsx")["default"]; - const IconCapPauseCircle: typeof import("~icons/cap/pause-circle.jsx")["default"]; - const IconCapPlay: typeof import("~icons/cap/play.jsx")["default"]; - const IconCapPlayCircle: typeof import("~icons/cap/play-circle.jsx")["default"]; - const IconCapPresets: typeof import("~icons/cap/presets.jsx")["default"]; - const IconCapPrev: typeof import("~icons/cap/prev.jsx")["default"]; - const IconCapRedo: typeof import("~icons/cap/redo.jsx")["default"]; - const IconCapRestart: typeof import("~icons/cap/restart.jsx")["default"]; - const IconCapScissors: typeof import("~icons/cap/scissors.jsx")["default"]; - const IconCapSettings: typeof import("~icons/cap/settings.jsx")["default"]; - const IconCapShadow: typeof import("~icons/cap/shadow.jsx")["default"]; - const IconCapSquare: typeof import("~icons/cap/square.jsx")["default"]; - const IconCapStopCircle: typeof import("~icons/cap/stop-circle.jsx")["default"]; - const IconCapTrash: typeof import("~icons/cap/trash.jsx")["default"]; - const IconCapUndo: typeof import("~icons/cap/undo.jsx")["default"]; - const IconCapUpload: typeof import("~icons/cap/upload.jsx")["default"]; - const IconCapZoomIn: typeof import("~icons/cap/zoom-in.jsx")["default"]; - const IconCapZoomOut: typeof import("~icons/cap/zoom-out.jsx")["default"]; - const IconFa6SolidDisplay: typeof import("~icons/fa6-solid/display.jsx")["default"]; - const IconHugeiconsEaseCurveControlPoints: typeof import("~icons/hugeicons/ease-curve-control-points.jsx")["default"]; - const IconIcBaselineMonitor: typeof import("~icons/ic/baseline-monitor.jsx")["default"]; - const IconIcRoundSearch: typeof import("~icons/ic/round-search.jsx")["default"]; - const IconLucideAppWindowMac: typeof import("~icons/lucide/app-window-mac.jsx")["default"]; - const IconLucideBell: typeof import("~icons/lucide/bell.jsx")["default"]; - const IconLucideBug: typeof import("~icons/lucide/bug.jsx")["default"]; - const IconLucideCheck: typeof import("~icons/lucide/check.jsx")["default"]; - const IconLucideClock: typeof import("~icons/lucide/clock.jsx")["default"]; - 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 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 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"]; - const IconLucideMonitor: typeof import("~icons/lucide/monitor.jsx")["default"]; - const IconLucideRectangleHorizontal: typeof import("~icons/lucide/rectangle-horizontal.jsx")["default"]; - const IconLucideRotateCcw: typeof import("~icons/lucide/rotate-ccw.jsx")["default"]; - const IconLucideSearch: typeof import("~icons/lucide/search.jsx")["default"]; - const IconLucideSquarePlay: typeof import("~icons/lucide/square-play.jsx")["default"]; - const IconLucideUnplug: typeof import("~icons/lucide/unplug.jsx")["default"]; - const IconLucideVolume2: typeof import("~icons/lucide/volume2.jsx")["default"]; - const IconLucideVolumeX: typeof import("~icons/lucide/volume-x.jsx")["default"]; - const IconLucideX: typeof import("~icons/lucide/x.jsx")["default"]; - const IconMaterialSymbolsLightScreenshotFrame2: typeof import("~icons/material-symbols-light/screenshot-frame2.jsx")["default"]; - const IconMaterialSymbolsLightScreenshotFrame2MaterialSymbolsScreenshotFrame2Rounded: typeof import("~icons/material-symbols-light/screenshot-frame2-material-symbols-screenshot-frame2-rounded.jsx")["default"]; - const IconMaterialSymbolsScreenshotFrame2Rounded: typeof import("~icons/material-symbols/screenshot-frame2-rounded.jsx")["default"]; - const IconMdiMonitor: typeof import("~icons/mdi/monitor.jsx")["default"]; - const IconPhMonitorBold: typeof import("~icons/ph/monitor-bold.jsx")["default"]; + const IconCapArrows: typeof import("~icons/cap/arrows.jsx")["default"] + const IconCapAudioOn: typeof import('~icons/cap/audio-on.jsx')['default'] + const IconCapBgBlur: typeof import('~icons/cap/bg-blur.jsx')['default'] + const IconCapCamera: typeof import('~icons/cap/camera.jsx')['default'] + const IconCapCaptions: typeof import('~icons/cap/captions.jsx')['default'] + const IconCapChevronDown: typeof import('~icons/cap/chevron-down.jsx')['default'] + const IconCapCircle: typeof import("~icons/cap/circle.jsx")["default"] + const IconCapCircleCheck: typeof import('~icons/cap/circle-check.jsx')['default'] + const IconCapCirclePlus: typeof import('~icons/cap/circle-plus.jsx')['default'] + const IconCapCircleX: typeof import('~icons/cap/circle-x.jsx')['default'] + const IconCapCopy: typeof import('~icons/cap/copy.jsx')['default'] + const IconCapCorners: typeof import('~icons/cap/corners.jsx')['default'] + const IconCapCrop: typeof import('~icons/cap/crop.jsx')['default'] + const IconCapCursor: typeof import('~icons/cap/cursor.jsx')['default'] + const IconCapEditor: typeof import("~icons/cap/editor.jsx")["default"] + const IconCapEnlarge: typeof import('~icons/cap/enlarge.jsx')['default'] + const IconCapFile: typeof import('~icons/cap/file.jsx')['default'] + const IconCapFilmCut: typeof import('~icons/cap/film-cut.jsx')['default'] + const IconCapGauge: typeof import('~icons/cap/gauge.jsx')['default'] + const IconCapHotkeys: typeof import('~icons/cap/hotkeys.jsx')['default'] + const IconCapImage: typeof import('~icons/cap/image.jsx')['default'] + const IconCapInfo: typeof import("~icons/cap/info.jsx")["default"] + const IconCapInstant: typeof import('~icons/cap/instant.jsx')['default'] + const IconCapLayout: typeof import('~icons/cap/layout.jsx')['default'] + const IconCapLink: typeof import('~icons/cap/link.jsx')['default'] + const IconCapLogo: typeof import('~icons/cap/logo.jsx')['default'] + const IconCapLogoFull: typeof import("~icons/cap/logo-full.jsx")["default"] + const IconCapLogoFullDark: typeof import("~icons/cap/logo-full-dark.jsx")["default"] + const IconCapMessageBubble: typeof import('~icons/cap/message-bubble.jsx')['default'] + const IconCapMicrophone: typeof import('~icons/cap/microphone.jsx')['default'] + const IconCapMoreVertical: typeof import("~icons/cap/more-vertical.jsx")["default"] + const IconCapNext: typeof import('~icons/cap/next.jsx')['default'] + const IconCapPadding: typeof import('~icons/cap/padding.jsx')['default'] + const IconCapPause: typeof import('~icons/cap/pause.jsx')['default'] + const IconCapPauseCircle: typeof import("~icons/cap/pause-circle.jsx")["default"] + const IconCapPlay: typeof import('~icons/cap/play.jsx')['default'] + const IconCapPlayCircle: typeof import("~icons/cap/play-circle.jsx")["default"] + const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default'] + const IconCapPrev: typeof import('~icons/cap/prev.jsx')['default'] + const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default'] + const IconCapRestart: typeof import("~icons/cap/restart.jsx")["default"] + const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default'] + const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default'] + const IconCapShadow: typeof import('~icons/cap/shadow.jsx')['default'] + const IconCapSquare: typeof import("~icons/cap/square.jsx")["default"] + const IconCapStopCircle: typeof import("~icons/cap/stop-circle.jsx")["default"] + const IconCapTrash: typeof import('~icons/cap/trash.jsx')['default'] + const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default'] + const IconCapUpload: typeof import("~icons/cap/upload.jsx")["default"] + const IconCapZoomIn: typeof import('~icons/cap/zoom-in.jsx')['default'] + const IconCapZoomOut: typeof import('~icons/cap/zoom-out.jsx')['default'] + const IconFa6SolidDisplay: typeof import("~icons/fa6-solid/display.jsx")["default"] + const IconHugeiconsEaseCurveControlPoints: typeof import('~icons/hugeicons/ease-curve-control-points.jsx')['default'] + const IconIcBaselineMonitor: typeof import("~icons/ic/baseline-monitor.jsx")["default"] + const IconIcRoundSearch: typeof import("~icons/ic/round-search.jsx")["default"] + const IconLucideAppWindowMac: typeof import('~icons/lucide/app-window-mac.jsx')['default'] + const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default'] + const IconLucideBug: typeof import('~icons/lucide/bug.jsx')['default'] + const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default'] + const IconLucideClock: typeof import('~icons/lucide/clock.jsx')['default'] + 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 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 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"] + const IconLucideMonitor: typeof import('~icons/lucide/monitor.jsx')['default'] + const IconLucideRectangleHorizontal: typeof import("~icons/lucide/rectangle-horizontal.jsx")["default"] + const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default'] + const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default'] + const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default'] + const IconLucideUnplug: typeof import('~icons/lucide/unplug.jsx')['default'] + const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default'] + const IconLucideVolumeX: typeof import("~icons/lucide/volume-x.jsx")["default"] + const IconLucideX: typeof import("~icons/lucide/x.jsx")["default"] + const IconMaterialSymbolsLightScreenshotFrame2: typeof import("~icons/material-symbols-light/screenshot-frame2.jsx")["default"] + const IconMaterialSymbolsLightScreenshotFrame2MaterialSymbolsScreenshotFrame2Rounded: typeof import("~icons/material-symbols-light/screenshot-frame2-material-symbols-screenshot-frame2-rounded.jsx")["default"] + const IconMaterialSymbolsScreenshotFrame2Rounded: typeof import('~icons/material-symbols/screenshot-frame2-rounded.jsx')['default'] + const IconMdiMonitor: typeof import('~icons/mdi/monitor.jsx')['default'] + const IconPhMonitorBold: typeof import('~icons/ph/monitor-bold.jsx')['default'] } From fbde152e5e8b41d3c89322ec02c23e8481ae550b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 21:06:57 +0100 Subject: [PATCH 02/25] fix: Zoom sidebar click + zoom image preview (red bg issue) --- .../src/routes/editor/ConfigSidebar.tsx | 4033 +++++++++-------- .../src/routes/editor/Timeline/ClipTrack.tsx | 5 +- apps/desktop/src/utils/tauri.ts | 7 + 3 files changed, 2051 insertions(+), 1994 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 4689f64b516..18487283df4 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -1,10 +1,10 @@ import { - Collapsible, - Collapsible as KCollapsible, + Collapsible, + Collapsible as KCollapsible, } from "@kobalte/core/collapsible"; import { - RadioGroup as KRadioGroup, - RadioGroup, + RadioGroup as KRadioGroup, + RadioGroup, } from "@kobalte/core/radio-group"; import { Select as KSelect } from "@kobalte/core/select"; import { Tabs as KTabs } from "@kobalte/core/tabs"; @@ -17,18 +17,18 @@ import { BaseDirectory, writeFile } from "@tauri-apps/plugin-fs"; import { type as ostype } from "@tauri-apps/plugin-os"; import { cx } from "cva"; import { - batch, - createEffect, - createMemo, - createResource, - createRoot, - createSignal, - For, - on, - onMount, - Show, - Suspense, - type ValidComponent, + batch, + createEffect, + createMemo, + createResource, + createRoot, + createSignal, + For, + on, + onMount, + Show, + Suspense, + type ValidComponent, } from "solid-js"; import { createStore, produce } from "solid-js/store"; import { Dynamic } from "solid-js/web"; @@ -40,462 +40,463 @@ import transparentBg from "~/assets/illustrations/transparent.webp"; import { Toggle } from "~/components/Toggle"; import { generalSettingsStore } from "~/store"; import { - type BackgroundSource, - type CameraShape, - commands, - type StereoMode, - type TimelineSegment, - type ZoomSegment, + type BackgroundSource, + type CameraShape, + commands, + type StereoMode, + type TimelineSegment, + type ZoomSegment, + type LayoutSegment, } from "~/utils/tauri"; import IconLucideSparkles from "~icons/lucide/sparkles"; import IconLucideMonitor from "~icons/lucide/monitor"; import { CaptionsTab } from "./CaptionsTab"; import { useEditorContext } from "./context"; import { - DEFAULT_GRADIENT_FROM, - DEFAULT_GRADIENT_TO, - type RGBColor, + DEFAULT_GRADIENT_FROM, + DEFAULT_GRADIENT_TO, + type RGBColor, } from "./projectConfig"; import ShadowSettings from "./ShadowSettings"; import { TextInput } from "./TextInput"; import { - ComingSoonTooltip, - EditorButton, - Field, - MenuItem, - MenuItemList, - PopperContent, - Slider, - Subfield, - topSlideAnimateClasses, + ComingSoonTooltip, + EditorButton, + Field, + MenuItem, + MenuItemList, + PopperContent, + Slider, + Subfield, + topSlideAnimateClasses, } from "./ui"; const BACKGROUND_SOURCES = { - wallpaper: "Wallpaper", - image: "Image", - color: "Color", - gradient: "Gradient", + wallpaper: "Wallpaper", + image: "Image", + color: "Color", + gradient: "Gradient", } satisfies Record; const BACKGROUND_ICONS = { - wallpaper: imageBg, - image: transparentBg, - color: colorBg, - gradient: gradientBg, + wallpaper: imageBg, + image: transparentBg, + color: colorBg, + gradient: gradientBg, } satisfies Record; const BACKGROUND_SOURCES_LIST = [ - "wallpaper", - "image", - "color", - "gradient", + "wallpaper", + "image", + "color", + "gradient", ] satisfies Array; const BACKGROUND_COLORS = [ - "#FF0000", // Red - "#FF4500", // Orange-Red - "#FF8C00", // Orange - "#FFD700", // Gold - "#FFFF00", // Yellow - "#ADFF2F", // Green-Yellow - "#32CD32", // Lime Green - "#008000", // Green - "#00CED1", // Dark Turquoise - "#4785FF", // Dodger Blue - "#0000FF", // Blue - "#4B0082", // Indigo - "#800080", // Purple - "#A9A9A9", // Dark Gray - "#FFFFFF", // White - "#000000", // Black + "#FF0000", // Red + "#FF4500", // Orange-Red + "#FF8C00", // Orange + "#FFD700", // Gold + "#FFFF00", // Yellow + "#ADFF2F", // Green-Yellow + "#32CD32", // Lime Green + "#008000", // Green + "#00CED1", // Dark Turquoise + "#4785FF", // Dodger Blue + "#0000FF", // Blue + "#4B0082", // Indigo + "#800080", // Purple + "#A9A9A9", // Dark Gray + "#FFFFFF", // White + "#000000", // Black ]; const BACKGROUND_GRADIENTS = [ - { from: [15, 52, 67], to: [52, 232, 158] }, // Dark Blue to Teal - { from: [34, 193, 195], to: [253, 187, 45] }, // Turquoise to Golden Yellow - { from: [29, 253, 251], to: [195, 29, 253] }, // Cyan to Purple - { from: [69, 104, 220], to: [176, 106, 179] }, // Blue to Violet - { from: [106, 130, 251], to: [252, 92, 125] }, // Soft Blue to Pinkish Red - { from: [131, 58, 180], to: [253, 29, 29] }, // Purple to Red - { from: [249, 212, 35], to: [255, 78, 80] }, // Yellow to Coral Red - { from: [255, 94, 0], to: [255, 42, 104] }, // Orange to Reddish Pink - { from: [255, 0, 150], to: [0, 204, 255] }, // Pink to Sky Blue - { from: [0, 242, 96], to: [5, 117, 230] }, // Green to Blue - { from: [238, 205, 163], to: [239, 98, 159] }, // Peach to Soft Pink - { from: [44, 62, 80], to: [52, 152, 219] }, // Dark Gray Blue to Light Blue - { from: [168, 239, 255], to: [238, 205, 163] }, // Light Blue to Peach - { from: [74, 0, 224], to: [143, 0, 255] }, // Deep Blue to Bright Purple - { from: [252, 74, 26], to: [247, 183, 51] }, // Deep Orange to Soft Yellow - { from: [0, 255, 255], to: [255, 20, 147] }, // Cyan to Deep Pink - { from: [255, 127, 0], to: [255, 255, 0] }, // Orange to Yellow - { from: [255, 0, 255], to: [0, 255, 0] }, // Magenta to Green + { from: [15, 52, 67], to: [52, 232, 158] }, // Dark Blue to Teal + { from: [34, 193, 195], to: [253, 187, 45] }, // Turquoise to Golden Yellow + { from: [29, 253, 251], to: [195, 29, 253] }, // Cyan to Purple + { from: [69, 104, 220], to: [176, 106, 179] }, // Blue to Violet + { from: [106, 130, 251], to: [252, 92, 125] }, // Soft Blue to Pinkish Red + { from: [131, 58, 180], to: [253, 29, 29] }, // Purple to Red + { from: [249, 212, 35], to: [255, 78, 80] }, // Yellow to Coral Red + { from: [255, 94, 0], to: [255, 42, 104] }, // Orange to Reddish Pink + { from: [255, 0, 150], to: [0, 204, 255] }, // Pink to Sky Blue + { from: [0, 242, 96], to: [5, 117, 230] }, // Green to Blue + { from: [238, 205, 163], to: [239, 98, 159] }, // Peach to Soft Pink + { from: [44, 62, 80], to: [52, 152, 219] }, // Dark Gray Blue to Light Blue + { from: [168, 239, 255], to: [238, 205, 163] }, // Light Blue to Peach + { from: [74, 0, 224], to: [143, 0, 255] }, // Deep Blue to Bright Purple + { from: [252, 74, 26], to: [247, 183, 51] }, // Deep Orange to Soft Yellow + { from: [0, 255, 255], to: [255, 20, 147] }, // Cyan to Deep Pink + { from: [255, 127, 0], to: [255, 255, 0] }, // Orange to Yellow + { from: [255, 0, 255], to: [0, 255, 0] }, // Magenta to Green ] satisfies Array<{ from: RGBColor; to: RGBColor }>; const WALLPAPER_NAMES = [ - // macOS wallpapers - "macOS/sequoia-dark", - "macOS/sequoia-light", - "macOS/sonoma-clouds", - "macOS/sonoma-dark", - "macOS/sonoma-evening", - "macOS/sonoma-fromabove", - "macOS/sonoma-horizon", - "macOS/sonoma-light", - "macOS/sonoma-river", - "macOS/ventura-dark", - "macOS/ventura-semi-dark", - "macOS/ventura", - // Blue wallpapers - "blue/1", - "blue/2", - "blue/3", - "blue/4", - "blue/5", - "blue/6", - // Purple wallpapers - "purple/1", - "purple/2", - "purple/3", - "purple/4", - "purple/5", - "purple/6", - // Dark wallpapers - "dark/1", - "dark/2", - "dark/3", - "dark/4", - "dark/5", - "dark/6", - // Orange wallpapers - "orange/1", - "orange/2", - "orange/3", - "orange/4", - "orange/5", - "orange/6", - "orange/7", - "orange/8", - "orange/9", + // macOS wallpapers + "macOS/sequoia-dark", + "macOS/sequoia-light", + "macOS/sonoma-clouds", + "macOS/sonoma-dark", + "macOS/sonoma-evening", + "macOS/sonoma-fromabove", + "macOS/sonoma-horizon", + "macOS/sonoma-light", + "macOS/sonoma-river", + "macOS/ventura-dark", + "macOS/ventura-semi-dark", + "macOS/ventura", + // Blue wallpapers + "blue/1", + "blue/2", + "blue/3", + "blue/4", + "blue/5", + "blue/6", + // Purple wallpapers + "purple/1", + "purple/2", + "purple/3", + "purple/4", + "purple/5", + "purple/6", + // Dark wallpapers + "dark/1", + "dark/2", + "dark/3", + "dark/4", + "dark/5", + "dark/6", + // Orange wallpapers + "orange/1", + "orange/2", + "orange/3", + "orange/4", + "orange/5", + "orange/6", + "orange/7", + "orange/8", + "orange/9", ] as const; const STEREO_MODES = [ - { name: "Stereo", value: "stereo" }, - { name: "Mono L", value: "monoL" }, - { name: "Mono R", value: "monoR" }, + { name: "Stereo", value: "stereo" }, + { name: "Mono L", value: "monoL" }, + { name: "Mono R", value: "monoR" }, ] satisfies Array<{ name: string; value: StereoMode }>; const CAMERA_SHAPES = [ - { - name: "Square", - value: "square", - }, - { - name: "Source", - value: "source", - }, + { + name: "Square", + value: "square", + }, + { + name: "Source", + value: "source", + }, ] satisfies Array<{ name: string; value: CameraShape }>; const BACKGROUND_THEMES = { - macOS: "macOS", - dark: "Dark", - blue: "Blue", - purple: "Purple", - orange: "Orange", + macOS: "macOS", + dark: "Dark", + blue: "Blue", + purple: "Purple", + orange: "Orange", }; const TAB_IDS = { - background: "background", - camera: "camera", - transcript: "transcript", - audio: "audio", - cursor: "cursor", - hotkeys: "hotkeys", + background: "background", + camera: "camera", + transcript: "transcript", + audio: "audio", + cursor: "cursor", + hotkeys: "hotkeys", } as const; export function ConfigSidebar() { - const { project, setProject, editorInstance, editorState, meta } = - useEditorContext(); - - const [state, setState] = createStore({ - selectedTab: "background" as - | "background" - | "camera" - | "transcript" - | "audio" - | "cursor" - | "hotkeys" - | "captions", - }); - - let scrollRef!: HTMLDivElement; - - return ( - - - s.camera === null, - ), - }, - { id: TAB_IDS.audio, icon: IconCapAudioOn }, - { - id: TAB_IDS.cursor, - icon: IconCapCursor, - disabled: !( - meta().type === "multiple" && (meta() as any).segments[0].cursor - ), - }, - window.FLAGS.captions && { - id: "captions" as const, - icon: IconCapMessageBubble, - }, - // { id: "hotkeys" as const, icon: IconCapHotkeys }, - ].filter(Boolean)} - > - {(item) => ( - { - setState("selectedTab", item.id); - scrollRef.scrollTo({ - top: 0, - }); - }} - disabled={item.disabled} - > -
- -
-
- )} -
- - {/** Center the indicator with the icon */} - -
- - -
- - - - } - > - - setProject("audio", "mute", v)} - /> - - {editorInstance.recordings.segments[0].mic?.channels === 2 && ( - - - options={STEREO_MODES} - optionValue="value" - optionTextValue="name" - value={STEREO_MODES.find( - (v) => v.value === project.audio.micStereoMode, - )} - onChange={(v) => { - if (v) setProject("audio", "micStereoMode", v.value); - }} - disallowEmptySelection - itemComponent={(props) => ( - - as={KSelect.Item} - item={props.item} - > - - {props.item.rawValue.name} - - - )} - > - - class="flex-1 text-sm text-left truncate text-[--gray-500] font-normal"> - {(state) => {state.selectedOption().name}} - - - as={(props) => ( - - )} - /> - - - - as={KSelect.Content} - class={cx(topSlideAnimateClasses, "z-50")} - > - - class="overflow-y-auto max-h-32" - as={KSelect.Listbox} - /> - - - - - )} - - {/* + const { project, setProject, editorInstance, editorState, meta } = + useEditorContext(); + + const [state, setState] = createStore({ + selectedTab: "background" as + | "background" + | "camera" + | "transcript" + | "audio" + | "cursor" + | "hotkeys" + | "captions", + }); + + let scrollRef!: HTMLDivElement; + + return ( + + + s.camera === null + ), + }, + { id: TAB_IDS.audio, icon: IconCapAudioOn }, + { + id: TAB_IDS.cursor, + icon: IconCapCursor, + disabled: !( + meta().type === "multiple" && (meta() as any).segments[0].cursor + ), + }, + window.FLAGS.captions && { + id: "captions" as const, + icon: IconCapMessageBubble, + }, + // { id: "hotkeys" as const, icon: IconCapHotkeys }, + ].filter(Boolean)} + > + {(item) => ( + { + setState("selectedTab", item.id); + scrollRef.scrollTo({ + top: 0, + }); + }} + disabled={item.disabled} + > +
+ +
+
+ )} +
+ + {/** Center the indicator with the icon */} + +
+ + +
+ + + + } + > + + setProject("audio", "mute", v)} + /> + + {editorInstance.recordings.segments[0].mic?.channels === 2 && ( + + + options={STEREO_MODES} + optionValue="value" + optionTextValue="name" + value={STEREO_MODES.find( + (v) => v.value === project.audio.micStereoMode + )} + onChange={(v) => { + if (v) setProject("audio", "micStereoMode", v.value); + }} + disallowEmptySelection + itemComponent={(props) => ( + + as={KSelect.Item} + item={props.item} + > + + {props.item.rawValue.name} + + + )} + > + + class="flex-1 text-sm text-left truncate text-[--gray-500] font-normal"> + {(state) => {state.selectedOption().name}} + + + as={(props) => ( + + )} + /> + + + + as={KSelect.Content} + class={cx(topSlideAnimateClasses, "z-50")} + > + + class="overflow-y-auto max-h-32" + as={KSelect.Listbox} + /> + + + + + )} + + {/* setProject("audio", "mute", v)} /> */} - {/* + {/* */} - - {meta().hasMicrophone && ( - } - > - setProject("audio", "micVolumeDb", v[0])} - minValue={-30} - maxValue={10} - step={0.1} - formatTooltip={(v) => - v <= -30 ? "Muted" : `${v > 0 ? "+" : ""}${v.toFixed(1)} dB` - } - /> - - )} - {meta().hasSystemAudio && ( - } - > - setProject("audio", "systemVolumeDb", v[0])} - minValue={-30} - maxValue={10} - step={0.1} - formatTooltip={(v) => - v <= -30 ? "Muted" : `${v > 0 ? "+" : ""}${v.toFixed(1)} dB` - } - /> - - )} - - - } - value={ - { - setProject("cursor", "hide", !v); - }} - /> - } - /> - - }> - setProject("cursor", "size", v[0])} - minValue={20} - maxValue={300} - step={1} - /> - - - } - value={ - { - setProject("cursor", "raw", !value); - }} - /> - } - /> - - {/* if Content has padding or margin the animation doesn't look as good */} -
- - setProject("cursor", "tension", v[0])} - minValue={1} - maxValue={500} - step={1} - /> - - - setProject("cursor", "friction", v[0])} - minValue={0} - maxValue={50} - step={0.1} - /> - - - setProject("cursor", "mass", v[0])} - minValue={0.1} - maxValue={10} - step={0.01} - /> - -
-
-
- } - value={ - { - setProject("cursor", "useSvg" as any, value); - }} - /> - } - /> -
- - {/* + + {meta().hasMicrophone && ( + } + > + setProject("audio", "micVolumeDb", v[0])} + minValue={-30} + maxValue={10} + step={0.1} + formatTooltip={(v) => + v <= -30 ? "Muted" : `${v > 0 ? "+" : ""}${v.toFixed(1)} dB` + } + /> + + )} + {meta().hasSystemAudio && ( + } + > + setProject("audio", "systemVolumeDb", v[0])} + minValue={-30} + maxValue={10} + step={0.1} + formatTooltip={(v) => + v <= -30 ? "Muted" : `${v > 0 ? "+" : ""}${v.toFixed(1)} dB` + } + /> + + )} +
+ + } + value={ + { + setProject("cursor", "hide", !v); + }} + /> + } + /> + + }> + setProject("cursor", "size", v[0])} + minValue={20} + maxValue={300} + step={1} + /> + + + } + value={ + { + setProject("cursor", "raw", !value); + }} + /> + } + /> + + {/* if Content has padding or margin the animation doesn't look as good */} +
+ + setProject("cursor", "tension", v[0])} + minValue={1} + maxValue={500} + step={1} + /> + + + setProject("cursor", "friction", v[0])} + minValue={0} + maxValue={50} + step={0.1} + /> + + + setProject("cursor", "mass", v[0])} + minValue={0.1} + maxValue={10} + step={0.01} + /> + +
+
+
+ } + value={ + { + setProject("cursor", "useSvg" as any, value); + }} + /> + } + /> +
+ + {/* setProject("cursor", "motionBlur", v[0])} @@ -504,7 +505,7 @@ export function ConfigSidebar() { step={0.001} /> */} - {/* }> + {/* }> */} -
- - }> - - - - - - - - - - -
- - {(selection) => ( -
- - { - const zoomSelection = selection(); - if (zoomSelection.type !== "zoom") return; - - const segment = - project.timeline?.zoomSegments?.[zoomSelection.index]; - if (!segment) return; - - return { selection: zoomSelection, segment }; - })()} - > - {(value) => ( - - )} - - { - const layoutSelection = selection(); - if (layoutSelection.type !== "layout") return; - - const segment = - project.timeline?.layoutSegments?.[layoutSelection.index]; - if (!segment) return; - - return { selection: layoutSelection, segment }; - })()} - > - {(value) => ( - - )} - - { - const clipSegment = selection(); - if (clipSegment.type !== "clip") return; - - const segment = - project.timeline?.segments?.[clipSegment.index]; - if (!segment) return; - - return { selection: clipSegment, segment }; - })()} - > - {(value) => ( - - )} - - -
- )} -
- - ); + + + }> + + + + + + + + + + +
+ + {(selection) => ( +
+ + { + const zoomSelection = selection(); + if (zoomSelection.type !== "zoom") return; + + const segment = + project.timeline?.zoomSegments?.[zoomSelection.index]; + if (!segment) return; + + return { selection: zoomSelection, segment }; + })()} + > + {(value) => ( + + )} + + { + const layoutSelection = selection(); + if (layoutSelection.type !== "layout") return; + + const segment = + project.timeline?.layoutSegments?.[layoutSelection.index]; + if (!segment) return; + + return { selection: layoutSelection, segment }; + })()} + > + {(value) => ( + + )} + + { + const clipSegment = selection(); + if (clipSegment.type !== "clip") return; + + const segment = + project.timeline?.segments?.[clipSegment.index]; + if (!segment) return; + + return { selection: clipSegment, segment }; + })()} + > + {(value) => ( + + )} + + +
+ )} +
+
+ ); } function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { - const { project, setProject, projectHistory } = useEditorContext(); - - // Background tabs - const [backgroundTab, setBackgroundTab] = - createSignal("macOS"); - - const [wallpapers] = createResource(async () => { - // Only load visible wallpapers initially - const visibleWallpaperPaths = WALLPAPER_NAMES.map(async (id) => { - try { - const path = await resolveResource(`assets/backgrounds/${id}.jpg`); - return { id, path }; - } catch (err) { - return { id, path: null }; - } - }); - - // Load initial batch - const initialPaths = await Promise.all(visibleWallpaperPaths); - - return initialPaths - .filter((p) => p.path !== null) - .map(({ id, path }) => ({ - id, - url: convertFileSrc(path!), - rawPath: path!, - })); - }); - - // Validate background source path on mount - onMount(async () => { - if ( - project.background.source.type === "wallpaper" || - project.background.source.type === "image" - ) { - const path = project.background.source.path; - - if (path) { - if (project.background.source.type === "wallpaper") { - // If the path is just the wallpaper ID (e.g. "sequoia-dark"), get the full path - if ( - WALLPAPER_NAMES.includes(path as (typeof WALLPAPER_NAMES)[number]) - ) { - // Wait for wallpapers to load - const loadedWallpapers = wallpapers(); - if (!loadedWallpapers) return; - - // Find the wallpaper with matching ID - const wallpaper = loadedWallpapers.find((w) => w.id === path); - if (!wallpaper?.url) return; - - // Directly trigger the radio group's onChange handler - const radioGroupOnChange = async (photoUrl: string) => { - try { - const wallpaper = wallpapers()?.find((w) => w.url === photoUrl); - if (!wallpaper) return; - - // Get the raw path without any URL prefixes - const rawPath = decodeURIComponent( - photoUrl.replace("file://", ""), - ); - - debouncedSetProject(rawPath); - } catch (err) { - toast.error("Failed to set wallpaper"); - } - }; - - await radioGroupOnChange(wallpaper.url); - } - } else if (project.background.source.type === "image") { - (async () => { - try { - const convertedPath = convertFileSrc(path); - await fetch(convertedPath, { method: "HEAD" }); - } catch (err) { - setProject("background", "source", { - type: "image", - path: null, - }); - } - })(); - } - } - } - }); - - const filteredWallpapers = createMemo(() => { - const currentTab = backgroundTab(); - return wallpapers()?.filter((wp) => wp.id.startsWith(currentTab)) || []; - }); - - const [scrollX, setScrollX] = createSignal(0); - const [reachedEndOfScroll, setReachedEndOfScroll] = createSignal(false); - - const [backgroundRef, setBackgroundRef] = createSignal(); - - createEventListenerMap( - () => backgroundRef() ?? [], - { - /** Handle background tabs overflowing to show fade */ - scroll: () => { - const el = backgroundRef(); - if (el) { - setScrollX(el.scrollLeft); - const reachedEnd = el.scrollWidth - el.clientWidth - el.scrollLeft; - setReachedEndOfScroll(reachedEnd === 0); - } - }, - //Mouse wheel and touchpad support - wheel: (e: WheelEvent) => { - const el = backgroundRef(); - if (el) { - e.preventDefault(); - el.scrollLeft += - Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY; - } - }, - }, - { passive: false }, - ); - - let fileInput!: HTMLInputElement; - - // Optimize the debounced set project function - const debouncedSetProject = (wallpaperPath: string) => { - const resumeHistory = projectHistory.pause(); - queueMicrotask(() => { - batch(() => { - setProject("background", "source", { - type: "wallpaper", - path: wallpaperPath, - } as const); - resumeHistory(); - }); - }); - }; - - const backgrounds: { - [K in BackgroundSource["type"]]: Extract; - } = { - wallpaper: { - type: "wallpaper", - path: null, - }, - image: { - type: "image", - path: null, - }, - color: { - type: "color", - value: DEFAULT_GRADIENT_FROM, - }, - gradient: { - type: "gradient", - from: DEFAULT_GRADIENT_FROM, - to: DEFAULT_GRADIENT_TO, - }, - }; - - const generalSettings = generalSettingsStore.createQuery(); - const hapticsEnabled = () => - generalSettings.data?.hapticsEnabled && ostype() === "macos"; - - return ( - - } name="Background Image"> - { - const tab = v as BackgroundSource["type"]; - switch (tab) { - case "image": { - setProject("background", "source", { - type: "image", - path: - project.background.source.type === "image" - ? project.background.source.path - : null, - }); - break; - } - case "color": { - setProject("background", "source", { - type: "color", - value: - project.background.source.type === "color" - ? project.background.source.value - : DEFAULT_GRADIENT_FROM, - }); - break; - } - case "gradient": { - setProject("background", "source", { - type: "gradient", - from: - project.background.source.type === "gradient" - ? project.background.source.from - : DEFAULT_GRADIENT_FROM, - to: - project.background.source.type === "gradient" - ? project.background.source.to - : DEFAULT_GRADIENT_TO, - angle: - project.background.source.type === "gradient" - ? project.background.source.angle - : 90, - }); - break; - } - case "wallpaper": { - setProject("background", "source", { - type: "wallpaper", - path: - project.background.source.type === "wallpaper" - ? project.background.source.path - : null, - }); - break; - } - } - }} - > - - - {(item) => { - const el = (props?: object) => ( - -
- {(() => { - const getGradientBackground = () => { - const angle = - project.background.source.type === "gradient" - ? project.background.source.angle - : 90; - const fromColor = - project.background.source.type === "gradient" - ? project.background.source.from - : DEFAULT_GRADIENT_FROM; - const toColor = - project.background.source.type === "gradient" - ? project.background.source.to - : DEFAULT_GRADIENT_TO; - - return ( -
- ); - }; - - const getColorBackground = () => { - const backgroundColor = - project.background.source.type === "color" - ? project.background.source.value - : hexToRgb(BACKGROUND_COLORS[9]); - - return ( -
- ); - }; - - const getImageBackground = () => { - // Always start with the default icon - let imageSrc: string = BACKGROUND_ICONS[item]; - - // Only override for "image" if a valid path exists - if ( - item === "image" && - project.background.source.type === "image" && - project.background.source.path - ) { - const convertedPath = convertFileSrc( - project.background.source.path, - ); - // Only use converted path if it's valid - if (convertedPath) { - imageSrc = convertedPath; - } - } - // Only override for "wallpaper" if a valid wallpaper is found - else if ( - item === "wallpaper" && - project.background.source.type === "wallpaper" && - project.background.source.path - ) { - const selectedWallpaper = wallpapers()?.find((w) => - ( - project.background.source as { - path?: string; - } - ).path?.includes(w.id), - ); - // Only use wallpaper URL if it exists - if (selectedWallpaper?.url) { - imageSrc = selectedWallpaper.url; - } - } - - return ( - {BACKGROUND_SOURCES[item]} - ); - }; - - switch (item) { - case "gradient": - return getGradientBackground(); - case "color": - return getColorBackground(); - case "image": - case "wallpaper": - return getImageBackground(); - default: - return null; - } - })()} - {BACKGROUND_SOURCES[item]} -
- - ); - - return el({}); - }} - - - {/** Dashed divider */} -
- - {/** Background Tabs */} - - 0 ? "24px" : "0" - }, black calc(100% - ${ - reachedEndOfScroll() ? "0px" : "24px" - }), transparent)`, - - "mask-image": `linear-gradient(to right, transparent, black ${ - scrollX() > 0 ? "24px" : "0" - }, black calc(100% - ${ - reachedEndOfScroll() ? "0px" : "24px" - }), transparent);`, - }} - > - - {([key, value]) => ( - <> - - setBackgroundTab( - key as keyof typeof BACKGROUND_THEMES, - ) - } - value={key} - class="flex relative z-10 flex-1 justify-center items-center px-4 py-2 bg-transparent rounded-lg border transition-colors duration-200 text-gray-11 ui-not-selected:hover:border-gray-7 ui-selected:bg-gray-3 ui-selected:border-gray-3 group ui-selected:text-gray-12 disabled:opacity-50 focus:outline-none" - > - {value} - - - )} - - - - {/** End of Background Tabs */} - - ( - project.background.source as { path?: string } - ).path?.includes(w.id), - )?.url ?? undefined) - : undefined - } - onChange={(photoUrl) => { - try { - const wallpaper = wallpapers()?.find( - (w) => w.url === photoUrl, - ); - if (!wallpaper) return; - - // Get the raw path without any URL prefixes - - debouncedSetProject(wallpaper.rawPath); - } catch (err) { - toast.error("Failed to set wallpaper"); - } - }} - class="grid grid-cols-7 gap-2 h-auto" - > - -
-
- Loading wallpapers... -
-
- } - > - - {(photo) => ( - - - - Wallpaper option - - - )} - - - -
- - {(photo) => ( - - - - Wallpaper option - - - )} - -
-
-
-
-
-
- - fileInput.click()} - class="p-6 bg-gray-2 text-[13px] w-full rounded-[0.5rem] border border-gray-5 border-dashed flex flex-col items-center justify-center gap-[0.5rem] hover:bg-gray-3 transition-colors duration-100" - > - - - Click to select or drag and drop image - - - } - > - {(source) => ( -
- Selected background -
- -
-
- )} -
- { - const file = e.currentTarget.files?.[0]; - if (!file) return; - - /* + const { project, setProject, projectHistory } = useEditorContext(); + + // Background tabs + const [backgroundTab, setBackgroundTab] = + createSignal("macOS"); + + const [wallpapers] = createResource(async () => { + // Only load visible wallpapers initially + const visibleWallpaperPaths = WALLPAPER_NAMES.map(async (id) => { + try { + const path = await resolveResource(`assets/backgrounds/${id}.jpg`); + return { id, path }; + } catch (err) { + return { id, path: null }; + } + }); + + // Load initial batch + const initialPaths = await Promise.all(visibleWallpaperPaths); + + return initialPaths + .filter((p) => p.path !== null) + .map(({ id, path }) => ({ + id, + url: convertFileSrc(path!), + rawPath: path!, + })); + }); + + // Validate background source path on mount + onMount(async () => { + if ( + project.background.source.type === "wallpaper" || + project.background.source.type === "image" + ) { + const path = project.background.source.path; + + if (path) { + if (project.background.source.type === "wallpaper") { + // If the path is just the wallpaper ID (e.g. "sequoia-dark"), get the full path + if ( + WALLPAPER_NAMES.includes(path as (typeof WALLPAPER_NAMES)[number]) + ) { + // Wait for wallpapers to load + const loadedWallpapers = wallpapers(); + if (!loadedWallpapers) return; + + // Find the wallpaper with matching ID + const wallpaper = loadedWallpapers.find((w) => w.id === path); + if (!wallpaper?.url) return; + + // Directly trigger the radio group's onChange handler + const radioGroupOnChange = async (photoUrl: string) => { + try { + const wallpaper = wallpapers()?.find((w) => w.url === photoUrl); + if (!wallpaper) return; + + // Get the raw path without any URL prefixes + const rawPath = decodeURIComponent( + photoUrl.replace("file://", "") + ); + + debouncedSetProject(rawPath); + } catch (err) { + toast.error("Failed to set wallpaper"); + } + }; + + await radioGroupOnChange(wallpaper.url); + } + } else if (project.background.source.type === "image") { + (async () => { + try { + const convertedPath = convertFileSrc(path); + await fetch(convertedPath, { method: "HEAD" }); + } catch (err) { + setProject("background", "source", { + type: "image", + path: null, + }); + } + })(); + } + } + } + }); + + const filteredWallpapers = createMemo(() => { + const currentTab = backgroundTab(); + return wallpapers()?.filter((wp) => wp.id.startsWith(currentTab)) || []; + }); + + const [scrollX, setScrollX] = createSignal(0); + const [reachedEndOfScroll, setReachedEndOfScroll] = createSignal(false); + + const [backgroundRef, setBackgroundRef] = createSignal(); + + createEventListenerMap( + () => backgroundRef() ?? [], + { + /** Handle background tabs overflowing to show fade */ + scroll: () => { + const el = backgroundRef(); + if (el) { + setScrollX(el.scrollLeft); + const reachedEnd = el.scrollWidth - el.clientWidth - el.scrollLeft; + setReachedEndOfScroll(reachedEnd === 0); + } + }, + //Mouse wheel and touchpad support + wheel: (e: WheelEvent) => { + const el = backgroundRef(); + if (el) { + e.preventDefault(); + el.scrollLeft += + Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY; + } + }, + }, + { passive: false } + ); + + let fileInput!: HTMLInputElement; + + // Optimize the debounced set project function + const debouncedSetProject = (wallpaperPath: string) => { + const resumeHistory = projectHistory.pause(); + queueMicrotask(() => { + batch(() => { + setProject("background", "source", { + type: "wallpaper", + path: wallpaperPath, + } as const); + resumeHistory(); + }); + }); + }; + + const backgrounds: { + [K in BackgroundSource["type"]]: Extract; + } = { + wallpaper: { + type: "wallpaper", + path: null, + }, + image: { + type: "image", + path: null, + }, + color: { + type: "color", + value: DEFAULT_GRADIENT_FROM, + }, + gradient: { + type: "gradient", + from: DEFAULT_GRADIENT_FROM, + to: DEFAULT_GRADIENT_TO, + }, + }; + + const generalSettings = generalSettingsStore.createQuery(); + const hapticsEnabled = () => + generalSettings.data?.hapticsEnabled && ostype() === "macos"; + + return ( + + } name="Background Image"> + { + const tab = v as BackgroundSource["type"]; + switch (tab) { + case "image": { + setProject("background", "source", { + type: "image", + path: + project.background.source.type === "image" + ? project.background.source.path + : null, + }); + break; + } + case "color": { + setProject("background", "source", { + type: "color", + value: + project.background.source.type === "color" + ? project.background.source.value + : DEFAULT_GRADIENT_FROM, + }); + break; + } + case "gradient": { + setProject("background", "source", { + type: "gradient", + from: + project.background.source.type === "gradient" + ? project.background.source.from + : DEFAULT_GRADIENT_FROM, + to: + project.background.source.type === "gradient" + ? project.background.source.to + : DEFAULT_GRADIENT_TO, + angle: + project.background.source.type === "gradient" + ? project.background.source.angle + : 90, + }); + break; + } + case "wallpaper": { + setProject("background", "source", { + type: "wallpaper", + path: + project.background.source.type === "wallpaper" + ? project.background.source.path + : null, + }); + break; + } + } + }} + > + + + {(item) => { + const el = (props?: object) => ( + +
+ {(() => { + const getGradientBackground = () => { + const angle = + project.background.source.type === "gradient" + ? project.background.source.angle + : 90; + const fromColor = + project.background.source.type === "gradient" + ? project.background.source.from + : DEFAULT_GRADIENT_FROM; + const toColor = + project.background.source.type === "gradient" + ? project.background.source.to + : DEFAULT_GRADIENT_TO; + + return ( +
+ ); + }; + + const getColorBackground = () => { + const backgroundColor = + project.background.source.type === "color" + ? project.background.source.value + : hexToRgb(BACKGROUND_COLORS[9]); + + return ( +
+ ); + }; + + const getImageBackground = () => { + // Always start with the default icon + let imageSrc: string = BACKGROUND_ICONS[item]; + + // Only override for "image" if a valid path exists + if ( + item === "image" && + project.background.source.type === "image" && + project.background.source.path + ) { + const convertedPath = convertFileSrc( + project.background.source.path + ); + // Only use converted path if it's valid + if (convertedPath) { + imageSrc = convertedPath; + } + } + // Only override for "wallpaper" if a valid wallpaper is found + else if ( + item === "wallpaper" && + project.background.source.type === "wallpaper" && + project.background.source.path + ) { + const selectedWallpaper = wallpapers()?.find((w) => + ( + project.background.source as { + path?: string; + } + ).path?.includes(w.id) + ); + // Only use wallpaper URL if it exists + if (selectedWallpaper?.url) { + imageSrc = selectedWallpaper.url; + } + } + + return ( + {BACKGROUND_SOURCES[item]} + ); + }; + + switch (item) { + case "gradient": + return getGradientBackground(); + case "color": + return getColorBackground(); + case "image": + case "wallpaper": + return getImageBackground(); + default: + return null; + } + })()} + {BACKGROUND_SOURCES[item]} +
+ + ); + + return el({}); + }} + + + {/** Dashed divider */} +
+ + {/** Background Tabs */} + + 0 ? "24px" : "0" + }, black calc(100% - ${ + reachedEndOfScroll() ? "0px" : "24px" + }), transparent)`, + + "mask-image": `linear-gradient(to right, transparent, black ${ + scrollX() > 0 ? "24px" : "0" + }, black calc(100% - ${ + reachedEndOfScroll() ? "0px" : "24px" + }), transparent);`, + }} + > + + {([key, value]) => ( + <> + + setBackgroundTab( + key as keyof typeof BACKGROUND_THEMES + ) + } + value={key} + class="flex relative z-10 flex-1 justify-center items-center px-4 py-2 bg-transparent rounded-lg border transition-colors duration-200 text-gray-11 ui-not-selected:hover:border-gray-7 ui-selected:bg-gray-3 ui-selected:border-gray-3 group ui-selected:text-gray-12 disabled:opacity-50 focus:outline-none" + > + {value} + + + )} + + + + {/** End of Background Tabs */} + + ( + project.background.source as { path?: string } + ).path?.includes(w.id) + )?.url ?? undefined + : undefined + } + onChange={(photoUrl) => { + try { + const wallpaper = wallpapers()?.find( + (w) => w.url === photoUrl + ); + if (!wallpaper) return; + + // Get the raw path without any URL prefixes + + debouncedSetProject(wallpaper.rawPath); + } catch (err) { + toast.error("Failed to set wallpaper"); + } + }} + class="grid grid-cols-7 gap-2 h-auto" + > + +
+
+ Loading wallpapers... +
+
+ } + > + + {(photo) => ( + + + + Wallpaper option + + + )} + + + +
+ + {(photo) => ( + + + + Wallpaper option + + + )} + +
+
+
+
+
+
+ + fileInput.click()} + class="p-6 bg-gray-2 text-[13px] w-full rounded-[0.5rem] border border-gray-5 border-dashed flex flex-col items-center justify-center gap-[0.5rem] hover:bg-gray-3 transition-colors duration-100" + > + + + Click to select or drag and drop image + + + } + > + {(source) => ( +
+ Selected background +
+ +
+
+ )} +
+ { + const file = e.currentTarget.files?.[0]; + if (!file) return; + + /* this is a Tauri bug in WebKit so we need to validate the file type manually https://github.com/tauri-apps/tauri/issues/9158 */ - const validExtensions = [ - "jpg", - "jpeg", - "png", - "gif", - "webp", - "bmp", - ]; - const extension = file.name.split(".").pop()?.toLowerCase(); - if (!extension || !validExtensions.includes(extension)) { - toast.error("Invalid image file type"); - return; - } - - try { - const fileName = `bg-${Date.now()}-${file.name}`; - const arrayBuffer = await file.arrayBuffer(); - const uint8Array = new Uint8Array(arrayBuffer); - - const fullPath = `${await appDataDir()}/${fileName}`; - - await writeFile(fileName, uint8Array, { - baseDir: BaseDirectory.AppData, - }); - - setProject("background", "source", { - type: "image", - path: fullPath, - }); - } catch (err) { - toast.error("Failed to save image"); - } - }} - /> -
- - -
-
- { - setProject("background", "source", { - type: "color", - value, - }); - }} - /> -
- -
- - {(color) => ( -