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 ( - props.onClick?.()} - > - {props.value === 0 ? ( - - ) : ( - <>{formatTime(props.value)}s> - )} - - ); + const formatTime = (t: number) => + t < 1 ? Math.round(t * 10) / 10 : Math.round(t); + + return ( + props.onClick?.()} + > + {props.value === 0 ? ( + + ) : ( + <>{formatTime(props.value)}s> + )} + + ); } 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 ( - - ); - }; - - 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) => ( - - - - - - - )} - - - - - - {(photo) => ( - - - - - - - )} - - - - - - - - - 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) => ( - - - - - setProject("background", "source", { - type: "image", - path: null, - }) - } - class="p-2 text-white rounded-full transition-colors bg-black/50 hover:bg-black/70" - > - - - - - )} - - { - 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 ( + + ); + }; + + 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) => ( + + + + + + + )} + + + + + + {(photo) => ( + + + + + + + )} + + + + + + + + + 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) => ( + + + + + setProject("background", "source", { + type: "image", + path: null, + }) + } + class="p-2 text-white rounded-full transition-colors bg-black/50 hover:bg-black/70" + > + + + + + )} + + { + 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) => ( - - { - if (e.target.checked) { - backgrounds.color = { - type: "color", - value: hexToRgb(color) ?? [0, 0, 0], - }; - setProject( - "background", - "source", - backgrounds.color, - ); - } - }} - /> - - - )} - - - {/* + 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) => ( + + { + if (e.target.checked) { + backgrounds.color = { + type: "color", + value: hexToRgb(color) ?? [0, 0, 0], + }; + setProject( + "background", + "source", + backgrounds.color + ); + } + }} + /> + + + )} + + + {/* { @@ -1257,237 +1258,237 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { + */} - - - - - - {(source) => { - const max = 360; - - const { projectHistory } = useEditorContext(); - - const angle = () => source().angle ?? 90; - - return ( - <> - - - { - backgrounds.gradient.from = from; - setProject("background", "source", { - type: "gradient", - from, - }); - }} - /> - { - backgrounds.gradient.to = to; - setProject("background", "source", { - type: "gradient", - to, - }); - }} - /> - { - const start = angle(); - const resumeHistory = projectHistory.pause(); - - createRoot((dispose) => - createEventListenerMap(window, { - mouseup: () => { - dispose(); - resumeHistory(); - }, - mousemove: (moveEvent) => { - const rawNewAngle = - Math.round( - start + - (downEvent.clientY - moveEvent.clientY), - ) % max; - const newAngle = moveEvent.shiftKey - ? rawNewAngle - : Math.round(rawNewAngle / 45) * 45; - - if ( - !moveEvent.shiftKey && - hapticsEnabled() && - project.background.source.type === - "gradient" && - project.background.source.angle !== newAngle - ) { - commands.performHapticFeedback( - "Alignment", - "Now", - ); - } - - setProject("background", "source", { - type: "gradient", - angle: - newAngle < 0 ? newAngle + max : newAngle, - }); - }, - }), - ); - }} - > - - - - - - {(gradient) => ( - - { - if (e.target.checked) { - backgrounds.gradient = { - type: "gradient", - from: gradient.from, - to: gradient.to, - }; - setProject( - "background", - "source", - backgrounds.gradient, - ); - } - }} - /> - - - )} - - - - > - ); - }} - - - - - - }> - setProject("background", "blur", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - - {/** Dashed divider */} - - }> - setProject("background", "padding", v[0])} - minValue={0} - maxValue={40} - step={0.1} - formatTooltip="%" - /> - - }> - setProject("background", "rounding", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - - }> - { - batch(() => { - setProject("background", "shadow", v[0]); - // Initialize advanced shadow settings if they don't exist and shadow is enabled - if (v[0] > 0 && !project.background.advancedShadow) { - setProject("background", "advancedShadow", { - size: 50, - opacity: 18, - blur: 50, - }); - } - }); - }} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - { - setProject("background", "advancedShadow", { - ...(project.background.advancedShadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - size: v[0], - }); - }, - }} - opacity={{ - value: [project.background.advancedShadow?.opacity ?? 18], - onChange: (v) => { - setProject("background", "advancedShadow", { - ...(project.background.advancedShadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - opacity: v[0], - }); - }, - }} - blur={{ - value: [project.background.advancedShadow?.blur ?? 50], - onChange: (v) => { - setProject("background", "advancedShadow", { - ...(project.background.advancedShadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - blur: v[0], - }); - }, - }} - /> - - {/* + + + + + + {(source) => { + const max = 360; + + const { projectHistory } = useEditorContext(); + + const angle = () => source().angle ?? 90; + + return ( + <> + + + { + backgrounds.gradient.from = from; + setProject("background", "source", { + type: "gradient", + from, + }); + }} + /> + { + backgrounds.gradient.to = to; + setProject("background", "source", { + type: "gradient", + to, + }); + }} + /> + { + const start = angle(); + const resumeHistory = projectHistory.pause(); + + createRoot((dispose) => + createEventListenerMap(window, { + mouseup: () => { + dispose(); + resumeHistory(); + }, + mousemove: (moveEvent) => { + const rawNewAngle = + Math.round( + start + + (downEvent.clientY - moveEvent.clientY) + ) % max; + const newAngle = moveEvent.shiftKey + ? rawNewAngle + : Math.round(rawNewAngle / 45) * 45; + + if ( + !moveEvent.shiftKey && + hapticsEnabled() && + project.background.source.type === + "gradient" && + project.background.source.angle !== newAngle + ) { + commands.performHapticFeedback( + "Alignment", + "Now" + ); + } + + setProject("background", "source", { + type: "gradient", + angle: + newAngle < 0 ? newAngle + max : newAngle, + }); + }, + }) + ); + }} + > + + + + + + {(gradient) => ( + + { + if (e.target.checked) { + backgrounds.gradient = { + type: "gradient", + from: gradient.from, + to: gradient.to, + }; + setProject( + "background", + "source", + backgrounds.gradient + ); + } + }} + /> + + + )} + + + + > + ); + }} + + + + + + }> + setProject("background", "blur", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + + {/** Dashed divider */} + + }> + setProject("background", "padding", v[0])} + minValue={0} + maxValue={40} + step={0.1} + formatTooltip="%" + /> + + }> + setProject("background", "rounding", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + + }> + { + batch(() => { + setProject("background", "shadow", v[0]); + // Initialize advanced shadow settings if they don't exist and shadow is enabled + if (v[0] > 0 && !project.background.advancedShadow) { + setProject("background", "advancedShadow", { + size: 50, + opacity: 18, + blur: 50, + }); + } + }); + }} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + { + setProject("background", "advancedShadow", { + ...(project.background.advancedShadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + size: v[0], + }); + }, + }} + opacity={{ + value: [project.background.advancedShadow?.opacity ?? 18], + onChange: (v) => { + setProject("background", "advancedShadow", { + ...(project.background.advancedShadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + opacity: v[0], + }); + }, + }} + blur={{ + value: [project.background.advancedShadow?.blur ?? 50], + onChange: (v) => { + setProject("background", "advancedShadow", { + ...(project.background.advancedShadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + blur: v[0], + }); + }, + }} + /> + + {/* }> */} - - ); + + ); } function CameraConfig(props: { scrollRef: HTMLDivElement }) { - const { project, setProject } = useEditorContext(); - - return ( - - } name="Camera"> - - - - { - const [x, y] = v.split(":"); - setProject("camera", "position", { x, y } as any); - }} - class="mt-[0.75rem] rounded-[0.5rem] border border-gray-3 bg-gray-2 w-full h-[7.5rem] relative" - > - - {(item) => ( - - - setProject("camera", "position", item)} - > - - - - )} - - - - - setProject("camera", "hide", hide)} - /> - - - setProject("camera", "mirror", mirror)} - /> - - - - options={CAMERA_SHAPES} - optionValue="value" - optionTextValue="name" - value={CAMERA_SHAPES.find( - (v) => v.value === project.camera.shape, - )} - onChange={(v) => { - if (v) setProject("camera", "shape", 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 } = useEditorContext(); + + return ( + + } name="Camera"> + + + + { + const [x, y] = v.split(":"); + setProject("camera", "position", { x, y } as any); + }} + class="mt-[0.75rem] rounded-[0.5rem] border border-gray-3 bg-gray-2 w-full h-[7.5rem] relative" + > + + {(item) => ( + + + setProject("camera", "position", item)} + > + + + + )} + + + + + setProject("camera", "hide", hide)} + /> + + + setProject("camera", "mirror", mirror)} + /> + + + + options={CAMERA_SHAPES} + optionValue="value" + optionTextValue="name" + value={CAMERA_SHAPES.find( + (v) => v.value === project.camera.shape + )} + onChange={(v) => { + if (v) setProject("camera", "shape", 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("camera", "use_camera_aspect", v)} /> */} - - - {/** Dashed divider */} - - }> - setProject("camera", "size", v[0])} - minValue={20} - maxValue={80} - step={0.1} - formatTooltip="%" - /> - - }> - setProject("camera", "zoom_size", v[0])} - minValue={10} - maxValue={60} - step={0.1} - formatTooltip="%" - /> - - }> - setProject("camera", "rounding", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - - }> - - setProject("camera", "shadow", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - { - setProject("camera", "advanced_shadow", { - ...(project.camera.advanced_shadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - size: v[0], - }); - }, - }} - opacity={{ - value: [project.camera.advanced_shadow?.opacity ?? 18], - onChange: (v) => { - setProject("camera", "advanced_shadow", { - ...(project.camera.advanced_shadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - opacity: v[0], - }); - }, - }} - blur={{ - value: [project.camera.advanced_shadow?.blur ?? 50], - onChange: (v) => { - setProject("camera", "advanced_shadow", { - ...(project.camera.advanced_shadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - blur: v[0], - }); - }, - }} - /> - - - {/* + + + {/** Dashed divider */} + + }> + setProject("camera", "size", v[0])} + minValue={20} + maxValue={80} + step={0.1} + formatTooltip="%" + /> + + }> + setProject("camera", "zoom_size", v[0])} + minValue={10} + maxValue={60} + step={0.1} + formatTooltip="%" + /> + + }> + setProject("camera", "rounding", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + + }> + + setProject("camera", "shadow", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + { + setProject("camera", "advanced_shadow", { + ...(project.camera.advanced_shadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + size: v[0], + }); + }, + }} + opacity={{ + value: [project.camera.advanced_shadow?.opacity ?? 18], + onChange: (v) => { + setProject("camera", "advanced_shadow", { + ...(project.camera.advanced_shadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + opacity: v[0], + }); + }, + }} + blur={{ + value: [project.camera.advanced_shadow?.blur ?? 50], + onChange: (v) => { + setProject("camera", "advanced_shadow", { + ...(project.camera.advanced_shadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + blur: v[0], + }); + }, + }} + /> + + + {/* }> */} - - ); + + ); } function ZoomSegmentConfig(props: { - segmentIndex: number; - segment: ZoomSegment; + segmentIndex: number; + segment: ZoomSegment; }) { - const generalSettings = generalSettingsStore.createQuery(); - const { - project, - setProject, - editorInstance, - setEditorState, - projectHistory, - projectActions, - } = useEditorContext(); - - const states = { - manual: - props.segment.mode === "auto" - ? { x: 0.5, y: 0.5 } - : props.segment.mode.manual, - }; - - return ( - <> - - - setEditorState("timeline", "selection", null)} - leftIcon={} - > - Done - - - { - projectActions.deleteZoomSegment(props.segmentIndex); - }} - leftIcon={} - > - Delete - - - }> - - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "amount", - v[0], - ) - } - minValue={1} - maxValue={4.5} - step={0.001} - formatTooltip="x" - /> - - }> - { - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "mode", - v === "auto" ? "auto" : { manual: states.manual }, - ); - }} - > - - - Auto - - - Manual - - - - - - - { - const m = props.segment.mode; - if (m === "auto") return; - return m.manual; - })()} - > - {(mode) => { - const start = createMemo((prev) => { - if (projectHistory.isPaused()) return prev; - return props.segment.start; - }, 0); - - const segmentIndex = createMemo((prev) => { - if (projectHistory.isPaused()) return prev; - - const st = start(); - const i = project.timeline?.segments.findIndex( - (s) => s.start <= st && s.end > st, - ); - if (i === undefined || i === -1) return 0; - return i; - }, 0); - - const video = document.createElement("video"); - createEffect(() => { - video.src = convertFileSrc( - // TODO: this shouldn't be so hardcoded - `${ - editorInstance.path - }/content/segments/segment-${segmentIndex()}/display.mp4`, - ); - }); - - createEffect(() => { - const s = start(); - if (s === undefined) return; - video.currentTime = s; - }); - - createEffect( - on( - () => { - croppedPosition(); - croppedSize(); - }, - () => { - render(); - }, - ), - ); - - const render = () => { - const ctx = canvasRef.getContext("2d"); - ctx!.imageSmoothingEnabled = false; - ctx!.drawImage( - video, - croppedPosition().x, - croppedPosition().y, - croppedSize().x, - croppedSize().y, - 0, - 0, - canvasRef.width!, - canvasRef.height!, - ); - }; - - const [loaded, setLoaded] = createSignal(false); - video.onloadeddata = () => { - setLoaded(true); - render(); - }; - video.onseeked = render; - - let canvasRef!: HTMLCanvasElement; - - const [ref, setRef] = createSignal(); - const bounds = createElementBounds(ref); - const rawSize = () => { - const raw = editorInstance.recordings.segments[0].display; - return { x: raw.width, y: raw.height }; - }; - - const croppedPosition = () => { - const cropped = project.background.crop?.position; - if (cropped) return cropped; - - return { x: 0, y: 0 }; - }; - - const croppedSize = () => { - const cropped = project.background.crop?.size; - if (cropped) return cropped; - - return rawSize(); - }; - - const visualHeight = () => - (bounds.width! / croppedSize().x) * croppedSize().y; - - return ( - { - const bounds = - downEvent.currentTarget.getBoundingClientRect(); - - createRoot((dispose) => { - createEventListenerMap(window, { - mouseup: () => dispose(), - mousemove: (moveEvent) => { - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "mode", - "manual", - { - x: Math.max( - Math.min( - (moveEvent.clientX - bounds.left) / - bounds.width, - 1, - ), - 0, - ), - y: Math.max( - Math.min( - (moveEvent.clientY - bounds.top) / - bounds.height, - 1, - ), - 0, - ), - }, - ); - }, - }); - }); - }} - > - - - - - - ); - }} - - - - - > - ); + const generalSettings = generalSettingsStore.createQuery(); + const { + project, + setProject, + editorInstance, + setEditorState, + projectHistory, + projectActions, + } = useEditorContext(); + + const states = { + manual: + props.segment.mode === "auto" + ? { x: 0.5, y: 0.5 } + : props.segment.mode.manual, + }; + + return ( + <> + + + setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + + + { + projectActions.deleteZoomSegment(props.segmentIndex); + }} + leftIcon={} + > + Delete + + + }> + + setProject( + "timeline", + "zoomSegments", + props.segmentIndex, + "amount", + v[0] + ) + } + minValue={1} + maxValue={4.5} + step={0.001} + formatTooltip="x" + /> + + }> + { + setProject( + "timeline", + "zoomSegments", + props.segmentIndex, + "mode", + v === "auto" ? "auto" : { manual: states.manual } + ); + }} + > + + + Auto + + + Manual + + + + + + + { + const m = props.segment.mode; + if (m === "auto") return; + return m.manual; + })()} + > + {(mode) => { + const start = createMemo((prev) => { + if (projectHistory.isPaused()) return prev; + return props.segment.start; + }, 0); + + const segmentIndex = createMemo((prev) => { + if (projectHistory.isPaused()) return prev; + + const st = start(); + const i = project.timeline?.segments.findIndex( + (s) => s.start <= st && s.end > st + ); + if (i === undefined || i === -1) return 0; + return i; + }, 0); + + // Calculate the time relative to the video segment + const relativeTime = createMemo(() => { + const st = start(); + const segment = project.timeline?.segments[segmentIndex()]; + if (!segment) return 0; + // The time within the actual video file + return Math.max(0, st - segment.start); + }); + + const video = document.createElement("video"); + createEffect(() => { + const path = convertFileSrc( + // TODO: this shouldn't be so hardcoded + `${ + editorInstance.path + }/content/segments/segment-${segmentIndex()}/display.mp4` + ); + video.src = path; + // Force reload if video fails to load + video.load(); + }); + + createEffect(() => { + const t = relativeTime(); + if (t === undefined) return; + + // Ensure video is ready before seeking + if (video.readyState >= 2) { + video.currentTime = t; + } else { + // Wait for video to be ready, then seek + const handleCanPlay = () => { + video.currentTime = t; + video.removeEventListener("canplay", handleCanPlay); + }; + video.addEventListener("canplay", handleCanPlay); + } + }); + + createEffect( + on( + () => { + croppedPosition(); + croppedSize(); + }, + () => { + if (loaded()) { + render(); + } + } + ) + ); + + const render = () => { + if (!canvasRef || video.readyState < 2) return; + + const ctx = canvasRef.getContext("2d"); + if (!ctx) return; + + ctx.imageSmoothingEnabled = false; + // Clear canvas first + ctx.clearRect(0, 0, canvasRef.width, canvasRef.height); + // Draw video frame + ctx.drawImage( + video, + croppedPosition().x, + croppedPosition().y, + croppedSize().x, + croppedSize().y, + 0, + 0, + canvasRef.width!, + canvasRef.height! + ); + }; + + const [loaded, setLoaded] = createSignal(false); + video.onloadeddata = () => { + setLoaded(true); + render(); + }; + video.onseeked = render; + + // Add error handling + video.onerror = (e) => { + console.error("Failed to load video for zoom preview:", e); + // Try to reload after a short delay + setTimeout(() => { + video.load(); + }, 100); + }; + + let canvasRef!: HTMLCanvasElement; + + const [ref, setRef] = createSignal(); + const bounds = createElementBounds(ref); + const rawSize = () => { + const raw = editorInstance.recordings.segments[0].display; + return { x: raw.width, y: raw.height }; + }; + + const croppedPosition = () => { + const cropped = project.background.crop?.position; + if (cropped) return cropped; + + return { x: 0, y: 0 }; + }; + + const croppedSize = () => { + const cropped = project.background.crop?.size; + if (cropped) return cropped; + + return rawSize(); + }; + + const visualHeight = () => + (bounds.width! / croppedSize().x) * croppedSize().y; + + return ( + { + const bounds = + downEvent.currentTarget.getBoundingClientRect(); + + createRoot((dispose) => { + createEventListenerMap(window, { + mouseup: () => dispose(), + mousemove: (moveEvent) => { + setProject( + "timeline", + "zoomSegments", + props.segmentIndex, + "mode", + "manual", + { + x: Math.max( + Math.min( + (moveEvent.clientX - bounds.left) / + bounds.width, + 1 + ), + 0 + ), + y: Math.max( + Math.min( + (moveEvent.clientY - bounds.top) / + bounds.height, + 1 + ), + 0 + ), + } + ); + }, + }); + }); + }} + > + + + + + + + Loading preview... + + + + + + ); + }} + + + + + > + ); } function ClipSegmentConfig(props: { - segmentIndex: number; - segment: TimelineSegment; + segmentIndex: number; + segment: TimelineSegment; }) { - const { setProject, setEditorState, project, projectActions } = - useEditorContext(); - - return ( - <> - - - setEditorState("timeline", "selection", null)} - leftIcon={} - > - Done - - - { - projectActions.deleteClipSegment(props.segmentIndex); - }} - disabled={ - ( - project.timeline?.segments.filter( - (s) => s.recordingSegment === props.segment.recordingSegment, - ) ?? [] - ).length < 2 - } - leftIcon={} - > - Delete - - - - } /> - - - } - /> - - > - ); + const { setProject, setEditorState, project, projectActions } = + useEditorContext(); + + return ( + <> + + + setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + + + { + projectActions.deleteClipSegment(props.segmentIndex); + }} + disabled={ + ( + project.timeline?.segments.filter( + (s) => s.recordingSegment === props.segment.recordingSegment + ) ?? [] + ).length < 2 + } + leftIcon={} + > + Delete + + + + } /> + + + } + /> + + > + ); } function RgbInput(props: { - value: [number, number, number]; - onChange: (value: [number, number, number]) => void; + value: [number, number, number]; + onChange: (value: [number, number, number]) => void; }) { - const [text, setText] = createWritableMemo(() => rgbToHex(props.value)); - let prevHex = rgbToHex(props.value); - - let colorInput!: HTMLInputElement; - - return ( - - colorInput.click()} - /> - { - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - }} - /> - { - prevHex = rgbToHex(props.value); - }} - onInput={(e) => { - setText(e.currentTarget.value); - - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - }} - onBlur={(e) => { - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - else { - setText(prevHex); - props.onChange(hexToRgb(text())!); - } - }} - /> - - ); -} - -interface LayoutSegment { - start: number; - end: number; - mode?: "default" | "cameraOnly" | "hideCamera"; + const [text, setText] = createWritableMemo(() => rgbToHex(props.value)); + let prevHex = rgbToHex(props.value); + + let colorInput!: HTMLInputElement; + + return ( + + colorInput.click()} + /> + { + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + }} + /> + { + prevHex = rgbToHex(props.value); + }} + onInput={(e) => { + setText(e.currentTarget.value); + + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + }} + onBlur={(e) => { + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + else { + setText(prevHex); + props.onChange(hexToRgb(text())!); + } + }} + /> + + ); } function LayoutSegmentConfig(props: { - segmentIndex: number; - segment: LayoutSegment; + 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 - - > - ); + const { setProject, setEditorState, projectActions } = useEditorContext(); + + return ( + <> + + + setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + + + { + projectActions.deleteLayoutSegment(props.segmentIndex); + }} + leftIcon={} + > + Delete + + + }> + { + setProject( + "timeline", + "layoutSegments", + props.segmentIndex, + "mode", + v as "default" | "cameraOnly" | "hideCamera" + ); + }} + > + + + Default + + + Camera Only + + + Hide Camera + + + + + + + + + + • 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")) - .join("") - .toUpperCase()}`; + return `#${rgb + .map((c) => c.toString(16).padStart(2, "0")) + .join("") + .toUpperCase()}`; } function hexToRgb(hex: string): [number, number, number] | null { - const match = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); - if (!match) return null; - return match.slice(1).map((c) => Number.parseInt(c, 16)) as any; + const match = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); + if (!match) return null; + return match.slice(1).map((c) => Number.parseInt(c, 16)) as any; } diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx index e5dd2ff6067..6fd68958514 100644 --- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx @@ -353,8 +353,9 @@ export function ClipTrack( 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 + // Clear any existing selection (zoom, layout, etc.) when clicking on a clip + // This ensures the sidebar updates properly + setEditorState("timeline", "selection", null); } else { // When there are multiple segments, show the clip configuration setEditorState("timeline", "selection", { diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts index e2cd307ab9a..84c1629a1f1 100644 --- a/apps/desktop/src/utils/tauri.ts +++ b/apps/desktop/src/utils/tauri.ts @@ -721,9 +721,16 @@ export type TargetUnderCursor = { window: WindowUnderCursor | null; screen: ScreenUnderCursor | null; }; +export type LayoutSegment = { + start: number; + end: number; + mode?: "default" | "cameraOnly" | "hideCamera"; +}; + export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; + layoutSegments?: LayoutSegment[]; }; export type TimelineSegment = { recordingSegment?: number; From b9d40f39db411592c4c2c6a117df50982a2bc3f4 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 21:10:35 +0100 Subject: [PATCH 03/25] feat: Max duration calculation if placing segment between another --- .../routes/editor/Timeline/LayoutTrack.tsx | 895 +++++++++--------- 1 file changed, 460 insertions(+), 435 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx index 4d1135911ce..6f30f5394aa 100644 --- a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx @@ -1,24 +1,24 @@ import { - createEventListener, - createEventListenerMap, + 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, + batch, + createEffect, + createMemo, + createRoot, + createSignal, + For, + Show, } from "solid-js"; import { produce } from "solid-js/store"; import { useEditorContext } from "../context"; import { - useSegmentContext, - useTimelineContext, - useTrackContext, + useSegmentContext, + useTimelineContext, + useTrackContext, } from "./context"; import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track"; import IconLucideMonitor from "~icons/lucide/monitor"; @@ -26,429 +26,454 @@ import IconLucideVideo from "~icons/lucide/video"; import IconLucideEyeOff from "~icons/lucide/eye-off"; export type LayoutSegmentDragState = - | { type: "idle" } - | { type: "movePending" } - | { type: "moving" }; + | { type: "idle" } + | { type: "movePending" } + | { type: "moving" }; export function LayoutTrack(props: { - onDragStateChanged: (v: LayoutSegmentDragState) => void; - handleUpdatePlayhead: (e: MouseEvent) => void; + 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 + const { project, setProject, projectHistory, setEditorState, editorState } = + useEditorContext(); + + const { duration, secsPerPixel } = useTimelineContext(); + + const [hoveringSegment, setHoveringSegment] = createSignal(false); + const [hoveredTime, setHoveredTime] = createSignal(); + const [maxAvailableDuration, setMaxAvailableDuration] = + createSignal(3); + + // When we delete a segment that's being hovered, the onMouseLeave never fires + // because the element gets removed from the DOM. This leaves hoveringSegment stuck + // as true, which blocks the onMouseMove from setting hoveredTime, preventing + // users from creating new segments. This effect ensures we reset the hover state + // when all segments are deleted. + createEffect(() => { + const segments = project.timeline?.layoutSegments; + if (!segments || segments.length === 0) { + setHoveringSegment(false); + } + }); + + const getLayoutIcon = (mode: string) => { + 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 segments = project.timeline?.layoutSegments || []; + const nextSegmentIndex = segments.findIndex((s) => time < s.start); + + let maxDuration = 3; // Default duration + + if (nextSegmentIndex !== -1) { + const nextSegment = segments[nextSegmentIndex]; + const prevSegmentIndex = nextSegmentIndex - 1; + + if (prevSegmentIndex >= 0) { + const prevSegment = segments[prevSegmentIndex]; + const gapStart = prevSegment.end; + const gapEnd = nextSegment.start; + const availableSpace = gapEnd - gapStart; + + if (availableSpace < 0.5) { + setHoveredTime(undefined); + return; + } + + if (time < gapStart) { + time = gapStart; + } + + maxDuration = Math.min(3, gapEnd - time); + } else { + // No previous segment, only next segment + maxDuration = Math.min(3, nextSegment.start - time); + } + + if (nextSegment.start - time < 0.5) { + setHoveredTime(undefined); + return; + } + } else if (segments.length > 0) { + const lastSegment = segments[segments.length - 1]; + if (time < lastSegment.end) { + time = lastSegment.end; + } + maxDuration = Math.min(3, duration() - time); + } else { + maxDuration = Math.min(3, duration() - time); + } + + if (maxDuration < 0.5) { + setHoveredTime(undefined); + return; + } + + setMaxAvailableDuration(maxDuration); + setHoveredTime(Math.min(time, duration() - maxDuration)); + }} + onMouseLeave={() => { + setHoveredTime(); + setMaxAvailableDuration(3); + }} + onMouseDown={(e) => { + createRoot((dispose) => { + createEventListener(e.currentTarget, "mouseup", (e) => { + dispose(); + + const time = hoveredTime(); + const maxDuration = maxAvailableDuration(); + if (time === undefined) return; + + e.stopPropagation(); + batch(() => { + setProject("timeline", "layoutSegments", (v) => v ?? []); + setProject( + "timeline", + "layoutSegments", + produce((layoutSegments) => { + layoutSegments ??= []; + + let index = layoutSegments.length; + + for (let i = layoutSegments.length - 1; i >= 0; i--) { + if (layoutSegments[i].start > time) { + index = i; + break; + } + } + + layoutSegments.splice(index, 0, { + start: time, + end: time + maxDuration, + mode: "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) => ( + + + + + + + + + )} + + + ); +} From 220417a1f94b7aafe5cc15886bd7dd4c7c79c374 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 21:17:48 +0100 Subject: [PATCH 04/25] feat: Transition for "default" layout segments --- CLAUDE.md | 1 + crates/rendering/src/layout.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index 27a2faf2ab7..89cdb7d8cc5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -341,6 +341,7 @@ Minimize `useEffect` usage: compute during render, handle logic in event handler - Windowing/permissions are handled in Rust; keep UI logic in Solid and avoid mixing IPC with rendering logic. ## Conventions +- No code comments: Never add inline, block, or docstring comments in any language. Code must be self-explanatory through naming, types, and structure. Use docs/READMEs for explanations when necessary. - Directory naming: lower-case-dashed - Components: PascalCase; hooks: camelCase starting with `use` - Strict TypeScript; avoid `any`; leverage shared types diff --git a/crates/rendering/src/layout.rs b/crates/rendering/src/layout.rs index 0d47a7a7ee9..d2e500e75da 100644 --- a/crates/rendering/src/layout.rs +++ b/crates/rendering/src/layout.rs @@ -65,6 +65,8 @@ impl InterpolatedLayout { let (current_mode, next_mode, transition_progress) = if let Some(segment) = cursor.segment { let transition_start = segment.start - LAYOUT_TRANSITION_DURATION; + let transition_end = segment.end - LAYOUT_TRANSITION_DURATION; + if cursor.time < segment.start && cursor.time >= transition_start { let prev_mode = cursor .prev_segment @@ -76,6 +78,22 @@ impl InterpolatedLayout { segment.mode.clone(), ease_in_out(progress as f32) as f64, ) + } else if cursor.time >= transition_end && cursor.time < segment.end { + if let Some(next_seg) = cursor.next_segment() { + let progress = (cursor.time - transition_end) / LAYOUT_TRANSITION_DURATION; + ( + segment.mode.clone(), + next_seg.mode.clone(), + ease_in_out(progress as f32) as f64, + ) + } else { + let progress = (cursor.time - transition_end) / LAYOUT_TRANSITION_DURATION; + ( + segment.mode.clone(), + LayoutMode::Default, + ease_in_out(progress as f32) as f64, + ) + } } else { (segment.mode.clone(), segment.mode.clone(), 1.0) } From 46d70a9e1514bc0a294d7f09abf010c7916f8168 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 22:14:45 +0100 Subject: [PATCH 05/25] feat: Improved overlap transition --- crates/rendering/src/layout.rs | 72 +++++++++++++++++++++++++--------- crates/rendering/src/lib.rs | 19 +++++---- 2 files changed, 63 insertions(+), 28 deletions(-) diff --git a/crates/rendering/src/layout.rs b/crates/rendering/src/layout.rs index d2e500e75da..e7f6377ccd6 100644 --- a/crates/rendering/src/layout.rs +++ b/crates/rendering/src/layout.rs @@ -111,14 +111,9 @@ impl InterpolatedLayout { 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, - ) + // Small buffer after segment ends to complete the transition + if cursor.time < prev_segment.end + 0.05 { + (prev_segment.mode.clone(), LayoutMode::Default, 1.0) } else { (LayoutMode::Default, LayoutMode::Default, 1.0) } @@ -127,14 +122,9 @@ impl InterpolatedLayout { } } 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, - ) + // Small buffer after segment ends to complete the transition + if cursor.time < prev_segment.end + 0.05 { + (prev_segment.mode.clone(), LayoutMode::Default, 1.0) } else { (LayoutMode::Default, LayoutMode::Default, 1.0) } @@ -196,6 +186,8 @@ impl InterpolatedLayout { } pub fn is_transitioning_camera_only(&self) -> bool { + // Use camera_only layer when CameraOnly mode is involved in the transition + // Keep using it until the transition is truly complete to avoid gaps matches!(self.from_mode, LayoutMode::CameraOnly) || matches!(self.to_mode, LayoutMode::CameraOnly) } @@ -204,11 +196,22 @@ impl InterpolatedLayout { if matches!(self.from_mode, LayoutMode::CameraOnly) && !matches!(self.to_mode, LayoutMode::CameraOnly) { - 1.0 - self.transition_progress + // When transitioning FROM camera-only, keep it visible longer + if self.transition_progress < 0.8 { + 1.0 + } else { + // Quick fade in the last 20% of transition + 1.0 - (self.transition_progress - 0.8) * 5.0 + } } else if !matches!(self.from_mode, LayoutMode::CameraOnly) && matches!(self.to_mode, LayoutMode::CameraOnly) { - self.transition_progress + // When transitioning TO camera-only, fade in quickly at the start + if self.transition_progress < 0.2 { + self.transition_progress * 5.0 + } else { + 1.0 + } } else if matches!(self.from_mode, LayoutMode::CameraOnly) && matches!(self.to_mode, LayoutMode::CameraOnly) { @@ -217,4 +220,37 @@ impl InterpolatedLayout { 0.0 } } + + pub fn regular_camera_transition_opacity(&self) -> f64 { + // Handle camera overlay opacity during transitions to avoid double rendering + if matches!(self.from_mode, LayoutMode::CameraOnly) + && !matches!(self.to_mode, LayoutMode::CameraOnly) + { + // When transitioning FROM camera-only, use a sharp cutover to avoid overlap + // Start showing regular camera only after camera-only is mostly faded + if self.transition_progress > 0.8 { + // Fade in quickly in the last 20% of transition + ((self.transition_progress - 0.8) * 5.0) * self.camera_opacity + } else { + 0.0 + } + } else if !matches!(self.from_mode, LayoutMode::CameraOnly) + && matches!(self.to_mode, LayoutMode::CameraOnly) + { + // During transition TO camera-only, fade out the regular camera overlay early + if self.transition_progress < 0.2 { + (1.0 - self.transition_progress * 5.0) * self.camera_opacity + } else { + 0.0 + } + } else if matches!(self.from_mode, LayoutMode::CameraOnly) + || matches!(self.to_mode, LayoutMode::CameraOnly) + { + // During camera-only mode or transitions between camera-only modes, hide regular camera + 0.0 + } else { + // Normal operation + self.camera_opacity + } + } } diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs index 45f16a6b2f3..f424133fc94 100644 --- a/crates/rendering/src/lib.rs +++ b/crates/rendering/src/lib.rs @@ -642,10 +642,7 @@ impl ProjectUniforms { let camera = options .camera_size - .filter(|_| { - !project.camera.hide - && !matches!(layout.layout_mode, cap_project::LayoutMode::CameraOnly) - }) + .filter(|_| !project.camera.hide && layout.should_render_camera()) .map(|camera_size| { let output_size = [output_size.0 as f32, output_size.1 as f32]; let frame_size = [camera_size.x as f32, camera_size.y as f32]; @@ -747,7 +744,7 @@ impl ProjectUniforms { .advanced_shadow .as_ref() .map_or(50.0, |s| s.blur), - opacity: layout.camera_opacity as f32, + opacity: layout.regular_camera_transition_opacity() as f32, _padding: [0.0; 3], } }); @@ -1019,15 +1016,17 @@ impl RendererLayers { 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); - } - + // Render camera-only layer when transitioning with CameraOnly mode if uniforms.layout.is_transitioning_camera_only() { let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load); self.camera_only.render(&mut pass); } + + // Also render regular camera overlay during transitions when its opacity > 0 + if uniforms.layout.should_render_camera() && uniforms.layout.regular_camera_transition_opacity() > 0.01 { + let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load); + self.camera.render(&mut pass); + } } } From 63b9d7a350d3064427440755a254f0381378d5c1 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 23:12:17 +0100 Subject: [PATCH 06/25] feat: Camera Layout labels etc --- .../src/routes/editor/ConfigSidebar.tsx | 89 ++++++++++++------- .../routes/editor/Timeline/LayoutTrack.tsx | 12 ++- packages/ui-solid/src/auto-imports.d.ts | 2 + 3 files changed, 65 insertions(+), 38 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 18487283df4..ec7ea689168 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -2173,7 +2173,7 @@ function LayoutSegmentConfig(props: { Delete - }> + }> - - - Default - - - Camera Only - - - Hide Camera - - - - + + + + Default + + + Camera Only + + + Hide Camera + + + + + + + + + + + + {props.segment.mode === "cameraOnly" + ? "Shows only the camera feed" + : props.segment.mode === "hideCamera" + ? "Shows only the screen recording" + : "Shows both screen and camera"} + + + - - - • Default: Shows both screen and camera - - - • Camera Only: Shows only the camera feed - - - • Hide Camera: Shows only the screen recording - - > ); } diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx index 6f30f5394aa..51cf0408bf4 100644 --- a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx @@ -56,7 +56,7 @@ export function LayoutTrack(props: { } }); - const getLayoutIcon = (mode: string) => { + const getLayoutIcon = (mode: string | undefined) => { switch (mode) { case "cameraOnly": return ; @@ -67,7 +67,7 @@ export function LayoutTrack(props: { } }; - const getLayoutLabel = (mode: string) => { + const getLayoutLabel = (mode: string | undefined) => { switch (mode) { case "cameraOnly": return "Camera Only"; @@ -343,7 +343,9 @@ export function LayoutTrack(props: { "timeline", "layoutSegments", produce((s) => { - s.sort((a, b) => a.start - b.start); + if (s) { + s.sort((a, b) => a.start - b.start); + } }) ); } @@ -444,7 +446,9 @@ export function LayoutTrack(props: { "timeline", "layoutSegments", produce((s) => { - s.sort((a, b) => a.start - b.start); + if (s) { + s.sort((a, b) => a.start - b.start); + } }) ); } diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts index b6b6f3d663d..e246ef8fc1a 100644 --- a/packages/ui-solid/src/auto-imports.d.ts +++ b/packages/ui-solid/src/auto-imports.d.ts @@ -69,9 +69,11 @@ declare global { const IconLucideDatabase: typeof import('~icons/lucide/database.jsx')['default'] const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default'] const IconLucideEye: typeof import("~icons/lucide/eye.jsx")["default"] + const IconLucideEyeOff: typeof import('~icons/lucide/eye-off.jsx')['default'] const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default'] const IconLucideGift: typeof import('~icons/lucide/gift.jsx')['default'] const IconLucideHardDrive: typeof import('~icons/lucide/hard-drive.jsx')['default'] + const IconLucideLayout: typeof import('~icons/lucide/layout.jsx')['default'] const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default'] const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default'] const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"] From 37694d7f33f9d535f7dfa0a0db2abb39ceced800 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 23:27:15 +0100 Subject: [PATCH 07/25] feat: Smoother transition --- crates/rendering/src/layout.rs | 52 +++++++--------------------------- 1 file changed, 10 insertions(+), 42 deletions(-) diff --git a/crates/rendering/src/layout.rs b/crates/rendering/src/layout.rs index e7f6377ccd6..3f2f59cc801 100644 --- a/crates/rendering/src/layout.rs +++ b/crates/rendering/src/layout.rs @@ -1,6 +1,6 @@ use cap_project::{LayoutMode, LayoutSegment}; -pub const LAYOUT_TRANSITION_DURATION: f64 = 0.5; +pub const LAYOUT_TRANSITION_DURATION: f64 = 0.3; #[derive(Debug, Clone, Copy)] pub struct LayoutSegmentsCursor<'a> { @@ -111,7 +111,6 @@ impl InterpolatedLayout { ease_in_out(progress as f32) as f64, ) } else if let Some(prev_segment) = cursor.prev_segment { - // Small buffer after segment ends to complete the transition if cursor.time < prev_segment.end + 0.05 { (prev_segment.mode.clone(), LayoutMode::Default, 1.0) } else { @@ -122,7 +121,6 @@ impl InterpolatedLayout { } } else { if let Some(prev_segment) = cursor.prev_segment { - // Small buffer after segment ends to complete the transition if cursor.time < prev_segment.end + 0.05 { (prev_segment.mode.clone(), LayoutMode::Default, 1.0) } else { @@ -186,8 +184,6 @@ impl InterpolatedLayout { } pub fn is_transitioning_camera_only(&self) -> bool { - // Use camera_only layer when CameraOnly mode is involved in the transition - // Keep using it until the transition is truly complete to avoid gaps matches!(self.from_mode, LayoutMode::CameraOnly) || matches!(self.to_mode, LayoutMode::CameraOnly) } @@ -196,22 +192,11 @@ impl InterpolatedLayout { if matches!(self.from_mode, LayoutMode::CameraOnly) && !matches!(self.to_mode, LayoutMode::CameraOnly) { - // When transitioning FROM camera-only, keep it visible longer - if self.transition_progress < 0.8 { - 1.0 - } else { - // Quick fade in the last 20% of transition - 1.0 - (self.transition_progress - 0.8) * 5.0 - } + 1.0 - self.transition_progress } else if !matches!(self.from_mode, LayoutMode::CameraOnly) && matches!(self.to_mode, LayoutMode::CameraOnly) { - // When transitioning TO camera-only, fade in quickly at the start - if self.transition_progress < 0.2 { - self.transition_progress * 5.0 - } else { - 1.0 - } + self.transition_progress } else if matches!(self.from_mode, LayoutMode::CameraOnly) && matches!(self.to_mode, LayoutMode::CameraOnly) { @@ -220,36 +205,19 @@ impl InterpolatedLayout { 0.0 } } - + pub fn regular_camera_transition_opacity(&self) -> f64 { - // Handle camera overlay opacity during transitions to avoid double rendering if matches!(self.from_mode, LayoutMode::CameraOnly) - && !matches!(self.to_mode, LayoutMode::CameraOnly) - { - // When transitioning FROM camera-only, use a sharp cutover to avoid overlap - // Start showing regular camera only after camera-only is mostly faded - if self.transition_progress > 0.8 { - // Fade in quickly in the last 20% of transition - ((self.transition_progress - 0.8) * 5.0) * self.camera_opacity - } else { - 0.0 - } - } else if !matches!(self.from_mode, LayoutMode::CameraOnly) && matches!(self.to_mode, LayoutMode::CameraOnly) { - // During transition TO camera-only, fade out the regular camera overlay early - if self.transition_progress < 0.2 { - (1.0 - self.transition_progress * 5.0) * self.camera_opacity - } else { - 0.0 - } - } else if matches!(self.from_mode, LayoutMode::CameraOnly) - || matches!(self.to_mode, LayoutMode::CameraOnly) - { - // During camera-only mode or transitions between camera-only modes, hide regular camera 0.0 + } else if matches!(self.from_mode, LayoutMode::CameraOnly) { + let adjusted_progress = (self.transition_progress * 1.5).min(1.0); + adjusted_progress * self.camera_opacity + } else if matches!(self.to_mode, LayoutMode::CameraOnly) { + let adjusted_progress = ((1.0 - self.transition_progress) * 1.43).min(1.0); + adjusted_progress * self.camera_opacity } else { - // Normal operation self.camera_opacity } } From c8c732baf38418e17402b035761fe54a6463daa7 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 18 Aug 2025 23:38:14 +0100 Subject: [PATCH 08/25] feat: Improved UX in the editor for layout etc --- .../src/routes/editor/Timeline/LayoutTrack.tsx | 11 +++++++---- .../src/routes/editor/Timeline/ZoomTrack.tsx | 5 +++-- apps/desktop/src/routes/editor/Timeline/index.tsx | 15 +++++++++------ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx index 51cf0408bf4..b4cbabd5ee7 100644 --- a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx @@ -178,7 +178,7 @@ export function LayoutTrack(props: { layoutSegments.splice(index, 0, { start: time, end: time + maxDuration, - mode: "default", + mode: "cameraOnly", }); }) ); @@ -190,8 +190,11 @@ export function LayoutTrack(props: { - Click to add layout segment + + Click to add layout segment + + (Make the camera full screen, or hide it) + } > @@ -470,7 +473,7 @@ export function LayoutTrack(props: { end: time() + maxAvailableDuration(), }} > - + + diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx index 8d509d6a1b0..bc9070d4ce8 100644 --- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx @@ -169,8 +169,9 @@ export function ZoomTrack(props: { - Click to add zoom segment + + Click to add zoom segment + (Smoothly zoom in on important areas) } > diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx index 8c30b8e683d..66ad299e51a 100644 --- a/apps/desktop/src/routes/editor/Timeline/index.tsx +++ b/apps/desktop/src/routes/editor/Timeline/index.tsx @@ -26,6 +26,7 @@ export function Timeline() { totalDuration, editorState, projectActions, + meta, } = useEditorContext(); const duration = () => editorInstance.recordingDuration; @@ -233,12 +234,14 @@ export function Timeline() { }} handleUpdatePlayhead={handleUpdatePlayhead} /> - { - layoutSegmentDragState = v; - }} - handleUpdatePlayhead={handleUpdatePlayhead} - /> + + { + layoutSegmentDragState = v; + }} + handleUpdatePlayhead={handleUpdatePlayhead} + /> + ); From eaac5fb02cb0eb9afef47edade0374d4f55ac3cf Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 12:44:06 +0300 Subject: [PATCH 09/25] Update color of default, make camera only orange, and add multi select for deleting zoom segments --- .../routes/editor/Timeline/LayoutTrack.tsx | 942 +++++++++--------- .../src/routes/editor/Timeline/ZoomTrack.tsx | 85 +- .../src/routes/editor/Timeline/index.tsx | 26 +- apps/desktop/src/routes/editor/context.ts | 18 + 4 files changed, 589 insertions(+), 482 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx index b4cbabd5ee7..253173be97f 100644 --- a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx @@ -1,486 +1,488 @@ import { - createEventListener, - createEventListenerMap, + 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, + batch, + createEffect, + createMemo, + createRoot, + createSignal, + For, + Show, } from "solid-js"; import { produce } from "solid-js/store"; +import IconLucideEyeOff from "~icons/lucide/eye-off"; +import IconLucideMonitor from "~icons/lucide/monitor"; +import IconLucideVideo from "~icons/lucide/video"; import { useEditorContext } from "../context"; import { - useSegmentContext, - useTimelineContext, - useTrackContext, + 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" }; + | { type: "idle" } + | { type: "movePending" } + | { type: "moving" }; export function LayoutTrack(props: { - onDragStateChanged: (v: LayoutSegmentDragState) => void; - handleUpdatePlayhead: (e: MouseEvent) => void; + 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(); - const [maxAvailableDuration, setMaxAvailableDuration] = - createSignal(3); - - // When we delete a segment that's being hovered, the onMouseLeave never fires - // because the element gets removed from the DOM. This leaves hoveringSegment stuck - // as true, which blocks the onMouseMove from setting hoveredTime, preventing - // users from creating new segments. This effect ensures we reset the hover state - // when all segments are deleted. - createEffect(() => { - const segments = project.timeline?.layoutSegments; - if (!segments || segments.length === 0) { - setHoveringSegment(false); - } - }); - - const getLayoutIcon = (mode: string | undefined) => { - switch (mode) { - case "cameraOnly": - return ; - case "hideCamera": - return ; - default: - return ; - } - }; - - const getLayoutLabel = (mode: string | undefined) => { - 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 segments = project.timeline?.layoutSegments || []; - const nextSegmentIndex = segments.findIndex((s) => time < s.start); - - let maxDuration = 3; // Default duration - - if (nextSegmentIndex !== -1) { - const nextSegment = segments[nextSegmentIndex]; - const prevSegmentIndex = nextSegmentIndex - 1; - - if (prevSegmentIndex >= 0) { - const prevSegment = segments[prevSegmentIndex]; - const gapStart = prevSegment.end; - const gapEnd = nextSegment.start; - const availableSpace = gapEnd - gapStart; - - if (availableSpace < 0.5) { - setHoveredTime(undefined); - return; - } - - if (time < gapStart) { - time = gapStart; - } - - maxDuration = Math.min(3, gapEnd - time); - } else { - // No previous segment, only next segment - maxDuration = Math.min(3, nextSegment.start - time); - } - - if (nextSegment.start - time < 0.5) { - setHoveredTime(undefined); - return; - } - } else if (segments.length > 0) { - const lastSegment = segments[segments.length - 1]; - if (time < lastSegment.end) { - time = lastSegment.end; - } - maxDuration = Math.min(3, duration() - time); - } else { - maxDuration = Math.min(3, duration() - time); - } - - if (maxDuration < 0.5) { - setHoveredTime(undefined); - return; - } - - setMaxAvailableDuration(maxDuration); - setHoveredTime(Math.min(time, duration() - maxDuration)); - }} - onMouseLeave={() => { - setHoveredTime(); - setMaxAvailableDuration(3); - }} - onMouseDown={(e) => { - createRoot((dispose) => { - createEventListener(e.currentTarget, "mouseup", (e) => { - dispose(); - - const time = hoveredTime(); - const maxDuration = maxAvailableDuration(); - if (time === undefined) return; - - e.stopPropagation(); - batch(() => { - setProject("timeline", "layoutSegments", (v) => v ?? []); - setProject( - "timeline", - "layoutSegments", - produce((layoutSegments) => { - layoutSegments ??= []; - - let index = layoutSegments.length; - - for (let i = layoutSegments.length - 1; i >= 0; i--) { - if (layoutSegments[i].start > time) { - index = i; - break; - } - } - - layoutSegments.splice(index, 0, { - start: time, - end: time + maxDuration, - mode: "cameraOnly", - }); - }) - ); - }); - }); - }); - }} - > - - Click to add layout segment - - (Make the camera full screen, or hide it) - - - } - > - {(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) => { - if (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) => { - if (s) { - s.sort((a, b) => a.start - b.start); - } - }) - ); - } - )} - /> - - ); - }} - - - {(time) => ( - - - - + - - - - )} - - - ); + const { project, setProject, projectHistory, setEditorState, editorState } = + useEditorContext(); + + const { duration, secsPerPixel } = useTimelineContext(); + + const [hoveringSegment, setHoveringSegment] = createSignal(false); + const [hoveredTime, setHoveredTime] = createSignal(); + const [maxAvailableDuration, setMaxAvailableDuration] = + createSignal(3); + + // When we delete a segment that's being hovered, the onMouseLeave never fires + // because the element gets removed from the DOM. This leaves hoveringSegment stuck + // as true, which blocks the onMouseMove from setting hoveredTime, preventing + // users from creating new segments. This effect ensures we reset the hover state + // when all segments are deleted. + createEffect(() => { + const segments = project.timeline?.layoutSegments; + if (!segments || segments.length === 0) { + setHoveringSegment(false); + } + }); + + const getLayoutIcon = (mode: string | undefined) => { + switch (mode) { + case "cameraOnly": + return ; + case "hideCamera": + return ; + default: + return ; + } + }; + + const getLayoutLabel = (mode: string | undefined) => { + 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 segments = project.timeline?.layoutSegments || []; + const nextSegmentIndex = segments.findIndex((s) => time < s.start); + + let maxDuration = 3; // Default duration + + if (nextSegmentIndex !== -1) { + const nextSegment = segments[nextSegmentIndex]; + const prevSegmentIndex = nextSegmentIndex - 1; + + if (prevSegmentIndex >= 0) { + const prevSegment = segments[prevSegmentIndex]; + const gapStart = prevSegment.end; + const gapEnd = nextSegment.start; + const availableSpace = gapEnd - gapStart; + + if (availableSpace < 0.5) { + setHoveredTime(undefined); + return; + } + + if (time < gapStart) { + time = gapStart; + } + + maxDuration = Math.min(3, gapEnd - time); + } else { + // No previous segment, only next segment + maxDuration = Math.min(3, nextSegment.start - time); + } + + if (nextSegment.start - time < 0.5) { + setHoveredTime(undefined); + return; + } + } else if (segments.length > 0) { + const lastSegment = segments[segments.length - 1]; + if (time < lastSegment.end) { + time = lastSegment.end; + } + maxDuration = Math.min(3, duration() - time); + } else { + maxDuration = Math.min(3, duration() - time); + } + + if (maxDuration < 0.5) { + setHoveredTime(undefined); + return; + } + + setMaxAvailableDuration(maxDuration); + setHoveredTime(Math.min(time, duration() - maxDuration)); + }} + onMouseLeave={() => { + setHoveredTime(); + setMaxAvailableDuration(3); + }} + onMouseDown={(e) => { + createRoot((dispose) => { + createEventListener(e.currentTarget, "mouseup", (e) => { + dispose(); + + const time = hoveredTime(); + const maxDuration = maxAvailableDuration(); + if (time === undefined) return; + + e.stopPropagation(); + batch(() => { + setProject("timeline", "layoutSegments", (v) => v ?? []); + setProject( + "timeline", + "layoutSegments", + produce((layoutSegments) => { + layoutSegments ??= []; + + let index = layoutSegments.length; + + for (let i = layoutSegments.length - 1; i >= 0; i--) { + if (layoutSegments[i].start > time) { + index = i; + break; + } + } + + layoutSegments.splice(index, 0, { + start: time, + end: time + maxDuration, + mode: "cameraOnly", + }); + }), + ); + }); + }); + }); + }} + > + + Click to add layout segment + + (Make the camera full screen, or hide it) + + + } + > + {(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-[#E3701B] via-[#FF9D57] to-[#E3701B]"; + case "hideCamera": + return "from-[#EF4444] via-[#F87171] to-[#EF4444]"; + default: + return "from-[#069962] via-[#2FD49C] to-[#069962]"; + } + }; + + 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) => { + if (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) => { + if (s) { + s.sort((a, b) => a.start - b.start); + } + }), + ); + }, + )} + /> + + ); + }} + + + {(time) => ( + + + + + + + + + )} + + + ); } diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx index bc9070d4ce8..6e228dd1fa4 100644 --- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx @@ -171,7 +171,9 @@ export function ZoomTrack(props: { fallback={ Click to add zoom segment - (Smoothly zoom in on important areas) + + (Smoothly zoom in on important areas) + } > @@ -207,10 +209,67 @@ export function ZoomTrack(props: { resumeHistory(); if (!moved) { e.stopPropagation(); - setEditorState("timeline", "selection", { - type: "zoom", - index: i(), - }); + + const currentSelection = editorState.timeline.selection; + const segmentIndex = i(); + + // Handle multi-selection with Ctrl/Cmd+click + if (e.ctrlKey || e.metaKey) { + if (currentSelection?.type === "zoom") { + // If we already have zoom selections + if ( + "indices" in currentSelection && + Array.isArray(currentSelection.indices) + ) { + // Toggle this segment in the selection + const newIndices = currentSelection.indices.includes( + segmentIndex, + ) + ? currentSelection.indices.filter( + (idx) => idx !== segmentIndex, + ) + : [...currentSelection.indices, segmentIndex]; + + setEditorState( + "timeline", + "selection", + newIndices.length > 0 + ? { type: "zoom", indices: newIndices } + : null, + ); + } else if ( + "index" in currentSelection && + typeof currentSelection.index === "number" + ) { + // Convert single selection to multi-selection + const newIndices = + currentSelection.index === segmentIndex + ? [] // Deselect if clicking the same segment + : [currentSelection.index, segmentIndex]; + + setEditorState( + "timeline", + "selection", + newIndices.length > 0 + ? { type: "zoom", indices: newIndices } + : null, + ); + } + } else { + // Start new multi-selection + setEditorState("timeline", "selection", { + type: "zoom", + indices: [segmentIndex], + }); + } + } else { + // Regular single selection + setEditorState("timeline", "selection", { + type: "zoom", + index: segmentIndex, + }); + } + props.handleUpdatePlayhead(e); } props.onDragStateChanged({ type: "idle" }); @@ -256,7 +315,21 @@ export function ZoomTrack(props: { (s) => s.start === segment.start && s.end === segment.end, ); - return segmentIndex === selection.index; + // Support both single selection (index) and multi-selection (indices) + if ( + "indices" in selection && + Array.isArray(selection.indices) && + segmentIndex !== undefined + ) { + return selection.indices.includes(segmentIndex); + } else if ( + "index" in selection && + typeof selection.index === "number" + ) { + return segmentIndex === selection.index; + } + + return false; }); return ( diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx index 66ad299e51a..06308df42aa 100644 --- a/apps/desktop/src/routes/editor/Timeline/index.tsx +++ b/apps/desktop/src/routes/editor/Timeline/index.tsx @@ -11,8 +11,8 @@ import { useEditorContext } from "../context"; import { formatTime } from "../utils"; import { ClipTrack } from "./ClipTrack"; import { TimelineContextProvider, useTimelineContext } from "./context"; -import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack"; import { type LayoutSegmentDragState, LayoutTrack } from "./LayoutTrack"; +import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack"; const TIMELINE_PADDING = 16; @@ -96,16 +96,30 @@ export function Timeline() { const selection = editorState.timeline.selection; if (!selection) return; - if (selection.type === "zoom") - projectActions.deleteZoomSegment(selection.index); - else if (selection.type === "clip") + if (selection.type === "zoom") { + // Handle multiple zoom segment deletion + if ("indices" in selection && Array.isArray(selection.indices)) { + // Use bulk deletion for better performance + projectActions.deleteZoomSegments(selection.indices); + } else if ( + "index" in selection && + typeof selection.index === "number" + ) { + // Handle single zoom segment deletion + projectActions.deleteZoomSegment(selection.index); + } + } else if (selection.type === "clip") { projectActions.deleteClipSegment(selection.index); - else if (selection.type === "layout") + } else if (selection.type === "layout") { projectActions.deleteLayoutSegment(selection.index); + } } else if (e.code === "KeyC" && hasNoModifiers) { if (!editorState.previewTime) return; projectActions.splitClipSegment(editorState.previewTime); + } else if (e.code === "Escape" && hasNoModifiers) { + // Deselect all selected segments + setEditorState("timeline", "selection", null); } }); @@ -267,7 +281,7 @@ function TimelineMarkings() { {(second) => ( 0}> { + batch(() => { + setProject( + "timeline", + "zoomSegments", + produce((s) => { + if (!s) return; + // Sort indices in descending order to avoid index shifting issues + const sortedIndices = [...segmentIndices].sort((a, b) => b - a); + sortedIndices.forEach((index) => { + s.splice(index, 1); + }); + }), + ); + setEditorState("timeline", "selection", null); + }); + }, deleteLayoutSegment: (segmentIndex: number) => { batch(() => { setProject( @@ -251,6 +268,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( selection: null as | null | { type: "zoom"; index: number } + | { type: "zoom"; indices: number[] } | { type: "clip"; index: number } | { type: "layout"; index: number }, transform: { From 4fc6d85f61aee0fc8b490c254e5d9291bef5eedf Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 12:49:59 +0300 Subject: [PATCH 10/25] ts and formatting --- .../src/routes/editor/ConfigSidebar.tsx | 4139 +++++++++-------- 1 file changed, 2075 insertions(+), 2064 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index ec7ea689168..3ceff323abd 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,20 +17,20 @@ 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 { createStore } from "solid-js/store"; import { Dynamic } from "solid-js/web"; import toast from "solid-toast"; import colorBg from "~/assets/illustrations/color.webp"; @@ -40,463 +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 LayoutSegment, + 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 IconLucideSparkles from "~icons/lucide/sparkles"; 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])} @@ -505,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; + + // Only show config panel for single zoom segment selection + if ( + !("index" in zoomSelection) || + typeof zoomSelection.index !== "number" + ) + 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 ( - - ); - }; - - 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) => ( - - - - - - - )} - - - - - - {(photo) => ( - - - - - - - )} - - - - - - - - - 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) => ( - - - - - setProject("background", "source", { - type: "image", - path: null, - }) - } - class="p-2 text-white rounded-full transition-colors bg-black/50 hover:bg-black/70" - > - - - - - )} - - { - 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 ( + + ); + }; + + 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) => ( + + + + + + + )} + + + + + + {(photo) => ( + + + + + + + )} + + + + + + + + + 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) => ( + + + + + setProject("background", "source", { + type: "image", + path: null, + }) + } + class="p-2 text-white rounded-full transition-colors bg-black/50 hover:bg-black/70" + > + + + + + )} + + { + 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) => ( - - { - if (e.target.checked) { - backgrounds.color = { - type: "color", - value: hexToRgb(color) ?? [0, 0, 0], - }; - setProject( - "background", - "source", - backgrounds.color - ); - } - }} - /> - - - )} - - - {/* + 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) => ( + + { + if (e.target.checked) { + backgrounds.color = { + type: "color", + value: hexToRgb(color) ?? [0, 0, 0], + }; + setProject( + "background", + "source", + backgrounds.color, + ); + } + }} + /> + + + )} + + + {/* { @@ -1258,237 +1265,237 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { + */} - - - - - - {(source) => { - const max = 360; - - const { projectHistory } = useEditorContext(); - - const angle = () => source().angle ?? 90; - - return ( - <> - - - { - backgrounds.gradient.from = from; - setProject("background", "source", { - type: "gradient", - from, - }); - }} - /> - { - backgrounds.gradient.to = to; - setProject("background", "source", { - type: "gradient", - to, - }); - }} - /> - { - const start = angle(); - const resumeHistory = projectHistory.pause(); - - createRoot((dispose) => - createEventListenerMap(window, { - mouseup: () => { - dispose(); - resumeHistory(); - }, - mousemove: (moveEvent) => { - const rawNewAngle = - Math.round( - start + - (downEvent.clientY - moveEvent.clientY) - ) % max; - const newAngle = moveEvent.shiftKey - ? rawNewAngle - : Math.round(rawNewAngle / 45) * 45; - - if ( - !moveEvent.shiftKey && - hapticsEnabled() && - project.background.source.type === - "gradient" && - project.background.source.angle !== newAngle - ) { - commands.performHapticFeedback( - "Alignment", - "Now" - ); - } - - setProject("background", "source", { - type: "gradient", - angle: - newAngle < 0 ? newAngle + max : newAngle, - }); - }, - }) - ); - }} - > - - - - - - {(gradient) => ( - - { - if (e.target.checked) { - backgrounds.gradient = { - type: "gradient", - from: gradient.from, - to: gradient.to, - }; - setProject( - "background", - "source", - backgrounds.gradient - ); - } - }} - /> - - - )} - - - - > - ); - }} - - - - - - }> - setProject("background", "blur", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - - {/** Dashed divider */} - - }> - setProject("background", "padding", v[0])} - minValue={0} - maxValue={40} - step={0.1} - formatTooltip="%" - /> - - }> - setProject("background", "rounding", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - - }> - { - batch(() => { - setProject("background", "shadow", v[0]); - // Initialize advanced shadow settings if they don't exist and shadow is enabled - if (v[0] > 0 && !project.background.advancedShadow) { - setProject("background", "advancedShadow", { - size: 50, - opacity: 18, - blur: 50, - }); - } - }); - }} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - { - setProject("background", "advancedShadow", { - ...(project.background.advancedShadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - size: v[0], - }); - }, - }} - opacity={{ - value: [project.background.advancedShadow?.opacity ?? 18], - onChange: (v) => { - setProject("background", "advancedShadow", { - ...(project.background.advancedShadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - opacity: v[0], - }); - }, - }} - blur={{ - value: [project.background.advancedShadow?.blur ?? 50], - onChange: (v) => { - setProject("background", "advancedShadow", { - ...(project.background.advancedShadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - blur: v[0], - }); - }, - }} - /> - - {/* + + + + + + {(source) => { + const max = 360; + + const { projectHistory } = useEditorContext(); + + const angle = () => source().angle ?? 90; + + return ( + <> + + + { + backgrounds.gradient.from = from; + setProject("background", "source", { + type: "gradient", + from, + }); + }} + /> + { + backgrounds.gradient.to = to; + setProject("background", "source", { + type: "gradient", + to, + }); + }} + /> + { + const start = angle(); + const resumeHistory = projectHistory.pause(); + + createRoot((dispose) => + createEventListenerMap(window, { + mouseup: () => { + dispose(); + resumeHistory(); + }, + mousemove: (moveEvent) => { + const rawNewAngle = + Math.round( + start + + (downEvent.clientY - moveEvent.clientY), + ) % max; + const newAngle = moveEvent.shiftKey + ? rawNewAngle + : Math.round(rawNewAngle / 45) * 45; + + if ( + !moveEvent.shiftKey && + hapticsEnabled() && + project.background.source.type === + "gradient" && + project.background.source.angle !== newAngle + ) { + commands.performHapticFeedback( + "Alignment", + "Now", + ); + } + + setProject("background", "source", { + type: "gradient", + angle: + newAngle < 0 ? newAngle + max : newAngle, + }); + }, + }), + ); + }} + > + + + + + + {(gradient) => ( + + { + if (e.target.checked) { + backgrounds.gradient = { + type: "gradient", + from: gradient.from, + to: gradient.to, + }; + setProject( + "background", + "source", + backgrounds.gradient, + ); + } + }} + /> + + + )} + + + + > + ); + }} + + + + + + }> + setProject("background", "blur", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + + {/** Dashed divider */} + + }> + setProject("background", "padding", v[0])} + minValue={0} + maxValue={40} + step={0.1} + formatTooltip="%" + /> + + }> + setProject("background", "rounding", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + + }> + { + batch(() => { + setProject("background", "shadow", v[0]); + // Initialize advanced shadow settings if they don't exist and shadow is enabled + if (v[0] > 0 && !project.background.advancedShadow) { + setProject("background", "advancedShadow", { + size: 50, + opacity: 18, + blur: 50, + }); + } + }); + }} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + { + setProject("background", "advancedShadow", { + ...(project.background.advancedShadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + size: v[0], + }); + }, + }} + opacity={{ + value: [project.background.advancedShadow?.opacity ?? 18], + onChange: (v) => { + setProject("background", "advancedShadow", { + ...(project.background.advancedShadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + opacity: v[0], + }); + }, + }} + blur={{ + value: [project.background.advancedShadow?.blur ?? 50], + onChange: (v) => { + setProject("background", "advancedShadow", { + ...(project.background.advancedShadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + blur: v[0], + }); + }, + }} + /> + + {/* }> */} - - ); + + ); } function CameraConfig(props: { scrollRef: HTMLDivElement }) { - const { project, setProject } = useEditorContext(); - - return ( - - } name="Camera"> - - - - { - const [x, y] = v.split(":"); - setProject("camera", "position", { x, y } as any); - }} - class="mt-[0.75rem] rounded-[0.5rem] border border-gray-3 bg-gray-2 w-full h-[7.5rem] relative" - > - - {(item) => ( - - - setProject("camera", "position", item)} - > - - - - )} - - - - - setProject("camera", "hide", hide)} - /> - - - setProject("camera", "mirror", mirror)} - /> - - - - options={CAMERA_SHAPES} - optionValue="value" - optionTextValue="name" - value={CAMERA_SHAPES.find( - (v) => v.value === project.camera.shape - )} - onChange={(v) => { - if (v) setProject("camera", "shape", 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 } = useEditorContext(); + + return ( + + } name="Camera"> + + + + { + const [x, y] = v.split(":"); + setProject("camera", "position", { x, y } as any); + }} + class="mt-[0.75rem] rounded-[0.5rem] border border-gray-3 bg-gray-2 w-full h-[7.5rem] relative" + > + + {(item) => ( + + + setProject("camera", "position", item)} + > + + + + )} + + + + + setProject("camera", "hide", hide)} + /> + + + setProject("camera", "mirror", mirror)} + /> + + + + options={CAMERA_SHAPES} + optionValue="value" + optionTextValue="name" + value={CAMERA_SHAPES.find( + (v) => v.value === project.camera.shape, + )} + onChange={(v) => { + if (v) setProject("camera", "shape", 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("camera", "use_camera_aspect", v)} /> */} - - - {/** Dashed divider */} - - }> - setProject("camera", "size", v[0])} - minValue={20} - maxValue={80} - step={0.1} - formatTooltip="%" - /> - - }> - setProject("camera", "zoom_size", v[0])} - minValue={10} - maxValue={60} - step={0.1} - formatTooltip="%" - /> - - }> - setProject("camera", "rounding", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - - }> - - setProject("camera", "shadow", v[0])} - minValue={0} - maxValue={100} - step={0.1} - formatTooltip="%" - /> - { - setProject("camera", "advanced_shadow", { - ...(project.camera.advanced_shadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - size: v[0], - }); - }, - }} - opacity={{ - value: [project.camera.advanced_shadow?.opacity ?? 18], - onChange: (v) => { - setProject("camera", "advanced_shadow", { - ...(project.camera.advanced_shadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - opacity: v[0], - }); - }, - }} - blur={{ - value: [project.camera.advanced_shadow?.blur ?? 50], - onChange: (v) => { - setProject("camera", "advanced_shadow", { - ...(project.camera.advanced_shadow ?? { - size: 50, - opacity: 18, - blur: 50, - }), - blur: v[0], - }); - }, - }} - /> - - - {/* + + + {/** Dashed divider */} + + }> + setProject("camera", "size", v[0])} + minValue={20} + maxValue={80} + step={0.1} + formatTooltip="%" + /> + + }> + setProject("camera", "zoom_size", v[0])} + minValue={10} + maxValue={60} + step={0.1} + formatTooltip="%" + /> + + }> + setProject("camera", "rounding", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + + }> + + setProject("camera", "shadow", v[0])} + minValue={0} + maxValue={100} + step={0.1} + formatTooltip="%" + /> + { + setProject("camera", "advanced_shadow", { + ...(project.camera.advanced_shadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + size: v[0], + }); + }, + }} + opacity={{ + value: [project.camera.advanced_shadow?.opacity ?? 18], + onChange: (v) => { + setProject("camera", "advanced_shadow", { + ...(project.camera.advanced_shadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + opacity: v[0], + }); + }, + }} + blur={{ + value: [project.camera.advanced_shadow?.blur ?? 50], + onChange: (v) => { + setProject("camera", "advanced_shadow", { + ...(project.camera.advanced_shadow ?? { + size: 50, + opacity: 18, + blur: 50, + }), + blur: v[0], + }); + }, + }} + /> + + + {/* }> */} - - ); + + ); } function ZoomSegmentConfig(props: { - segmentIndex: number; - segment: ZoomSegment; + segmentIndex: number; + segment: ZoomSegment; }) { - const generalSettings = generalSettingsStore.createQuery(); - const { - project, - setProject, - editorInstance, - setEditorState, - projectHistory, - projectActions, - } = useEditorContext(); - - const states = { - manual: - props.segment.mode === "auto" - ? { x: 0.5, y: 0.5 } - : props.segment.mode.manual, - }; - - return ( - <> - - - setEditorState("timeline", "selection", null)} - leftIcon={} - > - Done - - - { - projectActions.deleteZoomSegment(props.segmentIndex); - }} - leftIcon={} - > - Delete - - - }> - - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "amount", - v[0] - ) - } - minValue={1} - maxValue={4.5} - step={0.001} - formatTooltip="x" - /> - - }> - { - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "mode", - v === "auto" ? "auto" : { manual: states.manual } - ); - }} - > - - - Auto - - - Manual - - - - - - - { - const m = props.segment.mode; - if (m === "auto") return; - return m.manual; - })()} - > - {(mode) => { - const start = createMemo((prev) => { - if (projectHistory.isPaused()) return prev; - return props.segment.start; - }, 0); - - const segmentIndex = createMemo((prev) => { - if (projectHistory.isPaused()) return prev; - - const st = start(); - const i = project.timeline?.segments.findIndex( - (s) => s.start <= st && s.end > st - ); - if (i === undefined || i === -1) return 0; - return i; - }, 0); - - // Calculate the time relative to the video segment - const relativeTime = createMemo(() => { - const st = start(); - const segment = project.timeline?.segments[segmentIndex()]; - if (!segment) return 0; - // The time within the actual video file - return Math.max(0, st - segment.start); - }); - - const video = document.createElement("video"); - createEffect(() => { - const path = convertFileSrc( - // TODO: this shouldn't be so hardcoded - `${ - editorInstance.path - }/content/segments/segment-${segmentIndex()}/display.mp4` - ); - video.src = path; - // Force reload if video fails to load - video.load(); - }); - - createEffect(() => { - const t = relativeTime(); - if (t === undefined) return; - - // Ensure video is ready before seeking - if (video.readyState >= 2) { - video.currentTime = t; - } else { - // Wait for video to be ready, then seek - const handleCanPlay = () => { - video.currentTime = t; - video.removeEventListener("canplay", handleCanPlay); - }; - video.addEventListener("canplay", handleCanPlay); - } - }); - - createEffect( - on( - () => { - croppedPosition(); - croppedSize(); - }, - () => { - if (loaded()) { - render(); - } - } - ) - ); - - const render = () => { - if (!canvasRef || video.readyState < 2) return; - - const ctx = canvasRef.getContext("2d"); - if (!ctx) return; - - ctx.imageSmoothingEnabled = false; - // Clear canvas first - ctx.clearRect(0, 0, canvasRef.width, canvasRef.height); - // Draw video frame - ctx.drawImage( - video, - croppedPosition().x, - croppedPosition().y, - croppedSize().x, - croppedSize().y, - 0, - 0, - canvasRef.width!, - canvasRef.height! - ); - }; - - const [loaded, setLoaded] = createSignal(false); - video.onloadeddata = () => { - setLoaded(true); - render(); - }; - video.onseeked = render; - - // Add error handling - video.onerror = (e) => { - console.error("Failed to load video for zoom preview:", e); - // Try to reload after a short delay - setTimeout(() => { - video.load(); - }, 100); - }; - - let canvasRef!: HTMLCanvasElement; - - const [ref, setRef] = createSignal(); - const bounds = createElementBounds(ref); - const rawSize = () => { - const raw = editorInstance.recordings.segments[0].display; - return { x: raw.width, y: raw.height }; - }; - - const croppedPosition = () => { - const cropped = project.background.crop?.position; - if (cropped) return cropped; - - return { x: 0, y: 0 }; - }; - - const croppedSize = () => { - const cropped = project.background.crop?.size; - if (cropped) return cropped; - - return rawSize(); - }; - - const visualHeight = () => - (bounds.width! / croppedSize().x) * croppedSize().y; - - return ( - { - const bounds = - downEvent.currentTarget.getBoundingClientRect(); - - createRoot((dispose) => { - createEventListenerMap(window, { - mouseup: () => dispose(), - mousemove: (moveEvent) => { - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "mode", - "manual", - { - x: Math.max( - Math.min( - (moveEvent.clientX - bounds.left) / - bounds.width, - 1 - ), - 0 - ), - y: Math.max( - Math.min( - (moveEvent.clientY - bounds.top) / - bounds.height, - 1 - ), - 0 - ), - } - ); - }, - }); - }); - }} - > - - - - - - - Loading preview... - - - - - - ); - }} - - - - - > - ); + const generalSettings = generalSettingsStore.createQuery(); + const { + project, + setProject, + editorInstance, + setEditorState, + projectHistory, + projectActions, + } = useEditorContext(); + + const states = { + manual: + props.segment.mode === "auto" + ? { x: 0.5, y: 0.5 } + : props.segment.mode.manual, + }; + + return ( + <> + + + setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + + + { + projectActions.deleteZoomSegment(props.segmentIndex); + }} + leftIcon={} + > + Delete + + + }> + + setProject( + "timeline", + "zoomSegments", + props.segmentIndex, + "amount", + v[0], + ) + } + minValue={1} + maxValue={4.5} + step={0.001} + formatTooltip="x" + /> + + }> + { + setProject( + "timeline", + "zoomSegments", + props.segmentIndex, + "mode", + v === "auto" ? "auto" : { manual: states.manual }, + ); + }} + > + + + Auto + + + Manual + + + + + + + { + const m = props.segment.mode; + if (m === "auto") return; + return m.manual; + })()} + > + {(mode) => { + const start = createMemo((prev) => { + if (projectHistory.isPaused()) return prev; + return props.segment.start; + }, 0); + + const segmentIndex = createMemo((prev) => { + if (projectHistory.isPaused()) return prev; + + const st = start(); + const i = project.timeline?.segments.findIndex( + (s) => s.start <= st && s.end > st, + ); + if (i === undefined || i === -1) return 0; + return i; + }, 0); + + // Calculate the time relative to the video segment + const relativeTime = createMemo(() => { + const st = start(); + const segment = project.timeline?.segments[segmentIndex()]; + if (!segment) return 0; + // The time within the actual video file + return Math.max(0, st - segment.start); + }); + + const video = document.createElement("video"); + createEffect(() => { + const path = convertFileSrc( + // TODO: this shouldn't be so hardcoded + `${ + editorInstance.path + }/content/segments/segment-${segmentIndex()}/display.mp4`, + ); + video.src = path; + // Force reload if video fails to load + video.load(); + }); + + createEffect(() => { + const t = relativeTime(); + if (t === undefined) return; + + // Ensure video is ready before seeking + if (video.readyState >= 2) { + video.currentTime = t; + } else { + // Wait for video to be ready, then seek + const handleCanPlay = () => { + video.currentTime = t; + video.removeEventListener("canplay", handleCanPlay); + }; + video.addEventListener("canplay", handleCanPlay); + } + }); + + createEffect( + on( + () => { + croppedPosition(); + croppedSize(); + }, + () => { + if (loaded()) { + render(); + } + }, + ), + ); + + const render = () => { + if (!canvasRef || video.readyState < 2) return; + + const ctx = canvasRef.getContext("2d"); + if (!ctx) return; + + ctx.imageSmoothingEnabled = false; + // Clear canvas first + ctx.clearRect(0, 0, canvasRef.width, canvasRef.height); + // Draw video frame + ctx.drawImage( + video, + croppedPosition().x, + croppedPosition().y, + croppedSize().x, + croppedSize().y, + 0, + 0, + canvasRef.width!, + canvasRef.height!, + ); + }; + + const [loaded, setLoaded] = createSignal(false); + video.onloadeddata = () => { + setLoaded(true); + render(); + }; + video.onseeked = render; + + // Add error handling + video.onerror = (e) => { + console.error("Failed to load video for zoom preview:", e); + // Try to reload after a short delay + setTimeout(() => { + video.load(); + }, 100); + }; + + let canvasRef!: HTMLCanvasElement; + + const [ref, setRef] = createSignal(); + const bounds = createElementBounds(ref); + const rawSize = () => { + const raw = editorInstance.recordings.segments[0].display; + return { x: raw.width, y: raw.height }; + }; + + const croppedPosition = () => { + const cropped = project.background.crop?.position; + if (cropped) return cropped; + + return { x: 0, y: 0 }; + }; + + const croppedSize = () => { + const cropped = project.background.crop?.size; + if (cropped) return cropped; + + return rawSize(); + }; + + const visualHeight = () => + (bounds.width! / croppedSize().x) * croppedSize().y; + + return ( + { + const bounds = + downEvent.currentTarget.getBoundingClientRect(); + + createRoot((dispose) => { + createEventListenerMap(window, { + mouseup: () => dispose(), + mousemove: (moveEvent) => { + setProject( + "timeline", + "zoomSegments", + props.segmentIndex, + "mode", + "manual", + { + x: Math.max( + Math.min( + (moveEvent.clientX - bounds.left) / + bounds.width, + 1, + ), + 0, + ), + y: Math.max( + Math.min( + (moveEvent.clientY - bounds.top) / + bounds.height, + 1, + ), + 0, + ), + }, + ); + }, + }); + }); + }} + > + + + + + + + Loading preview... + + + + + + ); + }} + + + + + > + ); } function ClipSegmentConfig(props: { - segmentIndex: number; - segment: TimelineSegment; + segmentIndex: number; + segment: TimelineSegment; }) { - const { setProject, setEditorState, project, projectActions } = - useEditorContext(); - - return ( - <> - - - setEditorState("timeline", "selection", null)} - leftIcon={} - > - Done - - - { - projectActions.deleteClipSegment(props.segmentIndex); - }} - disabled={ - ( - project.timeline?.segments.filter( - (s) => s.recordingSegment === props.segment.recordingSegment - ) ?? [] - ).length < 2 - } - leftIcon={} - > - Delete - - - - } /> - - - } - /> - - > - ); + const { setProject, setEditorState, project, projectActions } = + useEditorContext(); + + return ( + <> + + + setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + + + { + projectActions.deleteClipSegment(props.segmentIndex); + }} + disabled={ + ( + project.timeline?.segments.filter( + (s) => s.recordingSegment === props.segment.recordingSegment, + ) ?? [] + ).length < 2 + } + leftIcon={} + > + Delete + + + + } /> + + + } + /> + + > + ); } function RgbInput(props: { - value: [number, number, number]; - onChange: (value: [number, number, number]) => void; + value: [number, number, number]; + onChange: (value: [number, number, number]) => void; }) { - const [text, setText] = createWritableMemo(() => rgbToHex(props.value)); - let prevHex = rgbToHex(props.value); - - let colorInput!: HTMLInputElement; - - return ( - - colorInput.click()} - /> - { - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - }} - /> - { - prevHex = rgbToHex(props.value); - }} - onInput={(e) => { - setText(e.currentTarget.value); - - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - }} - onBlur={(e) => { - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - else { - setText(prevHex); - props.onChange(hexToRgb(text())!); - } - }} - /> - - ); + const [text, setText] = createWritableMemo(() => rgbToHex(props.value)); + let prevHex = rgbToHex(props.value); + + let colorInput!: HTMLInputElement; + + return ( + + colorInput.click()} + /> + { + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + }} + /> + { + prevHex = rgbToHex(props.value); + }} + onInput={(e) => { + setText(e.currentTarget.value); + + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + }} + onBlur={(e) => { + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + else { + setText(prevHex); + props.onChange(hexToRgb(text())!); + } + }} + /> + + ); } function LayoutSegmentConfig(props: { - segmentIndex: number; - segment: LayoutSegment; + segmentIndex: number; + segment: LayoutSegment; }) { - const { setProject, setEditorState, projectActions } = useEditorContext(); - - return ( - <> - - - setEditorState("timeline", "selection", null)} - leftIcon={} - > - Done - - - { - projectActions.deleteLayoutSegment(props.segmentIndex); - }} - leftIcon={} - > - Delete - - - }> - { - setProject( - "timeline", - "layoutSegments", - props.segmentIndex, - "mode", - v as "default" | "cameraOnly" | "hideCamera" - ); - }} - > - - - - Default - - - Camera Only - - - Hide Camera - - - - - - - - - - - - {props.segment.mode === "cameraOnly" - ? "Shows only the camera feed" - : props.segment.mode === "hideCamera" - ? "Shows only the screen recording" - : "Shows both screen and camera"} - - - - - - - > - ); + const { setProject, setEditorState, projectActions } = useEditorContext(); + + return ( + <> + + + setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + + + { + projectActions.deleteLayoutSegment(props.segmentIndex); + }} + leftIcon={} + > + Delete + + + }> + { + setProject( + "timeline", + "layoutSegments", + props.segmentIndex, + "mode", + v as "default" | "cameraOnly" | "hideCamera", + ); + }} + > + + + + Default + + + Camera Only + + + Hide Camera + + + + + + + + + + + + {props.segment.mode === "cameraOnly" + ? "Shows only the camera feed" + : props.segment.mode === "hideCamera" + ? "Shows only the screen recording" + : "Shows both screen and camera"} + + + + + + + > + ); } function rgbToHex(rgb: [number, number, number]) { - return `#${rgb - .map((c) => c.toString(16).padStart(2, "0")) - .join("") - .toUpperCase()}`; + return `#${rgb + .map((c) => c.toString(16).padStart(2, "0")) + .join("") + .toUpperCase()}`; } function hexToRgb(hex: string): [number, number, number] | null { - const match = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); - if (!match) return null; - return match.slice(1).map((c) => Number.parseInt(c, 16)) as any; + const match = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); + if (!match) return null; + return match.slice(1).map((c) => Number.parseInt(c, 16)) as any; } From 8b89c59313bb101c164c3e3ab072565e67f10d98 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 12:51:52 +0300 Subject: [PATCH 11/25] sort imports --- apps/desktop/src/routes/editor/ConfigSidebar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 3ceff323abd..8aaf4e01c85 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -43,10 +43,10 @@ import { type BackgroundSource, type CameraShape, commands, + type LayoutSegment, type StereoMode, type TimelineSegment, type ZoomSegment, - type LayoutSegment, } from "~/utils/tauri"; import IconLucideMonitor from "~icons/lucide/monitor"; import IconLucideSparkles from "~icons/lucide/sparkles"; From 5a3cd2644bbb1e5f077ae4a21b49eaf5aa942b41 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 19 Aug 2025 11:03:53 +0100 Subject: [PATCH 12/25] fix: CodeRabbit suggestions --- .../src/routes/editor/Timeline/ClipTrack.tsx | 13 +++++++--- .../routes/editor/Timeline/LayoutTrack.tsx | 5 ++++ .../src/routes/editor/Timeline/index.tsx | 5 +++- crates/project/src/configuration.rs | 4 ++- crates/rendering/src/composite_frame.rs | 25 ++++++++++++++++++- .../src/shaders/composite-video-frame.wgsl | 2 +- packages/ui-solid/src/auto-imports.d.ts | 20 +++++++-------- 7 files changed, 57 insertions(+), 17 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx index 6fd68958514..c828314baf5 100644 --- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx @@ -58,7 +58,10 @@ function WaveformCanvas(props: { ctx.moveTo(0, h); - const norm = (w: number) => 1.0 - Math.max(w + gain, -60) / -60; + const norm = (w: number) => { + const ww = Number.isFinite(w) ? w : -60; + return 1.0 - Math.max(ww + gain, -60) / -60; + }; for ( let segmentTime = props.segment.start; @@ -68,13 +71,17 @@ function WaveformCanvas(props: { const index = Math.floor(segmentTime * 10); const xTime = index / 10; - const amplitude = norm(waveform[index]) * maxAmplitude; + const currentDb = + typeof waveform[index] === "number" ? waveform[index] : -60; + const amplitude = norm(currentDb) * maxAmplitude; const x = (xTime - props.segment.start) / secsPerPixel(); const y = h - amplitude; const prevX = (xTime - 0.1 - props.segment.start) / secsPerPixel(); - const prevAmplitude = norm(waveform[index - 1]) * maxAmplitude; + const prevDb = + typeof waveform[index - 1] === "number" ? waveform[index - 1] : -60; + const prevAmplitude = norm(prevDb) * maxAmplitude; const prevY = h - prevAmplitude; const cpX1 = prevX + step / 2; diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx index 253173be97f..0ff5bb2dcbe 100644 --- a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx @@ -229,6 +229,11 @@ export function LayoutTrack(props: { index: i(), }); props.handleUpdatePlayhead(e); + } else { + setEditorState("timeline", "selection", { + type: "layout", + index: i(), + }); } props.onDragStateChanged({ type: "idle" }); setTrackState("draggingSegment", false); diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx index 06308df42aa..fa92cc338c0 100644 --- a/apps/desktop/src/routes/editor/Timeline/index.tsx +++ b/apps/desktop/src/routes/editor/Timeline/index.tsx @@ -78,7 +78,10 @@ export function Timeline() { async function handleUpdatePlayhead(e: MouseEvent) { const { left } = timelineBounds; - if (zoomSegmentDragState.type !== "moving") { + if ( + zoomSegmentDragState.type !== "moving" && + layoutSegmentDragState.type !== "moving" + ) { setEditorState( "playbackTime", Math.min( diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs index b8f9ff83880..8caa77a937d 100644 --- a/crates/project/src/configuration.rs +++ b/crates/project/src/configuration.rs @@ -456,9 +456,10 @@ pub enum ZoomMode { Manual { x: f32, y: f32 }, } -#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug)] +#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default)] #[serde(rename_all = "camelCase")] pub enum LayoutMode { + #[default] Default, CameraOnly, HideCamera, @@ -469,6 +470,7 @@ pub enum LayoutMode { pub struct LayoutSegment { pub start: f64, pub end: f64, + #[serde(default)] pub mode: LayoutMode, } diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rs index 06529d35a7b..e6481184365 100644 --- a/crates/rendering/src/composite_frame.rs +++ b/crates/rendering/src/composite_frame.rs @@ -8,7 +8,7 @@ pub struct CompositeVideoFramePipeline { pub render_pipeline: wgpu::RenderPipeline, } -#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)] +#[derive(Debug, Clone, Copy, Pod, Zeroable)] #[repr(C)] pub struct CompositeVideoFrameUniforms { pub crop_bounds: [f32; 4], @@ -29,6 +29,29 @@ pub struct CompositeVideoFrameUniforms { pub _padding: [f32; 3], } +impl Default for CompositeVideoFrameUniforms { + fn default() -> Self { + Self { + crop_bounds: Default::default(), + target_bounds: Default::default(), + output_size: Default::default(), + frame_size: Default::default(), + velocity_uv: Default::default(), + target_size: Default::default(), + rounding_px: Default::default(), + mirror_x: Default::default(), + motion_blur_amount: Default::default(), + camera_motion_blur_amount: Default::default(), + shadow: Default::default(), + shadow_size: Default::default(), + shadow_opacity: Default::default(), + shadow_blur: Default::default(), + opacity: 1.0, + _padding: Default::default(), + } + } +} + impl CompositeVideoFrameUniforms { pub fn to_buffer(self, device: &wgpu::Device) -> wgpu::Buffer { device.create_buffer_init( diff --git a/crates/rendering/src/shaders/composite-video-frame.wgsl b/crates/rendering/src/shaders/composite-video-frame.wgsl index ca4cc06f2b7..4f47f4fb1d2 100644 --- a/crates/rendering/src/shaders/composite-video-frame.wgsl +++ b/crates/rendering/src/shaders/composite-video-frame.wgsl @@ -148,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 * uniforms.opacity); + let blurred = vec4(final_color.rgb, base_color.a); 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 e246ef8fc1a..145665d9334 100644 --- a/packages/ui-solid/src/auto-imports.d.ts +++ b/packages/ui-solid/src/auto-imports.d.ts @@ -6,13 +6,13 @@ // biome-ignore lint: disable export {} declare global { - const IconCapArrows: typeof import("~icons/cap/arrows.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 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'] @@ -36,22 +36,22 @@ declare global { 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 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 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 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 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 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"] @@ -76,9 +76,9 @@ declare global { const IconLucideLayout: typeof import('~icons/lucide/layout.jsx')['default'] const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default'] const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default'] - const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"] + 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 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'] From 01e550ce101d5c81e49149c5b7881f3e98c27a4a Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 13:33:14 +0300 Subject: [PATCH 13/25] show selected zoom count --- .../src/routes/editor/ConfigSidebar.tsx | 245 ++++++++++-------- packages/ui-solid/src/auto-imports.d.ts | 172 ++++++------ 2 files changed, 219 insertions(+), 198 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 8aaf4e01c85..28466b94cf4 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -214,8 +214,15 @@ const TAB_IDS = { } as const; export function ConfigSidebar() { - const { project, setProject, editorInstance, editorState, meta } = - useEditorContext(); + const { + project, + setProject, + setEditorState, + projectActions, + editorInstance, + editorState, + meta, + } = useEditorContext(); const [state, setState] = createStore({ selectedTab: "background" as @@ -573,25 +580,69 @@ export function ConfigSidebar() { const zoomSelection = selection(); if (zoomSelection.type !== "zoom") return; - // Only show config panel for single zoom segment selection - if ( - !("index" in zoomSelection) || - typeof zoomSelection.index !== "number" - ) - return; - - const segment = - project.timeline?.zoomSegments?.[zoomSelection.index]; - if (!segment) return; - - return { selection: zoomSelection, segment }; + // Normalize single or multiple selection to indices array + const indices = + "indices" in zoomSelection + ? zoomSelection.indices + : [zoomSelection.index]; + + const segments = indices + .map((index) => ({ + index, + segment: project.timeline?.zoomSegments?.[index], + })) + .filter( + (item): item is { index: number; segment: ZoomSegment } => + item.segment !== undefined, + ); + + if (segments.length === 0) return; + return { selection: zoomSelection, segments }; })()} > {(value) => ( - + + + + + setEditorState("timeline", "selection", null) + } + leftIcon={} + > + Done + + + {value().segments.length} zoom{" "} + {value().segments.length === 1 + ? "segment" + : "segments"}{" "} + selected + + + { + projectActions.deleteZoomSegments( + value().segments.map((s) => s.index), + ); + }} + leftIcon={} + > + Delete + + + + {(item) => ( + + + + )} + + )} ( - project.background.source as { - path?: string; - } + project.background.source as { path?: string } ).path?.includes(w.id), ); // Only use wallpaper URL if it exists @@ -1315,10 +1364,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { createRoot((dispose) => createEventListenerMap(window, { - mouseup: () => { - dispose(); - resumeHistory(); - }, + mouseup: () => dispose(), mousemove: (moveEvent) => { const rawNewAngle = Math.round( @@ -1542,7 +1588,7 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) { - - - setEditorState("timeline", "selection", null)} - leftIcon={} - > - Done - - - { - projectActions.deleteZoomSegment(props.segmentIndex); - }} - leftIcon={} - > - Delete - - }> { const m = props.segment.mode; if (m === "auto") return; + return m.manual; })()} > {(mode) => { const start = createMemo((prev) => { if (projectHistory.isPaused()) return prev; + return props.segment.start; }, 0); @@ -1979,7 +2008,7 @@ function ZoomSegmentConfig(props: { const bounds = downEvent.currentTarget.getBoundingClientRect(); - createRoot((dispose) => { + createRoot((dispose) => createEventListenerMap(window, { mouseup: () => dispose(), mousemove: (moveEvent) => { @@ -2009,21 +2038,13 @@ function ZoomSegmentConfig(props: { }, ); }, - }); - }); + }), + ); }} > - + + + void; -}) { - const [text, setText] = createWritableMemo(() => rgbToHex(props.value)); - let prevHex = rgbToHex(props.value); - - let colorInput!: HTMLInputElement; - - return ( - - colorInput.click()} - /> - { - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - }} - /> - { - prevHex = rgbToHex(props.value); - }} - onInput={(e) => { - setText(e.currentTarget.value); - - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - }} - onBlur={(e) => { - const value = hexToRgb(e.target.value); - if (value) props.onChange(value); - else { - setText(prevHex); - props.onChange(hexToRgb(text())!); - } - }} - /> - - ); -} - function LayoutSegmentConfig(props: { segmentIndex: number; segment: LayoutSegment; @@ -2259,6 +2227,59 @@ function LayoutSegmentConfig(props: { ); } +function RgbInput(props: { + value: [number, number, number]; + onChange: (value: [number, number, number]) => void; +}) { + const [text, setText] = createWritableMemo(() => rgbToHex(props.value)); + let prevHex = rgbToHex(props.value); + + let colorInput!: HTMLInputElement; + + return ( + + colorInput.click()} + /> + { + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + }} + /> + { + prevHex = rgbToHex(props.value); + }} + onInput={(e) => { + setText(e.currentTarget.value); + + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + }} + onBlur={(e) => { + const value = hexToRgb(e.target.value); + if (value) props.onChange(value); + else { + setText(prevHex); + props.onChange(hexToRgb(text())!); + } + }} + /> + + ); +} + function rgbToHex(rgb: [number, number, number]) { return `#${rgb .map((c) => c.toString(16).padStart(2, "0")) diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts index 145665d9334..844138e5ca6 100644 --- a/packages/ui-solid/src/auto-imports.d.ts +++ b/packages/ui-solid/src/auto-imports.d.ts @@ -4,91 +4,91 @@ // 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 IconLucideEyeOff: typeof import('~icons/lucide/eye-off.jsx')['default'] - const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default'] - const IconLucideGift: typeof import('~icons/lucide/gift.jsx')['default'] - const IconLucideHardDrive: typeof import('~icons/lucide/hard-drive.jsx')['default'] - const IconLucideLayout: typeof import('~icons/lucide/layout.jsx')['default'] - const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default'] - const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default'] - const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default'] - 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 IconLucideEyeOff: typeof import("~icons/lucide/eye-off.jsx")["default"]; + const IconLucideFolder: typeof import("~icons/lucide/folder.jsx")["default"]; + const IconLucideGift: typeof import("~icons/lucide/gift.jsx")["default"]; + const IconLucideHardDrive: typeof import("~icons/lucide/hard-drive.jsx")["default"]; + const IconLucideLayout: typeof import("~icons/lucide/layout.jsx")["default"]; + const IconLucideLoaderCircle: typeof import("~icons/lucide/loader-circle.jsx")["default"]; + const IconLucideMessageSquarePlus: typeof import("~icons/lucide/message-square-plus.jsx")["default"]; + const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"]; + 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 8872dca8a148867f70648f1f7a8cc9b9e1ce3c60 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 13:35:26 +0300 Subject: [PATCH 14/25] formatting --- .../src/routes/editor/Timeline/ClipTrack.tsx | 1254 ++++++++--------- 1 file changed, 627 insertions(+), 627 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx index c828314baf5..ee132163d0c 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,640 +21,640 @@ 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) => { - const ww = Number.isFinite(w) ? w : -60; - return 1.0 - Math.max(ww + 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 currentDb = - typeof waveform[index] === "number" ? waveform[index] : -60; - const amplitude = norm(currentDb) * maxAmplitude; - - const x = (xTime - props.segment.start) / secsPerPixel(); - const y = h - amplitude; - - const prevX = (xTime - 0.1 - props.segment.start) / secsPerPixel(); - const prevDb = - typeof waveform[index - 1] === "number" ? waveform[index - 1] : -60; - const prevAmplitude = norm(prevDb) * 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) => { + const ww = Number.isFinite(w) ? w : -60; + return 1.0 - Math.max(ww + 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 currentDb = + typeof waveform[index] === "number" ? waveform[index] : -60; + const amplitude = norm(currentDb) * maxAmplitude; + + const x = (xTime - props.segment.start) / secsPerPixel(); + const y = h - amplitude; + + const prevX = (xTime - 0.1 - props.segment.start) / secsPerPixel(); + const prevDb = + typeof waveform[index - 1] === "number" ? waveform[index - 1] : -60; + const prevAmplitude = norm(prevDb) * 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(); - - // If there's only one segment, don't open the clip config panel - // since there's nothing to configure - just let the normal click behavior happen - const hasOnlyOneSegment = segments().length === 1; - - if (hasOnlyOneSegment) { - // Clear any existing selection (zoom, layout, etc.) when clicking on a clip - // This ensures the sidebar updates properly - setEditorState("timeline", "selection", null); - } else { - // When there are multiple segments, show the clip configuration - setEditorState("timeline", "selection", { - type: "clip", - index: i(), - }); - } - props.handleUpdatePlayhead(e); - }); - }); - } - }} - > - - - - - { - 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) { + // Clear any existing selection (zoom, layout, etc.) when clicking on a clip + // This ensures the sidebar updates properly + setEditorState("timeline", "selection", null); + } else { + // When there are multiple segments, show the clip configuration + setEditorState("timeline", "selection", { + type: "clip", + index: i(), + }); + } + props.handleUpdatePlayhead(e); + }); + }); + } + }} + > + + + + + { + 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 ( - props.onClick?.()} - > - {props.value === 0 ? ( - - ) : ( - <>{formatTime(props.value)}s> - )} - - ); + const formatTime = (t: number) => + t < 1 ? Math.round(t * 10) / 10 : Math.round(t); + + return ( + props.onClick?.()} + > + {props.value === 0 ? ( + + ) : ( + <>{formatTime(props.value)}s> + )} + + ); } 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); } From 9aa5747eca5314c55fc47ea4c5bf44ddf6d65dbc Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 19 Aug 2025 12:02:19 +0100 Subject: [PATCH 15/25] feat: Improved transition between camera and screen --- crates/rendering/src/layout.rs | 70 ++++++++-- crates/rendering/src/lib.rs | 21 +-- packages/ui-solid/src/auto-imports.d.ts | 172 ++++++++++++------------ 3 files changed, 160 insertions(+), 103 deletions(-) diff --git a/crates/rendering/src/layout.rs b/crates/rendering/src/layout.rs index 3f2f59cc801..03e6f1bfd59 100644 --- a/crates/rendering/src/layout.rs +++ b/crates/rendering/src/layout.rs @@ -57,6 +57,9 @@ pub struct InterpolatedLayout { pub transition_progress: f64, pub from_mode: LayoutMode, pub to_mode: LayoutMode, + pub screen_blur: f64, + pub camera_only_zoom: f64, + pub camera_only_blur: f64, } impl InterpolatedLayout { @@ -148,6 +151,48 @@ impl InterpolatedLayout { ); let camera_scale = Self::lerp(start_camera_scale, end_camera_scale, transition_progress); + let screen_blur = if matches!(current_mode, LayoutMode::CameraOnly) + || matches!(next_mode, LayoutMode::CameraOnly) + { + if matches!(current_mode, LayoutMode::CameraOnly) + && !matches!(next_mode, LayoutMode::CameraOnly) + { + Self::lerp(1.0, 0.0, transition_progress) + } else if !matches!(current_mode, LayoutMode::CameraOnly) + && matches!(next_mode, LayoutMode::CameraOnly) + { + transition_progress + } else { + 0.0 + } + } else { + 0.0 + }; + + let camera_only_zoom = if matches!(next_mode, LayoutMode::CameraOnly) + && !matches!(current_mode, LayoutMode::CameraOnly) + { + Self::lerp(1.1, 1.0, transition_progress) + } else if matches!(current_mode, LayoutMode::CameraOnly) + && !matches!(next_mode, LayoutMode::CameraOnly) + { + Self::lerp(1.0, 1.1, transition_progress) + } else { + 1.0 + }; + + let camera_only_blur = if matches!(next_mode, LayoutMode::CameraOnly) + && !matches!(current_mode, LayoutMode::CameraOnly) + { + Self::lerp(1.0, 0.0, transition_progress) + } else if matches!(current_mode, LayoutMode::CameraOnly) + && !matches!(next_mode, LayoutMode::CameraOnly) + { + transition_progress + } else { + 0.0 + }; + InterpolatedLayout { camera_opacity, screen_opacity, @@ -160,13 +205,16 @@ impl InterpolatedLayout { transition_progress, from_mode: current_mode, to_mode: next_mode, + screen_blur, + camera_only_zoom, + camera_only_blur, } } fn get_layout_values(mode: &LayoutMode) -> (f64, f64, f64) { match mode { LayoutMode::Default => (1.0, 1.0, 1.0), - LayoutMode::CameraOnly => (1.0, 0.0, 1.0), + LayoutMode::CameraOnly => (1.0, 1.0, 1.0), LayoutMode::HideCamera => (0.0, 1.0, 1.0), } } @@ -180,7 +228,7 @@ impl InterpolatedLayout { } pub fn should_render_screen(&self) -> bool { - self.screen_opacity > 0.01 + true } pub fn is_transitioning_camera_only(&self) -> bool { @@ -207,16 +255,20 @@ impl InterpolatedLayout { } pub fn regular_camera_transition_opacity(&self) -> f64 { - if matches!(self.from_mode, LayoutMode::CameraOnly) + if matches!(self.to_mode, LayoutMode::CameraOnly) + && !matches!(self.from_mode, LayoutMode::CameraOnly) + { + let fast_fade = (1.0 - self.transition_progress * 1.5).max(0.0); + fast_fade * self.camera_opacity + } else if matches!(self.from_mode, LayoutMode::CameraOnly) + && !matches!(self.to_mode, LayoutMode::CameraOnly) + { + let fast_fade = (self.transition_progress * 1.5).min(1.0); + fast_fade * self.camera_opacity + } else if matches!(self.from_mode, LayoutMode::CameraOnly) && matches!(self.to_mode, LayoutMode::CameraOnly) { 0.0 - } else if matches!(self.from_mode, LayoutMode::CameraOnly) { - let adjusted_progress = (self.transition_progress * 1.5).min(1.0); - adjusted_progress * self.camera_opacity - } else if matches!(self.to_mode, LayoutMode::CameraOnly) { - let adjusted_progress = ((1.0 - self.transition_progress) * 1.43).min(1.0); - adjusted_progress * self.camera_opacity } else { self.camera_opacity } diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs index f424133fc94..2e539a319dc 100644 --- a/crates/rendering/src/lib.rs +++ b/crates/rendering/src/lib.rs @@ -617,7 +617,7 @@ impl ProjectUniforms { rounding_px: (project.background.rounding / 100.0 * 0.5 * min_target_axis) as f32, mirror_x: 0.0, velocity_uv: velocity, - motion_blur_amount, + motion_blur_amount: (motion_blur_amount + layout.screen_blur as f32 * 0.8).min(1.0), camera_motion_blur_amount: 0.0, shadow: project.background.shadow, shadow_size: project @@ -759,10 +759,13 @@ impl ProjectUniforms { 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 zoom_factor = layout.camera_only_zoom as f32; + let size = [output_size[0] * zoom_factor, output_size[1] * zoom_factor]; - let position = [0.0, 0.0]; + let position = [ + (output_size[0] - size[0]) / 2.0, + (output_size[1] - size[1]) / 2.0, + ]; let target_bounds = [ position[0], @@ -780,7 +783,7 @@ impl ProjectUniforms { 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 + // 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] @@ -799,7 +802,7 @@ impl ProjectUniforms { 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, + camera_motion_blur_amount: layout.camera_only_blur as f32 * 0.5, shadow: 0.0, shadow_size: 0.0, shadow_opacity: 0.0, @@ -1021,9 +1024,11 @@ impl RendererLayers { let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load); self.camera_only.render(&mut pass); } - + // Also render regular camera overlay during transitions when its opacity > 0 - if uniforms.layout.should_render_camera() && uniforms.layout.regular_camera_transition_opacity() > 0.01 { + if uniforms.layout.should_render_camera() + && uniforms.layout.regular_camera_transition_opacity() > 0.01 + { let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load); self.camera.render(&mut pass); } diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts index 844138e5ca6..5756dd2b0a1 100644 --- a/packages/ui-solid/src/auto-imports.d.ts +++ b/packages/ui-solid/src/auto-imports.d.ts @@ -4,91 +4,91 @@ // 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 IconLucideEyeOff: typeof import("~icons/lucide/eye-off.jsx")["default"]; - const IconLucideFolder: typeof import("~icons/lucide/folder.jsx")["default"]; - const IconLucideGift: typeof import("~icons/lucide/gift.jsx")["default"]; - const IconLucideHardDrive: typeof import("~icons/lucide/hard-drive.jsx")["default"]; - const IconLucideLayout: typeof import("~icons/lucide/layout.jsx")["default"]; - const IconLucideLoaderCircle: typeof import("~icons/lucide/loader-circle.jsx")["default"]; - const IconLucideMessageSquarePlus: typeof import("~icons/lucide/message-square-plus.jsx")["default"]; - const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"]; - 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 IconLucideEyeOff: typeof import("~icons/lucide/eye-off.jsx")["default"] + const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default'] + const IconLucideGift: typeof import('~icons/lucide/gift.jsx')['default'] + const IconLucideHardDrive: typeof import('~icons/lucide/hard-drive.jsx')['default'] + const IconLucideLayout: typeof import('~icons/lucide/layout.jsx')['default'] + const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default'] + const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default'] + const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default'] + 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 47766999355880de17c59dabadf399936712e2d8 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 14:06:52 +0300 Subject: [PATCH 16/25] cleanup - we dont need deleteZoomSegment anymore --- .../src/routes/editor/Timeline/index.tsx | 6 - apps/desktop/src/routes/editor/context.ts | 13 -- packages/ui-solid/src/auto-imports.d.ts | 172 +++++++++--------- 3 files changed, 86 insertions(+), 105 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx index fa92cc338c0..82b12b06256 100644 --- a/apps/desktop/src/routes/editor/Timeline/index.tsx +++ b/apps/desktop/src/routes/editor/Timeline/index.tsx @@ -104,12 +104,6 @@ export function Timeline() { if ("indices" in selection && Array.isArray(selection.indices)) { // Use bulk deletion for better performance projectActions.deleteZoomSegments(selection.indices); - } else if ( - "index" in selection && - typeof selection.index === "number" - ) { - // Handle single zoom segment deletion - projectActions.deleteZoomSegment(selection.index); } } else if (selection.type === "clip") { projectActions.deleteClipSegment(selection.index); diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts index 3e9ab861efe..fab7f68c445 100644 --- a/apps/desktop/src/routes/editor/context.ts +++ b/apps/desktop/src/routes/editor/context.ts @@ -128,19 +128,6 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( setEditorState("timeline", "selection", null); }); }, - deleteZoomSegment: (segmentIndex: number) => { - batch(() => { - setProject( - "timeline", - "zoomSegments", - produce((s) => { - if (!s) return; - s.splice(segmentIndex, 1); - }), - ); - setEditorState("timeline", "selection", null); - }); - }, deleteZoomSegments: (segmentIndices: number[]) => { batch(() => { setProject( diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts index 5756dd2b0a1..844138e5ca6 100644 --- a/packages/ui-solid/src/auto-imports.d.ts +++ b/packages/ui-solid/src/auto-imports.d.ts @@ -4,91 +4,91 @@ // 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 IconLucideEyeOff: typeof import("~icons/lucide/eye-off.jsx")["default"] - const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default'] - const IconLucideGift: typeof import('~icons/lucide/gift.jsx')['default'] - const IconLucideHardDrive: typeof import('~icons/lucide/hard-drive.jsx')['default'] - const IconLucideLayout: typeof import('~icons/lucide/layout.jsx')['default'] - const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default'] - const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default'] - const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default'] - 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 IconLucideEyeOff: typeof import("~icons/lucide/eye-off.jsx")["default"]; + const IconLucideFolder: typeof import("~icons/lucide/folder.jsx")["default"]; + const IconLucideGift: typeof import("~icons/lucide/gift.jsx")["default"]; + const IconLucideHardDrive: typeof import("~icons/lucide/hard-drive.jsx")["default"]; + const IconLucideLayout: typeof import("~icons/lucide/layout.jsx")["default"]; + const IconLucideLoaderCircle: typeof import("~icons/lucide/loader-circle.jsx")["default"]; + const IconLucideMessageSquarePlus: typeof import("~icons/lucide/message-square-plus.jsx")["default"]; + const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"]; + 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 4a9fdd89b6b82ea4341a33cb48a6b72556715d38 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 14:34:45 +0300 Subject: [PATCH 17/25] get rid of un-needed type --- apps/desktop/src/routes/editor/Timeline/index.tsx | 6 +----- apps/desktop/src/routes/editor/context.ts | 1 - 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx index 82b12b06256..7c02b59c7d4 100644 --- a/apps/desktop/src/routes/editor/Timeline/index.tsx +++ b/apps/desktop/src/routes/editor/Timeline/index.tsx @@ -100,11 +100,7 @@ export function Timeline() { if (!selection) return; if (selection.type === "zoom") { - // Handle multiple zoom segment deletion - if ("indices" in selection && Array.isArray(selection.indices)) { - // Use bulk deletion for better performance - projectActions.deleteZoomSegments(selection.indices); - } + projectActions.deleteZoomSegments(selection.indices); } else if (selection.type === "clip") { projectActions.deleteClipSegment(selection.index); } else if (selection.type === "layout") { diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts index fab7f68c445..2293a264cd3 100644 --- a/apps/desktop/src/routes/editor/context.ts +++ b/apps/desktop/src/routes/editor/context.ts @@ -254,7 +254,6 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( interactMode: "seek" as "seek" | "split", selection: null as | null - | { type: "zoom"; index: number } | { type: "zoom"; indices: number[] } | { type: "clip"; index: number } | { type: "layout"; index: number }, From 6cec450ed30b460606b03b9d1c9182029ea68c40 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 14:42:11 +0300 Subject: [PATCH 18/25] cleanup ts --- .../src/routes/editor/ConfigSidebar.tsx | 8 +-- .../src/routes/editor/Timeline/ZoomTrack.tsx | 55 +++++-------------- 2 files changed, 15 insertions(+), 48 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 28466b94cf4..0e1b3c99fdd 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -580,13 +580,7 @@ export function ConfigSidebar() { const zoomSelection = selection(); if (zoomSelection.type !== "zoom") return; - // Normalize single or multiple selection to indices array - const indices = - "indices" in zoomSelection - ? zoomSelection.indices - : [zoomSelection.index]; - - const segments = indices + const segments = zoomSelection.indices .map((index) => ({ index, segment: project.timeline?.zoomSegments?.[index], diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx index 6e228dd1fa4..c4ece20b248 100644 --- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx @@ -217,44 +217,19 @@ export function ZoomTrack(props: { if (e.ctrlKey || e.metaKey) { if (currentSelection?.type === "zoom") { // If we already have zoom selections - if ( - "indices" in currentSelection && - Array.isArray(currentSelection.indices) - ) { - // Toggle this segment in the selection - const newIndices = currentSelection.indices.includes( - segmentIndex, - ) - ? currentSelection.indices.filter( - (idx) => idx !== segmentIndex, - ) - : [...currentSelection.indices, segmentIndex]; - - setEditorState( - "timeline", - "selection", - newIndices.length > 0 - ? { type: "zoom", indices: newIndices } - : null, - ); - } else if ( - "index" in currentSelection && - typeof currentSelection.index === "number" - ) { - // Convert single selection to multi-selection - const newIndices = - currentSelection.index === segmentIndex - ? [] // Deselect if clicking the same segment - : [currentSelection.index, segmentIndex]; - - setEditorState( - "timeline", - "selection", - newIndices.length > 0 - ? { type: "zoom", indices: newIndices } - : null, - ); - } + // Toggle this segment in the selection + const newIndices = currentSelection.indices.includes( + segmentIndex, + ) + ? currentSelection.indices.filter( + (idx) => idx !== segmentIndex, + ) + : [...currentSelection.indices, segmentIndex]; + + setEditorState("timeline", "selection", { + type: "zoom", + indices: newIndices, + }); } else { // Start new multi-selection setEditorState("timeline", "selection", { @@ -263,13 +238,11 @@ export function ZoomTrack(props: { }); } } else { - // Regular single selection setEditorState("timeline", "selection", { type: "zoom", - index: segmentIndex, + indices: [segmentIndex], }); } - props.handleUpdatePlayhead(e); } props.onDragStateChanged({ type: "idle" }); From b4054b5e76b2c04d8da95ae9dbba6a8a583609ba Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 14:46:20 +0300 Subject: [PATCH 19/25] apply coderabbit feedback --- apps/desktop/src/routes/editor/context.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts index 2293a264cd3..7a2c10dac7f 100644 --- a/apps/desktop/src/routes/editor/context.ts +++ b/apps/desktop/src/routes/editor/context.ts @@ -135,11 +135,12 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( "zoomSegments", produce((s) => { if (!s) return; - // Sort indices in descending order to avoid index shifting issues - const sortedIndices = [...segmentIndices].sort((a, b) => b - a); - sortedIndices.forEach((index) => { - s.splice(index, 1); - }); + // Normalize: numbers only, in-bounds, deduped, then descending + const sorted = [...new Set(segmentIndices)] + .filter((i) => Number.isInteger(i) && i >= 0 && i < s.length) + .sort((a, b) => b - a); + if (sorted.length === 0) return; + for (const i of sorted) s.splice(i, 1); }), ); setEditorState("timeline", "selection", null); From 02caf8367b5ac3fcd1cece429a538c0419893da8 Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 15:34:38 +0300 Subject: [PATCH 20/25] tweaks, improve hover color of shadow settings, and more --- .../src/routes/editor/ConfigSidebar.tsx | 15 ++++++++++-- .../src/routes/editor/ShadowSettings.tsx | 2 +- .../src/routes/editor/Timeline/ZoomTrack.tsx | 23 +++++++++++-------- apps/desktop/src/styles/theme.css | 1 + 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 0e1b3c99fdd..5b951d33eec 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -300,6 +300,9 @@ export function ConfigSidebar() { @@ -573,7 +576,12 @@ export function ConfigSidebar() { {(selection) => ( - + { @@ -1796,7 +1804,10 @@ function ZoomSegmentConfig(props: { return ( <> - }> + } + > diff --git a/apps/desktop/src/routes/editor/ShadowSettings.tsx b/apps/desktop/src/routes/editor/ShadowSettings.tsx index cbf0dcb85cc..cd67d95ae94 100644 --- a/apps/desktop/src/routes/editor/ShadowSettings.tsx +++ b/apps/desktop/src/routes/editor/ShadowSettings.tsx @@ -38,7 +38,7 @@ const ShadowSettings = (props: Props) => { Advanced shadow settings idx !== segmentIndex, - ) - : [...currentSelection.indices, segmentIndex]; + // Normalize to indices[] from either indices[] or legacy index + const baseIndices = + "indices" in currentSelection && + Array.isArray(currentSelection.indices) + ? currentSelection.indices + : "index" in currentSelection && + typeof currentSelection.index === "number" + ? [currentSelection.index] + : []; + + const exists = baseIndices.includes(segmentIndex); + const newIndices = exists + ? baseIndices.filter((idx) => idx !== segmentIndex) + : [...baseIndices, segmentIndex]; setEditorState("timeline", "selection", { type: "zoom", diff --git a/apps/desktop/src/styles/theme.css b/apps/desktop/src/styles/theme.css index ce6f5ee6d95..72a63df900b 100644 --- a/apps/desktop/src/styles/theme.css +++ b/apps/desktop/src/styles/theme.css @@ -151,6 +151,7 @@ .custom-scroll { margin-right: 3px; /* Add margin to create space between scrollbar and window edge */ overflow-y: scroll; + margin-top: var(--margin-top-scroll); } .custom-scroll::-webkit-scrollbar { From 4764fb0163819b7e43c5896b0fe48d9c3f3ccd6d Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 15:43:02 +0300 Subject: [PATCH 21/25] more code rabbit recommendations --- apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx index 15e43492c72..d38b5f69967 100644 --- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx @@ -49,6 +49,7 @@ export function ZoomTrack(props: { const segments = project.timeline?.zoomSegments; if (!segments || segments.length === 0) { setHoveringSegment(false); + setHoveredTime(undefined); } }); @@ -85,7 +86,7 @@ export function ZoomTrack(props: { return; } - const bounds = e.target.getBoundingClientRect()!; + const bounds = e.currentTarget.getBoundingClientRect()!; let time = (e.clientX - bounds.left) * secsPerPixel() + From 05fe3222a3509b3b8d84deff67cf26cfff21411d Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Tue, 19 Aug 2025 15:44:21 +0300 Subject: [PATCH 22/25] classname typo --- apps/desktop/src/routes/editor/ConfigSidebar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 5b951d33eec..bd30ab4190e 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -1590,7 +1590,7 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) { Date: Wed, 20 Aug 2025 11:09:23 +0300 Subject: [PATCH 23/25] update previews and use Index instead of for to avoid re-rendering --- .../src/routes/editor/ConfigSidebar.tsx | 171 ++++++++++++++++-- 1 file changed, 159 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index bd30ab4190e..070e5b25a4c 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -24,6 +24,7 @@ import { createRoot, createSignal, For, + Index, on, onMount, Show, @@ -598,7 +599,10 @@ export function ConfigSidebar() { item.segment !== undefined, ); - if (segments.length === 0) return; + if (segments.length === 0) { + setEditorState("timeline", "selection", null); + return; + } return { selection: zoomSelection, segments }; })()} > @@ -634,16 +638,34 @@ export function ConfigSidebar() { Delete - - {(item) => ( - - + + + {(item, index) => ( + + + + )} + - )} - + } + > + + {(item) => ( + + + + )} + + )} @@ -1781,6 +1803,125 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) { ); } +function ZoomSegmentPreview(props: { + segmentIndex: number; + segment: ZoomSegment; +}) { + const { project, editorInstance } = useEditorContext(); + + const start = createMemo(() => props.segment.start); + + const segmentIndex = createMemo(() => { + const st = start(); + const i = project.timeline?.segments.findIndex( + (s) => s.start <= st && s.end > st, + ); + if (i === undefined || i === -1) return 0; + return i; + }); + + const relativeTime = createMemo(() => { + const st = start(); + const segment = project.timeline?.segments[segmentIndex()]; + if (!segment) return 0; + return Math.max(0, st - segment.start); + }); + + const video = document.createElement("video"); + createEffect(() => { + const path = convertFileSrc( + `${editorInstance.path}/content/segments/segment-${segmentIndex()}/display.mp4`, + ); + video.src = path; + video.preload = "auto"; + video.load(); + }); + + createEffect(() => { + const t = relativeTime(); + if (t === undefined) return; + + if (video.readyState >= 2) { + video.currentTime = t; + } else { + const handleCanPlay = () => { + video.currentTime = t; + video.removeEventListener("canplay", handleCanPlay); + }; + video.addEventListener("canplay", handleCanPlay); + } + }); + + const render = () => { + if (!canvasRef || video.readyState < 2) return; + + const ctx = canvasRef.getContext("2d"); + if (!ctx) return; + + ctx.imageSmoothingEnabled = false; + ctx.clearRect(0, 0, canvasRef.width, canvasRef.height); + + const raw = editorInstance.recordings.segments[0].display; + const croppedPosition = project.background.crop?.position || { x: 0, y: 0 }; + const croppedSize = project.background.crop?.size || { + x: raw.width, + y: raw.height, + }; + + ctx.drawImage( + video, + croppedPosition.x, + croppedPosition.y, + croppedSize.x, + croppedSize.y, + 0, + 0, + canvasRef.width, + canvasRef.height, + ); + }; + + const [loaded, setLoaded] = createSignal(false); + video.onloadeddata = () => { + setLoaded(true); + render(); + }; + video.onseeked = render; + video.onerror = () => { + setTimeout(() => video.load(), 100); + }; + + let canvasRef!: HTMLCanvasElement; + + return ( + <> + + + Zoom {props.segmentIndex + 1} + + + + + + Loading... + + + + + + + {props.segment.amount.toFixed(1)}x + + > + ); +} + function ZoomSegmentConfig(props: { segmentIndex: number; segment: ZoomSegment; @@ -1792,7 +1933,6 @@ function ZoomSegmentConfig(props: { editorInstance, setEditorState, projectHistory, - projectActions, } = useEditorContext(); const states = { @@ -1902,6 +2042,7 @@ function ZoomSegmentConfig(props: { }/content/segments/segment-${segmentIndex()}/display.mp4`, ); video.src = path; + video.preload = "auto"; // Force reload if video fails to load video.load(); }); @@ -2047,7 +2188,13 @@ function ZoomSegmentConfig(props: { ); }} > - + From 06adbf5d54151a660d81b6bbb0b2963449417dcb Mon Sep 17 00:00:00 2001 From: ameer2468 <33054370+ameer2468@users.noreply.github.com> Date: Wed, 20 Aug 2025 11:34:49 +0300 Subject: [PATCH 24/25] single color --- .../src/routes/editor/Timeline/LayoutTrack.tsx | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx index 0ff5bb2dcbe..02d796fb825 100644 --- a/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/LayoutTrack.tsx @@ -281,22 +281,11 @@ export function LayoutTrack(props: { return segmentIndex === selection.index; }); - const segmentColor = () => { - switch (segment.mode) { - case "cameraOnly": - return "from-[#E3701B] via-[#FF9D57] to-[#E3701B]"; - case "hideCamera": - return "from-[#EF4444] via-[#F87171] to-[#EF4444]"; - default: - return "from-[#069962] via-[#2FD49C] to-[#069962]"; - } - }; - return ( Date: Wed, 20 Aug 2025 11:48:16 +0300 Subject: [PATCH 25/25] coderabbit feedback, although they are reactive --- apps/desktop/src/routes/editor/ConfigSidebar.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 070e5b25a4c..13c7cbac079 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -2191,8 +2191,8 @@ function ZoomSegmentConfig(props: {
• Default: Shows both screen and camera
• Camera Only: Shows only the camera feed
• Hide Camera: Shows only the screen recording
+ + +
+ • Default: Shows both screen and camera +
+ • Camera Only: Shows only the camera feed +
+ • Hide Camera: Shows only the screen recording +
- + -
- • Default: Shows both screen and camera -
- • Camera Only: Shows only the camera feed -
- • Hide Camera: Shows only the screen recording -
+
+ Loading... +
{props.segment.amount.toFixed(1)}x