import React, { useState, useEffect, useCallback } from 'react' import type { Project, Sequence } from '@adobe/premierepro' import type { LinkedSequenceAsset } from '../types/link' import { getActiveProject, getActiveSequence, getAllSequences, openSequenceInTimeline, getPremiereModule, } from '../services/premiere' import { getAllLinkedSequences, normalizeGuid, removeSequenceLink } from '../services/linkStorage' import { fetchAssetComments, syncCommentsToSequence } from '../services/markers' import { resolveAssetUrl, isSameEndpoint } from '../utils/url' import { formatDateAgo } from '../utils/date' import { ProgressCircle } from '@swc-react/progress-circle' export interface SequencesViewProps { endpoint: string apiKey: string onLinkCountChange?: (count: number) => void } export const SequencesView: React.FC = ({ endpoint, apiKey, onLinkCountChange, }) => { const [project, setProject] = useState(null) const [activeSeq, setActiveSeq] = useState(null) const [allSeqs, setAllSeqs] = useState([]) const [linkedSequences, setLinkedSequences] = useState([]) const [loading, setLoading] = useState(true) const [syncingGuid, setSyncingGuid] = useState(null) const [unlinkingGuid, setUnlinkingGuid] = useState(null) const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null) const loadData = useCallback(async () => { try { const pr = await getActiveProject() setProject(pr) if (!pr) { setActiveSeq(null) setAllSeqs([]) setLinkedSequences([]) onLinkCountChange?.(0) return } const [currentActive, seqsList] = await Promise.all([ getActiveSequence(pr), getAllSequences(pr), ]) setActiveSeq(currentActive) setAllSeqs(seqsList) const allLinks = await getAllLinkedSequences(pr, seqsList) // Hide foreign links entirely: only show sequences linked to the current endpoint const currentServerLinks = allLinks.filter( (link) => !link.endpoint || isSameEndpoint(link.endpoint, endpoint), ) setLinkedSequences(currentServerLinks) onLinkCountChange?.(currentServerLinks.length) } catch (err) { console.error('[SequencesView] Failed to load sequences data:', err) } finally { setLoading(false) } }, [endpoint, onLinkCountChange]) useEffect(() => { void loadData() // Listen for sequence activation events in Premiere Pro const ppro = getPremiereModule() if (ppro?.EventManager && ppro.Constants?.SequenceEvent?.ACTIVATED) { const handleActivated = () => { void loadData() } try { ppro.EventManager.addGlobalEventListener( ppro.Constants.SequenceEvent.ACTIVATED, handleActivated, true, ) return () => { try { ppro.EventManager.removeGlobalEventListener( ppro.Constants.SequenceEvent.ACTIVATED, handleActivated, ) } catch { // Ignore error on unmount } } } catch (err) { console.warn('[SequencesView] Could not add SequenceEvent listener:', err) } } }, [loadData]) const showToast = (type: 'success' | 'error', message: string, duration = 4000) => { setToast({ type, message }) setTimeout(() => { setToast((prev) => (prev?.message === message ? null : prev)) }, duration) } // Sync Now handler const handleSyncNow = async (link: LinkedSequenceAsset) => { if (!project || syncingGuid) return if (link.endpoint && !isSameEndpoint(link.endpoint, endpoint)) { showToast( 'error', `Cannot sync comments: sequence was linked to "${link.endpoint}". Connect to that server to sync.`, 5000, ) return } const targetSeq = allSeqs.find((s) => normalizeGuid(s.guid) === normalizeGuid(link.sequenceGuid)) || (await getAllSequences(project)).find( (s) => normalizeGuid(s.guid) === normalizeGuid(link.sequenceGuid), ) if (!targetSeq) return setSyncingGuid(link.sequenceGuid) try { const comments = await fetchAssetComments(endpoint, apiKey, link.assetId) const { updatedLink, addedCount } = await syncCommentsToSequence( project, targetSeq, comments, link, ) setLinkedSequences((prev) => prev.map((item) => normalizeGuid(item.sequenceGuid) === normalizeGuid(updatedLink.sequenceGuid) ? updatedLink : item, ), ) showToast( 'success', addedCount > 0 ? `Synced ${addedCount} new comment ${addedCount === 1 ? 'marker' : 'markers'} for "${link.sequenceName}".` : `All comments are already synced for "${link.sequenceName}".`, ) } catch (err) { console.error('[SequencesView] Failed to sync comments:', err) showToast( 'error', err instanceof Error ? err.message : 'Failed to sync comments from server.', 5000, ) } finally { setSyncingGuid(null) } } // Unlink handler const handleUnlink = async (link: LinkedSequenceAsset) => { if (!project || unlinkingGuid) return const targetSeq = allSeqs.find((s) => normalizeGuid(s.guid) === normalizeGuid(link.sequenceGuid)) || (await getAllSequences(project)).find( (s) => normalizeGuid(s.guid) === normalizeGuid(link.sequenceGuid), ) if (!targetSeq) return setUnlinkingGuid(link.sequenceGuid) try { await removeSequenceLink(project, targetSeq) setLinkedSequences((prev) => { const next = prev.filter( (item) => normalizeGuid(item.sequenceGuid) !== normalizeGuid(link.sequenceGuid), ) onLinkCountChange?.(next.length) return next }) showToast('success', `Unlinked "${link.sequenceName}" from "${link.assetName}".`, 3000) } catch (err) { console.error('[SequencesView] Failed to unlink sequence:', err) showToast('error', 'Failed to unlink sequence.', 4000) } finally { setUnlinkingGuid(null) } } // Open Sequence in Timeline handler const handleOpenSequence = async (link: LinkedSequenceAsset) => { if (!project) return const targetSeq = allSeqs.find((s) => normalizeGuid(s.guid) === normalizeGuid(link.sequenceGuid)) || (await getAllSequences(project)).find( (s) => normalizeGuid(s.guid) === normalizeGuid(link.sequenceGuid), ) if (!targetSeq) return await openSequenceInTimeline(targetSeq, project) setActiveSeq(targetSeq) } const renderToast = () => { if (!toast) return null const isError = toast.type === 'error' return (
{isError ? ( ) : ( )} {toast.message}
) } if (loading) { return (
) } const activeGuidStr = normalizeGuid(activeSeq?.guid) const currentSequenceLink = linkedSequences.find( (item) => normalizeGuid(item.sequenceGuid) === activeGuidStr, ) if (linkedSequences.length === 0) { return (
{renderToast()}
No Linked Sequences
{activeSeq ? `Active sequence "${activeSeq.name}" is not linked to any Shumai asset.` : 'Open a sequence in Premiere Pro and link it to a Shumai asset.'}
Linking a sequence enables automatic synchronization of comments from Shumai as timeline markers.
) } return (
{/* Toast Notification */} {renderToast()} {/* SECTION 1: Current Sequence Asset */}
Current Sequence Asset
{currentSequenceLink ? (
{currentSequenceLink.assetThumbnailUrl ? ( {currentSequenceLink.assetName} ) : ( )}
{currentSequenceLink.sequenceName} Active
Asset: {currentSequenceLink.assetName}
handleSyncNow(currentSequenceLink)} > {syncingGuid === currentSequenceLink.sequenceGuid ? ( ) : ( )} handleUnlink(currentSequenceLink)} > {unlinkingGuid === currentSequenceLink.sequenceGuid ? ( ) : ( )}
{currentSequenceLink.totalCommentsSynced}{' '} {currentSequenceLink.totalCommentsSynced === 1 ? 'comment' : 'comments'} synced Last sync: {formatDateAgo(currentSequenceLink.lastSyncAt) || 'Just now'}
) : (
{activeSeq ? activeSeq.name : 'No Active Sequence'}
{activeSeq ? 'This sequence is not linked to any Shumai asset.' : 'Open a sequence in the timeline to view its linked asset.'}
)}
{/* SECTION 2: All Sequence Assets */}
All Sequence Assets ({linkedSequences.length})
{linkedSequences.map((link) => { const isActive = normalizeGuid(link.sequenceGuid) === activeGuidStr const isSyncing = syncingGuid === link.sequenceGuid const isUnlinking = unlinkingGuid === link.sequenceGuid return (
{link.assetThumbnailUrl ? ( {link.assetName} ) : ( )}
{link.sequenceName} {isActive && ( Active )}
Asset: {link.assetName}
{!isActive && ( handleOpenSequence(link)} > )} handleSyncNow(link)} > {isSyncing ? ( ) : ( )} handleUnlink(link)} > {isUnlinking ? ( ) : ( )}
{link.totalCommentsSynced}{' '} {link.totalCommentsSynced === 1 ? 'comment' : 'comments'} synced Last sync: {formatDateAgo(link.lastSyncAt) || 'Just now'}
) })}
) }