replayContext.tsx 14 KB

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