replayContext.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import React, {useCallback, useContext, useEffect, useRef, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import {Replayer, ReplayerEvents} from 'rrweb';
  4. import {
  5. clearAllHighlights,
  6. highlightNode,
  7. removeHighlightedNode,
  8. } from 'sentry/utils/replays/highlightNode';
  9. import useRAF from 'sentry/utils/replays/hooks/useRAF';
  10. import type ReplayReader from 'sentry/utils/replays/replayReader';
  11. import usePrevious from 'sentry/utils/usePrevious';
  12. import HighlightReplayPlugin from './highlightReplayPlugin';
  13. type Dimensions = {height: number; width: number};
  14. type RootElem = null | HTMLDivElement;
  15. // Important: Don't allow context Consumers to access `Replayer` directly.
  16. // It has state that, when changed, will not trigger a react render.
  17. // Instead only expose methods that wrap `Replayer` and manage state.
  18. type ReplayPlayerContextProps = {
  19. /**
  20. * Clear all existing highlights in replay
  21. */
  22. clearAllHighlights: () => void;
  23. /**
  24. * The time, in milliseconds, where the user focus is.
  25. * The user focus can be reported by any collaborating object, usually on
  26. * hover.
  27. */
  28. currentHoverTime: undefined | number;
  29. /**
  30. * The current time of the video, in milliseconds
  31. * The value is updated on every animation frame, about every 16.6ms
  32. */
  33. currentTime: number;
  34. /**
  35. * Original dimensions in pixels of the captured browser window
  36. */
  37. dimensions: Dimensions;
  38. /**
  39. * Duration of the video, in miliseconds
  40. */
  41. duration: undefined | number;
  42. /**
  43. * The calculated speed of the player when fast-forwarding through idle moments in the video
  44. * The value is set to `0` when the video is not fast-forwarding
  45. * The speed is automatically determined by the length of each idle period
  46. */
  47. fastForwardSpeed: number;
  48. /**
  49. * Highlight a node in the replay
  50. */
  51. highlight: ({nodeId}: {nodeId: number}) => void;
  52. /**
  53. * Required to be called with a <div> Ref
  54. * Represents the location in the DOM where the iframe video should be mounted
  55. *
  56. * @param _root
  57. */
  58. initRoot: (root: RootElem) => void;
  59. /**
  60. * Set to true while the library is reconstructing the DOM
  61. */
  62. isBuffering: boolean;
  63. /**
  64. * Whether the video is currently playing
  65. */
  66. isPlaying: boolean;
  67. /**
  68. * Whether fast-forward mode is enabled if RRWeb detects idle moments in the video
  69. */
  70. isSkippingInactive: boolean;
  71. /**
  72. * Removes a highlighted node from the replay
  73. */
  74. removeHighlight: ({nodeId}: {nodeId: number}) => void;
  75. /**
  76. * The core replay data
  77. */
  78. replay: ReplayReader | null;
  79. /**
  80. * Set the currentHoverTime so collaborating components can highlight related
  81. * information
  82. */
  83. setCurrentHoverTime: (time: undefined | number) => void;
  84. /**
  85. * Jump the video to a specific time
  86. */
  87. setCurrentTime: (time: number) => void;
  88. /**
  89. * Set speed for normal playback
  90. */
  91. setSpeed: (speed: number) => void;
  92. /**
  93. * The speed for normal playback
  94. */
  95. speed: number;
  96. /**
  97. * Start or stop playback
  98. *
  99. * @param play
  100. */
  101. togglePlayPause: (play: boolean) => void;
  102. /**
  103. * Allow RRWeb to use Fast-Forward mode for idle moments in the video
  104. *
  105. * @param skip
  106. */
  107. toggleSkipInactive: (skip: boolean) => void;
  108. };
  109. const ReplayPlayerContext = React.createContext<ReplayPlayerContextProps>({
  110. clearAllHighlights: () => {},
  111. currentHoverTime: undefined,
  112. currentTime: 0,
  113. dimensions: {height: 0, width: 0},
  114. duration: undefined,
  115. fastForwardSpeed: 0,
  116. highlight: () => {},
  117. initRoot: () => {},
  118. isBuffering: false,
  119. isPlaying: false,
  120. isSkippingInactive: false,
  121. removeHighlight: () => {},
  122. replay: null,
  123. setCurrentHoverTime: () => {},
  124. setCurrentTime: () => {},
  125. setSpeed: () => {},
  126. speed: 1,
  127. togglePlayPause: () => {},
  128. toggleSkipInactive: () => {},
  129. });
  130. type Props = {
  131. children: React.ReactNode;
  132. replay: ReplayReader | null;
  133. /**
  134. * Time, in seconds, when the video should start
  135. */
  136. initialTimeOffset?: number;
  137. /**
  138. * Override return fields for testing
  139. */
  140. value?: Partial<ReplayPlayerContextProps>;
  141. };
  142. function useCurrentTime(callback: () => number) {
  143. const [currentTime, setCurrentTime] = useState(0);
  144. useRAF(() => setCurrentTime(callback));
  145. return currentTime;
  146. }
  147. export function Provider({children, replay, initialTimeOffset = 0, value = {}}: Props) {
  148. const events = replay?.getRRWebEvents();
  149. const theme = useTheme();
  150. const oldEvents = usePrevious(events);
  151. // Note we have to check this outside of hooks, see `usePrevious` comments
  152. const hasNewEvents = events !== oldEvents;
  153. const replayerRef = useRef<Replayer>(null);
  154. const [dimensions, setDimensions] = useState<Dimensions>({height: 0, width: 0});
  155. const [currentHoverTime, setCurrentHoverTime] = useState<undefined | number>();
  156. const [isPlaying, setIsPlaying] = useState(false);
  157. const [isSkippingInactive, setIsSkippingInactive] = useState(false);
  158. const [speed, setSpeedState] = useState(1);
  159. const [fastForwardSpeed, setFFSpeed] = useState(0);
  160. const [buffer, setBufferTime] = useState({target: -1, previous: -1});
  161. const playTimer = useRef<number | undefined>(undefined);
  162. const forceDimensions = (dimension: Dimensions) => {
  163. setDimensions(dimension);
  164. };
  165. const setPlayingFalse = () => {
  166. setIsPlaying(false);
  167. };
  168. const onFastForwardStart = (e: {speed: number}) => {
  169. setFFSpeed(e.speed);
  170. };
  171. const onFastForwardEnd = () => {
  172. setFFSpeed(0);
  173. };
  174. const highlight = useCallback(({nodeId}: {nodeId: number}) => {
  175. const replayer = replayerRef.current;
  176. if (!replayer) {
  177. return;
  178. }
  179. highlightNode({replayer, nodeId});
  180. }, []);
  181. const clearAllHighlightsCallback = useCallback(() => {
  182. const replayer = replayerRef.current;
  183. if (!replayer) {
  184. return;
  185. }
  186. clearAllHighlights({replayer});
  187. }, []);
  188. const removeHighlight = useCallback(({nodeId}: {nodeId: number}) => {
  189. const replayer = replayerRef.current;
  190. if (!replayer) {
  191. return;
  192. }
  193. removeHighlightedNode({replayer, nodeId});
  194. }, []);
  195. const initRoot = useCallback(
  196. (root: RootElem) => {
  197. if (events === undefined) {
  198. return;
  199. }
  200. if (root === null) {
  201. return;
  202. }
  203. if (replayerRef.current) {
  204. if (!hasNewEvents) {
  205. // Already have a player for these events, the parent node must've re-rendered
  206. return;
  207. }
  208. if (replayerRef.current.iframe.contentDocument?.body.childElementCount === 0) {
  209. // If this is true, then no need to clear old iframe as nothing was rendered
  210. return;
  211. }
  212. // We have new events, need to clear out the old iframe because a new
  213. // `Replayer` instance is about to be created
  214. while (root.firstChild) {
  215. root.removeChild(root.firstChild);
  216. }
  217. }
  218. const highlightReplayPlugin = new HighlightReplayPlugin();
  219. // eslint-disable-next-line no-new
  220. const inst = new Replayer(events, {
  221. root,
  222. blockClass: 'sr-block',
  223. // liveMode: false,
  224. // triggerFocus: false,
  225. mouseTail: {
  226. duration: 0.75 * 1000,
  227. lineCap: 'round',
  228. lineWidth: 2,
  229. strokeStyle: theme.purple200,
  230. },
  231. // unpackFn: _ => _,
  232. plugins: [highlightReplayPlugin],
  233. });
  234. // @ts-expect-error: rrweb types event handlers with `unknown` parameters
  235. inst.on(ReplayerEvents.Resize, forceDimensions);
  236. inst.on(ReplayerEvents.Finish, setPlayingFalse);
  237. // @ts-expect-error: rrweb types event handlers with `unknown` parameters
  238. inst.on(ReplayerEvents.SkipStart, onFastForwardStart);
  239. inst.on(ReplayerEvents.SkipEnd, onFastForwardEnd);
  240. // `.current` is marked as readonly, but it's safe to set the value from
  241. // inside a `useEffect` hook.
  242. // See: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
  243. // @ts-expect-error
  244. replayerRef.current = inst;
  245. },
  246. [events, theme.purple200, hasNewEvents]
  247. );
  248. useEffect(() => {
  249. const handleVisibilityChange = () => {
  250. if (document.visibilityState !== 'visible') {
  251. replayerRef.current?.pause();
  252. }
  253. };
  254. if (replayerRef.current && events) {
  255. initRoot(replayerRef.current.wrapper.parentElement as RootElem);
  256. document.addEventListener('visibilitychange', handleVisibilityChange);
  257. }
  258. return () => {
  259. document.removeEventListener('visibilitychange', handleVisibilityChange);
  260. };
  261. }, [initRoot, events]);
  262. const getCurrentTime = useCallback(
  263. () => (replayerRef.current ? Math.max(replayerRef.current.getCurrentTime(), 0) : 0),
  264. []
  265. );
  266. const setCurrentTime = useCallback(
  267. (requestedTimeMs: number) => {
  268. const replayer = replayerRef.current;
  269. if (!replayer) {
  270. return;
  271. }
  272. const maxTimeMs = replayerRef.current?.getMetaData().totalTime;
  273. const time = requestedTimeMs > maxTimeMs ? 0 : requestedTimeMs;
  274. // Sometimes rrweb doesn't get to the exact target time, as long as it has
  275. // changed away from the previous time then we can hide then buffering message.
  276. setBufferTime({target: time, previous: getCurrentTime()});
  277. // Clear previous timers. Without this (but with the setTimeout) multiple
  278. // requests to set the currentTime could finish out of order and cause jumping.
  279. if (playTimer.current) {
  280. window.clearTimeout(playTimer.current);
  281. }
  282. if (isPlaying) {
  283. playTimer.current = window.setTimeout(() => replayer.play(time), 0);
  284. setIsPlaying(true);
  285. } else {
  286. playTimer.current = window.setTimeout(() => replayer.pause(time), 0);
  287. setIsPlaying(false);
  288. }
  289. },
  290. [getCurrentTime, isPlaying]
  291. );
  292. const setSpeed = useCallback(
  293. (newSpeed: number) => {
  294. const replayer = replayerRef.current;
  295. if (!replayer) {
  296. return;
  297. }
  298. if (isPlaying) {
  299. replayer.pause();
  300. replayer.setConfig({speed: newSpeed});
  301. replayer.play(getCurrentTime());
  302. } else {
  303. replayer.setConfig({speed: newSpeed});
  304. }
  305. setSpeedState(newSpeed);
  306. },
  307. [getCurrentTime, isPlaying]
  308. );
  309. const togglePlayPause = useCallback(
  310. (play: boolean) => {
  311. const replayer = replayerRef.current;
  312. if (!replayer) {
  313. return;
  314. }
  315. if (play) {
  316. replayer.play(getCurrentTime());
  317. } else {
  318. replayer.pause(getCurrentTime());
  319. }
  320. setIsPlaying(play);
  321. },
  322. [getCurrentTime]
  323. );
  324. const toggleSkipInactive = useCallback((skip: boolean) => {
  325. const replayer = replayerRef.current;
  326. if (!replayer) {
  327. return;
  328. }
  329. if (skip !== replayer.config.skipInactive) {
  330. replayer.setConfig({skipInactive: skip});
  331. }
  332. setIsSkippingInactive(skip);
  333. }, []);
  334. // Only on pageload: set the initial playback timestamp
  335. useEffect(() => {
  336. if (initialTimeOffset && events && replayerRef.current) {
  337. setCurrentTime(initialTimeOffset * 1000);
  338. }
  339. }, [events, replayerRef.current]); // eslint-disable-line react-hooks/exhaustive-deps
  340. const currentPlayerTime = useCurrentTime(getCurrentTime);
  341. const [isBuffering, currentTime] =
  342. buffer.target !== -1 && buffer.previous === currentPlayerTime
  343. ? [true, buffer.target]
  344. : [false, currentPlayerTime];
  345. if (!isBuffering && buffer.target !== -1) {
  346. setBufferTime({target: -1, previous: -1});
  347. }
  348. const event = replay?.getEvent();
  349. const duration = event ? (event.endTimestamp - event.startTimestamp) * 1000 : undefined;
  350. return (
  351. <ReplayPlayerContext.Provider
  352. value={{
  353. clearAllHighlights: clearAllHighlightsCallback,
  354. currentHoverTime,
  355. currentTime,
  356. dimensions,
  357. duration,
  358. fastForwardSpeed,
  359. highlight,
  360. initRoot,
  361. isBuffering,
  362. isPlaying,
  363. isSkippingInactive,
  364. removeHighlight,
  365. replay,
  366. setCurrentHoverTime,
  367. setCurrentTime,
  368. setSpeed,
  369. speed,
  370. togglePlayPause,
  371. toggleSkipInactive,
  372. ...value,
  373. }}
  374. >
  375. {children}
  376. </ReplayPlayerContext.Provider>
  377. );
  378. }
  379. export const useReplayContext = () => useContext(ReplayPlayerContext);