Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(preview): wire zoom, annotation and speed regions plus the cursor pipeline into the preview
Etienne Lescot36637b85e4b7
diff --git a/.gitignore b/.gitignoreindex 33cf7a9d2..8ec9849f1 100644--- a/.gitignore+++ b/.gitignore@@ -40,6 +40,7 @@ xcuserdata/release/***.kiro/.claude/+.worktrees/# npx electron-builder --mac --win# Playwright@@ -67,3 +68,5 @@ result-*# Auto-caption model + ORT wasm — regenerated at build by scripts/fetch-caption-model.mjs/caption-assets/+opencode.json+opencode.jsondiff --git a/docs/architecture/ai-edition-data-flow.md b/docs/architecture/ai-edition-data-flow.mdnew file mode 100644index 000000000..cb7656d27--- /dev/null+++ b/docs/architecture/ai-edition-data-flow.md@@ -0,0 +1,80 @@+# AI-Edition — Data Flow++Companion to [`ai-edition-roadmap.md`](ai-edition-roadmap.md) (status/phasing) and+[`ai-edition-collision-analysis.md`](ai-edition-collision-analysis.md) (why decisions were+made). This doc answers a narrower question: **what talks to what, and who owns the truth**,+transcribed from a whiteboard sketch and cross-checked against the current code+(`feat/ai-edition`, 2026-07-02).++## 1. Diagram++```mermaid+flowchart TD+ User(("User"))+ Chat["Chat UI\n(LeftPanel.tsx)"]+ LLM["LLM Provider\n(llm-call.ts,\nprovider-registry.ts)"]+ DSL[["DSL File\n= AxcutDocument\n(schema/index.ts)\n— SSOT —"]]+ Store["projectStore.ts\n(Zustand, in-memory)"]+ Disk[(".openscreen v3 file\non disk\n(document-service.ts)")]++ MT1["Media Transcript\n(source A)"]+ MT2["Media Transcript\n(source B)"]++ Timeline["Timeline\n(TimelinePane.tsx)"]+ VPreview["Virtual Preview\n(VirtualPreview.tsx /\nPreviewCanvas.tsx)"]+ VTranscript["Virtual Transcript\n(TranscriptEditor.tsx)"]++ User <--> Chat+ Chat <--> LLM+ LLM -- "tool calls\n(agent-tools.ts:\naddSkip, setClipRange,\nreplaceTimeline...)" --> DSL++ MT1 -- "ingest on\ntranscribe/import" --> DSL+ MT2 -- "ingest on\ntranscribe/import" --> DSL++ User -- "direct edits" --> Timeline+ User -- "direct edits" --> VTranscript++ DSL <==> Store+ Store <==> Disk++ DSL <-.->|"read/write\n(store actions)"| Timeline+ DSL <-.->|"read/write\n(store actions)"| VPreview+ DSL <-.->|"read/write\n(store actions)"| VTranscript+```++## 2. What each node is, in code++| Sketch label | Code | Notes |+|---|---|---|+| **DSL File / SSOT** | `AxcutDocument` — Zod schema in `src/lib/ai-edition/schema/` | `project · assets[] · transcripts[] · timeline{clips,gaps,skip/mute/speed/captionRanges} · annotations[] · zoomRanges[] · legacyEditor · agent · preview · export · history`. Every pane below is a **view over this one document** — nothing keeps its own parallel state. |+| **DSL (persistence)** | `store/projectStore.ts` (Zustand, renderer) + `electron/ai-edition/document-service.ts` (main process) | Renderer holds the live document in a Zustand store; main process persists it to `userData/projects/<id>.axcut`. Legacy `.openscreen` v2 files migrate to v3 on first open (`lib/ai-edition/document/migrate*.ts`). |+| **Chat** | `src/components/ai-edition/LeftPanel.tsx` | Sends user messages to the LLM via IPC into `electron/ai-edition/chat-service.ts`. |+| **LLM** | `electron/ai-edition/llm-call.ts` + `provider-registry.ts` | Fetch-based calls, OpenAI-compatible + Anthropic today (8 providers registered; OAuth device-flow/PAT still stubbed — roadmap P2.2). |+| **Edits (LLM → DSL)** | `electron/ai-edition/agent-tools.ts` + tool-loop in `chat-service.ts` | The model doesn't free-write the document; it calls a fixed tool schema (`getCurrentDocument`, `getTranscript`, `addSkip`, `setSkipRange`, `setClipRange`, `replaceTimeline`, …). Each tool call is validated, applied to the store, and checkpointed first so the user can undo a whole batch (roadmap P1.1–P1.8). |+| **Media Transcript(s)** | Local Whisper (`@xenova/transformers`, in-browser, not gated by `AI_FEATURES_ENABLED`) | Produces `transcripts[]` entries keyed to an asset. The two boxes in the sketch are two independent transcript sources (e.g. two recorded assets / mic + system audio) that both land in the same document — there's no per-source document fork. |+| **Timeline** | `src/components/ai-edition/TimelinePane.tsx` | Renders `timeline.clips` + lanes (skip/speed/annotation/zoom ranges). Read/write against the store; drag, resize, reorder all dispatch store actions that mutate the DSL document (see roadmap §5 P0 table for the viewport/zoom/pan mechanics). |+| **Virtual Preview** | `VirtualPreview.tsx` / `PreviewCanvas.tsx` | Renders the composited frame (wallpaper, blur, webcam PiP, cursor overlay, zoom, annotations) by reading the document at the current playhead time — it never owns edit state, only projects it. |+| **Virtual Transcript** | `TranscriptEditor.tsx` | Editable view of `transcripts[]`; user edits here write back into the DSL document (word-level edits, not a separate buffer). |++## 3. Read this diagram as two loops++1. **Human loop** — User edits the Timeline / Transcript directly, or talks to the Chat panel,+ which drives the LLM, which edits the DSL document through the tool schema (never raw JSON+ patches). Both paths converge on the same document.+2. **Machine loop** — Media assets get transcribed locally (Whisper) and merged into the+ document's `transcripts[]`. Preview and Timeline are pure projections of the document at a+ given time/zoom — there is no independent "preview state" to desync from the DSL.++The one-document-many-views design is why the sketch draws `DSL File` as the hub: every arrow+either writes into it (Chat/LLM tool calls, direct user edits, transcript ingestion) or reads a+projection out of it (Timeline, Virtual Preview, Virtual Transcript). Persistence+(`projectStore.ts` ↔ `.openscreen` file) is a straight serialize/deserialize of the same shape,+not a separate model.++## 4. Open gaps vs. this flow (see roadmap §5 for detail)++- Chat history is still in-memory per session (`chat-service.ts`), not persisted to SQLite —+ roadmap P2.1.+- LLM auth is API-key only; OAuth device-flow/PAT is stubbed — roadmap P2.2.+- Streaming responses (SSE-style token rendering in Chat) not implemented — roadmap P2.4.+- Tool-call permission gate (confirm before a write tool runs) not implemented — roadmap P2.5.diff --git a/docs/architecture/ai-edition-roadmap.md b/docs/architecture/ai-edition-roadmap.mdindex 9f90145fe..c55d7def7 100644--- a/docs/architecture/ai-edition-roadmap.md+++ b/docs/architecture/ai-edition-roadmap.md@@ -9,6 +9,8 @@ Last updated: 2026-07-02 · Branch: `feat/ai-edition`> rationale), [`openscreen-inventory.md`](openscreen-inventory.md) and> [`axcut-inventory.md`](axcut-inventory.md) (source catalogs). The canonical UI target is> [`design/openscreen-editor.html`](../../design/openscreen-editor.html) + `design/DESIGN.md`.+> For a diagram of who reads/writes the DSL document, see+> [`ai-edition-data-flow.md`](ai-edition-data-flow.md).---diff --git a/docs/cursor-feature-inventory.md b/docs/cursor-feature-inventory.mdnew file mode 100644index 000000000..cf64ad705--- /dev/null+++ b/docs/cursor-feature-inventory.md@@ -0,0 +1,124 @@+# Cursor feature — exhaustive inventory++Port of the legacy (`main`) cursor pipeline into the AI-edition editor shell+(`port/cursor-from-main`). Reference: `docs/architecture/openscreen-inventory.md`+§ Cursor; rendered pipeline at `src/components/ai-edition/CursorPreviewLayer.tsx`.++## 1. Capture (native side)++| Surface | Platform | What it does |+| --- | --- | --- |+| `electron/native/screencapturekit/Sources/OpenScreenMacOSCursorHelper/main.swift` | macOS | ScreenCaptureKit cursor helper — streams cursor bitmaps + interaction events alongside the screen capture. |+| `electron/native/wgc-capture/src/cursor-sampler.cpp` | Windows | WGC cursor sampler — captures the system cursor bitmap, hotspot, and type from a desktop duplication session. |+| `electron/native-bridge/cursor/recording/macNativeCursorRecordingSession.ts` | macOS | Wraps the SCK helper for the main process. |+| `electron/native-bridge/cursor/recording/windowsNativeRecordingSession.ts` + `.types.ts` | Windows | Wraps the WGC sampler; types describe cursor samples + assets. |+| `electron/native-bridge/cursor/recording/telemetryRecordingSession.ts` | All | Fallback: cursor samples come from the recorder's telemetry stream (no bitmap). |+| `electron/native-bridge/cursor/recording/session.ts` | All | Common session interface (start / stop / on-sample). |+| `electron/native-bridge/cursor/recording/factory.ts` | All | Picks the right session for the OS / source. |+| `electron/native-bridge/cursor/adapter.ts` | All | Adapter from native session to the `CursorRecordingData` shape used by the renderer. |+| `electron/native-bridge/cursor/telemetryCursorAdapter.ts` | All | Telemetry-only adapter. |+| `electron/native-bridge/services/cursorService.ts` | All | IPC entry point; exposes `cursor.getRecordingData` and `cursor.getTelemetry` to the renderer. |++Contracts (`src/native/contracts.ts`): `CursorRecordingData`, `CursorRecordingSample`, `NativeCursorAsset`, `NativeCursorType`.++Supported native cursor types: `arrow`, `text`, `pointer`, `crosshair`, `open-hand`, `closed-hand`, `resize-ew`, `resize-ns`, `resize-nesw`, `resize-nwse`, `move`, `not-allowed`, `wait`, `app-starting`, `help`, `up-arrow`. The renderer also has a "telemetry-only" provider (`"none"`) for legacy recordings.++## 2. Renderer hooks++| File | Role |+| --- | --- |+| `src/native/hooks/useCursorRecordingData.ts` | Loads `CursorRecordingData` for a given video path via the native bridge. Returns `{ data, loading, error }`. |+| `src/native/hooks/useCursorTelemetry.ts` | Loads the `CursorTelemetryPoint[]` stream. |+| `src/lib/cursorTelemetryBuffer.ts` | Buffers telemetry during playback (rate-decoupled from rAF). |+| `scripts/inspect-native-cursor-click-bounce.mjs` | Diagnostic for the click-bounce animation (loads a recording and prints frame state). |+| `scripts/test-windows-native-cursor.mjs` | Smoke test for the WGC cursor sampler on a real Windows machine. |+| `docs/testing/macos-native-cursor.md` / `windows-native-cursor.md` | Manual test recipes. |++## 3. Cursor core library (`src/lib/cursor/`)++| File | Role |+| --- | --- |+| `cursorPathSmoothing.ts` + test | Offline spring-damper smoothing. Resamples the raw cursor path to a 240Hz grid, runs a spring over each visible run, and serves positions by lookup. Deterministic, so preview and export match. Memoized per (recordingData, strength) via a `WeakMap`. |+| `nativeCursor.ts` + test | Pretty-cursor mapping, native bitmaps, click-bounce progress, motion-blur px. Owns the `PRETTY_NATIVE_CURSOR_ASSETS` table that maps `NativeCursorType` → SVG / hotspot, the themed override resolver (`resolveNativeCursorRenderAsset`), and the `classifyCapturedCursorType` heuristic (macOS doesn't tag samples with a cursor type — we infer arrow / pointer from the hotspot). |+| `cursorThemes.ts` | Theme registry: 17 Sweezy-cursors packs (arrow + pointer PNGs) + the built-in "default" sentinel id. Helpers: `DEFAULT_CURSOR_THEME_ID`, `CURSOR_THEME_IDS`, `getCursorTheme`, `normalizeCursorThemeId`. |+| `uploadedCursorAssets.ts` | Bitmaps for the seven supported cursor types. Trim rects are pulled from the 1024px sample sheet. |+| `pixiCursorRenderer.ts` (renamed from `video-editor/videoPlayback/cursorRenderer.ts`) | The `PixiCursorOverlay` class: builds the Pixi stage for telemetry-driven cursor rendering, applies the SVG drop shadow, runs a 240Hz spring on the cursor position, animates a click ring, and adds a directional motion-blur filter. Owns `DEFAULT_CURSOR_CONFIG` (dotRadius 28, smoothing 0.18, motionBlur 0, clickBounce 1). |++## 4. Preview layer (`src/components/ai-edition/`)++| File | Role |+| --- | --- |+| `CursorPreviewLayer.tsx` + test | Shared overlay rendered above the `<video>` in the editor. Two render paths: Pixi (telemetry) and a DOM `<img>` (native bitmap). Reads `useCursorRecordingData` + `useCursorTelemetry`, and applies the editor settings (size, smoothing, motion blur, click bounce, theme, clip-to-bounds, show). |+| `CursorPreviewLayer.module.css` | Layer + native-cursor DOM styles. |+| `VirtualPreview.tsx` (line 292) | Mounts `<CursorPreviewLayer>` inside the live preview. |++## 5. Right-panel pane (UI)++`src/components/ai-edition/RightPanes.tsx` → `CursorPane`, mounted from `RightPanelStack.tsx:115`.++| Control | Setting key | Range / type | Default |+| --- | --- | --- | --- |+| Show cursor | `cursorShow` (top-level) | toggle | `true` |+| Clip to canvas | `cursor.clipToBounds` | toggle | `false` |+| Cursor style (grid) | `cursorTheme` | pick from 18 options (Default + 17 Sweezy packs) | `default` |+| Size | `cursor.size` | 0.5 – 10.0 (×10 on the slider) | `3.0` |+| Smoothing | `cursor.smoothing` | 0 – 100% | `0.67` |+| Motion blur | `cursor.motionBlur` | 0 – 100% | `0.35` |+| Click bounce | `cursor.clickBounce` | 0 – 5.0 (×10 on the slider) | `2.5` |++Defaults live in `src/components/video-editor/types.ts` (`DEFAULT_CURSOR_SIZE`, `DEFAULT_CURSOR_SMOOTHING`, `DEFAULT_CURSOR_MOTION_BLUR`, `DEFAULT_CURSOR_CLICK_BOUNCE`, `DEFAULT_CURSOR_CLIP_TO_BOUNDS`) and are surfaced through `useEditorSettings` (`src/lib/ai-edition/store/editorSettings.ts`).++## 6. Settings persistence++- v3 document has a passthrough `legacyEditor` blob; the cursor settings round-trip through it as `cursorShow`, `cursorSize`, `cursorSmoothing`, `cursorMotionBlur`, `cursorClickBounce`, `cursorClipToBounds`, `cursorTheme`.+- Reader: `getEditorSettings(doc)` in `src/lib/ai-edition/store/editorSettings.ts`. Exposes `settings.cursor` and `settings.cursorTheme`.+- Writer: `patchEditorSettings(doc, patch)` (and `useEditorSettings().set / setLive / commit`).+- Hook: `useEditorSettings` in `src/lib/ai-edition/store/useEditorSettings.ts`. `set` persists to disk; `setLive` updates the in-memory document for live preview; `commit` flushes the in-memory doc to disk (used on slider release).++## 7. Auto-follow (zoom / camera)++`src/components/video-editor/videoPlayback/cursorFollowUtils.ts` (kept in the legacy `video-editor` folder because it's shared by the zoom-region focus logic and the export frame renderer).++- `interpolateCursorAt(telemetry, timeMs)` — binary-search the sorted telemetry and lerp to the playback time.+- `smoothCursorFocus(raw, prev, factor)` — exponential smoothing.+- `advanceFollowFocus(prev, raw, dtMs, params)` — distance-adaptive factor re-framed in content time so preview (variable fps) and export (fixed fps) converge at the same speed.+- `timeCorrectedFollowFactor(baseFactor, dtMs, referenceMs)` — frame-rate-independent smoothing.+- `adaptiveSmoothFactor(raw, prev, min, max, rampDistance)` — natural deceleration as the camera nears the cursor.++Consumers: `src/components/video-editor/videoPlayback/zoomRegionUtils.ts` (camera target for auto-focus zooms) and `src/lib/exporter/frameRenderer.ts` (export).++## 8. Exporter++`src/lib/ai-edition/exporter/documentExporter.ts` reads cursor data from options and passes it down the render pipeline. Forwarded fields: `cursorRecordingData`, `cursorTelemetry`, `cursorClickTimestamps`, `cursorScale`, `cursorSmoothing`, `cursorMotionBlur`, `cursorClickBounce`, `cursorClipToBounds`, `cursorTheme`. The legacy v2 export chain (frame renderer + muxer) consumes the same fields, so the v3 document round-trips through v2 export without losing the cursor pipeline.++## 9. Bundled assets++- 17 Sweezy-cursors theme packs under `public/cursors/<id>/{arrow,pointer}.png`. Each pack has a 32-logical-pixel reference with normalized hotspots (divide 128px-pack hotspots by 4). Add a pack by dropping two PNGs + an entry in `src/lib/cursor/cursorThemes.ts`.+- 16 native cursor SVGs under `src/assets/cursors/Cursor=*.svg` (default, app-starting, beachball, cross, hand-*, help, menu, move, not-allowed, resize-*, text-cursor, up-arrow, wait, zoom-*).++## 10. i18n++- `src/i18n/locales/en/settings.json` → `cursor` block: `theme`, `themeDefault`, `show`, `size`, `smoothing`, `motionBlur`, `clickBounce`, `clipToBounds`, `clipToBoundsDescription`. The AI-edition shell currently renders the pane in English; the legacy `SettingsPanel` consumed these keys directly.++## 11. What's NOT ported / known gaps++- The right-rail cursor tab is always shown. The legacy `SettingsPanel` hid the tab when `hasCursorData` was false. The new shell treats it as a preference (visible even before recording), which is intentional.+- The ai-edition shell does not use `useScopedT` for these labels yet — i18n keys exist but are not wired up. This is a separate P2/P3 concern.+- No tests cover the new `CursorPane` directly (only the shared `CursorPreviewLayer`).++## 12. File map (port branch vs legacy main)++| Concern | Legacy (`main`) | Port branch (`port/cursor-from-main`) |+| --- | --- | --- |+| Editor | `src/components/video-editor/SettingsPanel.tsx`, `VideoEditor.tsx`, `videoPlayback/VideoPlayback.tsx` | `src/components/ai-edition/RightPanes.tsx` (`CursorPane`), `RightPanelStack.tsx`, `NewEditorShell.tsx`, `VirtualPreview.tsx` |+| Pixi overlay | `src/components/video-editor/videoPlayback/cursorRenderer.ts` | `src/lib/cursor/pixiCursorRenderer.ts` (renamed) |+| Uploaded-cursor bitmaps | `src/components/video-editor/videoPlayback/uploadedCursorAssets.ts` | `src/lib/cursor/uploadedCursorAssets.ts` (renamed) |+| Auto-follow | `src/components/video-editor/videoPlayback/cursorFollowUtils.ts` | unchanged |+| Spring config | `src/components/video-editor/videoPlayback/motionSmoothing.ts` | unchanged |+| Themes | `src/lib/cursor/cursorThemes.ts` | unchanged |+| Path smoothing | `src/lib/cursor/cursorPathSmoothing.ts` | unchanged |+| Pretty / native cursor | `src/lib/cursor/nativeCursor.ts` | unchanged |+| Telemetry buffer | `src/lib/cursorTelemetryBuffer.ts` | unchanged |+| Hooks | `src/native/hooks/useCursor*.ts` | unchanged |+| Native capture | `electron/native/{screencapturekit,wgc-capture}/...` + `electron/native-bridge/cursor/*` | unchanged |+| Export pipeline | `src/lib/exporter/frameRenderer.ts`, `muxer.ts` | adds `src/lib/ai-edition/exporter/documentExporter.ts` (v3 envelope) → forwards to v2 renderer |diff --git a/opencode.json b/opencode.jsondeleted file mode 100644index 4c1c60538..000000000--- a/opencode.json+++ /dev/null@@ -1,102 +0,0 @@-{- "$schema": "https://opencode.ai/config.json",- "mcp": {- "playwright-test": {- "type": "local",- "command": ["npx", "playwright", "run-test-mcp-server"],- "enabled": true- },- "open-computer-use": {- "type": "local",- "command": ["open-computer-use", "mcp"],- "enabled": true- }- },- "tools": {- "playwright*": false- },- "agent": {- "playwright-test-generator": {- "description": "Use this agent when you need to create automated browser tests using Playwright",- "mode": "subagent",- "prompt": "{file:.opencode/prompts/playwright-test-generator.md}",- "tools": {- "ls": true,- "glob": true,- "grep": true,- "read": true,- "playwright-test*browser_click": true,- "playwright-test*browser_drag": true,- "playwright-test*browser_evaluate": true,- "playwright-test*browser_file_upload": true,- "playwright-test*browser_handle_dialog": true,- "playwright-test*browser_hover": true,- "playwright-test*browser_navigate": true,- "playwright-test*browser_press_key": true,- "playwright-test*browser_select_option": true,- "playwright-test*browser_snapshot": true,- "playwright-test*browser_type": true,- "playwright-test*browser_verify_element_visible": true,- "playwright-test*browser_verify_list_visible": true,- "playwright-test*browser_verify_text_visible": true,- "playwright-test*browser_verify_value": true,- "playwright-test*browser_wait_for": true,- "playwright-test*generator_read_log": true,- "playwright-test*generator_setup_page": true,- "playwright-test*generator_write_test": true- }- },- "playwright-test-healer": {- "description": "Use this agent when you need to debug and fix failing Playwright tests",- "mode": "subagent",- "prompt": "{file:.opencode/prompts/playwright-test-healer.md}",- "tools": {- "ls": true,- "glob": true,- "grep": true,- "read": true,- "edit": true,- "write": true,- "playwright-test*browser_console_messages": true,- "playwright-test*browser_evaluate": true,- "playwright-test*browser_generate_locator": true,- "playwright-test*browser_network_requests": true,- "playwright-test*browser_snapshot": true,- "playwright-test*test_debug": true,- "playwright-test*test_list": true,- "playwright-test*test_run": true- }- },- "playwright-test-planner": {- "description": "Use this agent when you need to create comprehensive test plan for a web application or website",- "mode": "subagent",- "prompt": "{file:.opencode/prompts/playwright-test-planner.md}",- "tools": {- "ls": true,- "glob": true,- "grep": true,- "read": true,- "playwright-test*browser_click": true,- "playwright-test*browser_close": true,- "playwright-test*browser_console_messages": true,- "playwright-test*browser_drag": true,- "playwright-test*browser_evaluate": true,- "playwright-test*browser_file_upload": true,- "playwright-test*browser_handle_dialog": true,- "playwright-test*browser_hover": true,- "playwright-test*browser_navigate": true,- "playwright-test*browser_navigate_back": true,- "playwright-test*browser_network_requests": true,- "playwright-test*browser_press_key": true,- "playwright-test*browser_run_code": true,- "playwright-test*browser_select_option": true,- "playwright-test*browser_snapshot": true,- "playwright-test*browser_take_screenshot": true,- "playwright-test*browser_type": true,- "playwright-test*browser_wait_for": true,- "playwright-test*planner_setup_page": true,- "playwright-test*planner_save_plan": true- }- }- }-}diff --git a/src/components/ai-edition/AnnotationLayer.tsx b/src/components/ai-edition/AnnotationLayer.tsxnew file mode 100644index 000000000..9876158f6--- /dev/null+++ b/src/components/ai-edition/AnnotationLayer.tsx@@ -0,0 +1,90 @@+// Port of the annotation-rendering block inline in `VideoPlayback.tsx`+// (lines ~1988-2115 on main) as a standalone component. Main splits+// "annotation" and "blur" into two separate arrays/selection ids; the new+// editor's schema keeps all annotation types (including blur) in one+// `document.annotations[]` array, so this uses a single filtered+sorted+// list and a single selection id instead.++import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";+import { AnnotationOverlay } from "./AnnotationOverlay";++type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;++interface AnnotationLayerProps {+ annotations: AxcutAnnotationRegion[];+ selectedAnnotationId: string | null;+ currentTimeSec: number;+ containerWidth: number;+ containerHeight: number;+ videoElement?: HTMLVideoElement | null;+ onSelectAnnotation: (id: string) => void;+ onPositionChange: (id: string, position: { x: number; y: number }) => void;+ onSizeChange: (id: string, size: { width: number; height: number }) => void;+ onBlurDataChange: (id: string, blurData: BlurData) => void;+ onCommit: () => void;+}++export function AnnotationLayer({+ annotations,+ selectedAnnotationId,+ currentTimeSec,+ containerWidth,+ containerHeight,+ videoElement,+ onSelectAnnotation,+ onPositionChange,+ onSizeChange,+ onBlurDataChange,+ onCommit,+}: AnnotationLayerProps) {+ const currentTimeMs = Math.round(currentTimeSec * 1000);++ const visible = annotations+ .filter((annotation) => {+ if (typeof annotation.startMs !== "number" || typeof annotation.endMs !== "number") {+ return false;+ }+ if (annotation.id === selectedAnnotationId) return true;+ return currentTimeMs >= annotation.startMs && currentTimeMs < annotation.endMs;+ })+ .sort((a, b) => a.zIndex - b.zIndex);++ const handleClick = (clickedId: string) => {+ if (clickedId === selectedAnnotationId && visible.length > 1) {+ const currentIndex = visible.findIndex((a) => a.id === clickedId);+ const nextIndex = (currentIndex + 1) % visible.length;+ onSelectAnnotation(visible[nextIndex].id);+ } else {+ onSelectAnnotation(clickedId);+ }+ };++ if (containerWidth <= 0 || containerHeight <= 0) return null;++ return (+ <div className="absolute inset-0" style={{ pointerEvents: "none" }}>+ {visible.map((annotation) => (+ <AnnotationOverlay+ key={+ annotation.type === "blur"+ ? `${annotation.id}-${containerWidth}-${containerHeight}-${annotation.blurData?.shape ?? "rectangle"}-${annotation.blurData?.color ?? "white"}-${Math.round(annotation.blurData?.blockSize ?? 0)}-${(annotation.blurData?.freehandPoints ?? []).map((p) => `${Math.round(p.x)}_${Math.round(p.y)}`).join("-")}`+ : `${annotation.id}-${containerWidth}-${containerHeight}`+ }+ annotation={annotation}+ isSelected={annotation.id === selectedAnnotationId}+ containerWidth={containerWidth}+ containerHeight={containerHeight}+ onPositionChange={onPositionChange}+ onSizeChange={onSizeChange}+ onBlurDataChange={annotation.type === "blur" ? onBlurDataChange : undefined}+ onBlurDataCommit={annotation.type === "blur" ? onCommit : undefined}+ onClick={handleClick}+ zIndex={annotation.zIndex}+ isSelectedBoost={annotation.id === selectedAnnotationId}+ videoElement={videoElement}+ currentTimeMs={currentTimeMs}+ />+ ))}+ </div>+ );+}diff --git a/src/components/ai-edition/AnnotationOverlay.tsx b/src/components/ai-edition/AnnotationOverlay.tsxnew file mode 100644index 000000000..e4c92c833--- /dev/null+++ b/src/components/ai-edition/AnnotationOverlay.tsx@@ -0,0 +1,601 @@+// Port of `src/components/video-editor/AnnotationOverlay.tsx`, adapted for+// the new editor's CSS-only preview (no Pixi stage to `extract` a frame+// from): the mosaic blur effect samples pixels directly from the active+// <video> element via `drawImage` instead of a Pixi-rendered snapshot+// canvas. Everything else — Rnd drag/resize math, per-type rendering,+// freehand blur drawing, text animation — is ported verbatim so the preview+// behaves identically to the legacy editor.++import { type CSSProperties, type PointerEvent, useEffect, useRef, useState } from "react";+import { Rnd } from "react-rnd";+import {+ getBlurOverlayColor,+ getMosaicGridOverlayColor,+ getNormalizedMosaicBlockSize,+} from "@/lib/ai-edition/annotations/blurEffects";+import { DEFAULT_BLUR_BLOCK_SIZE, DEFAULT_BLUR_DATA } from "@/lib/ai-edition/annotations/constants";+import { getTextAnimationState } from "@/lib/ai-edition/annotations/textAnimation";+import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";+import { cn } from "@/lib/utils";+import { getArrowComponent } from "./ArrowSvgs";++type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;++const FREEHAND_POINT_THRESHOLD = 1;++function buildBlurPolygonClipPath(points: Array<{ x: number; y: number }>) {+ if (points.length < 3) return undefined;+ const polygon = points.map((point) => `${point.x}% ${point.y}%`).join(", ");+ return `polygon(${polygon})`;+}++function buildBlurFreehandPath(points: Array<{ x: number; y: number }>, closed = true) {+ if (closed ? points.length < 3 : points.length < 2) return null;+ const [firstPoint, ...rest] = points;+ const path = `M ${firstPoint.x} ${firstPoint.y} ${rest.map((point) => `L ${point.x} ${point.y}`).join(" ")}`;+ return closed ? `${path} Z` : path;+}++interface AnnotationOverlayProps {+ annotation: AxcutAnnotationRegion;+ isSelected: boolean;+ containerWidth: number;+ containerHeight: number;+ onPositionChange: (id: string, position: { x: number; y: number }) => void;+ onSizeChange: (id: string, size: { width: number; height: number }) => void;+ onBlurDataChange?: (id: string, blurData: BlurData) => void;+ onBlurDataCommit?: () => void;+ onClick: (id: string) => void;+ zIndex: number;+ isSelectedBoost: boolean;+ videoElement?: HTMLVideoElement | null;+ currentTimeMs: number;+}++export function AnnotationOverlay({+ annotation,+ isSelected,+ containerWidth,+ containerHeight,+ onPositionChange,+ onSizeChange,+ onBlurDataChange,+ onBlurDataCommit,+ onClick,+ zIndex,+ isSelectedBoost,+ videoElement,+ currentTimeMs,+}: AnnotationOverlayProps) {+ const committedX = (annotation.position.x / 100) * containerWidth;+ const committedY = (annotation.position.y / 100) * containerHeight;+ const committedWidth = (annotation.size.width / 100) * containerWidth;+ const committedHeight = (annotation.size.height / 100) * containerHeight;+ const blurShape = annotation.type === "blur" ? (annotation.blurData?.shape ?? "rectangle") : null;+ const isSelectedFreehandBlur = isSelected && blurShape === "freehand";+ const isDraggingRef = useRef(false);+ const isDrawingFreehandRef = useRef(false);+ const freehandPointsRef = useRef<Array<{ x: number; y: number }>>([]);+ const [isFreehandDrawing, setIsFreehandDrawing] = useState(false);+ const [draftFreehandPoints, setDraftFreehandPoints] = useState<Array<{ x: number; y: number }>>(+ [],+ );+ const [livePointerPoint, setLivePointerPoint] = useState<{ x: number; y: number } | null>(null);+ const mosaicCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const blurOverlayColor =+ annotation.type === "blur" ? getBlurOverlayColor(annotation.blurData) : "";+ const mosaicGridOverlayColor =+ annotation.type === "blur" ? getMosaicGridOverlayColor(annotation.blurData) : "";+ const [liveRect, setLiveRect] = useState({+ x: committedX,+ y: committedY,+ width: committedWidth,+ height: committedHeight,+ });++ useEffect(() => {+ setLiveRect({+ x: committedX,+ y: committedY,+ width: committedWidth,+ height: committedHeight,+ });+ }, [committedHeight, committedWidth, committedX, committedY]);++ const { x, y, width, height } = liveRect;++ // ponytail: legacy sampled from `app.renderer.extract.canvas(app.stage)` —+ // a Pixi-composited frame. The new preview has no Pixi stage for the main+ // video, so this samples the <video> element directly. Visually+ // equivalent as long as nothing else (zoom, cursor) sits between the+ // video and this overlay in z-order, which matches today's stacking.+ useEffect(() => {+ if (annotation.type !== "blur") return;+ void currentTimeMs;++ const canvas = mosaicCanvasRef.current;+ const video = videoElement;+ if (!canvas || !video || video.readyState < 2) return;++ const sourceWidth = video.videoWidth;+ const sourceHeight = video.videoHeight;+ const sourceClientWidth = video.clientWidth || containerWidth || sourceWidth;+ const sourceClientHeight = video.clientHeight || containerHeight || sourceHeight;+ if (+ sourceWidth <= 0 ||+ sourceHeight <= 0 ||+ sourceClientWidth <= 0 ||+ sourceClientHeight <= 0+ ) {+ return;+ }++ const drawWidth = Math.max(1, Math.round(width));+ const drawHeight = Math.max(1, Math.round(height));+ if (drawWidth <= 0 || drawHeight <= 0) return;++ const context = canvas.getContext("2d", { willReadFrequently: true });+ if (!context) return;++ const scaleX = sourceWidth / sourceClientWidth;+ const scaleY = sourceHeight / sourceClientHeight;+ const sourceX = Math.max(0, Math.floor(x * scaleX));+ const sourceY = Math.max(0, Math.floor(y * scaleY));+ const sourceSampleWidth = Math.max(1, Math.ceil(drawWidth * scaleX));+ const sourceSampleHeight = Math.max(1, Math.ceil(drawHeight * scaleY));+ const clampedSampleWidth = Math.max(1, Math.min(sourceSampleWidth, sourceWidth - sourceX));+ const clampedSampleHeight = Math.max(1, Math.min(sourceSampleHeight, sourceHeight - sourceY));+ const blockSize = getNormalizedMosaicBlockSize(annotation.blurData);+ const downscaledWidth = Math.max(1, Math.round(drawWidth / blockSize));+ const downscaledHeight = Math.max(1, Math.round(drawHeight / blockSize));+ canvas.width = downscaledWidth;+ canvas.height = downscaledHeight;++ context.clearRect(0, 0, downscaledWidth, downscaledHeight);+ context.imageSmoothingEnabled = true;+ context.drawImage(+ video,+ sourceX,+ sourceY,+ clampedSampleWidth,+ clampedSampleHeight,+ 0,+ 0,+ downscaledWidth,+ downscaledHeight,+ );+ }, [+ annotation,+ containerHeight,+ containerWidth,+ height,+ videoElement,+ currentTimeMs,+ width,+ x,+ y,+ ]);++ const renderArrow = () => {+ const direction = annotation.figureData?.arrowDirection || "right";+ const color = annotation.figureData?.color || "#34B27B";+ const strokeWidth = annotation.figureData?.strokeWidth || 4;+ const ArrowComponent = getArrowComponent(direction);+ return <ArrowComponent color={color} strokeWidth={strokeWidth} />;+ };++ const normalizePoint = (event: PointerEvent<HTMLDivElement>) => {+ const rect = event.currentTarget.getBoundingClientRect();+ const px = ((event.clientX - rect.left) / rect.width) * 100;+ const py = ((event.clientY - rect.top) / rect.height) * 100;+ return { x: Math.max(0, Math.min(100, px)), y: Math.max(0, Math.min(100, py)) };+ };++ const appendFreehandPoint = (point: { x: number; y: number }) => {+ const points = freehandPointsRef.current;+ const lastPoint = points[points.length - 1];+ if (!lastPoint) {+ points.push(point);+ return;+ }+ const dx = point.x - lastPoint.x;+ const dy = point.y - lastPoint.y;+ if (Math.hypot(dx, dy) >= FREEHAND_POINT_THRESHOLD) {+ points.push(point);+ }+ };++ const handleFreehandPointerDown = (event: PointerEvent<HTMLDivElement>) => {+ if (+ !isSelected ||+ annotation.type !== "blur" ||+ annotation.blurData?.shape !== "freehand" ||+ !onBlurDataChange+ ) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ event.currentTarget.setPointerCapture(event.pointerId);+ isDrawingFreehandRef.current = true;+ setIsFreehandDrawing(true);+ const point = normalizePoint(event);+ freehandPointsRef.current = [point];+ setDraftFreehandPoints([point]);+ setLivePointerPoint(point);+ };++ const handleFreehandPointerMove = (event: PointerEvent<HTMLDivElement>) => {+ if (!isDrawingFreehandRef.current) return;+ event.preventDefault();+ event.stopPropagation();+ const point = normalizePoint(event);+ setLivePointerPoint(point);+ appendFreehandPoint(point);+ setDraftFreehandPoints([...freehandPointsRef.current]);+ };++ const finishFreehandPointer = (event: PointerEvent<HTMLDivElement>) => {+ if (!isDrawingFreehandRef.current || !onBlurDataChange) return;+ isDrawingFreehandRef.current = false;+ setIsFreehandDrawing(false);+ try {+ event.currentTarget.releasePointerCapture(event.pointerId);+ } catch {+ // no-op if already released+ }+ const points = [...freehandPointsRef.current];+ if (livePointerPoint) {+ const last = points[points.length - 1];+ if (!last || Math.hypot(last.x - livePointerPoint.x, last.y - livePointerPoint.y) > 0.001) {+ points.push(livePointerPoint);+ }+ }+ if (points.length >= 3) {+ const closedPoints = [...points];+ const first = closedPoints[0];+ const last = closedPoints[closedPoints.length - 1];+ if (Math.hypot(last.x - first.x, last.y - first.y) > 0.001) {+ closedPoints.push({ ...first });+ }+ onBlurDataChange(annotation.id, {+ ...(annotation.blurData || { ...DEFAULT_BLUR_DATA, shape: "freehand" }),+ shape: "freehand",+ freehandPoints: closedPoints,+ });+ setDraftFreehandPoints(closedPoints);+ onBlurDataCommit?.();+ }+ setLivePointerPoint(null);+ };++ const renderContent = () => {+ switch (annotation.type) {+ case "text": {+ const animationState = getTextAnimationState(annotation, currentTimeMs);+ const typewriterClip =+ animationState.revealProgress < 1+ ? `inset(0 ${100 - animationState.revealProgress * 100}% 0 0)`+ : undefined;+ return (+ <div+ className="w-full h-full flex items-center p-2 overflow-hidden"+ style={{+ justifyContent:+ annotation.style.textAlign === "left"+ ? "flex-start"+ : annotation.style.textAlign === "right"+ ? "flex-end"+ : "center",+ alignItems: "center",+ }}+ >+ <span+ style={{+ color: annotation.style.color,+ backgroundColor: annotation.style.backgroundColor,+ fontSize: `${annotation.style.fontSize}px`,+ fontFamily: annotation.style.fontFamily,+ fontWeight: annotation.style.fontWeight,+ fontStyle: annotation.style.fontStyle,+ textDecoration: annotation.style.textDecoration,+ textAlign: annotation.style.textAlign,+ opacity: animationState.opacity,+ transform: `translate(${animationState.translateX}px, ${animationState.translateY}px) scale(${animationState.scale})`,+ transformOrigin: "center",+ clipPath: typewriterClip,+ WebkitClipPath: typewriterClip,+ wordBreak: "break-word",+ whiteSpace: "pre-wrap",+ boxDecorationBreak: "clone",+ WebkitBoxDecorationBreak: "clone",+ padding: "0.1em 0.2em",+ borderRadius: "4px",+ lineHeight: "1.4",+ }}+ >+ {annotation.content}+ </span>+ </div>+ );+ }++ case "image":+ if (annotation.content?.startsWith("data:image")) {+ return (+ <img+ src={annotation.content}+ alt="Annotation"+ className="w-full h-full object-contain"+ draggable={false}+ />+ );+ }+ return (+ <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">+ No image+ </div>+ );++ case "figure":+ if (!annotation.figureData) {+ return (+ <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">+ No arrow data+ </div>+ );+ }+ return (+ <div className="w-full h-full flex items-center justify-center p-2">{renderArrow()}</div>+ );++ case "blur": {+ const shape = annotation.blurData?.shape ?? "rectangle";+ const blockSize = Math.max(+ 1,+ Math.round(annotation.blurData?.blockSize ?? DEFAULT_BLUR_BLOCK_SIZE),+ );+ const activeFreehandPoints =+ shape === "freehand"+ ? isFreehandDrawing+ ? draftFreehandPoints+ : (annotation.blurData?.freehandPoints ?? [])+ : [];+ const drawingPoints =+ isFreehandDrawing && livePointerPoint+ ? (() => {+ const last = activeFreehandPoints[activeFreehandPoints.length - 1];+ if (!last) return [livePointerPoint];+ const dx = livePointerPoint.x - last.x;+ const dy = livePointerPoint.y - last.y;+ return Math.hypot(dx, dy) > 0.01+ ? [...activeFreehandPoints, livePointerPoint]+ : activeFreehandPoints;+ })()+ : activeFreehandPoints;+ const clipPath =+ shape === "freehand" ? buildBlurPolygonClipPath(activeFreehandPoints) : undefined;+ const freehandPath =+ shape === "freehand"+ ? buildBlurFreehandPath(+ isFreehandDrawing ? drawingPoints : activeFreehandPoints,+ !isFreehandDrawing,+ )+ : null;+ const currentPointerPoint = isFreehandDrawing+ ? livePointerPoint || drawingPoints[drawingPoints.length - 1] || null+ : null;+ const shapeBorderRadius = shape === "oval" ? "50%" : shape === "rectangle" ? "8px" : "0";+ const shouldShowFreehandBlurFill =+ shape !== "freehand" || (!!clipPath && !isFreehandDrawing);+ const shapeMaskStyle: CSSProperties = {+ borderRadius: shapeBorderRadius,+ clipPath: isFreehandDrawing ? undefined : clipPath,+ WebkitClipPath: isFreehandDrawing ? undefined : clipPath,+ };+ const isFreehandSelected = isSelectedFreehandBlur;+ return (+ <div className="w-full h-full relative">+ <div+ className="absolute inset-0 overflow-hidden"+ style={{ ...shapeMaskStyle, isolation: "isolate" }}+ >+ <div+ className="absolute inset-0"+ style={{+ ...shapeMaskStyle,+ backgroundColor: blurOverlayColor,+ opacity: shouldShowFreehandBlurFill ? 1 : 0,+ }}+ />+ {shouldShowFreehandBlurFill && (+ <canvas+ ref={mosaicCanvasRef}+ className="absolute inset-0 w-full h-full"+ style={{ ...shapeMaskStyle, imageRendering: "pixelated" }}+ />+ )}+ {shouldShowFreehandBlurFill && (+ <div+ className="absolute inset-0 pointer-events-none"+ style={{ ...shapeMaskStyle, backgroundColor: blurOverlayColor }}+ />+ )}+ <div+ className="absolute inset-0 pointer-events-none"+ style={{+ ...shapeMaskStyle,+ backgroundImage: `linear-gradient(${mosaicGridOverlayColor} 1px, transparent 1px), linear-gradient(90deg, ${mosaicGridOverlayColor} 1px, transparent 1px)`,+ backgroundSize: `${blockSize}px ${blockSize}px`,+ mixBlendMode: "screen",+ opacity: 0.35,+ }}+ />+ {isSelected && shape !== "freehand" && (+ <div+ className="absolute inset-0 pointer-events-none border-2 border-[#34B27B]/80"+ style={{ borderRadius: shapeBorderRadius }}+ />+ )}+ </div>+ {isSelected && shape === "freehand" && freehandPath && (+ <svg+ viewBox="0 0 100 100"+ preserveAspectRatio="none"+ className="absolute inset-0 pointer-events-none"+ >+ <path+ d={freehandPath}+ fill="none"+ stroke="#34B27B"+ strokeWidth="0.55"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ {currentPointerPoint && (+ <circle+ cx={currentPointerPoint.x}+ cy={currentPointerPoint.y}+ r="0.6"+ fill="#34B27B"+ />+ )}+ </svg>+ )}+ {isFreehandSelected && (+ <div+ className="absolute inset-0 cursor-crosshair"+ onPointerDown={handleFreehandPointerDown}+ onPointerMove={handleFreehandPointerMove}+ onPointerUp={finishFreehandPointer}+ onPointerCancel={finishFreehandPointer}+ />+ )}+ </div>+ );+ }++ default:+ return null;+ }+ };++ return (+ <Rnd+ position={{ x, y }}+ size={{ width, height }}+ onDragStart={() => {+ isDraggingRef.current = true;+ }}+ onDrag={(_e, d) => {+ setLiveRect((prev) => ({ ...prev, x: d.x, y: d.y }));+ }}+ onDragStop={(_e, d) => {+ setLiveRect((prev) => ({ ...prev, x: d.x, y: d.y }));+ const xPercent = (d.x / containerWidth) * 100;+ const yPercent = (d.y / containerHeight) * 100;+ onPositionChange(annotation.id, { x: xPercent, y: yPercent });+ setTimeout(() => {+ isDraggingRef.current = false;+ }, 100);+ }}+ onResize={(_e, _direction, ref, _delta, position) => {+ setLiveRect({+ x: position.x,+ y: position.y,+ width: ref.offsetWidth,+ height: ref.offsetHeight,+ });+ }}+ onResizeStop={(_e, _direction, ref, _delta, position) => {+ setLiveRect({+ x: position.x,+ y: position.y,+ width: ref.offsetWidth,+ height: ref.offsetHeight,+ });+ const xPercent = (position.x / containerWidth) * 100;+ const yPercent = (position.y / containerHeight) * 100;+ const widthPercent = (ref.offsetWidth / containerWidth) * 100;+ const heightPercent = (ref.offsetHeight / containerHeight) * 100;+ onPositionChange(annotation.id, { x: xPercent, y: yPercent });+ onSizeChange(annotation.id, { width: widthPercent, height: heightPercent });+ }}+ onClick={() => {+ if (isDraggingRef.current) return;+ onClick(annotation.id);+ }}+ bounds="parent"+ className={cn(+ "cursor-move",+ isSelected &&+ annotation.type !== "blur" &&+ "ring-2 ring-[#34B27B] ring-offset-2 ring-offset-transparent",+ )}+ style={{+ zIndex: isSelectedBoost ? zIndex + 1000 : zIndex,+ pointerEvents: isSelected ? "auto" : "none",+ border:+ isSelected && annotation.type !== "blur" ? "2px solid rgba(52, 178, 123, 0.8)" : "none",+ backgroundColor:+ isSelected && annotation.type !== "blur" ? "rgba(52, 178, 123, 0.1)" : "transparent",+ boxShadow:+ isSelected && annotation.type !== "blur" ? "0 0 0 1px rgba(52, 178, 123, 0.35)" : "none",+ }}+ enableResizing={isSelected && !isSelectedFreehandBlur}+ disableDragging={!isSelected || isSelectedFreehandBlur}+ resizeHandleStyles={{+ topLeft: {+ width: "12px",+ height: "12px",+ backgroundColor: isSelected ? "white" : "transparent",+ border: isSelected ? "2px solid #34B27B" : "none",+ borderRadius: "50%",+ left: "-6px",+ top: "-6px",+ cursor: "nwse-resize",+ },+ topRight: {+ width: "12px",+ height: "12px",+ backgroundColor: isSelected ? "white" : "transparent",+ border: isSelected ? "2px solid #34B27B" : "none",+ borderRadius: "50%",+ right: "-6px",+ top: "-6px",+ cursor: "nesw-resize",+ },+ bottomLeft: {+ width: "12px",+ height: "12px",+ backgroundColor: isSelected ? "white" : "transparent",+ border: isSelected ? "2px solid #34B27B" : "none",+ borderRadius: "50%",+ left: "-6px",+ bottom: "-6px",+ cursor: "nesw-resize",+ },+ bottomRight: {+ width: "12px",+ height: "12px",+ backgroundColor: isSelected ? "white" : "transparent",+ border: isSelected ? "2px solid #34B27B" : "none",+ borderRadius: "50%",+ right: "-6px",+ bottom: "-6px",+ cursor: "nwse-resize",+ },+ }}+ >+ <div+ className={cn(+ "w-full h-full",+ annotation.type !== "blur" && "rounded-lg",+ isSelected && annotation.type !== "blur" && "shadow-lg",+ )}+ >+ {renderContent()}+ </div>+ </Rnd>+ );+}diff --git a/src/components/ai-edition/ArrowSvgs.tsx b/src/components/ai-edition/ArrowSvgs.tsxnew file mode 100644index 000000000..092034efa--- /dev/null+++ b/src/components/ai-edition/ArrowSvgs.tsx@@ -0,0 +1,204 @@+// Port of `src/components/video-editor/ArrowSvgs.tsx` verbatim — inline SVG+// arrows for 8 directions (pure paths, not icon fonts, so export can+// replicate them identically to the live preview).++import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";++type ArrowDirection = NonNullable<AxcutAnnotationRegion["figureData"]>["arrowDirection"];++interface ArrowSvgProps {+ color: string;+ strokeWidth: number;+ className?: string;+}++export function ArrowUp({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 50 20 L 50 80 M 50 20 L 35 35 M 50 20 L 65 35"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function ArrowDown({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 50 20 L 50 80 M 50 80 L 35 65 M 50 80 L 65 65"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function ArrowLeft({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 80 50 L 20 50 M 20 50 L 35 35 M 20 50 L 35 65"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function ArrowRight({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 20 50 L 80 50 M 80 50 L 65 35 M 80 50 L 65 65"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function ArrowUpRight({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 25 75 L 75 25 M 75 25 L 60 30 M 75 25 L 70 40"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function ArrowUpLeft({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 75 75 L 25 25 M 25 25 L 40 30 M 25 25 L 30 40"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function ArrowDownRight({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 25 25 L 75 75 M 75 75 L 70 60 M 75 75 L 60 70"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function ArrowDownLeft({ color, strokeWidth, className }: ArrowSvgProps) {+ return (+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>+ <defs>+ <filter id="arrow-shadow">+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />+ </filter>+ </defs>+ <path+ d="M 75 25 L 25 75 M 25 75 L 30 60 M 25 75 L 40 70"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ filter="url(#arrow-shadow)"+ />+ </svg>+ );+}++export function getArrowComponent(direction: ArrowDirection) {+ switch (direction) {+ case "up":+ return ArrowUp;+ case "down":+ return ArrowDown;+ case "left":+ return ArrowLeft;+ case "right":+ return ArrowRight;+ case "up-right":+ return ArrowUpRight;+ case "up-left":+ return ArrowUpLeft;+ case "down-right":+ return ArrowDownRight;+ case "down-left":+ return ArrowDownLeft;+ default:+ return ArrowRight;+ }+}diff --git a/src/components/ai-edition/Bottombar.tsx b/src/components/ai-edition/Bottombar.tsxindex d8e0d4640..38445a91a 100644--- a/src/components/ai-edition/Bottombar.tsx+++ b/src/components/ai-edition/Bottombar.tsx@@ -8,7 +8,8 @@ import {WandSparkles,ZoomIn,} from "lucide-react";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import { createPortal } from "react-dom";import { toast } from "sonner";import type { AnnotationRegion } from "@/components/video-editor/types";import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";@@ -16,6 +17,7 @@ import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";import { useTimeline } from "@/lib/ai-edition/store/useTimeline";import { suggestZoomRegions } from "@/lib/ai-edition/store/zoomSuggestions";+import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";import { ASPECT_RATIOS, type AspectRatio } from "@/utils/aspectRatioUtils";import { EditClipModal } from "./Modals";import styles from "./NewEditorShell.module.css";@@ -88,6 +90,22 @@ export function Bottombar({const { settings, set } = useEditorSettings();const tl = useTimeline();const [ratioOpen, setRatioOpen] = useState(false);+ const ratioButtonRef = useRef<HTMLButtonElement | null>(null);+ // ponytail: `.bottombar` sets `overflow: hidden` to contain the timeline+ // lanes, which also clips any absolutely-positioned child that escapes+ // its box -- including this menu. Render it through a portal, positioned+ // from the button's live viewport rect, so it paints above everything+ // regardless of ancestor overflow/stacking.+ const [ratioMenuRect, setRatioMenuRect] = useState<{ left: number; bottom: number } | null>(+ null,+ );+ useEffect(() => {+ if (!ratioOpen) return;+ const button = ratioButtonRef.current;+ if (!button) return;+ const rect = button.getBoundingClientRect();+ setRatioMenuRect({ left: rect.left, bottom: window.innerHeight - rect.top + 4 });+ }, [ratioOpen]);const [editClipTarget, setEditClipTarget] = useState<AxcutClip | null>(null);const firstClip = clips[0] ?? null;// T11 — viewport state lifted from TimelinePane so the navigator strip@@ -181,7 +199,17 @@ export function Bottombar({if (zoomRegions.some((z) => z.id === id)) void tl.updateZoomSpan(id, span.start, span.end);else if (speedRegions.some((s) => s.id === id))void tl.updateSpeedSpan(id, span.start, span.end);- else void tl.updateAnnotationSpan(id, span.start, span.end);+ else if (skipRanges.some((s) => s.id === id)) {+ // ponytail: skip spans are edited in timeline (virtual) ms via the+ // same lane drag/resize as zoom/speed/annotation, but persisted in+ // source-time seconds (skipRangeSchema) — map back through the+ // clip the span resolves to.+ const startPos = locateVirtualPosition(clips, span.start / 1000);+ const endPos = locateVirtualPosition(clips, span.end / 1000);+ if (startPos && endPos) {+ void tl.updateSkipRange(id, startPos.sourceTimeSec, endPos.sourceTimeSec);+ }+ } else void tl.updateAnnotationSpan(id, span.start, span.end);};// ponytail: T10 removed the explicit onRemoveRegion prop (region// removal happens via the Del/Bksp shortcut wired in NewEditorShell).@@ -266,6 +294,7 @@ export function Bottombar({</VtBtn><div style={{ position: "relative" }}><button+ ref={ratioButtonRef}type="button"className={styles.ratio}onClick={() => setRatioOpen((v) => !v)}@@ -275,39 +304,42 @@ export function Bottombar({<span>{RATIO_LABELS[settings.aspectRatio]}</span><ChevronDown size={10} className="caret" /></button>- {ratioOpen ? (- <div- role="menu"- style={{- position: "absolute",- top: "calc(100% + 4px)",- left: 0,- minWidth: 120,- background: "var(--surface)",- border: "1px solid var(--border)",- borderRadius: "var(--r-md)",- boxShadow: "var(--elev-pop)",- padding: 4,- zIndex: 60,- }}- >- {ASPECT_RATIOS.map((r) => (- <button- type="button"- key={r}- role="menuitem"- style={menuItemStyle(r === settings.aspectRatio)}- disabled={!hasDoc}- onClick={() => {- void set({ aspectRatio: r });- setRatioOpen(false);+ {ratioOpen && ratioMenuRect+ ? createPortal(+ <div+ role="menu"+ style={{+ position: "fixed",+ left: ratioMenuRect.left,+ bottom: ratioMenuRect.bottom,+ minWidth: 120,+ background: "var(--surface)",+ border: "1px solid var(--border)",+ borderRadius: "var(--r-md)",+ boxShadow: "var(--elev-pop)",+ padding: 4,+ zIndex: 1000,}}>- {RATIO_LABELS[r]}- </button>- ))}- </div>- ) : null}+ {ASPECT_RATIOS.map((r) => (+ <button+ type="button"+ key={r}+ role="menuitem"+ style={menuItemStyle(r === settings.aspectRatio)}+ disabled={!hasDoc}+ onClick={() => {+ void set({ aspectRatio: r });+ setRatioOpen(false);+ }}+ >+ {RATIO_LABELS[r]}+ </button>+ ))}+ </div>,+ document.body,+ )+ : null}</div></div><div className={styles.hintRow}>@@ -365,16 +397,6 @@ export function Bottombar({onMoveClip={(clipId, toIndex) => void tl.moveClip(clipId, toIndex)}onEditClip={(clip) => setEditClipTarget(clip)}onRemoveClip={(clipId) => void tl.removeClip(clipId)}- onUpdateSkipRange={(skipId, s, e) => void tl.updateSkipRange(skipId, s, e)}- onPreviewSource={(timeSec, _assetId) => {- // T19 — drive the source-time clock so the preview- // video scrubs to the edge being dragged. We don't- // rebind the preview's activeSource because that- // resets playback; the existing Preview's- // seekToSourceTime handles the same-source case.- tl.setCurrentTime(timeSec);- }}- onRemoveSkipRange={(skipId) => void tl.removeRegion("skip", skipId)}onAddSkip={(assetId, s, e) => void tl.addSkipAt(assetId, s, e)}onRegionSpanChange={(id, span) => handleRegionSpanChange(id, span)}zoom={zoom}diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.cssindex 734778df6..d86303eed 100644--- a/src/components/ai-edition/NewEditorShell.module.css+++ b/src/components/ai-edition/NewEditorShell.module.css@@ -1448,7 +1448,8 @@* on each side, frame color per kind, gradient sheen on top. */.zoomPill,.speedPill,-.annotationPill {+.annotationPill,+.skipPill {--_pill: var(--accent);position: absolute;top: 50%;@@ -1486,6 +1487,9 @@.annotationPill {--_pill: var(--annotation);}+.skipPill {+ --_pill: var(--danger);+}.lanePillSelected {box-shadow:0 4px 12px -8px color-mix(in oklch, var(--_pill) 60%, transparent),@@ -1505,7 +1509,9 @@.speedPill::before,.speedPill::after,.annotationPill::before,-.annotationPill::after {+.annotationPill::after,+.skipPill::before,+.skipPill::after {content: "";position: absolute;top: 50%;@@ -1522,12 +1528,14 @@}.zoomPill::before,.speedPill::before,-.annotationPill::before {+.annotationPill::before,+.skipPill::before {left: -4px;}.zoomPill::after,.speedPill::after,-.annotationPill::after {+.annotationPill::after,+.skipPill::after {right: -4px;}.pillIcon {diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex 106571cb2..e8368d801 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -875,6 +875,29 @@ export function NewEditorShell() {hasAsset={hasAsset}videoSources={videoSources}clips={clips}+ zoomRegions={tl.zoomRegions}+ speedRegions={tl.speedRegions}+ skipRanges={tl.skipRanges}+ selectedZoomRegionId={tl.selection?.kind === "zoom" ? tl.selection.id : null}+ onZoomFocusChange={tl.updateZoomFocusLive}+ onZoomFocusCommit={() => void tl.commitZoomFocus()}+ annotationRegions={tl.annotationRegions}+ selectedAnnotationId={tl.selection?.kind === "annotation" ? tl.selection.id : null}+ onSelectAnnotation={(id) => tl.selectRegion("annotation", id)}+ onAnnotationPositionChange={(id, position) => {+ // ponytail: Rnd only calls this once per drag gesture (on+ // dragStop, not on every pointermove), so — unlike the zoom+ // focus overlay — there's no per-frame IPC risk here; commit+ // immediately.+ tl.updateAnnotationLive(id, { position });+ void tl.commitAnnotationChange();+ }}+ onAnnotationSizeChange={(id, size) => {+ tl.updateAnnotationLive(id, { size });+ void tl.commitAnnotationChange();+ }}+ onAnnotationBlurDataChange={(id, blurData) => tl.updateAnnotationLive(id, { blurData })}+ onAnnotationCommit={() => void tl.commitAnnotationChange()}seekTarget={seekTarget}onTimeChange={handleTimeChange}onSeek={handleSeek}diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsxindex 3748dc046..7c816d4ce 100644--- a/src/components/ai-edition/Preview.tsx+++ b/src/components/ai-edition/Preview.tsx@@ -1,16 +1,38 @@import { Maximize2, Pause, Play, Repeat, SkipBack, SkipForward } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";-import type { AxcutClip } from "@/lib/ai-edition/schema";+import type { ZoomFocus } from "@/components/video-editor/types";+import type {+ AxcutAnnotationRegion,+ AxcutClip,+ AxcutSkipRange,+ AxcutZoomRegion,+} from "@/lib/ai-edition/schema";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";import { EditorEmptyState } from "./EditorEmptyState";import styles from "./NewEditorShell.module.css";import { PreviewCanvas } from "./PreviewCanvas";+type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;+interface PreviewProps {hasProject: boolean;hasAsset: boolean;videoSources: import("./VirtualPreview").VideoSource[];clips: AxcutClip[];+ zoomRegions?: AxcutZoomRegion[];+ speedRegions?: SpeedRegion[];+ skipRanges?: AxcutSkipRange[];+ selectedZoomRegionId?: string | null;+ onZoomFocusChange?: (id: string, focus: ZoomFocus) => void;+ onZoomFocusCommit?: () => void;+ annotationRegions?: AxcutAnnotationRegion[];+ selectedAnnotationId?: string | null;+ onSelectAnnotation?: (id: string) => void;+ onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;+ onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;+ onAnnotationBlurDataChange?: (id: string, blurData: BlurData) => void;+ onAnnotationCommit?: () => void;seekTarget: { timeSec: number; requestId: number } | null;onTimeChange: (sec: number) => void;onSeek: (sec: number) => void;@@ -31,6 +53,19 @@ export function Preview({hasAsset,videoSources,clips,+ zoomRegions,+ speedRegions,+ skipRanges,+ selectedZoomRegionId,+ onZoomFocusChange,+ onZoomFocusCommit,+ annotationRegions,+ selectedAnnotationId,+ onSelectAnnotation,+ onAnnotationPositionChange,+ onAnnotationSizeChange,+ onAnnotationBlurDataChange,+ onAnnotationCommit,seekTarget,onTimeChange,onSeek,@@ -149,6 +184,19 @@ export function Preview({<PreviewCanvasvideoSources={videoSources}clips={clips}+ zoomRegions={zoomRegions}+ speedRegions={speedRegions}+ skipRanges={skipRanges}+ selectedZoomRegionId={selectedZoomRegionId}+ onZoomFocusChange={onZoomFocusChange}+ onZoomFocusCommit={onZoomFocusCommit}+ annotationRegions={annotationRegions}+ selectedAnnotationId={selectedAnnotationId}+ onSelectAnnotation={onSelectAnnotation}+ onAnnotationPositionChange={onAnnotationPositionChange}+ onAnnotationSizeChange={onAnnotationSizeChange}+ onAnnotationBlurDataChange={onAnnotationBlurDataChange}+ onAnnotationCommit={onAnnotationCommit}seekTarget={seekTarget}onTimeChange={onTimeChange}onSeek={onSeek}diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsxindex 2859e0091..0e6106cba 100644--- a/src/components/ai-edition/PreviewCanvas.tsx+++ b/src/components/ai-edition/PreviewCanvas.tsx@@ -24,22 +24,50 @@import type { PointerEvent as ReactPointerEvent } from "react";import { useEffect, useMemo, useRef, useState } from "react";-import type { WebcamLayoutPreset, WebcamMaskShape } from "@/components/video-editor/types";-import type { AxcutClip } from "@/lib/ai-edition/schema";+import type {+ WebcamLayoutPreset,+ WebcamMaskShape,+ ZoomFocus,+} from "@/components/video-editor/types";+import type {+ AxcutAnnotationRegion,+ AxcutClip,+ AxcutSkipRange,+ AxcutZoomRegion,+} from "@/lib/ai-edition/schema";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";import {computeCompositeLayout,getWebcamLayoutCssBoxShadow,type WebcamCompositeLayout,} from "@/lib/compositeLayout";import { getCssClipPath } from "@/lib/webcamMaskShapes";+import { getAspectRatioValue } from "@/utils/aspectRatioUtils";+import { AnnotationLayer } from "./AnnotationLayer";import styles from "./NewEditorShell.module.css";import { type VideoSource, VirtualPreview } from "./VirtualPreview";import { WebcamOverlay } from "./WebcamOverlay";+import { ZoomFocusOverlay } from "./ZoomFocusOverlay";++type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;interface PreviewCanvasProps {videoSources: VideoSource[];clips: AxcutClip[];+ zoomRegions?: AxcutZoomRegion[];+ speedRegions?: SpeedRegion[];+ skipRanges?: AxcutSkipRange[];+ selectedZoomRegionId?: string | null;+ onZoomFocusChange?: (id: string, focus: ZoomFocus) => void;+ onZoomFocusCommit?: () => void;+ annotationRegions?: AxcutAnnotationRegion[];+ selectedAnnotationId?: string | null;+ onSelectAnnotation?: (id: string) => void;+ onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;+ onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;+ onAnnotationBlurDataChange?: (id: string, blurData: BlurData) => void;+ onAnnotationCommit?: () => void;seekTarget: { timeSec: number; requestId: number } | null;onTimeChange: (sec: number) => void;onSeek: (sec: number) => void;@@ -61,6 +89,28 @@ export function PreviewCanvas(props: PreviewCanvasProps) {const frameRef = useRef<HTMLDivElement | null>(null);const webcamSlotRef = useRef<HTMLDivElement | null>(null);const [canvasSize, setCanvasSize] = useState({ width: 1280, height: 720 });+ // ponytail: contain-fit the frame within its wrapper ourselves. CSS+ // `aspect-ratio` + `width: 100%` + `max-height: 100%` only clamps height —+ // it never shrinks width back down to match, so portrait ratios (9:16 etc)+ // silently overflowed/stretched instead of fitting. Measuring the parent+ // (not the frame, which we're about to size) lets us compute an explicit+ // pixel box that actually respects the ratio on both axes.+ const [containerSize, setContainerSize] = useState({ width: 1280, height: 720 });++ useEffect(() => {+ const el = frameRef.current?.parentElement;+ if (!el) return;+ const update = () =>+ setContainerSize({+ width: el.clientWidth || 1280,+ height: el.clientHeight || 720,+ });+ update();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(update);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);useEffect(() => {const el = frameRef.current;@@ -77,6 +127,18 @@ export function PreviewCanvas(props: PreviewCanvasProps) {return () => observer.disconnect();}, []);+ const frameSize = useMemo(() => {+ const ratio = getAspectRatioValue(settings.aspectRatio);+ const { width: containerWidth, height: containerHeight } = containerSize;+ if (containerWidth <= 0 || containerHeight <= 0) return { width: containerWidth, height: containerHeight };+ if (containerWidth / containerHeight > ratio) {+ const height = containerHeight;+ return { width: Math.round(height * ratio), height: Math.round(height) };+ }+ const width = containerWidth;+ return { width: Math.round(width), height: Math.round(width / ratio) };+ }, [containerSize, settings.aspectRatio]);+const layout = useMemo(() => {const preset = settings.webcamLayoutPreset as WebcamLayoutPreset;const mask = settings.webcamMaskShape as WebcamMaskShape;@@ -124,10 +186,12 @@ export function PreviewCanvas(props: PreviewCanvasProps) {[layout, settings, canvasSize],);const [isPlaying, setIsPlaying] = useState(false);+ const [videoEl, setVideoEl] = useState<HTMLVideoElement | null>(null);const handleVideoElement = useMemo(() => props.onVideoElement, [props.onVideoElement]);const relayIsPlaying = (el: HTMLVideoElement | null) => {handleVideoElement(el);setIsPlaying(!el?.paused);+ setVideoEl(el);};const relayProps = { ...props, onVideoElement: relayIsPlaying };@@ -170,12 +234,48 @@ export function PreviewCanvas(props: PreviewCanvasProps) {const isPipGrab = settings.webcamLayoutPreset === "picture-in-picture";+ const selectedZoomRegion = props.selectedZoomRegionId+ ? (props.zoomRegions?.find((z) => z.id === props.selectedZoomRegionId) ?? null)+ : null;+return (- <div ref={frameRef} className={styles.previewFrame} style={frameStyle}>+ <div+ ref={frameRef}+ className={styles.previewFrame}+ style={{ ...frameStyle, width: frameSize.width, height: frameSize.height }}+ ><div className={styles.bgBlur} style={blurStyle} aria-hidden />{layout?.screenRect ? (<div className={styles.screenStage} style={screenStyle}><VirtualPreview {...relayProps} videoStyle={videoBorderRadiusStyle(settings)} />+ {selectedZoomRegion && props.onZoomFocusChange ? (+ <ZoomFocusOverlay+ region={selectedZoomRegion}+ isPlaying={isPlaying}+ onFocusChange={props.onZoomFocusChange}+ onFocusCommit={props.onZoomFocusCommit}+ />+ ) : null}+ {props.annotationRegions &&+ props.onSelectAnnotation &&+ props.onAnnotationPositionChange &&+ props.onAnnotationSizeChange &&+ props.onAnnotationBlurDataChange &&+ props.onAnnotationCommit ? (+ <AnnotationLayer+ annotations={props.annotationRegions}+ selectedAnnotationId={props.selectedAnnotationId ?? null}+ currentTimeSec={props.currentTimeSec}+ containerWidth={layout.screenRect.width}+ containerHeight={layout.screenRect.height}+ videoElement={videoEl}+ onSelectAnnotation={props.onSelectAnnotation}+ onPositionChange={props.onAnnotationPositionChange}+ onSizeChange={props.onAnnotationSizeChange}+ onBlurDataChange={props.onAnnotationBlurDataChange}+ onCommit={props.onAnnotationCommit}+ />+ ) : null}</div>) : null}{layout?.webcamRect ? (diff --git a/src/components/ai-edition/RegionTimeline.tsx b/src/components/ai-edition/RegionTimeline.tsxindex a13447a9b..66cc04bbd 100644--- a/src/components/ai-edition/RegionTimeline.tsx+++ b/src/components/ai-edition/RegionTimeline.tsx@@ -31,6 +31,9 @@ const MIN_ITEM_DURATION_MS = 100;interface RegionSpanRef {id: string;+ // ponytail: scopes collision to the same lane — zoom and speed rows are+ // independent tracks, so a zoom over a speed range (or vice versa) is fine.+ rowId: string;start: number;end: number;}@@ -66,20 +69,17 @@ export function RegionTimelineProvider({[safeTotalMs],);- const isCollidable = useCallback(- (id: string) => collidableSpans.some((r) => r.id === id),- [collidableSpans],- );-const hasOverlap = useCallback(- (span: Span, excludeId: string) =>- collidableSpans.some((r) => r.id !== excludeId && span.end > r.start && span.start < r.end),+ (span: Span, excludeId: string, rowId: string) =>+ collidableSpans.some(+ (r) => r.id !== excludeId && r.rowId === rowId && span.end > r.start && span.start < r.end,+ ),[collidableSpans],);const clampToNeighbours = useCallback(- (span: Span, activeItemId: string): Span => {- const siblings = collidableSpans.filter((r) => r.id !== activeItemId);+ (span: Span, activeItemId: string, rowId: string): Span => {+ const siblings = collidableSpans.filter((r) => r.id !== activeItemId && r.rowId === rowId);let { start, end } = span;for (const r of siblings) {if (end > r.start && start < r.start) end = r.start;@@ -99,14 +99,19 @@ export function RegionTimelineProvider({const resolveSpan = useCallback((rawSpan: Span, activeItemId: string): Span | null => {+ // Resolve the active item's row from the collidable set. Annotations+ // are intentionally not in it, so missing here means "no collision+ // rules apply" (annotations may freely overlap).+ const activeRow = collidableSpans.find((r) => r.id === activeItemId)?.rowId;+ if (!activeRow) return clampSpanToBounds(rawSpan);let span = clampSpanToBounds(rawSpan);- if (isCollidable(activeItemId) && hasOverlap(span, activeItemId)) {- span = clampToNeighbours(span, activeItemId);- if (hasOverlap(span, activeItemId)) return null;+ if (hasOverlap(span, activeItemId, activeRow)) {+ span = clampToNeighbours(span, activeItemId, activeRow);+ if (hasOverlap(span, activeItemId, activeRow)) return null;}return span;},- [clampSpanToBounds, clampToNeighbours, hasOverlap, isCollidable],+ [clampSpanToBounds, clampToNeighbours, hasOverlap, collidableSpans],);const [liveSpan, setLiveSpan] = useState<{ id: string; span: Span } | null>(null);@@ -251,7 +256,7 @@ interface RegionItemProps {selected: boolean;/** F2.7 — `additive` is true on shift-click (adds to the multi-selection). */onSelect: (additive: boolean) => void;- variant: "zoom" | "annotation" | "speed";+ variant: "zoom" | "annotation" | "speed" | "skip";}export function RegionItem({@@ -274,7 +279,9 @@ export function RegionItem({? styles.zoomPill: variant === "speed"? styles.speedPill- : styles.annotationPill;+ : variant === "skip"+ ? styles.skipPill+ : styles.annotationPill;return (<divref={setNodeRef}diff --git a/src/components/ai-edition/RightPanelStack.tsx b/src/components/ai-edition/RightPanelStack.tsxindex ed5384e69..6ac5edfe4 100644--- a/src/components/ai-edition/RightPanelStack.tsx+++ b/src/components/ai-edition/RightPanelStack.tsx@@ -9,6 +9,15 @@ import {Trash2,} from "lucide-react";import { useCallback, useEffect, useState } from "react";+import { toast } from "sonner";+import { parseCustomPlaybackSpeedInput } from "@/components/video-editor/customPlaybackSpeed";+import {+ MAX_ZOOM_SCALE,+ MIN_ZOOM_SCALE,+ SPEED_OPTIONS,+ ZOOM_DEPTH_SCALES,+ type ZoomDepth,+} from "@/components/video-editor/types";import type {AxcutAnnotationRegion,AxcutClip,@@ -164,8 +173,28 @@ function RegionInspector({: null;const depthNames = ["1.25×", "1.5×", "1.8×", "2.2×", "3.5×", "5×"];- const currentDepth =- selection.kind === "zoom" ? ((region as { depth?: number })?.depth ?? 3) - 1 : 0;+ const zoomRegion =+ selection.kind === "zoom"+ ? (region as { depth?: ZoomDepth; customScale?: number } | undefined)+ : undefined;+ const zoomDepth = zoomRegion?.depth ?? 3;+ // ponytail: matches main's SettingsPanel `effectiveScale` — a custom slider+ // value overrides the depth preset, so no preset button is highlighted+ // unless the value happens to equal one exactly.+ const effectiveZoomScale = zoomRegion?.customScale ?? ZOOM_DEPTH_SCALES[zoomDepth];+ const currentDepth = depthNames.findIndex(+ (_, i) => ZOOM_DEPTH_SCALES[(i + 1) as ZoomDepth] === effectiveZoomScale,+ );++ const speedValue = selection.kind === "speed" ? ((region as { speed?: number })?.speed ?? 1) : 1;+ // ponytail: mirrors main's CustomSpeedInput — the text field shows a draft+ // string, empty whenever the current value exactly matches a preset (so+ // the input looks "unused" while a preset is active), and only commits on+ // blur/Enter after validating range via parseCustomPlaybackSpeedInput.+ const [speedDraft, setSpeedDraft] = useState("");+ useEffect(() => {+ setSpeedDraft(SPEED_OPTIONS.some((o) => o.speed === speedValue) ? "" : String(speedValue));+ }, [speedValue]);// ponytail: keep rapid text edits in local state and flush on blur so we// don't push an undo snapshot per keystroke.@@ -199,6 +228,30 @@ function RegionInspector({[document, selection.id, setDocument, saveDocument],);+ // Speed regions live outside the schema (`legacyEditor.speedRegions`, see+ // useTimeline.ts) — same escape hatch pattern, so patch it directly here.+ const patchSpeed = useCallback(+ (speed: number) => {+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const prev = ((legacy.speedRegions as unknown[]) ?? []) as Array<{+ id: string;+ startMs: number;+ endMs: number;+ speed: number;+ }>;+ const next = {+ ...document,+ legacyEditor: {+ ...legacy,+ speedRegions: prev.map((s) => (s.id === selection.id ? { ...s, speed } : s)),+ },+ };+ setDocument(next);+ void saveDocument(next);+ },+ [document, selection.id, setDocument, saveDocument],+ );+return (<div style={{ display: "grid", gridTemplateRows: "auto 1fr", minHeight: 0 }}><header className={styles.paneHead}>@@ -256,6 +309,29 @@ function RegionInspector({</button>))}</div>+ <Field label={`Scale — ${effectiveZoomScale.toFixed(2)}×`}>+ <input+ type="range"+ min={MIN_ZOOM_SCALE}+ max={MAX_ZOOM_SCALE}+ step={0.01}+ value={effectiveZoomScale}+ onChange={(e) => {+ if (!region) return;+ const scale = Number(e.target.value);+ const next = document.zoomRanges.map((z) =>+ z.id === selection.id ? { ...z, customScale: scale } : z,+ ) as AxcutDocument["zoomRanges"];+ // ponytail: live-only while dragging — mirrors the+ // zoom-focus-overlay drag fix (setDocument, no IPC+ // save, per pixel). Commits on release below.+ setDocument({ ...document, zoomRanges: next });+ }}+ onMouseUp={() => void saveDocument(document)}+ onTouchEnd={() => void saveDocument(document)}+ style={{ width: "100%" }}+ />+ </Field>{region ? (<divstyle={{@@ -526,13 +602,73 @@ function RegionInspector({Trim region — drag the handles in the timeline to resize. Press Del to remove the cut.</div>) : region ? (- <div- style={{ font: "500 12px var(--font-body)", color: "var(--muted)", padding: "0 4px" }}- >- Speed: {(region as { speed: number }).speed}× ·{" "}- {Math.round((region as { startMs: number }).startMs)}ms—- {(region as { endMs: number }).endMs}ms- </div>+ <>+ <div+ style={{+ font: "500 11px/1.4 var(--font-mono)",+ color: "var(--muted)",+ padding: "0 4px",+ marginBottom: 8,+ }}+ >+ {Math.round((region as { startMs: number }).startMs)}ms —{" "}+ {Math.round((region as { endMs: number }).endMs)}ms+ </div>+ <Field label={`Speed — ${speedValue}×`}>+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(5, 1fr)",+ gap: 6,+ marginBottom: 8,+ }}+ >+ {SPEED_OPTIONS.map((option) => (+ <button+ type="button"+ key={option.label}+ onClick={() => patchSpeed(option.speed)}+ style={{+ padding: "6px 4px",+ border: `1px solid ${speedValue === option.speed ? "var(--accent)" : "var(--border)"}`,+ borderRadius: 8,+ background: speedValue === option.speed ? "var(--accent-wash)" : "var(--bg)",+ color: "var(--fg-2)",+ font: "500 11px/1 var(--font-mono)",+ cursor: "pointer",+ }}+ >+ {option.label}+ </button>+ ))}+ </div>+ <input+ type="text"+ inputMode="decimal"+ placeholder={`${speedValue}×`}+ value={speedDraft}+ onChange={(e) => setSpeedDraft(e.target.value)}+ onBlur={() => {+ const result = parseCustomPlaybackSpeedInput(speedDraft);+ if (result.status === "valid") patchSpeed(result.speed);+ else {+ if (result.status === "too-fast") toast.error("Speed can't exceed 16×.");+ setSpeedDraft(+ SPEED_OPTIONS.some((o) => o.speed === speedValue) ? "" : String(speedValue),+ );+ }+ }}+ onKeyDown={(e) => {+ if (e.key !== "Enter") return;+ const result = parseCustomPlaybackSpeedInput(speedDraft);+ if (result.status === "valid") patchSpeed(result.speed);+ else if (result.status === "too-fast") toast.error("Speed can't exceed 16×.");+ e.currentTarget.blur();+ }}+ style={{ width: "100%" }}+ />+ </Field>+ </>) : null}<buttontype="button"diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex ac0637e66..31916f56e 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -14,10 +14,12 @@ import {Palette,Sliders,} from "lucide-react";-import { type ChangeEvent, type ReactNode, useEffect, useRef, useState } from "react";+import { type ChangeEvent, type ReactNode, useEffect, useMemo, useRef, useState } from "react";+import defaultCursorPreviewUrl from "@/assets/cursors/Cursor=Default.svg";import type { AxcutClip, AxcutTranscript } from "@/lib/ai-edition/schema";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";-import { CURSOR_THEMES } from "@/lib/cursor/cursorThemes";+import { getAssetPath } from "@/lib/assetPath";+import { CURSOR_THEMES, DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes";import { resolveImageWallpaperUrl, WALLPAPER_PATHS } from "@/lib/wallpaper";import styles from "./NewEditorShell.module.css";import { TranscriptEditor } from "./TranscriptEditor";@@ -655,25 +657,39 @@ export function LayoutPane() {// ─── Cursor ───────────────────────────────────────────────────────-const CURSOR_STYLE_LABELS: Array<{ title: string; d: string }> = [- {- title: "Arrow",- d: "M5.5 3.21V20.8c0 .45.54.67.85.35l4.86-4.86 2.94 6.4c.5.1.8-.13.95-.55l1.86-6.4 6.4-1.86c.42-.15.65-.5.55-.95l-6.4-2.94 4.86-4.86c.32-.31.1-.85-.35-.85H5.5z",- },- {- title: "Pointer",- d: "M14 4.1 12 6 M5.1 8l-2.9-.8 M6 12l-1.9 2 M7.2 2.2 8 5.1 M9 11V6a3 3 0 1 1 6 0v5",- },- {- title: "Hand",- d: "M18 11V6a2 2 0 0 0-4 0v5 M14 10V4a2 2 0 0 0-4 0v6 M10 10.5V6a2 2 0 0 0-4 0v8",- },- { title: "Text", d: "M14 4.1 12 6 M5.1 8l-2.9-.8 M6 12l-1.9 2 M7.2 2.2 8 5.1" },- { title: "Cross", d: "M12 2v20M2 12h20" },-];+function safeAssetUrl(relativePath: string): string {+ try {+ return getAssetPath(relativePath);+ } catch {+ return `/${relativePath.replace(/^\/+/, "")}`;+ }+}export function CursorPane() {const { settings, set, setLive, commit, hasDocument } = useEditorSettings();++ // Built-in "Default" plus each bundled theme. Thumbnails use the theme's+ // arrow asset; the persisted value is the theme id. Same shape as the+ // legacy SettingsPanel picker.+ const cursorThemeOptions = useMemo(+ () => [+ {+ id: DEFAULT_CURSOR_THEME_ID,+ name: "Default",+ previewUrl: defaultCursorPreviewUrl,+ },+ ...CURSOR_THEMES.map((theme) => {+ const previewPath = (theme.assets.arrow ?? theme.assets.pointer)?.assetPath;+ return {+ id: theme.id,+ name: theme.name,+ previewUrl: previewPath ? safeAssetUrl(previewPath) : defaultCursorPreviewUrl,+ };+ }),+ ],+ [],+ );+return (<Panetitle="Cursor"@@ -698,20 +714,27 @@ export function CursorPane() {</div><div className={styles.sectionLabel}>Cursor style</div><div className={styles.cursorGrid}>- {CURSOR_THEMES.slice(0, 5).map((theme) => {- const isActive = settings.cursorTheme === theme.id;+ {cursorThemeOptions.map((option) => {+ const isActive = settings.cursorTheme === option.id;return (<buttontype="button"- key={theme.id}+ key={option.id}className={`${styles.cursorCell} ${isActive ? styles.isActive : ""}`}- title={theme.name}+ title={option.name}+ aria-label={option.name}+ aria-pressed={isActive}disabled={!hasDocument}- onClick={() => void set({ cursor: { theme: theme.id } })}+ onClick={() => void set({ cursor: { theme: option.id } })}>- <svg viewBox="0 0 24 24" fill="currentColor" width={18} height={18}>- <path d={CURSOR_STYLE_LABELS[0]?.d ?? ""} />- </svg>+ <img+ src={option.previewUrl}+ alt=""+ width={20}+ height={20}+ draggable={false}+ style={{ objectFit: "contain", pointerEvents: "none" }}+ /></button>);})}diff --git a/src/components/ai-edition/TimelinePane.tsx b/src/components/ai-edition/TimelinePane.tsxindex 8f4ac5cb7..1a498ccd6 100644--- a/src/components/ai-edition/TimelinePane.tsx+++ b/src/components/ai-edition/TimelinePane.tsx@@ -1,13 +1,5 @@import { type Span } from "dnd-timeline";-import {- ChevronLeft,- ChevronRight,- MessageSquare,- Pencil,- Timer,- Trash2,- ZoomIn,-} from "lucide-react";+import { MessageSquare, Pencil, Scissors, Timer, Trash2, ZoomIn } from "lucide-react";import {type DragEvent as ReactDragEvent,type PointerEvent as ReactPointerEvent,@@ -20,7 +12,11 @@ import {} from "react";import type { AxcutClip } from "@/lib/ai-edition/schema";import { startGlobalPointerDrag } from "@/lib/ai-edition/timeline/pointer-drag";-import { formatSeconds, locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";+import {+ formatSeconds,+ locateSourcePosition,+ locateVirtualPosition,+} from "@/lib/ai-edition/timeline/virtual-preview";import {RegionItem,RegionRow,@@ -36,7 +32,6 @@ const MAX_PX_PER_SEC = 280;const MIN_SOURCE_DURATION_SEC = 0.001;const TIMELINE_START_GUTTER_PX = 6;const TIMELINE_END_GUTTER_PX = 6;-const SKIP_CONTROLS_HIDE_DELAY_MS = 220;const CLIP_REORDER_THRESHOLD_PX = 6;const ASSET_MIME = "application/x-axcut-asset";@@ -100,12 +95,6 @@ interface TimelinePaneProps {onMoveClip: (clipId: string, toIndex: number) => void;onEditClip: (clip: AxcutClip) => void;onRemoveClip: (clipId: string) => void;- onUpdateSkipRange: (skipId: string, startSec: number, endSec: number) => void;- // T19 — called during skip-edge resize so the preview video can- // scrub to the edge being dragged. Wire from Bottombar →- // tl.previewSource(timeSec, assetId) (no-op if undefined).- onPreviewSource?: (sourceTimeSec: number, assetId: string) => void;- onRemoveSkipRange: (skipId: string) => void;// T15 — Place-skip callback. Bottombar wires this to// tl.addSkipAt(assetId, sourceStartSec, sourceEndSec) so the timeline// pane can add a skip at the cursor's source position without jumping@@ -134,33 +123,6 @@ interface TimelinePaneProps {onCancelPlaceSkip: () => void;}-type KeepSegment = { kind: "keep"; len: number };-type CutSegment = {- kind: "cut";- len: number;- skipId: string;- startSec: number;- endSec: number;- minStartSec: number;- maxEndSec: number;-};-type Segment = KeepSegment | CutSegment;--// Live state of an in-flight skip-edge resize. Refs are used as a hot-path-// mirror so move handlers read fresh values without re-creating callbacks.-type ResizeState = {- id: number;- itemId: string;- edge: "start" | "end";- startClientX: number;- startSec: number;- endSec: number;- currentStartSec: number;- currentEndSec: number;- minStartSec: number;- maxEndSec: number;-};-// T07 — Pan via Alt+drag or middle-click-drag. Refs only; no state needed// because the visible window updates frequently and the only side-effect is// the cursor class.@@ -194,38 +156,6 @@ function clamp(value: number, min: number, max: number): number {return Math.min(max, Math.max(min, value));}-// Split a clip's source span into keep/cut segments using the asset's skip-// ranges. Cut segments carry the skip id + local drag bounds (clamped to the-// clip's own source span and the neighboring skip) so they can be resized or-// deleted in place — mirrors Axcut's per-clip skip strips.-function clipSegments(clip: AxcutClip, skips: SkipRange[]): Segment[] {- const s0 = clip.sourceStartSec;- const s1 = clip.sourceEndSec ?? s0;- const span = Math.max(0.001, s1 - s0);- const cuts = skips- .filter((k) => k.assetId === clip.assetId && k.endSec > s0 && k.startSec < s1)- .map((k) => ({ skipId: k.id, start: Math.max(s0, k.startSec), end: Math.min(s1, k.endSec) }))- .sort((a, b) => a.start - b.start);- const segs: Segment[] = [];- let cur = s0;- cuts.forEach((c, i) => {- if (c.start > cur) segs.push({ kind: "keep", len: c.start - cur });- segs.push({- kind: "cut",- len: c.end - c.start,- skipId: c.skipId,- startSec: c.start,- endSec: c.end,- minStartSec: i > 0 ? cuts[i - 1].end : s0,- maxEndSec: i < cuts.length - 1 ? cuts[i + 1].start : s1,- });- cur = Math.max(cur, c.end);- });- if (cur < s1) segs.push({ kind: "keep", len: s1 - cur });- if (segs.length === 0) segs.push({ kind: "keep", len: span });- return segs;-}-// Adaptive ruler: major step is the smallest entry in the standard// [0.1..600s] ladder whose px-size ≥ 90. Minor ticks fall at major/4. As// you zoom in the step shrinks; zoom out, it grows.@@ -287,21 +217,13 @@ export function TimelinePane({onMoveClip,onEditClip,onRemoveClip,- onUpdateSkipRange,- onPreviewSource,- onRemoveSkipRange,onAddSkip,onRegionSpanChange,}: TimelinePaneProps) {const viewportRef = useRef<HTMLDivElement | null>(null);- const resizeRef = useRef<ResizeState | null>(null);const panRef = useRef<PanState | null>(null);const clipReorderRef = useRef<ClipReorderState | null>(null);const [viewportWidthPx, setViewportWidthPx] = useState(0);- // T18 — viewportLeftPx + windowWidthPx for viewport-aware controlsShiftPx- // (keeps skip hover-controls onscreen near the viewport edge).- const [viewportLeftPx, setViewportLeftPx] = useState(0);- const [windowWidthPx, setWindowWidthPx] = useState(0);// T16 — tracks whether the user is currently scrubbing so the body// cursor can flip to ew-resize. Cleared on pointerup.const [scrubbing, setScrubbing] = useState(false);@@ -311,18 +233,10 @@ export function TimelinePane({// viewport state is owned by Bottombar (T11). We only mirror it here.const [panning, setPanning] = useState(false);const [clipReorderState, setClipReorderState] = useState<ClipReorderState | null>(null);- const [hoveredCutId, setHoveredCutId] = useState<string | null>(null);- const [dragPreview, setDragPreview] = useState<{- skipId: string;- startSec: number;- endSec: number;- } | null>(null);const [dropIndex, setDropIndex] = useState<number | null>(null);// T15 — place-skip state lives in Bottombar (it owns the body class// + Esc-to-cancel). TimelinePane reads it as a prop to render the// preview marker and dispatch the click.- const hideControlsTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const resizeSequenceRef = useRef(0);const sourceDuration = useMemo(() =>@@ -365,46 +279,32 @@ export function TimelinePane({[assets],);- // T18 — per-skip viewport-aware shift so the hover-controls stay onscreen- // when the skip is near the viewport's left/right edge. axcut- // TimelinePane.tsx builds the same map inline.- const skipControlsShiftPxBySkipId = useMemo(() => {- if (viewportLeftPx <= 0) return new Map<string, number>();- const SKIP_CONTROLS_VIEWPORT_MARGIN_PX = 4;- const visibleLeftPx = SKIP_CONTROLS_VIEWPORT_MARGIN_PX;- const visibleRightPx = Math.max(- visibleLeftPx,- windowWidthPx - SKIP_CONTROLS_VIEWPORT_MARGIN_PX,- );- // Resize=25 + remove=31 + two 3px gaps. Actual values mirror axcut.- const controlsHalfWidthPx = (31 + 25 + 25 + 3 * 3) / 2;- const map = new Map<string, number>();- for (const clip of orderedClips) {- for (const skip of clip.sourceEndSec == null- ? []- : skipRanges.filter((k) => k.assetId === clip.assetId)) {- const skipCenterSec = (skip.startSec + skip.endSec) / 2;- const skipScreenCenterPx =- viewportLeftPx + TIMELINE_START_GUTTER_PX + skipCenterSec * pxPerSec - canvasOffsetPx;- let shift = 0;- if (skipScreenCenterPx - controlsHalfWidthPx < visibleLeftPx) {- shift = visibleLeftPx - (skipScreenCenterPx - controlsHalfWidthPx);- } else if (skipScreenCenterPx + controlsHalfWidthPx > visibleRightPx) {- shift = visibleRightPx - (skipScreenCenterPx + controlsHalfWidthPx);- }- if (shift !== 0) map.set(skip.id, shift);- }+ // Skip ranges are source-time and get their own lane (mirrors main's+ // TrimRegion row) instead of the old in-clip chevron strip. Map each+ // skip's source-time span through whichever clip it falls within to+ // get a timeline(ms) span for the lane — same coordinate space the+ // zoom/speed/annotation lanes already use.+ const skipRegionSpans = useMemo(() => {+ const spans: Array<{ id: string; start: number; end: number; durationSec: number }> = [];+ for (const skip of skipRanges) {+ const startPos = locateSourcePosition(orderedClips, skip.startSec, skip.assetId);+ const endPos = locateSourcePosition(orderedClips, skip.endSec, skip.assetId);+ if (!startPos || !endPos) continue;+ spans.push({+ id: skip.id,+ start: startPos.virtualTimeSec * 1000,+ end: endPos.virtualTimeSec * 1000,+ durationSec: skip.endSec - skip.startSec,+ });}- return map;- }, [orderedClips, skipRanges, pxPerSec, canvasOffsetPx, viewportLeftPx, windowWidthPx]);+ return spans;+ }, [skipRanges, orderedClips]);useEffect(() => {const el = viewportRef.current;if (!el) return;const updateMetrics = () => {setViewportWidthPx(el.clientWidth);- setViewportLeftPx(el.getBoundingClientRect().left);- setWindowWidthPx(window.innerWidth);};updateMetrics();const observer = new ResizeObserver(updateMetrics);@@ -456,7 +356,6 @@ export function TimelinePane({useEffect(() => () => {- if (hideControlsTimerRef.current) clearTimeout(hideControlsTimerRef.current);document.body.classList.remove("timeline-panning");document.body.classList.remove("timeline-reordering");// ponytail: timeline-placing-cut body class is now owned by@@ -486,22 +385,6 @@ export function TimelinePane({[orderedClips, onAddSkip],);- const showCutControls = useCallback((cutId: string) => {- if (hideControlsTimerRef.current) {- clearTimeout(hideControlsTimerRef.current);- hideControlsTimerRef.current = null;- }- setHoveredCutId(cutId);- }, []);-- const scheduleHideCutControls = useCallback((cutId: string) => {- if (hideControlsTimerRef.current) clearTimeout(hideControlsTimerRef.current);- hideControlsTimerRef.current = setTimeout(() => {- setHoveredCutId((current) => (current === cutId ? null : current));- hideControlsTimerRef.current = null;- }, SKIP_CONTROLS_HIDE_DELAY_MS);- }, []);-// Convert screen-x (PointerEvent.clientX) to source-time, accounting for// the canvas's translateX pan offset.const sourceSecFromClientX = useCallback(@@ -836,87 +719,6 @@ export function TimelinePane({],);- // Skip chevron pointerdown → resize the cut's start or end.- const startResizeSkip = useCallback(- (- clipId: string,- seg: CutSegment,- edge: "start" | "end",- event: ReactPointerEvent<HTMLElement>,- ) => {- event.preventDefault();- event.stopPropagation();- const clip = orderedClips.find((c) => c.id === clipId);- if (!clip) return;- const id = resizeSequenceRef.current + 1;- resizeSequenceRef.current = id;- const initial: ResizeState = {- id,- itemId: seg.skipId,- edge,- startClientX: event.clientX,- startSec: seg.startSec,- endSec: seg.endSec,- currentStartSec: seg.startSec,- currentEndSec: seg.endSec,- minStartSec: seg.minStartSec,- maxEndSec: seg.maxEndSec,- };- resizeRef.current = initial;- setDragPreview({ skipId: seg.skipId, startSec: seg.startSec, endSec: seg.endSec });-- startGlobalPointerDrag(event, {- onMove: (moveEvent) => {- const current = resizeRef.current;- if (!current || current.id !== id) return;- const deltaSec = (moveEvent.clientX - current.startClientX) / Math.max(pxPerSec, 0.001);- const nextStartSec =- current.edge === "start"- ? clamp(- current.startSec + deltaSec,- current.minStartSec,- current.currentEndSec - 0.05,- )- : current.currentStartSec;- const nextEndSec =- current.edge === "end"- ? clamp(current.endSec + deltaSec, nextStartSec + 0.05, current.maxEndSec)- : current.currentEndSec;- const next = {- ...current,- currentStartSec: nextStartSec,- currentEndSec: nextEndSec,- };- resizeRef.current = next;- setDragPreview({ skipId: seg.skipId, startSec: nextStartSec, endSec: nextEndSec });- // T19 — scrub the preview video to the edge being- // dragged so the user sees exactly which frame is the- // cut boundary. axcut TimelinePane.tsx startResizeSkip.- onPreviewSource?.(current.edge === "start" ? nextStartSec : nextEndSec, clip.assetId);- },- onEnd: () => {- const current = resizeRef.current;- if (!current || current.id !== id) {- resizeRef.current = null;- setDragPreview(null);- return;- }- const changed =- Math.abs(current.currentStartSec - current.startSec) > 0.001 ||- Math.abs(current.currentEndSec - current.endSec) > 0.001;- resizeRef.current = null;- if (changed) {- onUpdateSkipRange(seg.skipId, current.currentStartSec, current.currentEndSec);- }- requestAnimationFrame(() => {- setDragPreview(null);- });- },- });- },- [orderedClips, onUpdateSkipRange, onPreviewSource, pxPerSec],- );-// T12 — setVisibleWindow helper. Computes the new pxPerSec to fit// [startSec, endSec] into the viewport, derives the matching zoom// multiplier, and updates visibleStartSec + zoom atomically. axcut@@ -1111,14 +913,22 @@ export function TimelinePane({collidableSpans={[...zoomRegions.map((z) => ({id: z.id,+ rowId: "zoom",start: z.startMs,end: z.endMs,})),...speedRegions.map((s) => ({id: s.id,+ rowId: "speed",start: s.startMs,end: s.endMs,})),+ ...skipRegionSpans.map((s) => ({+ id: s.id,+ rowId: "skip",+ start: s.start,+ end: s.end,+ })),]}onItemSpanChange={onRegionSpanChange}>@@ -1153,6 +963,21 @@ export function TimelinePane({/>))}</RegionRow>+ <RegionRow id="skip" empty="No skips">+ {skipRegionSpans.map((s) => (+ <RegionItem+ key={s.id}+ id={s.id}+ rowId="skip"+ span={{ start: s.start, end: s.end }}+ label={formatSeconds(s.durationSec)}+ icon={<Scissors size={11} strokeWidth={2} aria-hidden="true" />}+ selected={isRegionSelected("skip", s.id)}+ onSelect={(additive) => onSelectRegion("skip", s.id, additive)}+ variant="skip"+ />+ ))}+ </RegionRow><RegionRow id="zoom" empty="No zoom regions">{zoomRegions.map((z) => (<RegionItem@@ -1188,15 +1013,6 @@ export function TimelinePane({// even when adjacent. The .joinedPrev / .joinedNext classes are removed// from the rendered classList, and the CSS for them is dropped too.// Adjacent clips keep their own border + border-radius on every side.- const previewedSkips = dragPreview- ? skipRanges.map((k) =>- k.id === dragPreview.skipId- ? { ...k, startSec: dragPreview.startSec, endSec: dragPreview.endSec }- : k,- )- : skipRanges;- const segs = clipSegments(clip, previewedSkips);- const segTotal = segs.reduce((m, s) => m + s.len, 0) || 1;const selected = clip.id === selectedClipId;const classes = [styles.trackBlock];if (selected) classes.push(styles.selected);@@ -1234,82 +1050,11 @@ export function TimelinePane({title={`${assetLabel(clip.assetId)} · ${formatSeconds(clip.timelineStartSec)}–${formatSeconds(clip.timelineEndSec)}`}><div className={styles.trackVisual}>- {segs.map((s, si) =>- s.kind === "keep" ? (- <div- key={si}- className={`${styles.segment} ${styles.keep}`}- aria-hidden="true"- style={{ flexGrow: (s.len / segTotal) * 100 }}- />- ) : (- <div- key={s.skipId}- className={`${styles.segment} ${styles.cut}`}- style={{ flexGrow: (s.len / segTotal) * 100 }}- onPointerEnter={() => showCutControls(s.skipId)}- onPointerLeave={() => scheduleHideCutControls(s.skipId)}- title={`Skip ${formatSeconds(s.startSec)}–${formatSeconds(s.endSec)}`}- >- {hoveredCutId === s.skipId || dragPreview?.skipId === s.skipId ? (- <div- className={styles.skipControls}- style={- skipControlsShiftPxBySkipId.has(s.skipId)- ? ({- "--skip-controls-shift-px": `${skipControlsShiftPxBySkipId.get(s.skipId)}px`,- } as React.CSSProperties)- : undefined- }- onPointerEnter={() => showCutControls(s.skipId)}- onPointerLeave={() => scheduleHideCutControls(s.skipId)}- >- <button- type="button"- className={styles.skipControlBtn}- aria-label={`Adjust skip start at ${formatSeconds(s.startSec)}`}- title="Adjust skip start"- onPointerDown={(e) => startResizeSkip(clip.id, s, "start", e)}- onClick={(e) => e.stopPropagation()}- >- <ChevronLeft size={13} />- </button>- <button- type="button"- className={`${styles.skipControlBtn} ${styles.skipControlDelete}`}- aria-label={`Remove skip ${formatSeconds(s.startSec)}–${formatSeconds(s.endSec)}`}- title="Remove skip"- onPointerDown={(e) => {- // ponytail: stop the clip block's- // startClipReorder from grabbing- // pointer capture and rerouting the- // click up to the block (then- // nowhere). Without this, the trash- // button's onClick never fires.- e.stopPropagation();- }}- onClick={(e) => {- e.stopPropagation();- onRemoveSkipRange(s.skipId);- }}- >- <Trash2 size={12} />- </button>- <button- type="button"- className={styles.skipControlBtn}- aria-label={`Adjust skip end at ${formatSeconds(s.endSec)}`}- title="Adjust skip end"- onPointerDown={(e) => startResizeSkip(clip.id, s, "end", e)}- onClick={(e) => e.stopPropagation()}- >- <ChevronRight size={13} />- </button>- </div>- ) : null}- </div>- ),- )}+ <div+ className={`${styles.segment} ${styles.keep}`}+ aria-hidden="true"+ style={{ flexGrow: 100 }}+ /></div><div className={styles.trackInfo}><button@@ -1384,35 +1129,6 @@ export function TimelinePane({aria-hidden="true"/>) : null}- {/* T24 + T25 — snap-guide lines + floating drag tooltip for- skip-edge resize. Two thin vertical lines in the- ruler (one per edge being dragged) plus a small- pill near the cursor showing the new time range.- Matches axcut TimelinePane.tsx dragPreview styling- and controlsVisible. */}- {dragPreview ? (- <>- <div- className={styles.snapGuide}- style={{ left: TIMELINE_START_GUTTER_PX + dragPreview.startSec * pxPerSec }}- aria-hidden="true"- />- <div- className={styles.snapGuide}- style={{ left: TIMELINE_START_GUTTER_PX + dragPreview.endSec * pxPerSec }}- aria-hidden="true"- />- <div- className={styles.dragTooltip}- style={{- left: TIMELINE_START_GUTTER_PX + (dragPreview.endSec * pxPerSec + 6),- }}- aria-hidden="true"- >- {formatSeconds(dragPreview.startSec)} → {formatSeconds(dragPreview.endSec)}- </div>- </>- ) : null}</div>)}</div>diff --git a/src/components/ai-edition/VirtualPreview.module.css b/src/components/ai-edition/VirtualPreview.module.cssindex 9829585cf..7c9ed195a 100644--- a/src/components/ai-edition/VirtualPreview.module.css+++ b/src/components/ai-edition/VirtualPreview.module.css@@ -15,6 +15,8 @@display: flex;align-items: center;justify-content: center;+ transform-origin: 0 0;+ will-change: transform;}.video {diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex b0e8bca4c..60f8b187f 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -1,12 +1,17 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { fromFileUrl } from "@/components/video-editor/projectPersistence";-import type { AxcutClip } from "@/lib/ai-edition/schema";+import type { AxcutClip, AxcutSkipRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";+import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";import {clampVirtualTime,locateSourcePosition,locateVirtualPosition,totalVirtualDuration,} from "@/lib/ai-edition/timeline/virtual-preview";+import {+ computeZoomPreviewTransform,+ IDENTITY_ZOOM_TRANSFORM,+} from "@/lib/ai-edition/timeline/zoom-preview";import { CursorPreviewLayer } from "./CursorPreviewLayer";import styles from "./VirtualPreview.module.css";@@ -19,6 +24,9 @@ export interface VideoSource {interface VirtualPreviewProps {videoSources: VideoSource[];clips: AxcutClip[];+ zoomRegions?: AxcutZoomRegion[];+ speedRegions?: SpeedRegion[];+ skipRanges?: AxcutSkipRange[];seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;onTimeChange?: (timeSec: number) => void;onLoadedMetadata?: (durationSec: number, assetId: string) => void;@@ -30,6 +38,9 @@ interface VirtualPreviewProps {export function VirtualPreview({videoSources,clips,+ zoomRegions = [],+ speedRegions = [],+ skipRanges = [],seekTarget,onTimeChange,onLoadedMetadata,@@ -38,6 +49,7 @@ export function VirtualPreview({onVideoError,}: VirtualPreviewProps) {const videoRef = useRef<HTMLVideoElement | null>(null);+ const videoFrameRef = useRef<HTMLDivElement | null>(null);const isProgrammaticSeekRef = useRef(false);const pendingSeekRef = useRef<{ sourceTimeSec: number; play: boolean } | null>(null);@@ -83,6 +95,10 @@ export function VirtualPreview({virtualTimeSecRef.current = virtualTimeSec;const virtualDurationSecRef = useRef(virtualDurationSec);virtualDurationSecRef.current = virtualDurationSec;+ const speedRegionsRef = useRef(speedRegions);+ speedRegionsRef.current = speedRegions;+ const skipRangesRef = useRef(skipRanges);+ skipRangesRef.current = skipRanges;// biome-ignore lint/correctness/useExhaustiveDependencies: re-create the rAF when the active source swaps.useEffect(() => {let raf = 0;@@ -93,6 +109,34 @@ export function VirtualPreview({return;}const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;+ // Skip regions only skip ahead during actual playback — mirrors+ // main's videoEventHandlers.ts (findActiveTrimRegion + jump to+ // endMs, gated on `!video.paused`). Scrubbing/paused seeks are+ // intentionally NOT clamped: the user can navigate freely inside+ // a skip while editing; only Play/export treats it as a cut.+ if (!v.paused) {+ const activeSkip = skipRangesRef.current.find(+ (skip) =>+ skip.assetId === activeSourceId &&+ v.currentTime >= skip.startSec &&+ v.currentTime < skip.endSec,+ );+ if (activeSkip) {+ if (activeSkip.endSec >= (v.duration || Infinity)) {+ v.pause();+ } else {+ // ponytail: seeking to exactly `endSec` can land the decoder a+ // hair before it (frame/sample quantization), which still+ // satisfies `currentTime < skip.endSec` — the next tick+ // re-seeks to the same spot, forever, so playback never+ // actually progresses past the skip (looked like a hard+ // stop instead of an invisible cut). A small epsilon past+ // the boundary guarantees each re-check reads past it.+ v.currentTime = activeSkip.endSec + 0.05;+ }+ return;+ }+ }// ponytail: also push setSourceTimeSec every frame (was previously// in a separate rAF effect). Cheap; <video>.readyState >= 2 guards// against drawing a black frame into the cursor overlay.@@ -163,10 +207,46 @@ export function VirtualPreview({(nextTimeSec: number) => {setVirtualTimeSec(nextTimeSec);onTimeChange?.(nextTimeSec);+ // ponytail: mirrors main's per-frame `video.playbackRate = ...`+ // (videoEventHandlers.ts) — the browser does the actual time+ // warping, so this is the only thing speed regions need. No+ // virtual-timeline remap: a sped-up region still occupies its+ // original span on the ruler, it's just played through faster.+ const v = videoRef.current;+ if (v) {+ const activeRegion = findActiveSpeedRegion(+ speedRegionsRef.current,+ Math.round(nextTimeSec * 1000),+ );+ const rate = activeRegion?.speed ?? 1;+ if (v.playbackRate !== rate) v.playbackRate = rate;+ }},[onTimeChange],);+ // Apply the zoom-region transform directly to the DOM (bypassing React+ // render) so it stays in lockstep with the 60 Hz virtual-time updates+ // above without adding a style-prop re-render on every frame.+ useEffect(() => {+ const frame = videoFrameRef.current;+ if (!frame) return;+ // ponytail: scale the zoom-in/out transition windows by the current+ // playback rate so the transition stays wall-clock constant inside+ // speed regions. The cursor still flies through (ruler + playhead+ // read source-time), only the easing duration is decoupled.+ const activeSpeedRegion = findActiveSpeedRegion(+ speedRegionsRef.current,+ Math.round(virtualTimeSec * 1000),+ );+ const playbackRate = activeSpeedRegion?.speed ?? 1;+ const transform =+ zoomRegions.length === 0+ ? IDENTITY_ZOOM_TRANSFORM+ : computeZoomPreviewTransform(zoomRegions, virtualTimeSec * 1000, undefined, playbackRate);+ frame.style.transform = `translate(${transform.translateXPercent}%, ${transform.translateYPercent}%) scale(${transform.scale})`;+ }, [zoomRegions, virtualTimeSec]);+const seekToVirtualTime = useCallback((nextVirtualTimeSec: number, preservePlayback = false) => {const position = locateVirtualPosition(clips, nextVirtualTimeSec);@@ -227,7 +307,7 @@ export function VirtualPreview({return (<div className={styles.container}>{activeSource ? (- <div className={styles.videoFrame}>+ <div ref={videoFrameRef} className={styles.videoFrame}><videokey={activeSource.src}ref={videoRef}diff --git a/src/components/ai-edition/ZoomFocusOverlay.module.css b/src/components/ai-edition/ZoomFocusOverlay.module.cssnew file mode 100644index 000000000..f0f549bfc--- /dev/null+++ b/src/components/ai-edition/ZoomFocusOverlay.module.css@@ -0,0 +1,15 @@+.overlay {+ position: absolute;+ inset: 0;+ z-index: 30;+ user-select: none;+ touch-action: none;+}++.indicator {+ position: absolute;+ border: 1px solid rgba(52, 178, 123, 0.8);+ background: rgba(52, 178, 123, 0.2);+ border-radius: 6px;+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.25);+}diff --git a/src/components/ai-edition/ZoomFocusOverlay.tsx b/src/components/ai-edition/ZoomFocusOverlay.tsxnew file mode 100644index 000000000..adf1dd827--- /dev/null+++ b/src/components/ai-edition/ZoomFocusOverlay.tsx@@ -0,0 +1,125 @@+// Draggable rectangle that lets the user reposition a zoom region's focus+// point directly on the preview, mirroring the legacy editor's Pixi overlay+// (`src/components/video-editor/VideoPlayback.tsx` + `videoPlayback/overlayUtils.ts`)+// but as a plain CSS overlay div — the new editor's preview has no Pixi stage.+//+// The rectangle's size reflects the zoom crop window (1/zoomScale of the+// stage), not just a crosshair, so the user sees exactly what will be+// visible once zoomed in.++import type { PointerEvent as ReactPointerEvent } from "react";+import { useCallback, useRef } from "react";+import { getZoomScale, type ZoomFocus } from "@/components/video-editor/types";+import { getFocusBoundsForScale } from "@/components/video-editor/videoPlayback/focusUtils";+import type { AxcutZoomRegion } from "@/lib/ai-edition/schema";+import styles from "./ZoomFocusOverlay.module.css";++interface ZoomFocusOverlayProps {+ region: AxcutZoomRegion;+ isPlaying: boolean;+ /** Called on every pointermove while dragging — must be cheap/local-only. */+ onFocusChange: (id: string, focus: ZoomFocus) => void;+ /** Called once on pointer release to persist the final position. */+ onFocusCommit?: () => void;+}++function clamp01(v: number): number {+ return Math.min(1, Math.max(0, v));+}++export function ZoomFocusOverlay({+ region,+ isPlaying,+ onFocusChange,+ onFocusCommit,+}: ZoomFocusOverlayProps) {+ const overlayRef = useRef<HTMLDivElement | null>(null);+ const draggingRef = useRef(false);++ const updateFromClientPoint = useCallback(+ (clientX: number, clientY: number) => {+ const el = overlayRef.current;+ if (!el) return;+ const rect = el.getBoundingClientRect();+ if (!rect.width || !rect.height) return;++ const zoomScale = getZoomScale(region);+ const bounds = getFocusBoundsForScale(zoomScale);+ const cx = clamp01((clientX - rect.left) / rect.width);+ const cy = clamp01((clientY - rect.top) / rect.height);++ onFocusChange(region.id, {+ cx: Math.min(bounds.maxX, Math.max(bounds.minX, cx)),+ cy: Math.min(bounds.maxY, Math.max(bounds.minY, cy)),+ });+ },+ [region, onFocusChange],+ );++ const handlePointerDown = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ if (isPlaying || region.focusMode === "auto") return;+ event.preventDefault();+ draggingRef.current = true;+ event.currentTarget.setPointerCapture(event.pointerId);+ updateFromClientPoint(event.clientX, event.clientY);+ },+ [isPlaying, region.focusMode, updateFromClientPoint],+ );++ const handlePointerMove = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ if (!draggingRef.current) return;+ event.preventDefault();+ updateFromClientPoint(event.clientX, event.clientY);+ },+ [updateFromClientPoint],+ );++ const endDrag = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ if (!draggingRef.current) return;+ draggingRef.current = false;+ try {+ event.currentTarget.releasePointerCapture(event.pointerId);+ } catch {+ // pointer already released+ }+ onFocusCommit?.();+ },+ [onFocusCommit],+ );++ // Auto-follow (cursor-driven) regions have no user-placed focus point.+ if (region.focusMode === "auto") return null;++ const zoomScale = getZoomScale(region);+ const widthPercent = Math.min(100, (1 / zoomScale) * 100);+ const heightPercent = Math.min(100, (1 / zoomScale) * 100);+ const rawLeft = clamp01(region.focus.cx) * 100 - widthPercent / 2;+ const rawTop = clamp01(region.focus.cy) * 100 - heightPercent / 2;+ const left = Math.min(100 - widthPercent, Math.max(0, rawLeft));+ const top = Math.min(100 - heightPercent, Math.max(0, rawTop));++ return (+ <div+ ref={overlayRef}+ className={styles.overlay}+ style={{ pointerEvents: isPlaying ? "none" : "auto", cursor: isPlaying ? "default" : "move" }}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={endDrag}+ onPointerLeave={endDrag}+ >+ <div+ className={styles.indicator}+ style={{+ width: `${widthPercent}%`,+ height: `${heightPercent}%`,+ left: `${left}%`,+ top: `${top}%`,+ }}+ />+ </div>+ );+}diff --git a/src/components/video-editor/videoPlayback/zoomRegionUtils.ts b/src/components/video-editor/videoPlayback/zoomRegionUtils.tsindex 34fceffe7..54edfbe2e 100644--- a/src/components/video-editor/videoPlayback/zoomRegionUtils.ts+++ b/src/components/video-editor/videoPlayback/zoomRegionUtils.ts@@ -13,6 +13,7 @@ type DominantRegionOptions = {connectZooms?: boolean;cursorTelemetry?: CursorTelemetryPoint[];viewportRatio?: ViewportRatio;+ playbackRate?: number;};type ConnectedRegionPair = {@@ -38,17 +39,30 @@ function easeConnectedPan(value: number) {return cubicBezier(0.1, 0.0, 0.2, 1.0, value);}-export function computeRegionStrength(region: ZoomRegion, timeMs: number) {+// ponytail: `playbackRate` lets the caller scale the lead-in / lead-out+// windows in source-time so the zoom transition stays wall-clock constant+// inside speed regions (2× speed → window is 2× source-ms → takes 1×+// wall-clock-ms to traverse). Hold span between `zoomInEnd` and+// `region.endMs` stays in source-time, so the zoomed state still flies+// through under speed regions — that's the duration the user expects+// to scale.+export function computeRegionStrength(+ region: ZoomRegion,+ timeMs: number,+ playbackRate = 1,+): number {+ const zoomInWindow = ZOOM_IN_TRANSITION_WINDOW_MS * playbackRate;+ const zoomOutWindow = TRANSITION_WINDOW_MS * playbackRate;const zoomInEnd = region.startMs + ZOOM_IN_OVERLAP_MS;- const leadInStart = zoomInEnd - ZOOM_IN_TRANSITION_WINDOW_MS;- const leadOutEnd = region.endMs + TRANSITION_WINDOW_MS;+ const leadInStart = zoomInEnd - zoomInWindow;+ const leadOutEnd = region.endMs + zoomOutWindow;if (timeMs < leadInStart || timeMs > leadOutEnd) {return 0;}if (timeMs < zoomInEnd) {- const progress = (timeMs - leadInStart) / ZOOM_IN_TRANSITION_WINDOW_MS;+ const progress = (timeMs - leadInStart) / zoomInWindow;return easeOutScreenStudio(progress);}@@ -56,7 +70,7 @@ export function computeRegionStrength(region: ZoomRegion, timeMs: number) {return 1;}- const progress = clamp01((timeMs - region.endMs) / TRANSITION_WINDOW_MS);+ const progress = clamp01((timeMs - region.endMs) / zoomOutWindow);return 1 - easeOutScreenStudio(progress);}@@ -126,6 +140,7 @@ function getActiveRegion(connectedPairs: ConnectedRegionPair[],cursorTelemetry?: CursorTelemetryPoint[],viewportRatio?: ViewportRatio,+ playbackRate = 1,) {const activeRegions = regions.map((region) => {@@ -139,7 +154,7 @@ function getActiveRegion(return { region, strength: 0 };}- return { region, strength: computeRegionStrength(region, timeMs) };+ return { region, strength: computeRegionStrength(region, timeMs, playbackRate) };}).filter((entry) => entry.strength > 0).sort((left, right) => {@@ -276,6 +291,7 @@ type DominantRegionResult = {let dominantRegionCache: {regions: ZoomRegion[];timeMsKey: number;+ playbackRateKey: number;telemetry: CursorTelemetryPoint[] | undefined;connectZooms: boolean;viewportRatio: ViewportRatio | undefined;@@ -290,7 +306,9 @@ export function findDominantRegion(const connectZooms = !!options.connectZooms;const telemetry = options.cursorTelemetry;const vr = options.viewportRatio;+ const playbackRate = options.playbackRate ?? 1;const timeMsKey = Math.round(timeMs);+ const playbackRateKey = Math.round(playbackRate * 1000);if (dominantRegionCache &&@@ -298,7 +316,8 @@ export function findDominantRegion(dominantRegionCache.timeMsKey === timeMsKey &&dominantRegionCache.telemetry === telemetry &&dominantRegionCache.connectZooms === connectZooms &&- dominantRegionCache.viewportRatio === vr+ dominantRegionCache.viewportRatio === vr &&+ dominantRegionCache.playbackRateKey === playbackRateKey) {return dominantRegionCache.result;}@@ -315,7 +334,14 @@ export function findDominantRegion(if (connectedHold) {result = { ...connectedHold, transition: null };} else {- const activeRegion = getActiveRegion(regions, timeMs, connectedPairs, telemetry, vr);+ const activeRegion = getActiveRegion(+ regions,+ timeMs,+ connectedPairs,+ telemetry,+ vr,+ playbackRate,+ );result = activeRegion? { ...activeRegion, transition: null }: {@@ -328,7 +354,14 @@ export function findDominantRegion(}}} else {- const activeRegion = getActiveRegion(regions, timeMs, connectedPairs, telemetry, vr);+ const activeRegion = getActiveRegion(+ regions,+ timeMs,+ connectedPairs,+ telemetry,+ vr,+ playbackRate,+ );result = activeRegion? { ...activeRegion, transition: null }: {@@ -343,6 +376,7 @@ export function findDominantRegion(dominantRegionCache = {regions,timeMsKey,+ playbackRateKey,telemetry,connectZooms,viewportRatio: vr,diff --git a/src/lib/ai-edition/annotations/blurEffects.ts b/src/lib/ai-edition/annotations/blurEffects.tsnew file mode 100644index 000000000..7c0fe3ea8--- /dev/null+++ b/src/lib/ai-edition/annotations/blurEffects.ts@@ -0,0 +1,53 @@+// Port of `src/lib/blurEffects.ts` (the preview-facing helpers only —+// `applyMosaicToImageData` is export-pipeline-only and unused by the live+// preview, so it isn't ported here).++import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";+import {+ DEFAULT_BLUR_BLOCK_SIZE,+ DEFAULT_BLUR_INTENSITY,+ MAX_BLUR_BLOCK_SIZE,+ MAX_BLUR_INTENSITY,+ MIN_BLUR_BLOCK_SIZE,+ MIN_BLUR_INTENSITY,+} from "./constants";++type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;+type BlurColor = BlurData["color"];++function clamp(value: number, min: number, max: number) {+ if (!Number.isFinite(value)) return min;+ return Math.min(max, Math.max(min, value));+}++export function normalizeBlurColor(value: unknown): BlurColor {+ return value === "black" ? "black" : "white";+}++export function getNormalizedBlurIntensity(blurData?: BlurData | null): number {+ return clamp(+ blurData?.intensity ?? DEFAULT_BLUR_INTENSITY,+ MIN_BLUR_INTENSITY,+ MAX_BLUR_INTENSITY,+ );+}++export function getNormalizedMosaicBlockSize(blurData?: BlurData | null, scaleFactor = 1): number {+ const rawBlockSize = clamp(+ blurData?.blockSize ?? DEFAULT_BLUR_BLOCK_SIZE,+ MIN_BLUR_BLOCK_SIZE,+ MAX_BLUR_BLOCK_SIZE,+ );+ return Math.max(1, Math.round(rawBlockSize * Math.max(scaleFactor, 0.01)));+}++export function getBlurOverlayColor(blurData?: BlurData | null): string {+ const blurColor = normalizeBlurColor(blurData?.color);+ return blurColor === "black" ? "rgba(0, 0, 0, 0.72)" : "rgba(255, 255, 255, 0.06)";+}++export function getMosaicGridOverlayColor(blurData?: BlurData | null): string {+ return normalizeBlurColor(blurData?.color) === "black"+ ? "rgba(255,255,255,0.05)"+ : "rgba(255,255,255,0.04)";+}diff --git a/src/lib/ai-edition/annotations/constants.ts b/src/lib/ai-edition/annotations/constants.tsnew file mode 100644index 000000000..3f4ae8081--- /dev/null+++ b/src/lib/ai-edition/annotations/constants.ts@@ -0,0 +1,57 @@+// Defaults ported verbatim from `src/components/video-editor/types.ts` so+// newly-created annotations look identical between the legacy and new editor.++import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";++type AnnotationStyle = AxcutAnnotationRegion["style"];+type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;+type FigureData = NonNullable<AxcutAnnotationRegion["figureData"]>;++export const DEFAULT_ANNOTATION_POSITION = { x: 50, y: 50 };+export const DEFAULT_ANNOTATION_SIZE = { width: 30, height: 20 };++export const DEFAULT_ANNOTATION_STYLE: AnnotationStyle = {+ color: "#ffffff",+ backgroundColor: "transparent",+ fontSize: 32,+ fontFamily: "Inter",+ fontWeight: "bold",+ fontStyle: "normal",+ textDecoration: "none",+ textAlign: "center",+ textAnimation: "none",+};++export const DEFAULT_FIGURE_DATA: FigureData = {+ arrowDirection: "right",+ color: "#34B27B",+ strokeWidth: 4,+};++export const MIN_BLUR_INTENSITY = 2;+export const MAX_BLUR_INTENSITY = 40;+export const DEFAULT_BLUR_INTENSITY = 12;+export const MIN_BLUR_BLOCK_SIZE = 4;+export const MAX_BLUR_BLOCK_SIZE = 48;+export const DEFAULT_BLUR_BLOCK_SIZE = 12;++export const DEFAULT_BLUR_FREEHAND_POINTS: Array<{ x: number; y: number }> = [+ { x: 10, y: 30 },+ { x: 25, y: 10 },+ { x: 55, y: 8 },+ { x: 82, y: 20 },+ { x: 90, y: 45 },+ { x: 78, y: 72 },+ { x: 52, y: 90 },+ { x: 22, y: 84 },+ { x: 8, y: 58 },+];++export const DEFAULT_BLUR_DATA: BlurData = {+ type: "mosaic",+ shape: "rectangle",+ color: "white",+ intensity: DEFAULT_BLUR_INTENSITY,+ blockSize: DEFAULT_BLUR_BLOCK_SIZE,+ freehandPoints: DEFAULT_BLUR_FREEHAND_POINTS,+};diff --git a/src/lib/ai-edition/annotations/textAnimation.ts b/src/lib/ai-edition/annotations/textAnimation.tsnew file mode 100644index 000000000..0f3826aed--- /dev/null+++ b/src/lib/ai-edition/annotations/textAnimation.ts@@ -0,0 +1,109 @@+// Port of `src/lib/annotationTextAnimation.ts` — pure, no Pixi/React deps,+// copied verbatim (only the annotation param type changed to structurally+// match `AxcutAnnotationRegion` instead of the legacy `AnnotationRegion`).++export type AnnotationTextAnimation =+ | "none"+ | "fade"+ | "rise"+ | "pop"+ | "slide-left"+ | "typewriter"+ | "pulse";++export const TEXT_ANIMATION_DURATION_MS = 700;++export interface TextAnimationState {+ opacity: number;+ scale: number;+ translateX: number;+ translateY: number;+ revealProgress: number;+}++const TEXT_ANIMATION_VALUES: AnnotationTextAnimation[] = [+ "none",+ "fade",+ "rise",+ "pop",+ "slide-left",+ "typewriter",+ "pulse",+];++function clamp(value: number, min = 0, max = 1) {+ return Math.min(max, Math.max(min, value));+}++function easeOutCubic(value: number) {+ const t = clamp(value);+ return 1 - (1 - t) ** 3;+}++function easeOutBack(value: number) {+ const t = clamp(value);+ const c1 = 1.70158;+ const c3 = c1 + 1;+ return 1 + c3 * (t - 1) ** 3 + c1 * (t - 1) ** 2;+}++export function normalizeTextAnimation(value: unknown): AnnotationTextAnimation {+ return TEXT_ANIMATION_VALUES.includes(value as AnnotationTextAnimation)+ ? (value as AnnotationTextAnimation)+ : "none";+}++export function getTextAnimationState(+ annotation: { startMs: number; style: { textAnimation?: string } },+ currentTimeMs: number,+): TextAnimationState {+ const animation = normalizeTextAnimation(annotation.style.textAnimation);+ if (animation === "none") {+ return { opacity: 1, scale: 1, translateX: 0, translateY: 0, revealProgress: 1 };+ }++ const elapsedMs = Math.max(0, currentTimeMs - annotation.startMs);+ const progress = clamp(elapsedMs / TEXT_ANIMATION_DURATION_MS);+ const eased = easeOutCubic(progress);++ switch (animation) {+ case "fade":+ return { opacity: eased, scale: 1, translateX: 0, translateY: 0, revealProgress: 1 };+ case "rise":+ return {+ opacity: eased,+ scale: 1,+ translateX: 0,+ translateY: (1 - eased) * 18,+ revealProgress: 1,+ };+ case "pop":+ return {+ opacity: eased,+ scale: Math.max(0.72, easeOutBack(progress)),+ translateX: 0,+ translateY: 0,+ revealProgress: 1,+ };+ case "slide-left":+ return {+ opacity: eased,+ scale: 1,+ translateX: (1 - eased) * -28,+ translateY: 0,+ revealProgress: 1,+ };+ case "typewriter":+ return { opacity: 1, scale: 1, translateX: 0, translateY: 0, revealProgress: progress };+ case "pulse":+ return {+ opacity: 1,+ scale: 1 + Math.sin(progress * Math.PI) * 0.06,+ translateX: 0,+ translateY: 0,+ revealProgress: 1,+ };+ default:+ return { opacity: 1, scale: 1, translateX: 0, translateY: 0, revealProgress: 1 };+ }+}diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex 4d5c871fc..2c6c9c8e6 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -34,6 +34,7 @@ export function useTimeline() {const projectId = useProjectStore((s) => s.projectId);const currentTimeSec = useProjectStore((s) => s.currentTimeSec);const saveDocument = useProjectStore((s) => s.saveDocument);+ const setDocument = useProjectStore((s) => s.setDocument);const [selection, setSelection] = useState<RegionHandle | null>(null);// F2.7 — shift-click multi-selection. `selection` stays the inspector's// focused region (the last one clicked); `multiSelection` is the full set@@ -209,6 +210,33 @@ export function useTimeline() {[document, saveDocument],);+ // ponytail: the focus overlay drags at pointermove frequency (~60-120 Hz).+ // Routing every frame through `saveDocument` (IPC round-trip + disk write+ // + zod re-parse + full store replace) made dragging visibly laggy.+ // `updateZoomFocusLive` mirrors `useEditorSettings`'s setLive/commit split:+ // local-only store writes while dragging, one persisted save on release.+ const updateZoomFocusLive = useCallback(+ (id: string, focus: { cx: number; cy: number }) => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ const clamp01 = (n: number) => (Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0.5);+ const next: AxcutDocument = {+ ...doc,+ zoomRanges: doc.zoomRanges.map((z) =>+ z.id === id ? { ...z, focus: { cx: clamp01(focus.cx), cy: clamp01(focus.cy) } } : z,+ ) as AxcutDocument["zoomRanges"],+ };+ setDocument(next);+ },+ [setDocument],+ );++ const commitZoomFocus = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ await saveDocument(doc);+ }, [saveDocument]);+const updateAnnotationSpan = useCallback(async (id: string, startMs: number, endMs: number) => {if (!document) return;@@ -226,6 +254,28 @@ export function useTimeline() {[document, saveDocument],);+ // Drag/resize on the preview overlay (position, size, blur mask edits) — same+ // live/commit split as updateZoomFocusLive/commitZoomFocus, for the same+ // reason: local-only writes while dragging, one persisted save on release.+ const updateAnnotationLive = useCallback(+ (id: string, patch: Partial<AxcutDocument["annotations"][number]>) => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ const next: AxcutDocument = {+ ...doc,+ annotations: doc.annotations.map((a) => (a.id === id ? { ...a, ...patch } : a)),+ };+ setDocument(next);+ },+ [setDocument],+ );++ const commitAnnotationChange = useCallback(async () => {+ const doc = useProjectStore.getState().document;+ if (!doc) return;+ await saveDocument(doc);+ }, [saveDocument]);+const updateSpeedSpan = useCallback(async (id: string, startMs: number, endMs: number) => {if (!document) return;@@ -749,7 +799,11 @@ export function useTimeline() {clearClipSelection,updateSkipRange,updateZoomSpan,+ updateZoomFocusLive,+ commitZoomFocus,updateAnnotationSpan,+ updateAnnotationLive,+ commitAnnotationChange,updateSpeedSpan,// T19 — drives the preview video during skip-edge resize.setCurrentTime: useProjectStore((s) => s.setCurrentTime),diff --git a/src/lib/ai-edition/timeline/speed.ts b/src/lib/ai-edition/timeline/speed.tsnew file mode 100644index 000000000..765edb6a2--- /dev/null+++ b/src/lib/ai-edition/timeline/speed.ts@@ -0,0 +1,18 @@+// Port of `findActiveSpeedRegion` from+// `src/components/video-editor/videoPlayback/videoEventHandlers.ts` — main+// applies speed by literally setting `<video>.playbackRate` every frame from+// whichever region contains the current time (first match wins on overlap),+// leaving the browser to do the actual time-warping. No virtual-timeline+// remap: a sped-up region still occupies its original span on the ruler,+// it's just played through faster — same behavior ported here.++export interface SpeedRegion {+ id: string;+ startMs: number;+ endMs: number;+ speed: number;+}++export function findActiveSpeedRegion(regions: SpeedRegion[], timeMs: number): SpeedRegion | null {+ return regions.find((region) => timeMs >= region.startMs && timeMs < region.endMs) ?? null;+}diff --git a/src/lib/ai-edition/timeline/zoom-preview.ts b/src/lib/ai-edition/timeline/zoom-preview.tsnew file mode 100644index 000000000..a73846f2a--- /dev/null+++ b/src/lib/ai-edition/timeline/zoom-preview.ts@@ -0,0 +1,91 @@+// Live-preview zoom transform for the new editor's CSS-based preview stack.+//+// Reuses the legacy editor's region math (`findDominantRegion`,+// `computeZoomTransform`) so zoom-in/out easing, region priority, and focus+// resolution stay identical between the two editors — only the output+// differs: a CSS translate/scale pair instead of a Pixi container transform.+//+// `computeZoomTransform` is called with a unit stage ({width:1, height:1}),+// which makes its pixel-space output already a fraction of the preview+// box — exactly what CSS `translate(x%, y%)` expects (percentages resolve+// against the transformed element's own layout box).++import type {+ CursorTelemetryPoint,+ ZoomRegion as LegacyZoomRegion,+} from "@/components/video-editor/types";+import { getZoomScale } from "@/components/video-editor/types";+import { findDominantRegion } from "@/components/video-editor/videoPlayback/zoomRegionUtils";+import { computeZoomTransform } from "@/components/video-editor/videoPlayback/zoomTransform";+import type { AxcutZoomRegion } from "@/lib/ai-edition/schema";++export interface ZoomPreviewTransform {+ scale: number;+ translateXPercent: number;+ translateYPercent: number;+}++export const IDENTITY_ZOOM_TRANSFORM: ZoomPreviewTransform = {+ scale: 1,+ translateXPercent: 0,+ translateYPercent: 0,+};++const UNIT_STAGE = { width: 1, height: 1 };+const UNIT_MASK = { x: 0, y: 0, width: 1, height: 1 };++function toLegacyZoomRegion(region: AxcutZoomRegion): LegacyZoomRegion {+ return {+ id: region.id,+ startMs: region.startMs,+ endMs: region.endMs,+ depth: region.depth,+ focus: region.focus,+ focusMode: region.focusMode,+ rotationPreset: region.rotationPreset,+ customScale: region.customScale,+ source: region.source,+ };+}++/**+ * Resolves the zoom transform to apply to the preview at a given point on+ * the virtual (edited) timeline. `virtualTimeMs` must be in the same+ * coordinate space as `zoomRegion.startMs`/`endMs` (the timeline shown in+ * the ruler, not raw source-media time).+ *+ * `playbackRate` scales the zoom-in/out transition windows in source-time+ * so the transition keeps its authored wall-clock duration inside speed+ * regions. Defaults to 1 (no scaling).+ */+export function computeZoomPreviewTransform(+ zoomRegions: AxcutZoomRegion[],+ virtualTimeMs: number,+ cursorTelemetry?: CursorTelemetryPoint[],+ playbackRate = 1,+): ZoomPreviewTransform {+ if (zoomRegions.length === 0) return IDENTITY_ZOOM_TRANSFORM;++ const legacyRegions = zoomRegions.map(toLegacyZoomRegion);+ const dominant = findDominantRegion(legacyRegions, virtualTimeMs, {+ cursorTelemetry,+ playbackRate,+ });+ if (!dominant.region || dominant.strength <= 0) return IDENTITY_ZOOM_TRANSFORM;++ const zoomScale = dominant.blendedScale ?? getZoomScale(dominant.region);+ const transform = computeZoomTransform({+ stageSize: UNIT_STAGE,+ baseMask: UNIT_MASK,+ zoomScale,+ zoomProgress: dominant.strength,+ focusX: dominant.region.focus.cx,+ focusY: dominant.region.focus.cy,+ });++ return {+ scale: transform.scale,+ translateXPercent: transform.x * 100,+ translateYPercent: transform.y * 100,+ };+}