What does MediaGalleryItem's VideoContent subcomponent look like? Read src/shared/components/MediaGalleryItem/components/ to see VideoContent implementation. Does it already support HoverScrubVideo or similar scrubbing?
What does MediaGalleryItem NOT have that VideoItem does? Specifically:
Collage mode (showing segment grid for parent generations)
HoverScrubVideo with scrubbing
Mobile video preloading (hidden video element creation)
Apply settings from task button
The custom memo comparator
What does VideoItem NOT have that MediaGalleryItem does? (shot management, drag-drop, progressive loading, star toggle, etc.)
Look at the VideoGallery/index.tsx to understand what data shape it works with (GenerationRow) vs what MediaGalleryItem expects (GeneratedImageWithMetadata). How different are these types?
Read the relevant files to answer these questions thoroughly.
Assistant
I'll systematically explore these files to understand the relationship between VideoItem and MediaGalleryItem.
Assistant
Now let me read the VideoGallery consumer and FinalVideoSection to see how VideoItem is used:
Assistant
Now let me check the types used by both components:
Assistant
Let me check the GenerationRow and GeneratedImageWithMetadata definitions:
Assistant
User
I need to understand the useShareGeneration hook that MediaGalleryItem uses for sharing. Read these files:
src/shared/hooks/useShareGeneration.ts - The full hook implementation, its API, params, and return values
src/shared/components/MediaGalleryItem.tsx - Just check how it calls useShareGeneration (around line 148) and how it uses the returned values in the share button JSX
Also check: Does VideoItem.tsx import or reference useShareGeneration anywhere? Search for "useShareGeneration" across the codebase to see all consumers.
I need to know:
What params useShareGeneration takes
What it returns
Whether VideoItem's inline share logic does anything extra that useShareGeneration doesn't cover (e.g., the sanitizeTaskDataForSharing function, the slug generation with retry, the batch share slug cache via existingShareSlug/onShareCreated props)
Assistant
I'll help you understand the useShareGeneration hook and how it's used across the codebase. Let me gather the necessary information.
Assistant
Now let me check VideoItem.tsx to see how it handles sharing:
User
I'm planning to refactor VideoItem.tsx (1500 lines) to reduce its size. I need to understand two large self-contained blocks:
Mobile video preloading (lines ~413-556 in VideoItem.tsx):
How does the window.mobileVideoPreloadMap work?
Who calls the preload functions stored in that map? Search for mobileVideoPreloadMap across the codebase.
Is this still actively used or could it be dead code?
Join clips functionality (lines ~115-354 in VideoItem.tsx):
The child generation fetching effect
The join modal and handleConfirmJoin
Could this be extracted to a hook like useJoinClips(video, projectId, projectAspectRatio) that returns { childGenerations, shouldShowJoinButton, canJoinClips, showJoinModal, setShowJoinModal, handleJoinClipsClick, joinSettings, JoinClipsModal }?
Also check: Are there any other consumers of join clips logic elsewhere? Search for createJoinClipsTask imports and join_clips references to understand if this pattern exists elsewhere.
Read the relevant sections of VideoItem.tsx and search for these patterns.
Assistant
I'll analyze VideoItem.tsx and search for these patterns to help you understand the refactoring opportunities.
Assistant
Now let me check the FinalVideoSection.tsx to see if it uses useShareGeneration:
Assistant
Now let me search for more details on how the mobile preload map is used in the parent component and examine the other join clips patterns:
Assistant
Excellent! Now let me check the JoinClipsPage to see if there's a complete example of join clips usage:
Assistant
Assistant
User
Assistant
I'll explore the codebase thoroughly to understand the current state, existing patterns, and dependencies before designing the plan.
Assistant
Now let me explore the existing hook patterns, the join clips implementations elsewhere, and the directory structure.
Assistant
Let me now explore the MediaGalleryItem's usage of useShareGeneration more closely, plus look at how the hook's barrel file is organized.
Assistant
Now let me look at how the existing useShareGeneration is used with MediaGalleryItem, specifically to understand the reset effect behavior and whether the hook already supports initial slugs.
Assistant
Let me check the parent gallery to understand how existingShareSlug and onShareCreated are passed.
Assistant
Now let me look at the JoinClipsSettingsForm to understand the modal extraction target.
Assistant
Now let me check the parent gallery's use of the preload map to understand that integration.
Assistant
Now let me look at how many lines the rendering JSX is (post-extraction estimate) and check for any other patterns I should be aware of.
Assistant
Let me also quickly check the rendering portion of VideoItem to understand the remaining size after extractions and whether further extraction is warranted.
Assistant
Perfect! Now I have all the information needed. Let me create a comprehensive analysis document.
Comprehensive Analysis: VideoItem vs MediaGalleryItem Replacement Feasibility
Based on my thorough code exploration, here's a detailed analysis addressing all your questions:
1. Shared Components Used by Both
Both VideoItem and MediaGalleryItem use these shared components:
Shared:
HoverScrubVideo - for video scrubbing interaction
TimeStamp - for creation time display
VariantBadge - for showing variant counts and "new" indicators
Tooltip/TooltipProvider/TooltipContent - for help text
VideoItem expects full params object for apply settings + join clips logic
MediaGalleryItem uses metadata (DisplayableMetadata) - a pre-extracted, safe subset
MediaGalleryItem has all_shot_associations array (for multi-shot images)
MediaGalleryItem has urlIdentity & thumbUrlIdentity for stable comparison
VideoItem has parent_generation_id, child_order (join clips specific)
The type mismatch is significant - VideoItem reads raw params to extract task data, while MediaGalleryItem uses pre-processed metadata. This is intentional for security (metadata sanitization).
8. Data Shape Differences in VideoGallery
VideoGallery uses GenerationRow:
Fetched via useVideoOutputs(shotId) which wraps useShotImages
Returns timeline order (oldest first)
Must be client-side sorted by date (lines 423-433)
Includes full params for task reconstruction
MediaGallery uses GeneratedImageWithMetadata:
Fetched via dedicated query with metadata transformation
Already filtered/mapped to safe structures
Includes urlIdentity for stable URL comparison
Processed for display-safe metadata
Why this matters:
VideoItem needs location || imageUrl to be reliable for all cases
MediaGalleryItem normalizes this into single url field
VideoItem's join clips needs to inspect params directly
MediaGalleryItem never exposes raw params to components
VERDICT: Replacement is NOT Feasible
Critical Blockers:
Join Clips is Travel-Specific (~240 lines)
Creates parent_generation_id relationships
Manages segment deduplication logic
Forms full task params
This feature is only used in VideoGallery context
Mobile Preloading is Custom Optimization (~140 lines)
Registers functions in global window.mobileVideoPreloadMap
Not applicable to image gallery context
Solves iOS autoplay budget issue specific to travel tool
Parent components expect different callback shapes
Custom Memo Comparator
VideoItem has sophisticated equality check for refetch patterns
MediaGalleryItem doesn't need this (no 5-second refetches)
Would be unnecessary overhead
Practical Consequences:
If you merged them:
VideoGallery would bundle 500+ lines of shot management UI it never uses
MediaGallery would bundle 240 lines of join clips logic unused
Mobile preloading complexity would confuse the shared component
Type system would become a union mess trying to handle both GenerationRow and GeneratedImageWithMetadata
Custom comparator logic would apply unnecessarily to image galleries
Recommendation:
Keep them separate. They have fundamentally different purposes:
VideoItem: Single-purpose tool-specific component for video gallery with join clips + mobile optimization
MediaGalleryItem: Multi-purpose gallery component for mixed image/video with shot management
Extract shared video rendering logic (HoverScrubVideo, VideoContent) into a reusable VideoItemDisplay or similar, but keep the container components separate.
Perfect! Now I have all the information I need. Let me compile a comprehensive analysis for you.
VideoItem does NOT use the useShareGeneration hook at all. Instead, it implements sharing entirely inline with duplicated logic. Here's what VideoItem adds that useShareGeneration doesn't directly expose:
VideoItem does NOT use this hook - implements sharing inline instead.
Why This Duplication Exists
VideoItem needs:
Batch slug caching via existingShareSlug prop (prevents refetching in galleries with 100+ videos)
Parent notification via onShareCreated callback (updates parent's share slug cache)
Independence from hook's automatic reset logic (doesn't want to lose slug when list updates)
The hook's automatic reset on dependency change works fine for single-item scenarios (MediaGalleryItem, FinalVideoSection) but breaks batch operations where you want to reuse slugs across renders.
Now I have all the information I need. Let me provide a comprehensive analysis:
Supports both legacy (2-video) and new multi-clip orchestration
Already has good separation of concerns
Pattern Analysis:
There are two different join clips patterns in the codebase:
Component
Approach
Complexity
Reusability
JoinClipsPage
Standalone full-featured tool
High
Low (purpose-built)
useJoinSegmentsHandler
Shot-context aware hook
High
Medium (specific to ShotEditor)
VideoItem
Embedded inline logic
Low
Low (currently not reusable)
Insight: The useJoinSegmentsHandler from ShotEditor is actually a better template for refactoring VideoItem's logic than building from scratch. It shows:
How to validate clips
How to manage settings with updateField/updateFields
How to integrate with incoming tasks
How to handle LoRA managers (not needed in VideoItem, but shows extensibility)
4. RECOMMENDATION SUMMARY
Component
Status
Recommendation
Mobile preload map
Active, not dead
Keep as-is (works well, low maintenance)
Join clips logic
Extractable
Create useJoinClips hook (~200 LOC)
Reuse patterns
Inconsistent
Use useJoinSegmentsHandler pattern as template
Next Steps for Refactoring:
Extract join clips logic to src/shared/hooks/useJoinClips.ts
Keep join settings (prompt, frames, etc.) as simple useState calls or extract to useJoinClipsSettings if shared
VideoItem becomes much simpler (remove lines 115-354, replace with hook call)
Consider whether useJoinSegmentsHandler should be harmonized with the new hook for consistency
Uses createJoinClipsTask from src/shared/lib/tasks/joinClips.ts
A similar pattern exists in useJoinSegmentsHandler.ts (ShotEditor's version)
Plan: Extract to useJoinClips(video, projectId, projectAspectRatio) hook + JoinClipsModal component
3. Mobile Video Preloading (~140 lines, lines 413-556)
Creates hidden video elements for iOS autoplay budget
Registers preload functions in window.mobileVideoPreloadMap
Called by parent gallery's handleMobilePreload
Plan: Extract to useMobileVideoPreload(video, index, originalIndex, isMobile, onMobilePreload) hook
Constraints
Must preserve the existing prop API of VideoItem (no changes to parent components)
Must preserve the custom React.memo comparator
Hooks must be called before any early returns (Rules of Hooks)
Follow existing patterns in the codebase: hooks go in the same directory or shared hooks
The join clips modal JSX (~140 lines) should become a standalone component
Questions for the plan:
Where should the extracted hooks live? Options:
a. src/tools/travel-between-images/components/VideoGallery/hooks/ (co-located with VideoItem)
b. src/shared/hooks/ (if reusable)
For the join clips hook + modal: Since join clips is used in 3 places (VideoItem, ShotEditor, JoinClipsPage), should the hook go in shared?
Should the mobile preload hook stay tool-specific (it uses a global window map pattern)?
After these extractions, VideoItem should drop from ~1504 to ~800-900 lines. The refactoring_patterns.md says hooks >1000 lines need splitting, components >600 lines. Should we do further extraction of the remaining rendering logic (collage mode, mobile poster mode, desktop video mode)?
Please design a concrete implementation plan with file paths, extraction boundaries, and ordering.
Now I have a thorough understanding of all the pieces. Let me design the plan.
Here is the complete implementation plan for refactoring VideoItem.tsx from 1504 lines down to approximately 800-900 lines through three targeted extractions, plus an assessment of whether further extraction is warranted.
Implementation Plan: VideoItem.tsx Refactoring
Overview
The file has three self-contained concerns to extract, ordered by dependency safety:
Phase 1: Extend useShareGeneration to Support VideoItem's Needs
Problem: VideoItem reimplements ~240 lines of share logic (lines 108-111, 130-135, 559-797) that is nearly identical to the shared useShareGeneration hook. The two key differences are:
VideoItem receives existingShareSlug from the parent (batch-fetched) and needs to seed the hook's state with it
VideoItem calls onShareCreated to update the parent's batch cache when a new share is created
The hook's reset effect (setShareSlug(null) on generationId/shotId change) would wipe a batch-fetched slug
File to modify: /Users/user_c042661f/Documents/reigh/src/shared/hooks/useShareGeneration.ts
Changes:
Add an optional options parameter to useShareGeneration:
Note on taskMapping dependency: The current VideoItem code checks taskMapping?.taskId before calling share logic. The shared hook already handles taskId being null/undefined gracefully (it skips task data fetch). The only nuance is that VideoItem's inline code shows a toast "Task information not available" when taskMapping?.taskId is missing. The shared hook shows "Generation information not available" when generationId is missing. Since VideoItem always has a generationId (it is the video.id), and the hook already handles missing taskId by making the task fetch optional, this is compatible. If we want the VideoItem-specific "Task information not available" toast, we can either:
(a) Accept the hook's behavior (it will attempt to share without task data, which is the correct behavior), or
(b) Guard the share button visibility on taskMapping?.taskId in JSX (already done at line 1296), making the toast unreachable anyway.
Option (a) is correct -- the button is already hidden when there is no taskMapping.
Phase 2: Extract useMobileVideoPreload Hook
Problem: Lines 416-556 (~140 lines) manage mobile video preloading -- creating hidden video elements, registering in a global window map, cleanup on unmount. This is self-contained DOM manipulation logic.
New file: /Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/VideoGallery/hooks/useMobileVideoPreload.ts
Location rationale: This hook uses a window.mobileVideoPreloadMap pattern specific to the VideoGallery. It is not reusable outside this tool. Co-locating with the existing hooks in VideoGallery/hooks/ follows the established pattern (sibling to useVideoLoader.ts, useThumbnailLoader.ts, etc.).
Cleanup effect on unmount/video change (lines 518-531)
handleMobilePreload callback (lines 538-540)
Window map registration effect (lines 543-556)
Key detail: The declare global { interface Window { mobileVideoPreloadMap? ... } } declaration should move to a shared types file or stay in the hook file. Since it is already duplicated in both VideoItem.tsx and index.tsx, moving it to the hook file is the right place (the parent gallery file can import the type or keep its own declaration since it only reads from the map).
Update barrel: Add to /Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/VideoGallery/hooks/index.ts:
typescript
export { useMobileVideoPreload } from './useMobileVideoPreload';
3a. New hook: /Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/VideoGallery/hooks/useVideoItemJoinClips.ts
Location rationale: The ShotEditor's useJoinSegmentsHandler is significantly more complex (LoRA support, incoming tasks, segment slots, advanced phase config). VideoItem's join is a simplified version for quick joins from the gallery. The two implementations serve different UX contexts and have different prop shapes. Making them share code would require significant abstraction that provides little value. Keep the VideoItem version co-located in VideoGallery/hooks/.
Extraction boundary: Move the Dialog JSX from lines 1151-1290. This is a pure presentational component.
Update barrel: Add to VideoGallery/hooks/index.ts:
typescript
export { useVideoItemJoinClips } from './useVideoItemJoinClips';
Lines removed from VideoItem: ~366 (hook state/logic) + ~140 (modal JSX) = ~366 total (the modal JSX count is already included in the hook's scope since it replaces inline JSX with <JoinClipsModal ... />).
Phase 4 Assessment: Further Rendering Extraction
After phases 1-3, the estimated line count breakdown:
Section
Lines (approx)
Imports + interface + memo wrapper start
~100
Remaining hooks (videoLoader, thumbnailLoader, element integration, transition state, aspect ratio)
This is above the 600-line component guideline but within acceptable range. The action buttons panel (lines 1292-1451, ~160 lines) is the most extractable remaining piece. However, I would recommend deferring further extraction to a follow-up for these reasons:
The action buttons have tight coupling to many state values (settingsApplied, taskMapping, share state, deletingVideoId) -- extracting them means passing 15+ props or creating a context.
The three render modes (collage/mobile/desktop) are mutually exclusive branches, not independent components with their own state.
At ~740 lines post-extraction, the component is within a reasonable range and the remaining code is mostly render logic (not complex business logic).
If you want to go further, the best candidate is extracting the action buttons into a VideoItemActions component, similar to how MediaGalleryItem extracts its ActionButtons into /Users/user_c042661f/Documents/reigh/src/shared/components/MediaGalleryItem/components/ActionButtons.tsx. This would remove ~160 lines.
Implementation Order and Dependencies
code
Phase 1: useShareGeneration extension
|
+-- No dependency on other phases
|
Phase 2: useMobileVideoPreload extraction
|
+-- No dependency on other phases
|
Phase 3: useVideoItemJoinClips + JoinClipsModal
|
+-- No dependency on other phases
|
Phase 4 (optional): VideoItemActions component
|
+-- Depends on Phase 1 (share state is provided by hook)
Phases 1, 2, and 3 are independent and can be done in any order. I recommend the order listed (1, 2, 3) because:
Phase 1 tests the shared hook modification with minimal risk
Phase 2 is a clean mechanical extraction
Phase 3 is the largest change and benefits from confidence built in prior phases
Answers to Your Specific Questions
Q1: Where should extracted hooks live?
Share hook: Already in src/shared/hooks/useShareGeneration.ts -- just extend it. Used by both MediaGalleryItem and VideoItem.
Mobile preload hook: src/tools/travel-between-images/components/VideoGallery/hooks/useMobileVideoPreload.ts -- co-located. Not reusable outside this gallery.
Join clips hook: src/tools/travel-between-images/components/VideoGallery/hooks/useVideoItemJoinClips.ts -- co-located. The VideoItem's simplified join is specific to gallery context.
Q2: Should the join clips hook go in shared?
No. The three join implementations serve different contexts with different complexity levels:
JoinClipsPage (src/tools/join-clips/): Full standalone tool with file upload, DnD reorder, per-transition prompts, clip metadata extraction
VideoItem: Simplified quick-join from gallery with basic settings modal
They all call the same createJoinClipsTask from src/shared/lib/tasks/joinClips.ts, which is where the shared logic correctly lives. The orchestration above that shared task creator is appropriately different per context.
Q3: Should mobile preload stay tool-specific?
Yes. The window.mobileVideoPreloadMap pattern is specific to how VideoGallery coordinates preloading between parent and child components. No other gallery uses this pattern (MediaGallery uses a completely different image loading pipeline). Keep it in VideoGallery/hooks/.
Q4: Should we do further extraction beyond the three?
Probably not in this PR. At ~740 lines post-extraction, VideoItem is within acceptable limits for a component that handles three distinct render modes and has a custom memo comparator. If you want to go further, extract the action buttons panel into a VideoItemActions component as a follow-up.
Critical Files for Implementation
/Users/user_c042661f/Documents/reigh/src/shared/hooks/useShareGeneration.ts - Extend with options parameter for initial slug and callback
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/VideoGallery/components/VideoItem.tsx - Primary refactoring target, remove extracted code and wire up new hooks/components
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/VideoGallery/hooks/index.ts - Update barrel exports for new hooks
/Users/user_c042661f/Documents/reigh/src/shared/components/MediaGalleryItem.tsx - Verify no regression in existing useShareGeneration usage (read-only validation)
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/ShotEditor/hooks/useJoinSegmentsHandler.ts - Reference pattern for join clips hook structure