Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

improve replay perf (#935)

Goldflagd949e7957d73
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
index f85fd4d74..b59ec8291 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
@@ -6,13 +6,23 @@ import { APIResponse } from "../../../../../../api/types";
import { authedFetch, buildApiParams } from "../../../../../../api/utils";
import { getFilteredFilters, useStore } from "../../../../../../lib/store";
import { SESSION_PAGE_FILTERS } from "../../../../../../lib/filterGroups";
+import { useShallow } from "zustand/react/shallow";
import { useTimelineStore } from "../../../timelineStore";
import { calculateWindowSize } from "../../../timelineUtils";
import { MAX_PAGES, PAGE_SIZE } from "./timelineLayerConstants";
export function useTimelineSessions() {
const { time, site, timezone: storeTimezone } = useStore();
- const { manualWindowSize, setTimeRange, setWindowSize, setAllSessions, setLoading, setError } = useTimelineStore();
+ const { manualWindowSize, setTimeRange, setWindowSize, setAllSessions, setLoading, setError } = useTimelineStore(
+ useShallow(s => ({
+ manualWindowSize: s.manualWindowSize,
+ setTimeRange: s.setTimeRange,
+ setWindowSize: s.setWindowSize,
+ setAllSessions: s.setAllSessions,
+ setLoading: s.setLoading,
+ setError: s.setError,
+ }))
+ );
// Resolve "system" to actual timezone, but keep reactivity from useStore
const timezone = storeTimezone === "system" ? Intl.DateTimeFormat().resolvedOptions().timeZone : storeTimezone;
diff --git a/client/src/app/[site]/globe/components/TimelineScrubber.tsx b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
index 18b9c344f..347ad5d2a 100644
--- a/client/src/app/[site]/globe/components/TimelineScrubber.tsx
+++ b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { TimelineSlider } from "../../../../components/ui/timeline-slider";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../../../../components/ui/tooltip";
import { useStore } from "../../../../lib/store";
+import { useShallow } from "zustand/react/shallow";
import { useTimelineStore, useActiveSessions } from "../timelineStore";
import { formatTimelineTime, generateTimeWindows, getSessionCountsPerWindow } from "../timelineUtils";
import { MAX_PAGES, PAGE_SIZE } from "../3d/hooks/timelineLayer/timelineLayerConstants";
@@ -12,7 +13,17 @@ import { MAX_PAGES, PAGE_SIZE } from "../3d/hooks/timelineLayer/timelineLayerCon
export function TimelineScrubber() {
const t = useExtracted();
const { currentTime, timeRange, windowSize, setCurrentTime, allSessions, isLoading, hasMoreData } =
- useTimelineStore();
+ useTimelineStore(
+ useShallow(s => ({
+ currentTime: s.currentTime,
+ timeRange: s.timeRange,
+ windowSize: s.windowSize,
+ setCurrentTime: s.setCurrentTime,
+ allSessions: s.allSessions,
+ isLoading: s.isLoading,
+ hasMoreData: s.hasMoreData,
+ }))
+ );
const activeSessions = useActiveSessions();
// Use reactive timezone from useStore
const storeTimezone = useStore(state => state.timezone);
diff --git a/client/src/app/[site]/globe/page.tsx b/client/src/app/[site]/globe/page.tsx
index ce6687862..29f02eeb3 100644
--- a/client/src/app/[site]/globe/page.tsx
+++ b/client/src/app/[site]/globe/page.tsx
@@ -23,6 +23,7 @@ import { useCountriesLayer } from "./3d/hooks/useCountriesLayer";
import { useLayerVisibility } from "./3d/hooks/useLayerVisibility";
import { useMapbox } from "./3d/hooks/useMapbox";
import { useSubdivisionsLayer } from "./3d/hooks/useSubdivisionsLayer";
+import { useShallow } from "zustand/react/shallow";
import { useTimelineStore } from "./timelineStore";
import { useTimelineSessions } from "./3d/hooks/timelineLayer/useTimelineSessions";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
@@ -31,12 +32,23 @@ import { WINDOW_SIZE_OPTIONS } from "./timelineUtils";
export default function GlobePage() {
useSetPageTitle("Globe");
const mapContainer = useRef<HTMLDivElement>(null);
- const { windowSize, setManualWindowSize } = useTimelineStore();
+ const { windowSize, setManualWindowSize } = useTimelineStore(
+ useShallow(s => ({ windowSize: s.windowSize, setManualWindowSize: s.setManualWindowSize }))
+ );
// Fetch timeline sessions and update store
useTimelineSessions();
- const { mapView, mapMode, mapStyle, setMapStyle, timelineStyle, setTimelineStyle } = useGlobeStore();
+ const { mapView, mapMode, mapStyle, setMapStyle, timelineStyle, setTimelineStyle } = useGlobeStore(
+ useShallow(s => ({
+ mapView: s.mapView,
+ mapMode: s.mapMode,
+ mapStyle: s.mapStyle,
+ setMapStyle: s.setMapStyle,
+ timelineStyle: s.timelineStyle,
+ setTimelineStyle: s.setTimelineStyle,
+ }))
+ );
// Automatically switch styles based on view
useEffect(() => {
diff --git a/client/src/app/[site]/replay/components/ReplayCard.tsx b/client/src/app/[site]/replay/components/ReplayCard.tsx
index c09d98342..fde3dbbbd 100644
--- a/client/src/app/[site]/replay/components/ReplayCard.tsx
+++ b/client/src/app/[site]/replay/components/ReplayCard.tsx
@@ -28,6 +28,7 @@ import { Badge } from "../../../../components/ui/badge";
import { Button } from "../../../../components/ui/button";
import { Skeleton } from "../../../../components/ui/skeleton";
import { cn, formatter, getUserDisplayName } from "../../../../lib/utils";
+import { useShallow } from "zustand/react/shallow";
import { useReplayStore } from "@/components/replay/replayStore";
interface SessionReplayListItem {
@@ -55,7 +56,13 @@ interface SessionReplayListItem {
export function ReplayCard({ replay }: { replay: SessionReplayListItem }) {
const t = useExtracted();
const { formatRelative } = useDateTimeFormat();
- const { sessionId, setSessionId, resetPlayerState } = useReplayStore();
+ const { sessionId, setSessionId, resetPlayerState } = useReplayStore(
+ useShallow(s => ({
+ sessionId: s.sessionId,
+ setSessionId: s.setSessionId,
+ resetPlayerState: s.resetPlayerState,
+ }))
+ );
const [isDialogOpen, setIsDialogOpen] = useState(false);
const deleteSessionReplay = useDeleteSessionReplay();
const startTime = DateTime.fromSQL(replay.start_time, {
diff --git a/client/src/app/[site]/replay/components/ReplayList.tsx b/client/src/app/[site]/replay/components/ReplayList.tsx
index 78a2f476b..7d63d38d9 100644
--- a/client/src/app/[site]/replay/components/ReplayList.tsx
+++ b/client/src/app/[site]/replay/components/ReplayList.tsx
@@ -6,13 +6,21 @@ import { NothingFound } from "../../../../components/NothingFound";
import { ReplayCard, ReplayCardSkeleton } from "./ReplayCard";
import { useGetSessionReplays } from "../../../../api/analytics/hooks/sessionReplay/useGetSessionReplays";
import { SessionReplayListItem } from "../../../../api/analytics/endpoints";
+import { useShallow } from "zustand/react/shallow";
import { useReplayStore } from "@/components/replay/replayStore";
import { ScrollArea } from "../../../../components/ui/scroll-area";
import { Input } from "../../../../components/ui/input";
export function ReplayList() {
const t = useExtracted();
- const { sessionId, setSessionId, minDuration, setMinDuration } = useReplayStore();
+ const { sessionId, setSessionId, minDuration, setMinDuration } = useReplayStore(
+ useShallow(s => ({
+ sessionId: s.sessionId,
+ setSessionId: s.setSessionId,
+ minDuration: s.minDuration,
+ setMinDuration: s.setMinDuration,
+ }))
+ );
const { data, isLoading, error, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionReplays({
minDuration,
diff --git a/client/src/components/replay/ReplayBreadcrumbs.tsx b/client/src/components/replay/ReplayBreadcrumbs.tsx
index c1ec84f0d..1407ce4bf 100644
--- a/client/src/components/replay/ReplayBreadcrumbs.tsx
+++ b/client/src/components/replay/ReplayBreadcrumbs.tsx
@@ -27,12 +27,13 @@ import {
import { DateTime, Duration } from "luxon";
import Link from "next/link";
import { useParams } from "next/navigation";
-import { useMemo } from "react";
+import { useCallback, useMemo, useRef } from "react";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { useShallow } from "zustand/react/shallow";
import { useGetSessionReplayEvents } from "@/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents";
import { Avatar } from "@/components/Avatar";
import { IdentifiedBadge } from "@/components/IdentifiedBadge";
import { Button } from "@/components/ui/button";
-import { ScrollArea } from "@/components/ui/scroll-area";
import { getTimezone } from "@/lib/store";
import { cn, getUserDisplayName } from "@/lib/utils";
import { useReplayStore } from "./replayStore";
@@ -150,11 +151,37 @@ const getEventColor = (event: any) => {
return eventInfo?.color || "text-neutral-400";
};
+interface EventGroup {
+ events: any[];
+ type: string;
+ subType?: number;
+ startTime: number;
+ endTime: number;
+ count: number;
+}
+
+function getGroupDescription(group: EventGroup): string {
+ const firstEvent = group.events[0];
+ const baseDescription = getEventDescription(firstEvent);
+
+ if (group.count > 1) {
+ return `${baseDescription} (×${group.count})`;
+ }
+
+ return baseDescription;
+}
+
export function ReplayBreadcrumbs() {
const t = useExtracted();
const params = useParams();
const siteId = Number(params.site);
- const { sessionId, player, setCurrentTime } = useReplayStore();
+ const { sessionId, player, setCurrentTime } = useReplayStore(
+ useShallow(s => ({
+ sessionId: s.sessionId,
+ player: s.player,
+ setCurrentTime: s.setCurrentTime,
+ }))
+ );
const { data, isLoading, error } = useGetSessionReplayEvents(siteId, sessionId);
@@ -162,16 +189,9 @@ export function ReplayBreadcrumbs() {
const groupedEvents = useMemo(() => {
if (!data?.events) return [];
- const groups: Array<{
- events: any[];
- type: string;
- subType?: number;
- startTime: number;
- endTime: number;
- count: number;
- }> = [];
+ const groups: EventGroup[] = [];
- let currentGroup: (typeof groups)[0] | null = null;
+ let currentGroup: EventGroup | null = null;
data.events.forEach(event => {
const eventTypeStr = String(event.type);
@@ -220,16 +240,37 @@ export function ReplayBreadcrumbs() {
return timestamp - (firstTimestamp ?? 0);
};
- const handleEventClick = (timestamp: number) => {
- if (!player || !firstTimestamp) return;
+ const handleEventClick = useCallback(
+ (timestamp: number) => {
+ if (!player || !firstTimestamp) return;
- const timeInMs = timestamp - firstTimestamp;
- const timeInSeconds = timeInMs / 1000;
+ const timeInMs = timestamp - firstTimestamp;
- // Seek to the specific time
- player.goto(timeInMs);
- setCurrentTime(timeInSeconds);
- };
+ // Seek to the specific time
+ player.goto(timeInMs);
+ setCurrentTime(timeInMs);
+ },
+ [player, firstTimestamp, setCurrentTime]
+ );
+
+ const handleGroupClick = useCallback(
+ (group: EventGroup) => {
+ // Jump to the middle of the group
+ const middleIndex = Math.floor(group.events.length / 2);
+ const middleEvent = group.events[middleIndex];
+ handleEventClick(middleEvent.timestamp);
+ },
+ [handleEventClick]
+ );
+
+ // Virtualization
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
+ const virtualizer = useVirtualizer({
+ count: groupedEvents.length,
+ getScrollElement: () => scrollContainerRef.current,
+ estimateSize: () => 40,
+ overscan: 20,
+ });
if (isLoading || !data?.events) {
return (
@@ -239,24 +280,6 @@ export function ReplayBreadcrumbs() {
);
}
- const getGroupDescription = (group: (typeof groupedEvents)[0]) => {
- const firstEvent = group.events[0];
- const baseDescription = getEventDescription(firstEvent);
-
- if (group.count > 1) {
- return `${baseDescription} (×${group.count})`;
- }
-
- return baseDescription;
- };
-
- const handleGroupClick = (group: (typeof groupedEvents)[0]) => {
- // Jump to the middle of the group
- const middleIndex = Math.floor(group.events.length / 2);
- const middleEvent = group.events[middleIndex];
- handleEventClick(middleEvent.timestamp);
- };
-
// Calculate display name based on identification status
const isIdentified = !!data.metadata.identified_user_id;
const userLink = isIdentified
@@ -287,9 +310,13 @@ export function ReplayBreadcrumbs() {
<div className="p-2 border-b border-neutral-100 dark:border-neutral-800 text-xs text-neutral-600 dark:text-neutral-400 shrink-0">
{t("{count} events captured ({groupCount} groups)", { count: String(data.events.length), groupCount: String(groupedEvents.length) })}
</div>
- <ScrollArea className="flex-1 rounded-lg">
- <div className="overflow-x-hidden">
- {groupedEvents.map((group, index) => {
+ <div ref={scrollContainerRef} className="flex-1 overflow-auto rounded-lg">
+ <div
+ className="overflow-x-hidden relative"
+ style={{ height: `${virtualizer.getTotalSize()}px` }}
+ >
+ {virtualizer.getVirtualItems().map(virtualRow => {
+ const group = groupedEvents[virtualRow.index];
const firstEvent = group.events[0];
const Icon = getEventIcon(firstEvent);
const color = getEventColor(firstEvent);
@@ -300,12 +327,15 @@ export function ReplayBreadcrumbs() {
return (
<div
- key={`${group.startTime}-${index}`}
+ key={virtualRow.key}
+ data-index={virtualRow.index}
+ ref={virtualizer.measureElement}
className={cn(
"p-2 border-b border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900",
"hover:bg-neutral-50 dark:hover:bg-neutral-800/80 transition-colors cursor-pointer",
- "flex items-center gap-2 group"
+ "flex items-center gap-2 group absolute left-0 right-0"
)}
+ style={{ top: `${virtualRow.start}px` }}
onClick={() => handleGroupClick(group)}
>
<div className="text-xs text-neutral-600 dark:text-neutral-400 w-10">
@@ -331,7 +361,7 @@ export function ReplayBreadcrumbs() {
);
})}
</div>
- </ScrollArea>
+ </div>
</div>
</div>
);
diff --git a/client/src/components/replay/player/ReplayPlayer.tsx b/client/src/components/replay/player/ReplayPlayer.tsx
index 065d67707..09c860bfc 100644
--- a/client/src/components/replay/player/ReplayPlayer.tsx
+++ b/client/src/components/replay/player/ReplayPlayer.tsx
@@ -1,6 +1,7 @@
import { useParams } from "next/navigation";
-import { useEffect } from "react";
+import { useCallback, useEffect } from "react";
import "rrweb-player/dist/style.css";
+import { useShallow } from "zustand/react/shallow";
import { useGetSessionReplayEvents } from "@/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents";
import { ThreeDotLoader } from "@/components/Loaders";
import { useReplayStore } from "../replayStore";
@@ -24,7 +25,19 @@ export function ReplayPlayer({ width, height, isDrawer }: { width: number; heigh
duration,
setPlaybackSpeed,
resetPlayerState,
- } = useReplayStore();
+ } = useReplayStore(
+ useShallow(s => ({
+ sessionId: s.sessionId,
+ player: s.player,
+ isPlaying: s.isPlaying,
+ setIsPlaying: s.setIsPlaying,
+ currentTime: s.currentTime,
+ setCurrentTime: s.setCurrentTime,
+ duration: s.duration,
+ setPlaybackSpeed: s.setPlaybackSpeed,
+ resetPlayerState: s.resetPlayerState,
+ }))
+ );
const { data, isLoading, error } = useGetSessionReplayEvents(siteId, sessionId);
@@ -36,7 +49,7 @@ export function ReplayPlayer({ width, height, isDrawer }: { width: number; heigh
// Calculate activity periods when player and data are ready
useActivityPeriods({ data, player });
- const handlePlayPause = () => {
+ const handlePlayPause = useCallback(() => {
if (!player) return;
const newPlayingState = !isPlaying;
@@ -47,37 +60,43 @@ export function ReplayPlayer({ width, height, isDrawer }: { width: number; heigh
player.play();
}
setIsPlaying(newPlayingState);
- };
+ }, [player, isPlaying, setIsPlaying]);
- const handleSkipBack = () => {
+ const handleSkipBack = useCallback(() => {
if (!player) return;
const newTime = Math.max(0, currentTime - SKIP_SECONDS);
player.goto(newTime);
- };
+ }, [player, currentTime]);
- const handleSkipForward = () => {
+ const handleSkipForward = useCallback(() => {
if (!player) return;
const newTime = Math.min(duration, currentTime + SKIP_SECONDS);
player.goto(newTime);
- };
+ }, [player, duration, currentTime]);
- const handleSliderChange = (value: number[]) => {
- if (!player || !duration) return;
+ const handleSliderChange = useCallback(
+ (value: number[]) => {
+ if (!player || !duration) return;
- // Pause the player when user scrubs manually
- player.pause();
- setIsPlaying(false);
+ // Pause the player when user scrubs manually
+ player.pause();
+ setIsPlaying(false);
- const newTime = (value[0] / 100) * duration;
- player.goto(newTime);
- setCurrentTime(newTime);
- };
+ const newTime = (value[0] / 100) * duration;
+ player.goto(newTime);
+ setCurrentTime(newTime);
+ },
+ [player, duration, setIsPlaying, setCurrentTime]
+ );
- const handleSpeedChange = (speed: string) => {
- if (!player) return;
- setPlaybackSpeed(speed);
- player.setSpeed(parseFloat(speed));
- };
+ const handleSpeedChange = useCallback(
+ (speed: string) => {
+ if (!player) return;
+ setPlaybackSpeed(speed);
+ player.setSpeed(parseFloat(speed));
+ },
+ [player, setPlaybackSpeed]
+ );
// Add keyboard shortcuts
useReplayKeyboardShortcuts({
diff --git a/client/src/components/replay/player/ReplayPlayerControls.tsx b/client/src/components/replay/player/ReplayPlayerControls.tsx
index a7e44a397..d3c071601 100644
--- a/client/src/components/replay/player/ReplayPlayerControls.tsx
+++ b/client/src/components/replay/player/ReplayPlayerControls.tsx
@@ -3,7 +3,8 @@ import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Maximize2, Pause, Play } from "lucide-react";
-import { useState } from "react";
+import { memo, useState } from "react";
+import { useShallow } from "zustand/react/shallow";
import { ReplayDrawer } from "../../Sessions/ReplayDrawer";
import { useReplayStore } from "../replayStore";
import { formatTime, PLAYBACK_SPEEDS } from "./utils/replayUtils";
@@ -16,14 +17,24 @@ interface ReplayPlayerControlsProps {
isDrawer?: boolean;
}
-export function ReplayPlayerControls({
+export const ReplayPlayerControls = memo(function ReplayPlayerControls({
events,
onPlayPause,
onSliderChange,
onSpeedChange,
isDrawer,
}: ReplayPlayerControlsProps) {
- const { sessionId, player, isPlaying, currentTime, duration, playbackSpeed, activityPeriods } = useReplayStore();
+ const { sessionId, player, isPlaying, currentTime, duration, playbackSpeed, activityPeriods } = useReplayStore(
+ useShallow(s => ({
+ sessionId: s.sessionId,
+ player: s.player,
+ isPlaying: s.isPlaying,
+ currentTime: s.currentTime,
+ duration: s.duration,
+ playbackSpeed: s.playbackSpeed,
+ activityPeriods: s.activityPeriods,
+ }))
+ );
const [replayDrawerOpen, setReplayDrawerOpen] = useState(false);
return (
@@ -73,4 +84,4 @@ export function ReplayPlayerControls({
</div>
</div>
);
-}
+});
diff --git a/client/src/components/replay/player/ReplayPlayerTopbar.tsx b/client/src/components/replay/player/ReplayPlayerTopbar.tsx
index 1cda1ff5b..5a2492939 100644
--- a/client/src/components/replay/player/ReplayPlayerTopbar.tsx
+++ b/client/src/components/replay/player/ReplayPlayerTopbar.tsx
@@ -8,12 +8,25 @@ import {
DeviceTypeTooltipIcon,
OperatingSystemTooltipIcon,
} from "@/components/TooltipIcons/TooltipIcons";
+import { useShallow } from "zustand/react/shallow";
import { useReplayStore } from "../replayStore";
+// Extract pathname from full URL for display
+function getDisplayPath(url: string): string {
+ try {
+ const urlObj = new URL(url);
+ return urlObj.hostname + urlObj.pathname + urlObj.search + urlObj.hash;
+ } catch {
+ return url;
+ }
+}
+
export function ReplayPlayerTopbar() {
const params = useParams();
const siteId = Number(params.site);
- const { sessionId, currentTime } = useReplayStore();
+ const { sessionId, currentTime } = useReplayStore(
+ useShallow(s => ({ sessionId: s.sessionId, currentTime: s.currentTime }))
+ );
const { data } = useGetSessionReplayEvents(siteId, sessionId);
@@ -21,19 +34,18 @@ export function ReplayPlayerTopbar() {
const screenDimensions = `${metadata?.screen_width} × ${metadata?.screen_height}`;
const pageViewEvents = useMemo(() => {
- return data?.events?.filter(event => event.type === 4);
+ return data?.events?.filter((event: any) => Number(event.type) === 4);
}, [data?.events]);
// Get the current page URL based on the replay currentTime
const pageUrl = useMemo(() => {
- if (!pageViewEvents || currentTime === 0) {
+ if (!pageViewEvents || pageViewEvents.length === 0 || currentTime === 0) {
return metadata?.page_url;
}
let currentUrl = metadata?.page_url;
const firstTimestamp = pageViewEvents[0].timestamp;
- // Find the most recent Meta event (type 4) with href before currentTime
for (const event of pageViewEvents) {
if (event.timestamp - firstTimestamp > currentTime) break;
if (event.data?.href) {
@@ -59,16 +71,6 @@ export function ReplayPlayerTopbar() {
);
}
- // Extract pathname from full URL for display
- const getDisplayPath = (url: string): string => {
- try {
- const urlObj = new URL(url);
- return urlObj.hostname + urlObj.pathname + urlObj.search + urlObj.hash;
- } catch {
- return url;
- }
- };
-
return (
<div className="border border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900 px-2 py-2 rounded-t-lg overflow-hidden">
<div className="flex items-center justify-between min-w-0">
diff --git a/client/src/components/replay/player/hooks/useReplayPlayer.ts b/client/src/components/replay/player/hooks/useReplayPlayer.ts
index 114c94ea5..a9c77c5e2 100644
--- a/client/src/components/replay/player/hooks/useReplayPlayer.ts
+++ b/client/src/components/replay/player/hooks/useReplayPlayer.ts
@@ -1,5 +1,6 @@
import { useEffect, useRef } from "react";
import rrwebPlayer from "rrweb-player";
+import { useShallow } from "zustand/react/shallow";
import { useReplayStore } from "../../replayStore";
import { CONTROLS_HEIGHT } from "../utils/replayUtils";
@@ -11,8 +12,23 @@ interface UseReplayPlayerProps {
export const useReplayPlayer = ({ data, width, height }: UseReplayPlayerProps) => {
const playerContainerRef = useRef<HTMLDivElement>(null);
- const { setPlayer, setCurrentTime, setIsPlaying, setDuration, setActivityPeriods } = useReplayStore();
-
+ const playerRef = useRef<any>(null);
+ const { setPlayer, setCurrentTime, setIsPlaying, setDuration } = useReplayStore(
+ useShallow(s => ({
+ setPlayer: s.setPlayer,
+ setCurrentTime: s.setCurrentTime,
+ setIsPlaying: s.setIsPlaying,
+ setDuration: s.setDuration,
+ }))
+ );
+
+ // Store width/height in refs for the resize effect
+ const widthRef = useRef(width);
+ const heightRef = useRef(height);
+ widthRef.current = width;
+ heightRef.current = height;
+
+ // Initialize player when data changes
useEffect(() => {
if (data?.events && playerContainerRef.current) {
// Clear any existing content first
@@ -27,14 +43,15 @@ export const useReplayPlayer = ({ data, width, height }: UseReplayPlayerProps) =
target: playerContainerRef.current,
props: {
events: data.events as any, // Cast to any to handle type compatibility with rrweb
- width: width,
+ width: widthRef.current,
// subtract for the custom controls
- height: height - CONTROLS_HEIGHT,
+ height: heightRef.current - CONTROLS_HEIGHT,
autoPlay: false,
showController: false, // We'll use custom controls
},
});
+ playerRef.current = newPlayer;
setPlayer(newPlayer);
// Set up event listeners
@@ -117,10 +134,22 @@ export const useReplayPlayer = ({ data, width, height }: UseReplayPlayerProps) =
if (handleVisibilityChange) {
document.removeEventListener("visibilitychange", handleVisibilityChange);
}
+ playerRef.current = null;
setPlayer(null);
};
}
- }, [data, width, height, setPlayer, setCurrentTime, setIsPlaying, setDuration, setActivityPeriods]);
+ }, [data, setPlayer, setCurrentTime, setIsPlaying, setDuration]);
+
+ // Update dimensions without recreating the player
+ useEffect(() => {
+ if (playerRef.current) {
+ playerRef.current.$set({
+ width,
+ height: height - CONTROLS_HEIGHT,
+ });
+ playerRef.current.triggerResize();
+ }
+ }, [width, height]);
return { playerContainerRef };
};