A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
Play,
Pause,
RotateCcw,
Trash2,
ChevronLeft,
ChevronRight,
X,
} from 'lucide-react';
import { AnimationTimeline as TimelineData, LayerItem, AnimationExportFormat } from '../types/editor';
import { useDocumentStore } from '../stores';
import {
exportAnimationToGif,
exportAnimationToApng,
exportAnimationToVideo,
exportAnimationToPngZip,
saveAnimationBlob,
} from '../utils/animationEngine';
import { isImeComposing, useI18n } from '../i18n';
export interface AnimationTimelineProps {
timeline: TimelineData;
onChangeTimeline: (timeline: TimelineData) => void;
layers: LayerItem[];
dimensions: { width: number; height: number };
onAddCel: (frameIndex: number) => void;
onDeleteCel: (frameIndex: number) => void;
onSelectCelLayer?: (layerId: string) => void;
onClose?: () => void;
}
export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
timeline,
onChangeTimeline,
layers,
dimensions,
onAddCel,
onDeleteCel,
onSelectCelLayer,
onClose,
}) => {
const { t } = useI18n();
const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
const [isPlaying, setIsPlaying] = useState<boolean>(false);
const [showOnionSettings, setShowOnionSettings] = useState<boolean>(false);
const [showExportModal, setShowExportModal] = useState<boolean>(false);
const [exportFormat, setExportFormat] = useState<AnimationExportFormat>('gif');
const [isExporting, setIsExporting] = useState<boolean>(false);
const [exportProgress, setExportProgress] = useState<string>('');
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const scrubberRef = useRef<HTMLDivElement | null>(null);
const playTimerRef = useRef<number | null>(null);
const timelineRef = useRef<TimelineData>(timeline);
timelineRef.current = timeline;
const onChangeTimelineRef = useRef(onChangeTimeline);
onChangeTimelineRef.current = onChangeTimeline;
// Playback timer loop
useEffect(() => {
if (!isPlaying) {
if (playTimerRef.current !== null) {
clearInterval(playTimerRef.current);
playTimerRef.current = null;
}
return;
}
const intervalMs = Math.max(10, Math.round(1000 / Math.max(1, timeline.fps)));
playTimerRef.current = window.setInterval(() => {
const curr = timelineRef.current;
const nextFrame =
curr.currentFrame + 1 >= curr.totalFrames
? curr.loop
? 0
: curr.totalFrames - 1
: curr.currentFrame + 1;
onChangeTimelineRef.current({
...curr,
currentFrame: nextFrame,
});
if (!curr.loop && curr.currentFrame + 1 >= curr.totalFrames) {
setIsPlaying(false);
}
}, intervalMs);
return () => {
if (playTimerRef.current !== null) {
clearInterval(playTimerRef.current);
playTimerRef.current = null;
}
};
}, [isPlaying, timeline.fps]);
// Synchronize active cel layer when frame changes
useEffect(() => {
const celId = timeline.cels[timeline.currentFrame];
if (celId && onSelectCelLayer) {
onSelectCelLayer(celId);
}
}, [timeline.currentFrame, timeline.cels, onSelectCelLayer]);
const scrubCleanupRef = useRef<(() => void) | null>(null);
useEffect(() => {
return () => {
scrubCleanupRef.current?.();
scrubCleanupRef.current = null;
};
}, []);
// Handle Scrub Click/Drag
const handleScrub = useCallback((clientX: number) => {
if (!scrubberRef.current) return;
const rect = scrubberRef.current.getBoundingClientRect();
if (rect.width <= 0) return;
const curr = timelineRef.current;
const totalFrames = Math.max(1, curr.totalFrames);
const clickX = Math.max(0, Math.min(rect.width, clientX - rect.left));
const frameRatio = clickX / rect.width;
const newFrame = Math.max(0, Math.min(totalFrames - 1, Math.floor(frameRatio * totalFrames)));
onChangeTimelineRef.current({
...curr,
currentFrame: newFrame,
});
}, []);
const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
e.preventDefault();
scrubCleanupRef.current?.();
handleScrub(e.clientX);
const onPointerMove = (ev: PointerEvent) => handleScrub(ev.clientX);
const cleanup = () => {
window.removeEventListener('pointermove', onPointerMove);
window.removeEventListener('pointerup', cleanup);
window.removeEventListener('pointercancel', cleanup);
if (scrubCleanupRef.current === cleanup) {
scrubCleanupRef.current = null;
}
};
scrubCleanupRef.current = cleanup;
window.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerup', cleanup);
window.addEventListener('pointercancel', cleanup);
};
// Keyboard navigation shortcuts (Alt+Space anywhere, or Space when timeline has focus, avoiding canvas Space-pan collision)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
const target = e.target as HTMLElement | null;
if (
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
target?.isContentEditable ||
document.querySelector('[role="dialog"]')
) {
return;
}
if (e.code === 'Space') {
if (e.repeat || e.ctrlKey || e.metaKey) return;
const isTimelineFocused = Boolean(
timelineRootRef.current && document.activeElement && timelineRootRef.current.contains(document.activeElement)
);
if (e.altKey || isTimelineFocused) {
e.preventDefault();
setIsPlaying((p) => !p);
}
return;
}
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return;
if (e.code === 'ArrowLeft') {
e.preventDefault();
onChangeTimeline({
...timeline,
currentFrame: Math.max(0, timeline.currentFrame - 1),
});
} else if (e.code === 'ArrowRight') {
e.preventDefault();
onChangeTimeline({
...timeline,
currentFrame: Math.min(timeline.totalFrames - 1, timeline.currentFrame + 1),
});
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [timeline, onChangeTimeline]);
// Export Action
const handleExport = async () => {
setIsExporting(true);
setExportProgress(t('Encoding frames...'));
try {
const onProgress = (current: number, total: number) => {
setExportProgress(t('Rendering {current}/{total}...', { current, total }));
};
let blob: Blob;
let filename = `animation_${Date.now()}`;
if (exportFormat === 'gif') {
blob = await exportAnimationToGif(timeline, layers, dimensions, onProgress, activeDocumentId);
filename += '.gif';
} else if (exportFormat === 'apng') {
blob = await exportAnimationToApng(timeline, layers, dimensions, onProgress, activeDocumentId);
filename += '.png';
} else if (exportFormat === 'webm' || exportFormat === 'mp4') {
blob = await exportAnimationToVideo(timeline, layers, dimensions, onProgress, activeDocumentId);
filename += exportFormat === 'mp4' ? '.mp4' : '.webm';
} else {
blob = await exportAnimationToPngZip(timeline, layers, dimensions, onProgress, activeDocumentId);
filename += '.zip';
}
const saveRes = await saveAnimationBlob(blob, filename);
if (saveRes.canceled) {
return;
}
setShowExportModal(false);
} catch (err) {
console.error('[Animation Export Failed]:', err);
} finally {
setIsExporting(false);
setExportProgress('');
}
};
const currentCelId = timeline.cels[timeline.currentFrame];
const currentCelLayer = currentCelId ? layers.find((l) => l.id === currentCelId) : null;
return (
<div
ref={timelineRootRef}
data-native-occluder="true"
tabIndex={-1}
className="absolute inset-x-0 bottom-0 z-40 bg-ui-panel border-t border-ui-default shadow-ui-floating flex flex-col select-none text-xs text-ui-primary outline-none"
>
{/* 1. Header & Transport Controls Dock */}
<div className="flex items-center justify-between px-3 py-1.5 border-b border-ui-subtle bg-ui-header">
{/* Playback Transport */}
<div className="flex items-center space-x-1.5">
<button
type="button"
onClick={() => onChangeTimeline({ ...timeline, currentFrame: 0 })}
className="p-1 hover:bg-ui-control-hover rounded-ui-xs text-ui-icon-muted hover:text-ui-primary transition-colors cursor-pointer"
title={t('First Frame (Home)')}
>
<RotateCcw className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() =>
onChangeTimeline({
...timeline,
currentFrame: Math.max(0, timeline.currentFrame - 1),
})
}
className="p-1 hover:bg-ui-control-hover rounded-ui-xs text-ui-icon-muted hover:text-ui-primary transition-colors cursor-pointer"
title={t('Previous Frame (Left Arrow)')}
>
<ChevronLeft className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => setIsPlaying(!isPlaying)}
className={`py-1 px-2.5 rounded-ui-sm font-medium flex items-center space-x-1.5 transition-colors cursor-pointer ${
isPlaying
? 'bg-ui-control-active text-ui-accent ring-1 ring-ui-accent-border'
: 'bg-ui-accent text-ui-accent-contrast hover:opacity-90'
}`}
title={t('Play / Pause (Alt+Space)')}
>
{isPlaying ? <Pause className="w-3.5 h-3.5" /> : <Play className="w-3.5 h-3.5" />}
<span className="text-[11px] font-medium">{isPlaying ? t('Pause') : t('Play')}</span>
</button>
<button
type="button"
onClick={() =>
onChangeTimeline({
...timeline,
currentFrame: Math.min(timeline.totalFrames - 1, timeline.currentFrame + 1),
})
}
className="p-1 hover:bg-ui-control-hover rounded-ui-xs text-ui-icon-muted hover:text-ui-primary transition-colors cursor-pointer"
title={t('Next Frame (Right Arrow)')}
>
<ChevronRight className="w-4 h-4" />
</button>
{/* Loop Toggle */}
<button
type="button"
onClick={() => onChangeTimeline({ ...timeline, loop: !timeline.loop })}
className={`px-2 py-1 rounded-ui-sm text-[11px] transition-colors cursor-pointer ${
timeline.loop
? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-ui-accent-border'
: 'bg-ui-input border border-ui-subtle text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
}`}
title={t('Loop Playback')}
>
{t('Loop')}
</button>
{/* Frame Rate FPS Selector */}
<div className="flex items-center space-x-1 bg-ui-input rounded-ui-sm px-2 py-0.5 border border-ui-subtle">
<span className="text-[10px] text-ui-muted font-ui-mono">FPS</span>
<select
value={timeline.fps}
onChange={(e) =>
onChangeTimeline({
...timeline,
fps: parseInt(e.target.value, 10),
})
}
className="bg-transparent text-ui-primary font-ui-mono tabular-nums text-[11px] outline-none cursor-pointer"
>
{[6, 8, 12, 16, 24, 30, 60].map((rate) => (
<option key={rate} value={rate} className="bg-ui-elevated text-ui-primary">
{rate} fps
</option>
))}
</select>
</div>
{/* Frame Ticker Counter */}
<div className="font-ui-mono tabular-nums text-ui-primary bg-ui-input px-2.5 py-0.5 rounded-ui-sm border border-ui-subtle text-[11px] tracking-wider">
{String(timeline.currentFrame + 1).padStart(3, '0')} / {String(timeline.totalFrames).padStart(3, '0')}
</div>
</div>
{/* Cel & Onion Skin Tools */}
<div className="flex items-center space-x-1.5">
{/* Add Cel Button */}
<button
type="button"
onClick={() => onAddCel(timeline.currentFrame)}
className="px-2.5 py-1 bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary rounded-ui-sm text-[11px] font-medium transition-colors cursor-pointer"
title={t('Add Cel for Current Frame')}
>
{t('+ Add Cel')}
</button>
{/* Delete Cel Button */}
{currentCelId && (
<button
type="button"
onClick={() => onDeleteCel(timeline.currentFrame)}
className="p-1 hover:bg-ui-danger/15 text-ui-icon-muted hover:text-ui-danger rounded-ui-xs transition-colors cursor-pointer"
title={t('Delete Cel from Current Frame')}
>
<Trash2 className="w-3.5 h-3.5" />
</button>
)}
{/* Onion Skin Quick Settings Popover */}
<div className="relative">
<button
type="button"
onClick={() => setShowOnionSettings(!showOnionSettings)}
className={`px-2.5 py-1 rounded-ui-sm text-[11px] transition-colors cursor-pointer ${
timeline.onionSkin.enabled
? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-ui-accent-border'
: 'bg-ui-input border border-ui-subtle text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
}`}
title={t('Configure Colored Onion Skinning')}
>
{t('Onion Skin')}
</button>
{showOnionSettings && (
<div className="absolute bottom-full mb-2 right-0 bg-ui-elevated border border-ui-default rounded-ui-md p-3 shadow-ui-popover z-50 flex flex-col space-y-2.5 w-64">
<div className="flex items-center justify-between">
<span className="font-medium text-ui-primary text-xs">{t('Onion Skin')}</span>
<label className="flex items-center space-x-1.5 cursor-pointer">
<input
type="checkbox"
checked={timeline.onionSkin.enabled}
onChange={(e) =>
onChangeTimeline({
...timeline,
onionSkin: {
...timeline.onionSkin,
enabled: e.target.checked,
},
})
}
/>
<span className="text-[10px] text-ui-muted">{t('Enabled')}</span>
</label>
</div>
{/* Prior Frames Settings */}
<div className="flex items-center justify-between text-[11px] text-ui-secondary">
<span className="tabular-nums">
{t('Prior Frames ({count})', { count: timeline.onionSkin.prevFrames })}
</span>
<div className="flex items-center space-x-2">
<input
type="color"
value={timeline.onionSkin.prevTint}
onChange={(e) =>
onChangeTimeline({
...timeline,
onionSkin: {
...timeline.onionSkin,
prevTint: e.target.value,
},
})
}
className="w-5 h-5 rounded-ui-xs cursor-pointer border-0 bg-transparent"
/>
<input
type="range"
min="1"
max="5"
value={timeline.onionSkin.prevFrames}
onChange={(e) =>
onChangeTimeline({
...timeline,
onionSkin: {
...timeline.onionSkin,
prevFrames: parseInt(e.target.value, 10),
},
})
}
className="w-16"
/>
</div>
</div>
{/* Next Frames Settings */}
<div className="flex items-center justify-between text-[11px] text-ui-secondary">
<span className="tabular-nums">
{t('Next Frames ({count})', { count: timeline.onionSkin.nextFrames })}
</span>
<div className="flex items-center space-x-2">
<input
type="color"
value={timeline.onionSkin.nextTint}
onChange={(e) =>
onChangeTimeline({
...timeline,
onionSkin: {
...timeline.onionSkin,
nextTint: e.target.value,
},
})
}
className="w-5 h-5 rounded-ui-xs cursor-pointer border-0 bg-transparent"
/>
<input
type="range"
min="1"
max="5"
value={timeline.onionSkin.nextFrames}
onChange={(e) =>
onChangeTimeline({
...timeline,
onionSkin: {
...timeline.onionSkin,
nextFrames: parseInt(e.target.value, 10),
},
})
}
className="w-16"
/>
</div>
</div>
{/* Base Opacity */}
<div className="flex items-center justify-between text-[11px] text-ui-secondary">
<span>{t('Opacity')}</span>
<div className="flex items-center space-x-2">
<input
type="range"
min="0.1"
max="0.8"
step="0.05"
value={timeline.onionSkin.opacity}
onChange={(e) =>
onChangeTimeline({
...timeline,
onionSkin: {
...timeline.onionSkin,
opacity: parseFloat(e.target.value),
},
})
}
className="w-24"
/>
<span className="font-ui-mono tabular-nums text-[10px] w-7 text-right text-ui-muted">
{Math.round(timeline.onionSkin.opacity * 100)}%
</span>
</div>
</div>
</div>
)}
</div>
{/* Total Frames Adjuster */}
<div className="flex items-center space-x-1 bg-ui-input rounded-ui-sm px-1.5 py-0.5 border border-ui-subtle">
<span className="text-[10px] text-ui-muted">{t('Total')}</span>
<input
type="number"
min="2"
max="240"
value={timeline.totalFrames}
onChange={(e) =>
onChangeTimeline({
...timeline,
totalFrames: Math.max(2, Math.min(240, parseInt(e.target.value, 10) || 24)),
})
}
onKeyDown={(e) => {
e.stopPropagation();
if (isImeComposing(e)) return;
}}
className="w-10 bg-transparent font-ui-mono tabular-nums text-ui-primary text-center text-[11px] outline-none"
/>
</div>
{/* Export Video Modal Button */}
<button
type="button"
onClick={() => setShowExportModal(true)}
className="px-2.5 py-1 bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary rounded-ui-sm text-[11px] font-medium transition-colors cursor-pointer"
title={t('Export Animation')}
>
{t('Export')}
</button>
{/* Close Timeline */}
{onClose && (
<button
type="button"
onClick={onClose}
className="p-1 text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover rounded-ui-xs transition-colors cursor-pointer"
title={t('Close Timeline Dock')}
>
<X className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
{/* 2. Interactive Scrubber Timeline Track */}
<div className="px-3 py-2 flex flex-col space-y-1 bg-ui-void">
{/* Frame Ruler Numbers */}
<div
ref={scrubberRef}
onPointerDown={handlePointerDown}
className="relative h-14 bg-ui-input rounded-ui-sm border border-ui-default cursor-pointer overflow-hidden flex flex-col justify-between"
>
{/* Top Frame Tick Ruler */}
<div className="relative h-5 border-b border-ui-subtle bg-ui-header flex items-center">
{Array.from({ length: timeline.totalFrames }).map((_, f) => (
<div
key={f}
style={{
width: `${100 / timeline.totalFrames}%`,
}}
className={`h-full border-r border-ui-subtle flex items-center justify-center text-[9px] font-ui-mono tabular-nums select-none ${
f % 5 === 0 ? 'text-ui-primary font-semibold' : 'text-ui-muted text-[8px]'
}`}
>
{f % 2 === 0 || timeline.totalFrames <= 24 ? f + 1 : ''}
</div>
))}
</div>
{/* Cel Slots Track */}
<div className="relative h-9 flex items-center">
{Array.from({ length: timeline.totalFrames }).map((_, f) => {
const hasCel = !!timeline.cels[f];
const isCurrent = timeline.currentFrame === f;
return (
<div
key={f}
style={{
width: `${100 / timeline.totalFrames}%`,
}}
className={`h-full border-r border-ui-subtle flex items-center justify-center p-0.5 transition-colors ${
isCurrent ? 'bg-ui-accent-subtle' : ''
}`}
>
{hasCel ? (
<div
className={`w-full h-5 rounded-ui-xs flex items-center justify-center text-[9px] font-ui-mono font-medium truncate ${
isCurrent
? 'bg-ui-accent text-ui-accent-contrast font-semibold'
: 'bg-ui-control text-ui-secondary hover:bg-ui-control-hover border border-ui-subtle'
}`}
title={t('Frame {frame}: Cel Assigned', { frame: f + 1 })}
>
<span className="w-1.5 h-1.5 rounded-full bg-current" />
</div>
) : (
<div className="w-1 h-1 rounded-full bg-ui-disabled" />
)}
</div>
);
})}
</div>
{/* Scrub Playhead Line */}
<div
className="absolute top-0 bottom-0 pointer-events-none z-20 transition-all duration-75 flex flex-col items-center"
style={{
left: `${((timeline.currentFrame + 0.5) / timeline.totalFrames) * 100}%`,
transform: 'translateX(-50%)',
}}
>
<div className="w-2.5 h-1.5 bg-ui-danger rounded-b" />
<div className="w-[1.5px] h-full bg-ui-danger" />
</div>
</div>
{/* Cel Info Bar */}
<div className="flex items-center justify-between text-[10px] text-ui-muted px-1">
<div className="flex items-center space-x-2">
<span>
{t('Active Cel:')}{' '}
{currentCelLayer ? (
<span className="text-ui-accent font-medium font-ui-mono">{currentCelLayer.name}</span>
) : (
<span className="text-ui-muted italic">
{t('None (Drawing creates new frame cel)')}
</span>
)}
</span>
</div>
<div className="flex items-center space-x-3 text-ui-muted">
<span>{t('Drag scrubber to navigate')}</span>
<span>·</span>
<span>{t('Alt+Space: Play/Pause')}</span>
<span>·</span>
<span>{t('← / →: Step frame')}</span>
</div>
</div>
</div>
{/* 3. Export Modal */}
{showExportModal && (
<div
role="dialog"
aria-modal="true"
className="fixed inset-0 z-50 bg-ui-overlay flex items-center justify-center"
onKeyDown={(e) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape' && !isExporting) {
e.preventDefault();
setShowExportModal(false);
}
}}
>
<div className="bg-ui-elevated border border-ui-default rounded-ui-lg p-4 shadow-ui-popover w-80 flex flex-col space-y-3.5">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-ui-primary">{t('Export Animation')}</span>
<button
type="button"
onClick={() => setShowExportModal(false)}
aria-label={t('Close')}
className="p-1 text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover rounded-ui-xs transition-colors cursor-pointer"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
<div className="flex flex-col space-y-1.5">
<label className="text-[11px] text-ui-muted">{t('Format')}</label>
<div className="grid grid-cols-2 gap-1.5 text-[11px]">
{(
[
['gif', 'Animated GIF'],
['apng', 'Animated PNG'],
['webm', 'WebM Video'],
['png-zip', 'PNG Sequence (.zip)'],
] as Array<[AnimationExportFormat, string]>
).map(([fmt, label]) => (
<button
key={fmt}
type="button"
onClick={() => setExportFormat(fmt)}
className={`py-1.5 px-2.5 rounded-ui-sm text-left border transition-colors cursor-pointer ${
exportFormat === fmt
? 'bg-ui-accent-subtle border-ui-accent-border text-ui-accent font-medium'
: 'bg-ui-input border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
}`}
>
{t(label)}
</button>
))}
</div>
</div>
<div className="text-[11px] text-ui-secondary space-y-1 bg-ui-input p-2.5 rounded-ui-sm border border-ui-subtle font-ui-mono tabular-nums">
<div>
{t('Resolution: {width} × {height} px', {
width: dimensions.width,
height: dimensions.height,
})}
</div>
<div>{t('Frame Rate: {fps} FPS', { fps: timeline.fps })}</div>
<div>{t('Total Frames: {count}', { count: timeline.totalFrames })}</div>
</div>
<button
type="button"
onClick={handleExport}
disabled={isExporting}
className="w-full py-1.5 bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium rounded-ui-sm text-xs transition-opacity disabled:opacity-50 cursor-pointer"
>
{isExporting ? exportProgress || t('Exporting...') : t('Start Export')}
</button>
</div>
</div>
)}
</div>
);
};