replayContext.tsx 15 KB

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