mishig HF Staff commited on
Commit
0f3f322
·
verified ·
1 Parent(s): b66698a

Sync from huggingface/lerobot-dataset-visualizer via hub-sync

Browse files
src/app/[org]/[dataset]/[episode]/episode-viewer.tsx CHANGED
@@ -5,7 +5,7 @@ import { useRouter, useSearchParams } from "next/navigation";
5
  import { postParentMessageWithParams } from "@/utils/postParentMessage";
6
  import { SimpleVideosPlayer } from "@/components/simple-videos-player";
7
  import PlaybackBar from "@/components/playback-bar";
8
- import { TimeProvider, useTime } from "@/context/time-context";
9
  import { FlaggedEpisodesProvider } from "@/context/flagged-episodes-context";
10
  import {
11
  AnnotationsProvider,
@@ -449,12 +449,10 @@ function EpisodeViewerInner({
449
  }
450
  };
451
 
452
- // `currentTime` is intentionally NOT read here. Subscribing to it would
453
- // re-render this 700-line component every ~80ms during playback. The
454
- // <UrlTimeSync /> child handles its only consumer (the ?t= URL writer).
455
- // `seek` and `setIsPlaying` are stable references from useCallback /
456
- // useState — they don't drive renders.
457
- const { seek, setIsPlaying } = useTime();
458
 
459
  // URDFViewer episode changer and play toggle — populated by URDFViewer on mount
460
  const urdfChangerRef = useRef<((ep: number) => void) | undefined>(undefined);
 
5
  import { postParentMessageWithParams } from "@/utils/postParentMessage";
6
  import { SimpleVideosPlayer } from "@/components/simple-videos-player";
7
  import PlaybackBar from "@/components/playback-bar";
8
+ import { TimeProvider, useTime, useTimeControls } from "@/context/time-context";
9
  import { FlaggedEpisodesProvider } from "@/context/flagged-episodes-context";
10
  import {
11
  AnnotationsProvider,
 
449
  }
450
  };
451
 
452
+ // Not `useTime()`: any consumer of it re-renders on every playback tick,
453
+ // which would redraw this whole component ~12×/s. <UrlTimeSync /> handles
454
+ // the one thing here that needs `currentTime` (the ?t= URL writer).
455
+ const { seek, setIsPlaying } = useTimeControls();
 
 
456
 
457
  // URDFViewer episode changer and play toggle — populated by URDFViewer on mount
458
  const urdfChangerRef = useRef<((ep: number) => void) | undefined>(undefined);
src/components/annotations-panel.tsx CHANGED
@@ -18,7 +18,7 @@ import "./annotations-skin.css";
18
  */
19
 
20
  import React, { useMemo, useState } from "react";
21
- import { useTime } from "../context/time-context";
22
  import { useAnnotations } from "../context/annotations-context";
23
  import {
24
  buildSpeechAtom,
@@ -426,7 +426,7 @@ const RAIL_GROUPS: RailGroupDef[] = [
426
  ];
427
 
428
  function useJump(): (ts: number) => void {
429
- const { seek, setIsPlaying } = useTime();
430
  return React.useCallback(
431
  (ts: number) => {
432
  seek(ts, "external");
 
18
  */
19
 
20
  import React, { useMemo, useState } from "react";
21
+ import { useTime, useTimeControls } from "../context/time-context";
22
  import { useAnnotations } from "../context/annotations-context";
23
  import {
24
  buildSpeechAtom,
 
426
  ];
427
 
428
  function useJump(): (ts: number) => void {
429
+ const { seek, setIsPlaying } = useTimeControls();
430
  return React.useCallback(
431
  (ts: number) => {
432
  seek(ts, "external");
src/components/data-recharts.tsx CHANGED
@@ -6,8 +6,9 @@ import React, {
6
  useMemo,
7
  useRef,
8
  useState,
 
9
  } from "react";
10
- import { useTime } from "../context/time-context";
11
  import {
12
  LineChart,
13
  Line,
@@ -16,7 +17,6 @@ import {
16
  CartesianGrid,
17
  ResponsiveContainer,
18
  Tooltip,
19
- ReferenceLine,
20
  } from "recharts";
21
 
22
  type ChartRow = Record<string, number | Record<string, number>>;
@@ -43,6 +43,67 @@ const CHART_COLORS = [
43
  "#84cc16",
44
  ];
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  function mergeGroups(data: ChartRow[][]): ChartRow[] {
47
  if (data.length <= 1) return data[0] ?? [];
48
  const maxLen = Math.max(...data.map((g) => g.length));
@@ -67,7 +128,7 @@ function mergeGroups(data: ChartRow[][]): ChartRow[] {
67
 
68
  export const DataRecharts = React.memo(
69
  ({ data, onChartsReady }: DataGraphProps) => {
70
- const [hoveredTime, setHoveredTime] = useState<number | null>(null);
71
  const [expanded, setExpanded] = useState(false);
72
 
73
  useEffect(() => {
@@ -126,21 +187,11 @@ export const DataRecharts = React.memo(
126
  )}
127
 
128
  {expanded ? (
129
- <SingleDataGraph
130
- data={combinedData}
131
- hoveredTime={hoveredTime}
132
- setHoveredTime={setHoveredTime}
133
- tall
134
- />
135
  ) : (
136
  <div className="grid md:grid-cols-2 grid-cols-1 gap-4">
137
  {data.map((group, idx) => (
138
- <SingleDataGraph
139
- key={idx}
140
- data={group}
141
- hoveredTime={hoveredTime}
142
- setHoveredTime={setHoveredTime}
143
- />
144
  ))}
145
  </div>
146
  )}
@@ -149,19 +200,159 @@ export const DataRecharts = React.memo(
149
  },
150
  );
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  const SingleDataGraph = React.memo(
153
  ({
154
  data,
155
- hoveredTime,
156
- setHoveredTime,
157
  tall,
158
  }: {
159
  data: ChartRow[];
160
- hoveredTime: number | null;
161
- setHoveredTime: (t: number | null) => void;
162
  tall?: boolean;
163
  }) => {
164
- const { currentTime, seek } = useTime();
165
  const flattenRow = useCallback(
166
  (row: Record<string, number | Record<string, number>>, prefix = "") => {
167
  const result: Record<string, number> = {};
@@ -245,19 +436,7 @@ const SingleDataGraph = React.memo(
245
  return { groups: grouped, singles: singleList, groupColorMap: colorMap };
246
  }, [dataKeys]);
247
 
248
- // Find the closest data point to the current time for highlighting
249
- const findClosestDataIndex = (time: number) => {
250
- if (!chartData.length) return 0;
251
- // Find the index of the first data point whose timestamp is >= time (ceiling)
252
- const idx = chartData.findIndex((point) => point.timestamp >= time);
253
- if (idx !== -1) return idx;
254
- // If all timestamps are less than time, return the last index
255
- return chartData.length - 1;
256
- };
257
-
258
- const handleMouseLeave = () => {
259
- setHoveredTime(null);
260
- };
261
 
262
  const handleClick = (
263
  data: { activePayload?: { payload: { timestamp: number } }[] } | null,
@@ -267,127 +446,6 @@ const SingleDataGraph = React.memo(
267
  }
268
  };
269
 
270
- // Custom legend to show current value next to each series
271
- const CustomLegend = () => {
272
- const closestIndex = findClosestDataIndex(
273
- hoveredTime != null ? hoveredTime : currentTime,
274
- );
275
- const currentData = chartData[closestIndex] || {};
276
-
277
- const isGroupChecked = (group: string) =>
278
- groups[group].every((k) => visibleKeys.includes(k));
279
- const isGroupIndeterminate = (group: string) =>
280
- groups[group].some((k) => visibleKeys.includes(k)) &&
281
- !isGroupChecked(group);
282
-
283
- const handleGroupCheckboxChange = (group: string) => {
284
- if (isGroupChecked(group)) {
285
- // Uncheck all children
286
- setVisibleKeys((prev) =>
287
- prev.filter((k) => !groups[group].includes(k)),
288
- );
289
- } else {
290
- // Check all children
291
- setVisibleKeys((prev) =>
292
- Array.from(new Set([...prev, ...groups[group]])),
293
- );
294
- }
295
- };
296
-
297
- const handleCheckboxChange = (key: string) => {
298
- setVisibleKeys((prev) =>
299
- prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],
300
- );
301
- };
302
-
303
- return (
304
- <div className="flex flex-wrap gap-x-5 gap-y-2 px-1 pt-2">
305
- {Object.entries(groups).map(([group, children]) => {
306
- const color = groupColorMap[group];
307
- return (
308
- <div key={group}>
309
- <label className="flex items-center gap-1.5 cursor-pointer select-none">
310
- <input
311
- type="checkbox"
312
- checked={isGroupChecked(group)}
313
- ref={(el) => {
314
- if (el) el.indeterminate = isGroupIndeterminate(group);
315
- }}
316
- onChange={() => handleGroupCheckboxChange(group)}
317
- className="size-3"
318
- style={{ accentColor: color }}
319
- />
320
- <span className="text-xs font-semibold text-slate-200">
321
- {group}
322
- </span>
323
- </label>
324
- <div className="pl-5 flex flex-col gap-0.5 mt-0.5">
325
- {children.map((key) => {
326
- const label = key.split(SERIES_NAME_DELIMITER).pop() ?? key;
327
- return (
328
- <label
329
- key={key}
330
- className="flex items-center gap-1.5 cursor-pointer select-none"
331
- >
332
- <input
333
- type="checkbox"
334
- checked={visibleKeys.includes(key)}
335
- onChange={() => handleCheckboxChange(key)}
336
- className="size-2.5"
337
- style={{ accentColor: color }}
338
- />
339
- <span
340
- className={`text-xs ${visibleKeys.includes(key) ? "text-slate-300" : "text-slate-500"}`}
341
- >
342
- {label}
343
- </span>
344
- <span
345
- className={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}
346
- >
347
- {typeof currentData[key] === "number"
348
- ? currentData[key].toFixed(2)
349
- : "–"}
350
- </span>
351
- </label>
352
- );
353
- })}
354
- </div>
355
- </div>
356
- );
357
- })}
358
- {singles.map((key) => {
359
- const color = groupColorMap[key];
360
- return (
361
- <label
362
- key={key}
363
- className="flex items-center gap-1.5 cursor-pointer select-none"
364
- >
365
- <input
366
- type="checkbox"
367
- checked={visibleKeys.includes(key)}
368
- onChange={() => handleCheckboxChange(key)}
369
- className="size-3"
370
- style={{ accentColor: color }}
371
- />
372
- <span
373
- className={`text-xs ${visibleKeys.includes(key) ? "text-slate-200" : "text-slate-500"}`}
374
- >
375
- {key}
376
- </span>
377
- <span
378
- className={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}
379
- >
380
- {typeof currentData[key] === "number"
381
- ? currentData[key].toFixed(2)
382
- : "–"}
383
- </span>
384
- </label>
385
- );
386
- })}
387
- </div>
388
- );
389
- };
390
-
391
  // Derive chart title from the grouped feature names
392
  const chartTitle = useMemo(() => {
393
  const featureNames = Object.keys(groups);
@@ -412,20 +470,20 @@ const SingleDataGraph = React.memo(
412
  </p>
413
  )}
414
  <div
415
- className={`w-full ${tall ? "h-[500px]" : "h-72"}`}
416
  onMouseLeave={handleMouseLeave}
417
  >
418
  <ResponsiveContainer width="100%" height="100%">
419
  <LineChart
420
  data={chartData}
421
  syncId="episode-sync"
422
- margin={{ top: 12, right: 12, left: -8, bottom: 8 }}
423
  onClick={handleClick}
424
  onMouseMove={(state) => {
425
  const payload = state?.activePayload?.[0]?.payload as
426
  | { timestamp?: number }
427
  | undefined;
428
- setHoveredTime(payload?.timestamp ?? null);
429
  }}
430
  onMouseLeave={handleMouseLeave}
431
  >
@@ -444,13 +502,14 @@ const SingleDataGraph = React.memo(
444
  stroke="#64748b"
445
  tick={{ fontSize: 12, fill: "#94a3b8" }}
446
  minTickGap={30}
 
447
  allowDataOverflow={true}
448
  />
449
  <YAxis
450
  domain={["auto", "auto"]}
451
  stroke="#64748b"
452
  tick={{ fontSize: 12, fill: "#94a3b8" }}
453
- width={55}
454
  allowDataOverflow={true}
455
  tickFormatter={(v: number) => {
456
  if (v === 0) return "0";
@@ -460,21 +519,7 @@ const SingleDataGraph = React.memo(
460
  }}
461
  />
462
 
463
- <Tooltip
464
- content={() => null}
465
- active={true}
466
- isAnimationActive={false}
467
- defaultIndex={
468
- !hoveredTime ? findClosestDataIndex(currentTime) : undefined
469
- }
470
- />
471
-
472
- <ReferenceLine
473
- x={currentTime}
474
- stroke="#f97316"
475
- strokeWidth={1.5}
476
- strokeOpacity={0.7}
477
- />
478
 
479
  {dataKeys.map((key) => {
480
  const group = key.includes(SERIES_NAME_DELIMITER)
@@ -505,8 +550,20 @@ const SingleDataGraph = React.memo(
505
  })}
506
  </LineChart>
507
  </ResponsiveContainer>
 
 
 
 
508
  </div>
509
- <CustomLegend />
 
 
 
 
 
 
 
 
510
  </div>
511
  );
512
  },
 
6
  useMemo,
7
  useRef,
8
  useState,
9
+ useSyncExternalStore,
10
  } from "react";
11
+ import { useTime, useTimeControls } from "../context/time-context";
12
  import {
13
  LineChart,
14
  Line,
 
17
  CartesianGrid,
18
  ResponsiveContainer,
19
  Tooltip,
 
20
  } from "recharts";
21
 
22
  type ChartRow = Record<string, number | Record<string, number>>;
 
43
  "#84cc16",
44
  ];
45
 
46
+ /// Plot-area geometry, shared by the chart and the playback cursor drawn over it.
47
+ const CHART_MARGIN = { top: 12, right: 12, left: -8, bottom: 8 };
48
+ const Y_AXIS_WIDTH = 55;
49
+ const X_AXIS_HEIGHT = 30;
50
+
51
+ /**
52
+ * The time under the pointer, shared by every chart's legend. A store rather than state, so moving
53
+ * the pointer re-renders the legends only, not every chart.
54
+ */
55
+ type HoverStore = {
56
+ get: () => number | null;
57
+ set: (t: number | null) => void;
58
+ subscribe: (cb: () => void) => () => void;
59
+ };
60
+
61
+ function createHoverStore(): HoverStore {
62
+ let time: number | null = null;
63
+ const listeners = new Set<() => void>();
64
+ return {
65
+ get: () => time,
66
+ set: (t) => {
67
+ if (t === time) return;
68
+ time = t;
69
+ listeners.forEach((cb) => cb());
70
+ },
71
+ subscribe: (cb) => {
72
+ listeners.add(cb);
73
+ return () => listeners.delete(cb);
74
+ },
75
+ };
76
+ }
77
+
78
+ /** Index of the first point at or after `time`, or the last point. */
79
+ function closestDataIndex(chartData: Record<string, number>[], time: number) {
80
+ if (!chartData.length) return 0;
81
+ const idx = chartData.findIndex((point) => point.timestamp >= time);
82
+ return idx !== -1 ? idx : chartData.length - 1;
83
+ }
84
+
85
+ /**
86
+ * Drawn over the chart instead of as a Recharts ReferenceLine: a ReferenceLine
87
+ * makes the whole chart re-render on every playback tick.
88
+ */
89
+ function PlaybackCursor({ start, end }: { start: number; end: number }) {
90
+ const { currentTime } = useTime();
91
+ if (end <= start) return null;
92
+ const fraction = (currentTime - start) / (end - start);
93
+ if (fraction < 0 || fraction > 1) return null;
94
+ const left = CHART_MARGIN.left + Y_AXIS_WIDTH;
95
+ return (
96
+ <div
97
+ className="pointer-events-none absolute w-[1.5px] bg-orange-500/70"
98
+ style={{
99
+ top: CHART_MARGIN.top,
100
+ bottom: CHART_MARGIN.bottom + X_AXIS_HEIGHT,
101
+ left: `calc(${left}px + (100% - ${left + CHART_MARGIN.right}px) * ${fraction})`,
102
+ }}
103
+ />
104
+ );
105
+ }
106
+
107
  function mergeGroups(data: ChartRow[][]): ChartRow[] {
108
  if (data.length <= 1) return data[0] ?? [];
109
  const maxLen = Math.max(...data.map((g) => g.length));
 
128
 
129
  export const DataRecharts = React.memo(
130
  ({ data, onChartsReady }: DataGraphProps) => {
131
+ const [hoverStore] = useState(createHoverStore);
132
  const [expanded, setExpanded] = useState(false);
133
 
134
  useEffect(() => {
 
187
  )}
188
 
189
  {expanded ? (
190
+ <SingleDataGraph data={combinedData} hoverStore={hoverStore} tall />
 
 
 
 
 
191
  ) : (
192
  <div className="grid md:grid-cols-2 grid-cols-1 gap-4">
193
  {data.map((group, idx) => (
194
+ <SingleDataGraph key={idx} data={group} hoverStore={hoverStore} />
 
 
 
 
 
195
  ))}
196
  </div>
197
  )}
 
200
  },
201
  );
202
 
203
+ /** Series toggles with each series' value at the hovered time, or the playback time. */
204
+ function ChartLegend({
205
+ chartData,
206
+ groups,
207
+ singles,
208
+ groupColorMap,
209
+ visibleKeys,
210
+ setVisibleKeys,
211
+ hoverStore,
212
+ }: {
213
+ chartData: Record<string, number>[];
214
+ groups: Record<string, string[]>;
215
+ singles: string[];
216
+ groupColorMap: Record<string, string>;
217
+ visibleKeys: string[];
218
+ setVisibleKeys: React.Dispatch<React.SetStateAction<string[]>>;
219
+ hoverStore: HoverStore;
220
+ }) {
221
+ const { currentTime } = useTime();
222
+ const hoveredTime = useSyncExternalStore(
223
+ hoverStore.subscribe,
224
+ hoverStore.get,
225
+ hoverStore.get,
226
+ );
227
+ const closestIndex = closestDataIndex(
228
+ chartData,
229
+ hoveredTime != null ? hoveredTime : currentTime,
230
+ );
231
+ const currentData = chartData[closestIndex] || {};
232
+
233
+ const isGroupChecked = (group: string) =>
234
+ groups[group].every((k) => visibleKeys.includes(k));
235
+ const isGroupIndeterminate = (group: string) =>
236
+ groups[group].some((k) => visibleKeys.includes(k)) &&
237
+ !isGroupChecked(group);
238
+
239
+ const handleGroupCheckboxChange = (group: string) => {
240
+ if (isGroupChecked(group)) {
241
+ // Uncheck all children
242
+ setVisibleKeys((prev) => prev.filter((k) => !groups[group].includes(k)));
243
+ } else {
244
+ // Check all children
245
+ setVisibleKeys((prev) =>
246
+ Array.from(new Set([...prev, ...groups[group]])),
247
+ );
248
+ }
249
+ };
250
+
251
+ const handleCheckboxChange = (key: string) => {
252
+ setVisibleKeys((prev) =>
253
+ prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],
254
+ );
255
+ };
256
+
257
+ return (
258
+ <div className="flex flex-wrap gap-x-5 gap-y-2 px-1 pt-2">
259
+ {Object.entries(groups).map(([group, children]) => {
260
+ const color = groupColorMap[group];
261
+ return (
262
+ <div key={group}>
263
+ <label className="flex items-center gap-1.5 cursor-pointer select-none">
264
+ <input
265
+ type="checkbox"
266
+ checked={isGroupChecked(group)}
267
+ ref={(el) => {
268
+ if (el) el.indeterminate = isGroupIndeterminate(group);
269
+ }}
270
+ onChange={() => handleGroupCheckboxChange(group)}
271
+ className="size-3"
272
+ style={{ accentColor: color }}
273
+ />
274
+ <span className="text-xs font-semibold text-slate-200">
275
+ {group}
276
+ </span>
277
+ </label>
278
+ <div className="pl-5 flex flex-col gap-0.5 mt-0.5">
279
+ {children.map((key) => {
280
+ const label = key.split(SERIES_NAME_DELIMITER).pop() ?? key;
281
+ return (
282
+ <label
283
+ key={key}
284
+ className="flex items-center gap-1.5 cursor-pointer select-none"
285
+ >
286
+ <input
287
+ type="checkbox"
288
+ checked={visibleKeys.includes(key)}
289
+ onChange={() => handleCheckboxChange(key)}
290
+ className="size-2.5"
291
+ style={{ accentColor: color }}
292
+ />
293
+ <span
294
+ className={`text-xs ${visibleKeys.includes(key) ? "text-slate-300" : "text-slate-500"}`}
295
+ >
296
+ {label}
297
+ </span>
298
+ <span
299
+ className={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}
300
+ >
301
+ {typeof currentData[key] === "number"
302
+ ? currentData[key].toFixed(2)
303
+ : "–"}
304
+ </span>
305
+ </label>
306
+ );
307
+ })}
308
+ </div>
309
+ </div>
310
+ );
311
+ })}
312
+ {singles.map((key) => {
313
+ const color = groupColorMap[key];
314
+ return (
315
+ <label
316
+ key={key}
317
+ className="flex items-center gap-1.5 cursor-pointer select-none"
318
+ >
319
+ <input
320
+ type="checkbox"
321
+ checked={visibleKeys.includes(key)}
322
+ onChange={() => handleCheckboxChange(key)}
323
+ className="size-3"
324
+ style={{ accentColor: color }}
325
+ />
326
+ <span
327
+ className={`text-xs ${visibleKeys.includes(key) ? "text-slate-200" : "text-slate-500"}`}
328
+ >
329
+ {key}
330
+ </span>
331
+ <span
332
+ className={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}
333
+ >
334
+ {typeof currentData[key] === "number"
335
+ ? currentData[key].toFixed(2)
336
+ : "–"}
337
+ </span>
338
+ </label>
339
+ );
340
+ })}
341
+ </div>
342
+ );
343
+ }
344
+
345
  const SingleDataGraph = React.memo(
346
  ({
347
  data,
348
+ hoverStore,
 
349
  tall,
350
  }: {
351
  data: ChartRow[];
352
+ hoverStore: HoverStore;
 
353
  tall?: boolean;
354
  }) => {
355
+ const { seek } = useTimeControls();
356
  const flattenRow = useCallback(
357
  (row: Record<string, number | Record<string, number>>, prefix = "") => {
358
  const result: Record<string, number> = {};
 
436
  return { groups: grouped, singles: singleList, groupColorMap: colorMap };
437
  }, [dataKeys]);
438
 
439
+ const handleMouseLeave = () => hoverStore.set(null);
 
 
 
 
 
 
 
 
 
 
 
 
440
 
441
  const handleClick = (
442
  data: { activePayload?: { payload: { timestamp: number } }[] } | null,
 
446
  }
447
  };
448
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  // Derive chart title from the grouped feature names
450
  const chartTitle = useMemo(() => {
451
  const featureNames = Object.keys(groups);
 
470
  </p>
471
  )}
472
  <div
473
+ className={`relative w-full ${tall ? "h-[500px]" : "h-72"}`}
474
  onMouseLeave={handleMouseLeave}
475
  >
476
  <ResponsiveContainer width="100%" height="100%">
477
  <LineChart
478
  data={chartData}
479
  syncId="episode-sync"
480
+ margin={CHART_MARGIN}
481
  onClick={handleClick}
482
  onMouseMove={(state) => {
483
  const payload = state?.activePayload?.[0]?.payload as
484
  | { timestamp?: number }
485
  | undefined;
486
+ hoverStore.set(payload?.timestamp ?? null);
487
  }}
488
  onMouseLeave={handleMouseLeave}
489
  >
 
502
  stroke="#64748b"
503
  tick={{ fontSize: 12, fill: "#94a3b8" }}
504
  minTickGap={30}
505
+ height={X_AXIS_HEIGHT}
506
  allowDataOverflow={true}
507
  />
508
  <YAxis
509
  domain={["auto", "auto"]}
510
  stroke="#64748b"
511
  tick={{ fontSize: 12, fill: "#94a3b8" }}
512
+ width={Y_AXIS_WIDTH}
513
  allowDataOverflow={true}
514
  tickFormatter={(v: number) => {
515
  if (v === 0) return "0";
 
519
  }}
520
  />
521
 
522
+ <Tooltip content={() => null} isAnimationActive={false} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
 
524
  {dataKeys.map((key) => {
525
  const group = key.includes(SERIES_NAME_DELIMITER)
 
550
  })}
551
  </LineChart>
552
  </ResponsiveContainer>
553
+ <PlaybackCursor
554
+ start={chartData.at(0)?.timestamp ?? 0}
555
+ end={chartData.at(-1)?.timestamp ?? 0}
556
+ />
557
  </div>
558
+ <ChartLegend
559
+ chartData={chartData}
560
+ groups={groups}
561
+ singles={singles}
562
+ groupColorMap={groupColorMap}
563
+ visibleKeys={visibleKeys}
564
+ setVisibleKeys={setVisibleKeys}
565
+ hoverStore={hoverStore}
566
+ />
567
  </div>
568
  );
569
  },
src/context/time-context.tsx CHANGED
@@ -5,6 +5,7 @@ import React, {
5
  useState,
6
  useCallback,
7
  useEffect,
 
8
  } from "react";
9
 
10
  // `external` (default) — user-initiated seek (slider drag, chart click,
@@ -17,14 +18,8 @@ import React, {
17
  // report, not a command.
18
  type TimeUpdateSource = "external" | "video";
19
 
20
- type TimeContextType = {
21
- currentTime: number;
22
  seek: (t: number, source?: TimeUpdateSource) => void;
23
- // Monotonically increasing counter that bumps on every `external` seek.
24
- // Sync effects compare the current value against a stored ref to detect
25
- // user-initiated seeks without relying on heuristics like "did the time
26
- // jump by more than 0.3s".
27
- externalSeekVersion: number;
28
  subscribe: (cb: (t: number) => void) => () => void;
29
  isPlaying: boolean;
30
  setIsPlaying: React.Dispatch<React.SetStateAction<boolean>>;
@@ -32,14 +27,37 @@ type TimeContextType = {
32
  setDuration: React.Dispatch<React.SetStateAction<number>>;
33
  };
34
 
 
 
 
 
 
 
 
 
 
 
35
  const TimeContext = createContext<TimeContextType | undefined>(undefined);
36
 
 
37
  export const useTime = () => {
38
  const ctx = useContext(TimeContext);
39
  if (!ctx) throw new Error("useTime must be used within a TimeProvider");
40
  return ctx;
41
  };
42
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  const TIME_RENDER_THROTTLE_MS = 80;
44
 
45
  export const TimeProvider: React.FC<{
@@ -106,20 +124,25 @@ export const TimeProvider: React.FC<{
106
  return () => listeners.current.delete(cb);
107
  }, []);
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  return (
110
- <TimeContext.Provider
111
- value={{
112
- currentTime,
113
- seek: updateTime,
114
- externalSeekVersion,
115
- subscribe,
116
- isPlaying,
117
- setIsPlaying,
118
- duration,
119
- setDuration,
120
- }}
121
- >
122
- {children}
123
- </TimeContext.Provider>
124
  );
125
  };
 
5
  useState,
6
  useCallback,
7
  useEffect,
8
+ useMemo,
9
  } from "react";
10
 
11
  // `external` (default) — user-initiated seek (slider drag, chart click,
 
18
  // report, not a command.
19
  type TimeUpdateSource = "external" | "video";
20
 
21
+ type TimeControls = {
 
22
  seek: (t: number, source?: TimeUpdateSource) => void;
 
 
 
 
 
23
  subscribe: (cb: (t: number) => void) => () => void;
24
  isPlaying: boolean;
25
  setIsPlaying: React.Dispatch<React.SetStateAction<boolean>>;
 
27
  setDuration: React.Dispatch<React.SetStateAction<number>>;
28
  };
29
 
30
+ type TimeContextType = TimeControls & {
31
+ currentTime: number;
32
+ // Monotonically increasing counter that bumps on every `external` seek.
33
+ // Sync effects compare the current value against a stored ref to detect
34
+ // user-initiated seeks without relying on heuristics like "did the time
35
+ // jump by more than 0.3s".
36
+ externalSeekVersion: number;
37
+ };
38
+
39
+ const TimeControlsContext = createContext<TimeControls | undefined>(undefined);
40
  const TimeContext = createContext<TimeContextType | undefined>(undefined);
41
 
42
+ /** Everything, including `currentTime`: re-renders on every playback tick. */
43
  export const useTime = () => {
44
  const ctx = useContext(TimeContext);
45
  if (!ctx) throw new Error("useTime must be used within a TimeProvider");
46
  return ctx;
47
  };
48
 
49
+ /**
50
+ * Seeking and play state without `currentTime`. A component that only seeks or toggles playback
51
+ * should use this: reading `useTime()` at all re-renders it on every playback tick, whichever
52
+ * fields it destructures.
53
+ */
54
+ export const useTimeControls = () => {
55
+ const ctx = useContext(TimeControlsContext);
56
+ if (!ctx)
57
+ throw new Error("useTimeControls must be used within a TimeProvider");
58
+ return ctx;
59
+ };
60
+
61
  const TIME_RENDER_THROTTLE_MS = 80;
62
 
63
  export const TimeProvider: React.FC<{
 
124
  return () => listeners.current.delete(cb);
125
  }, []);
126
 
127
+ const controls = useMemo(
128
+ () => ({
129
+ seek: updateTime,
130
+ subscribe,
131
+ isPlaying,
132
+ setIsPlaying,
133
+ duration,
134
+ setDuration,
135
+ }),
136
+ [updateTime, subscribe, isPlaying, duration],
137
+ );
138
+ const value = useMemo(
139
+ () => ({ ...controls, currentTime, externalSeekVersion }),
140
+ [controls, currentTime, externalSeekVersion],
141
+ );
142
+
143
  return (
144
+ <TimeControlsContext.Provider value={controls}>
145
+ <TimeContext.Provider value={value}>{children}</TimeContext.Provider>
146
+ </TimeControlsContext.Provider>
 
 
 
 
 
 
 
 
 
 
 
147
  );
148
  };