File size: 7,855 Bytes
56e8946
 
 
 
 
 
 
 
 
 
 
 
 
 
82c6e5a
 
 
 
 
 
 
56e8946
 
 
 
 
 
 
 
 
 
82c6e5a
 
 
 
 
 
 
56e8946
 
 
 
 
 
 
 
 
 
 
 
 
 
82c6e5a
 
 
 
56e8946
 
 
82c6e5a
56e8946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82c6e5a
56e8946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82c6e5a
56e8946
 
 
 
 
 
 
82c6e5a
56e8946
 
82c6e5a
 
56e8946
 
 
 
 
 
 
 
82c6e5a
56e8946
 
 
82c6e5a
56e8946
 
 
82c6e5a
56e8946
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import React, { useRef, useEffect, useCallback } from 'react';
import { useStudioStore } from '../store/useStudioStore';
import { Keyframe } from '../utils/timeline';
import './Timeline.css';

const Timeline: React.FC = () => {
  const {
    objects, selectedId,
    tracks, playhead, setPlayhead,
    timelinePlaying, setTimelinePlaying,
    timelineDuration, setTimelineDuration,
    addKeyframe, removeKeyframe,
  } = useStudioStore();

  const rafRef      = useRef<number>(0);
  const lastTimeRef = useRef<number>(0);
  const playheadRef = useRef<number>(playhead);   // โ† ref so tick closure stays fresh
  const rulerRef    = useRef<HTMLDivElement>(null);

  // Keep ref in sync with store value
  useEffect(() => { playheadRef.current = playhead; }, [playhead]);

  // โ”€โ”€ Playback loop โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  useEffect(() => {
    if (!timelinePlaying) {
      cancelAnimationFrame(rafRef.current);
      return;
    }
    const tick = (now: number) => {
      const delta = (now - lastTimeRef.current) / 1000;
      lastTimeRef.current = now;
      const next = playheadRef.current + delta;
      if (next >= timelineDuration) {
        setPlayhead(timelineDuration);
        setTimelinePlaying(false);
        return;
      }
      setPlayhead(next);
      rafRef.current = requestAnimationFrame(tick);
    };
    lastTimeRef.current = performance.now();
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [timelinePlaying, timelineDuration, setPlayhead, setTimelinePlaying]);

  // โ”€โ”€ Add keyframe at playhead for selected object โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  const handleAddKeyframe = useCallback(() => {
    if (!selectedId) return;
    const obj = objects.find(o => o.id === selectedId);
    if (!obj) return;
    const kf: Keyframe = {
      id:       Math.random().toString(36).slice(2),
      time:     parseFloat(playheadRef.current.toFixed(3)),
      position: [...obj.position] as [number, number, number],
      rotation: [...obj.rotation] as [number, number, number],
      scale:    [...obj.scale]    as [number, number, number],
      easing:   'ease-in-out',
    };
    addKeyframe(selectedId, kf);
  }, [selectedId, objects, addKeyframe]);

  // โ”€โ”€ Keyboard shortcut: I = insert keyframe โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'i' || e.key === 'I') handleAddKeyframe();
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [handleAddKeyframe]);

  // โ”€โ”€ Click ruler to seek โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  const handleRulerClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    const rect = rulerRef.current?.getBoundingClientRect();
    if (!rect) return;
    const t = ((e.clientX - rect.left) / rect.width) * timelineDuration;
    setPlayhead(Math.max(0, Math.min(timelineDuration, t)));
  }, [timelineDuration, setPlayhead]);

  const fmt = (t: number) => {
    const s = Math.floor(t);
    const f = Math.floor((t % 1) * 30);
    return `${String(s).padStart(2, '0')}:${String(f).padStart(2, '0')}`;
  };

  const playheadPct = (playhead / timelineDuration) * 100;

  return (
    <div className="timeline">

      {/* โ”€โ”€ Controls bar โ”€โ”€ */}
      <div className="tl-controls">
        <button className="tl-btn" title="Rewind"
          onClick={() => { setPlayhead(0); setTimelinePlaying(false); }}>โฎ</button>

        <button
          className={`tl-btn tl-play ${timelinePlaying ? 'playing' : ''}`}
          onClick={() => setTimelinePlaying(!timelinePlaying)}
        >
          {timelinePlaying ? 'โธ' : 'โ–ถ'}
        </button>

        <button className="tl-btn" title="Go to end"
          onClick={() => { setPlayhead(timelineDuration); setTimelinePlaying(false); }}>โญ</button>

        <div className="tl-time">{fmt(playhead)} / {fmt(timelineDuration)}</div>

        <button
          className={`tl-btn tl-kf-btn ${!selectedId ? 'disabled' : ''}`}
          onClick={handleAddKeyframe}
          disabled={!selectedId}
          title="Add keyframe at playhead (I)"
        >
          โ—† ADD KEY
        </button>

        <div className="tl-duration">
          <label>Dur</label>
          <input
            type="number" min={1} max={120} step={1}
            value={timelineDuration}
            onChange={(e) => setTimelineDuration(parseInt(e.target.value) || 5)}
          />
          <span>s</span>
        </div>
      </div>

      {/* โ”€โ”€ Track area โ”€โ”€ */}
      <div className="tl-body">

        {/* Object labels column */}
        <div className="tl-labels">
          {objects.length === 0 && (
            <div className="tl-empty">Load a model first</div>
          )}
          {objects.map(obj => {
            const kfCount = tracks.find(t => t.objectId === obj.id)?.keyframes.length ?? 0;
            return (
              <div key={obj.id}
                className={`tl-label ${selectedId === obj.id ? 'active' : ''}`}>
                <span className="tl-label-dot">โ—ˆ</span>
                <span className="tl-label-name">{obj.name}</span>
                {kfCount > 0 && <span className="tl-kf-count">{kfCount}K</span>}
              </div>
            );
          })}
        </div>

        {/* Ruler + tracks column */}
        <div className="tl-tracks-wrap">

          {/* Ruler */}
          <div className="tl-ruler" ref={rulerRef} onClick={handleRulerClick}>
            {Array.from({ length: timelineDuration + 1 }, (_, i) => (
              <div key={i} className="tl-tick"
                style={{ left: `${(i / timelineDuration) * 100}%` }}>
                <span>{i}s</span>
              </div>
            ))}
            <div className="tl-playhead" style={{ left: `${playheadPct}%` }} />
          </div>

          {/* Keyframe tracks */}
          <div className="tl-tracks">
            {objects.map(obj => {
              const track  = tracks.find(t => t.objectId === obj.id);
              const sorted = track
                ? [...track.keyframes].sort((a, b) => a.time - b.time)
                : [];
              return (
                <div key={obj.id}
                  className={`tl-track ${selectedId === obj.id ? 'active' : ''}`}>

                  {/* Connection lines */}
                  {sorted.map((kf, i) => {
                    if (i === sorted.length - 1) return null;
                    const x1 = (kf.time          / timelineDuration) * 100;
                    const x2 = (sorted[i+1].time / timelineDuration) * 100;
                    return (
                      <div key={kf.id + '-line'} className="tl-kf-line"
                        style={{ left: `${x1}%`, width: `${x2 - x1}%` }} />
                    );
                  })}

                  {/* Keyframe diamonds */}
                  {sorted.map(kf => (
                    <div key={kf.id}
                      className="tl-kf-diamond"
                      style={{ left: `${(kf.time / timelineDuration) * 100}%` }}
                      title={`${kf.time.toFixed(2)}s  โ€ข  click to delete`}
                      onClick={(e) => { e.stopPropagation(); removeKeyframe(obj.id, kf.id); }}
                    >โ—†</div>
                  ))}

                  {/* Playhead ghost line */}
                  <div className="tl-track-playhead"
                    style={{ left: `${playheadPct}%` }} />
                </div>
              );
            })}
          </div>

        </div>
      </div>
    </div>
  );
};

export default Timeline;