-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathgatsby-browser.tsx
84 lines (69 loc) · 2.48 KB
/
gatsby-browser.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import React, { useEffect, useRef } from 'react';
import type { GatsbyBrowser } from 'gatsby';
import { reducerFlashes } from '@ably/ui/core/Flash';
import { initInsights, trackPageView, setupObserver } from '@ably/ui/core/insights';
import {
attachStoreToWindow,
createRemoteDataStore,
reducerBlogPosts,
reducerSessionData,
} from '@ably/ui/core/scripts';
import { reducerApiKeyData } from './src/redux/api-key/api-key-reducer';
import UserContextWrapper from './src/contexts/user-context/wrap-with-provider';
import { useSiteMetadata } from './src/hooks/use-site-metadata';
const onClientEntry: GatsbyBrowser['onClientEntry'] = () => {
setupObserver();
const store = createRemoteDataStore({
...reducerBlogPosts,
...reducerSessionData,
...reducerApiKeyData,
...reducerFlashes,
});
attachStoreToWindow(store);
};
/**
* The 'shouldUpdateScroll' function will fire when navigating to new pages within Gatsby
*/
const shouldUpdateScroll: GatsbyBrowser['shouldUpdateScroll'] = ({ prevRouterProps, routerProps: { location } }) => {
if (!prevRouterProps || !location) {
return false;
}
const curr = location.pathname;
const prev = prevRouterProps.location.pathname;
return (
curr !== prev && // If the current location is a variant of the previous location, do not update scroll
!(curr.indexOf('#') > -1) &&
!(prev.indexOf('#') > -1) // If we're going to or from any hash link on page B from page A, do not update scroll; we want to visit the specific section
);
};
const InsightsWrapper = ({ children }) => {
// Use a ref to track if we've already initialized
const initialized = useRef(false);
const { externalScriptsData } = useSiteMetadata();
useEffect(() => {
// Initialize insights only once
if (!initialized.current) {
initialized.current = true;
initInsights({
debug: externalScriptsData.insightsDebug,
mixpanelToken: externalScriptsData.mixpanelApiKey,
mixpanelAutoCapture: externalScriptsData.mixpanelAutoCapture,
posthogApiKey: externalScriptsData.posthogApiKey,
posthogApiHost: externalScriptsData.posthogHost,
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return children;
};
export const wrapRootElement = ({ element }) => {
return (
<InsightsWrapper>
<UserContextWrapper element={element} />
</InsightsWrapper>
);
};
export const onRouteUpdate = () => {
trackPageView();
};
export { onClientEntry, shouldUpdateScroll };