Files
sexy/components/sessions/ReplayPlayer.tsx
T
valknarandClaude Sonnet 5 1bad1f4e33 Streamline the Replay view with the Control view
Page title is now "{session name} - Replay" (matching generateMetadata)
instead of a bare "Replay" heading with the name duplicated inside a
Card title. Dropped that redundant outer Card - the pre-connection
scan/match buttons now sit in a flat row below the header, same as
Control's scan/record row, with the same "no devices connected" hint
card shown underneath when nothing's connected yet. Playback controls
once a replay starts still live in a card, matching DeviceCard's style.
Also gave "Match & replay" a Play icon.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzyfRyA7h5rs5SCAahLAWd
2026-08-31 17:31:57 +02:00

260 lines
9.9 KiB
TypeScript

"use client";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Slider } from "@/components/ui/slider";
import { DeviceScanPanel } from "@/components/control/DeviceScanPanel";
import { DeviceRemapDialog } from "./DeviceRemapDialog";
import { disconnectAll, getButtplugClientHandle, getDevice, startScanning, stopScanning } from "@/lib/buttplug/client";
import { SessionPlayer, type SessionEventRow } from "@/lib/buttplug/player";
import { useButtplugStore } from "@/lib/buttplug/store";
import type { ActuatorInfo, ReplayDeviceSlot } from "@/lib/buttplug/types";
import { Pause, Play } from "lucide-react";
interface ReplayDataResponse {
session: {
id: number;
name: string | null;
durationMs: number;
};
deviceSlots: ReplayDeviceSlot[];
events: SessionEventRow[];
}
function formatTime(ms: number): string {
const totalSeconds = Math.floor(ms / 1000);
return `${Math.floor(totalSeconds / 60)}:${(totalSeconds % 60).toString().padStart(2, "0")}`;
}
export function ReplayPlayer({ sessionId }: { sessionId: number }) {
const scanning = useButtplugStore((s) => s.scanning);
const devices = useButtplugStore((s) => s.devices);
const setActuatorValue = useButtplugStore((s) => s.setActuatorValue);
const removeDevice = useButtplugStore((s) => s.removeDevice);
const connectedDevices = useMemo(() => Object.values(devices), [devices]);
const [data, setData] = useState<ReplayDataResponse | null>(null);
const [showRemap, setShowRemap] = useState(false);
const [starting, setStarting] = useState(false);
const [player, setPlayer] = useState<SessionPlayer | null>(null);
const [playing, setPlaying] = useState(false);
const [elapsedMs, setElapsedMs] = useState(0);
const [replayTargets, setReplayTargets] = useState<{ slotLabel: string; deviceName: string }[]>([]);
const [replayDeviceIndexes, setReplayDeviceIndexes] = useState<number[]>([]);
useEffect(() => {
fetch(`/api/sessions/${sessionId}/replay`)
.then((r) => r.json())
.then(setData)
.catch(() => toast.error("Could not load session"));
}, [sessionId]);
useEffect(() => {
return () => {
void disconnectAll();
};
}, []);
async function resetReplayDevices() {
await Promise.all(
replayDeviceIndexes.map(async (deviceIndex) => {
const liveDevice = await getDevice(deviceIndex);
await liveDevice?.stop().catch(() => {});
devices[deviceIndex]?.actuators.forEach((a) => setActuatorValue(deviceIndex, a.featureIndex, 0));
}),
);
}
async function handleConfirmRemap(mapping: Map<number, number>) {
if (!data) return;
setShowRemap(false);
setStarting(true);
try {
const orderedSlots = data.deviceSlots.filter((s) => mapping.has(s.sourceSessionDeviceId));
const targets = orderedSlots.map((slot) => {
const deviceIndex = mapping.get(slot.sourceSessionDeviceId)!;
const device = connectedDevices.find((d) => d.index === deviceIndex)!;
return { slotLabel: slot.slotLabel, deviceName: device.displayName ?? device.name };
});
// Replaying creates no session or events of its own - it just plays this
// session's already-recorded events back onto the mapped devices, and
// marks it as replayed (playCount/lastPlayedAt).
void fetch(`/api/sessions/${data.session.id}/replay`, { method: "POST" }).catch(() => {});
// `mapping` is already keyed by the source session's session_device id
// (see DeviceRemapDialog), exactly what SessionPlayer needs.
const sessionDeviceIdToDeviceIndex = mapping;
const actuatorsByDeviceIndex = new Map<number, ActuatorInfo[]>(
connectedDevices.map((d) => [d.index, d.actuators]),
);
// Reset every actuator on every device that will take part in this replay before
// the first scheduled event fires, so playback always starts from a known-zero
// state rather than whatever intensity was left over from manual control.
const deviceIndexes = new Set(sessionDeviceIdToDeviceIndex.values());
await Promise.all(
[...deviceIndexes].map(async (deviceIndex) => {
const liveDevice = await getDevice(deviceIndex);
await liveDevice?.stop().catch(() => {});
actuatorsByDeviceIndex.get(deviceIndex)?.forEach((a) => setActuatorValue(deviceIndex, a.featureIndex, 0));
}),
);
const { runtime } = await getButtplugClientHandle();
const instance = new SessionPlayer({
events: data.events,
durationMs: data.session.durationMs,
sessionDeviceIdToDeviceIndex,
actuatorsByDeviceIndex,
runtime,
onProgress: (elapsed) => setElapsedMs(elapsed),
onError: (message) => toast.error(`Replay command failed: ${message}`),
onComplete: () => {
setPlaying(false);
toast.success("Replay finished");
},
});
setReplayTargets(targets);
setReplayDeviceIndexes([...deviceIndexes]);
setPlayer(instance);
instance.play();
setPlaying(true);
} catch {
toast.error("Could not start replay");
} finally {
setStarting(false);
}
}
if (!data) {
return <p className="text-sm text-muted-foreground">Loading session...</p>;
}
return (
<div className="flex flex-col gap-6">
{!player ? (
<>
<div className="flex flex-wrap items-center gap-3">
<DeviceScanPanel scanning={scanning} onScan={() => void startScanning()} onStopScan={() => void stopScanning()} />
<Button
onClick={async () => {
try {
await getButtplugClientHandle();
setShowRemap(true);
} catch {
toast.error("Could not connect to Buttplug client");
}
}}
disabled={connectedDevices.length === 0 || starting}
>
{starting ? (
"Starting..."
) : (
<>
<Play className="size-3.5" /> Match & replay
</>
)}
</Button>
</div>
{connectedDevices.length === 0 && (
<Card className="bp-glass">
<CardContent className="py-6 text-sm text-muted-foreground">
No devices connected yet. Scan to discover nearby toys, then match them to this session&apos;s
original device slots.
</CardContent>
</Card>
)}
</>
) : (
<Card className="bp-glass">
<CardContent className="flex flex-col gap-3 py-6">
{replayTargets.length > 0 && (
<div className="flex flex-wrap gap-2">
{replayTargets.map((t) => (
<span
key={t.slotLabel}
className="bp-readout rounded-md border border-border bg-card/60 px-2 py-1 text-xs text-muted-foreground"
>
{t.slotLabel} {t.deviceName}
</span>
))}
</div>
)}
<Slider
value={[elapsedMs]}
max={data.session.durationMs}
onValueChange={([v]) => player.seek(v)}
/>
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="bp-readout text-xs text-muted-foreground">
{formatTime(elapsedMs)} / {formatTime(data.session.durationMs)}
</span>
<div className="flex items-center gap-2">
<Button
size="icon"
variant="outline"
onClick={async () => {
if (playing) {
player.pause();
setPlaying(false);
} else {
player.play();
setPlaying(true);
}
// Toggling either way leaves the toy holding whatever intensity was
// last sent - zero it out so pause always actually stops the device,
// and resume always starts from a clean, known state.
await resetReplayDevices();
}}
aria-label={playing ? "Pause" : "Play"}
>
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
</Button>
<Button
size="sm"
variant="ghost"
onClick={async () => {
player.stop();
setPlaying(false);
setElapsedMs(0);
// Fully disconnect every device that took part in this replay,
// not just stop the player - see handleDisconnectDevice in
// ButtplugConsole for why "stop + remove from store" is the
// closest equivalent Buttplug's protocol allows per-device.
await Promise.all(
replayDeviceIndexes.map(async (deviceIndex) => {
const liveDevice = await getDevice(deviceIndex);
await liveDevice?.stop().catch(() => {});
removeDevice(deviceIndex);
}),
);
setPlayer(null);
setReplayTargets([]);
setReplayDeviceIndexes([]);
}}
>
Stop
</Button>
</div>
</div>
</CardContent>
</Card>
)}
<DeviceRemapDialog
open={showRemap}
deviceSlots={data.deviceSlots}
connectedDevices={connectedDevices}
onCancel={() => setShowRemap(false)}
onConfirm={(mapping) => void handleConfirmRemap(mapping)}
/>
</div>
);
}