Skip to content

Commit

Permalink
Revert "fix: analytics at boot time (#3759)"
Browse files Browse the repository at this point in the history
This reverts commit 5b55e3b.
  • Loading branch information
rebelchris authored Dec 23, 2024
1 parent 5b55e3b commit 6e1db5a
Show file tree
Hide file tree
Showing 8 changed files with 161 additions and 164 deletions.
10 changes: 6 additions & 4 deletions packages/extension/src/companion/Companion.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,13 @@ export default function Companion({
}),
});
const [assetsLoadedDebounce] = useDebounceFn(() => setAssetsLoaded(true), 10);
const routeChangedCallback = useLogPageView();
const routeChangedCallbackRef = useLogPageView();

useEffect(() => {
routeChangedCallback?.();
}, [routeChangedCallback]);
if (routeChangedCallbackRef.current) {
routeChangedCallbackRef.current();
}
}, [routeChangedCallbackRef]);

const [checkAssets, clearCheckAssets] = useDebounceFn(() => {
if (containerRef?.current?.offsetLeft === 0) {
Expand All @@ -131,7 +133,7 @@ export default function Companion({
}

checkAssets();
routeChangedCallback?.();
routeChangedCallbackRef.current();
// @NOTE see https://dailydotdev.atlassian.net/l/cp/dK9h1zoM
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [containerRef]);
Expand Down
8 changes: 4 additions & 4 deletions packages/extension/src/newtab/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ function InternalApp(): ReactElement {
const { contentScriptGranted } = useContentScriptStatus();
const { hostGranted, isFetching: isCheckingHostPermissions } =
useHostStatus();
const routeChangedCallback = useLogPageView();
const routeChangedCallbackRef = useLogPageView();
useConsoleLogo();
const { user, isAuthReady } = useAuthContext();
const { growthbook } = useGrowthBookContext();
Expand All @@ -92,10 +92,10 @@ function InternalApp(): ReactElement {
const isFirefoxExtension = process.env.TARGET_BROWSER === 'firefox';

useEffect(() => {
if (isPageReady && currentPage) {
routeChangedCallback?.();
if (routeChangedCallbackRef.current && isPageReady) {
routeChangedCallbackRef.current();
}
}, [isPageReady, routeChangedCallback, currentPage]);
}, [isPageReady, routeChangedCallbackRef, currentPage]);

const { dismissToast } = useToastNotification();

Expand Down
11 changes: 5 additions & 6 deletions packages/shared/src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { AccessToken, Boot, Visit } from '../lib/boot';
import { isCompanionActivated } from '../lib/element';
import { AuthTriggers, AuthTriggersType } from '../lib/auth';
import { Squad } from '../graphql/sources';
import { checkIsExtension } from '../lib/func';
import { checkIsExtension, isNullOrUndefined } from '../lib/func';

export interface LoginState {
trigger: AuthTriggersType;
Expand Down Expand Up @@ -65,7 +65,6 @@ export interface AuthContextData {
isAuthReady?: boolean;
geo?: Boot['geo'];
}

const isExtension = checkIsExtension();
const AuthContext = React.createContext<AuthContextData>(null);
export const useAuthContext = (): AuthContextData => useContext(AuthContext);
Expand Down Expand Up @@ -105,7 +104,7 @@ export type AuthContextProviderProps = {
isFetched?: boolean;
isLegacyLogout?: boolean;
children?: ReactNode;
isAuthReady?: boolean;
firstLoad?: boolean;
} & Pick<
AuthContextData,
| 'getRedirectUri'
Expand Down Expand Up @@ -134,15 +133,15 @@ export const AuthContextProvider = ({
isLegacyLogout,
accessToken,
squads,
isAuthReady,
firstLoad,
geo,
}: AuthContextProviderProps): ReactElement => {
const [loginState, setLoginState] = useState<LoginState | null>(null);
const endUser = user && 'providers' in user ? user : null;
const referral = user?.referralId || user?.referrer;
const referralOrigin = user?.referralOrigin;

if (!!isAuthReady && endUser && !endUser?.infoConfirmed) {
if (firstLoad === true && endUser && !endUser?.infoConfirmed) {
logout(LogoutReason.IncomleteOnboarding);
}

Expand All @@ -153,7 +152,7 @@ export const AuthContextProvider = ({
return (
<AuthContext.Provider
value={{
isAuthReady,
isAuthReady: !isNullOrUndefined(firstLoad),
user: endUser,
isLoggedIn: !!endUser?.id,
referral: loginState?.referral ?? referral,
Expand Down
90 changes: 48 additions & 42 deletions packages/shared/src/contexts/BootProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import React, {
ReactElement,
ReactNode,
useCallback,
useMemo,
useEffect,
useRef,
useState,
} from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
Expand Down Expand Up @@ -86,7 +87,7 @@ const updateLocalBootData = (
return result;
};

const getCachedBootOrNull = () => {
const getCachedOrNull = () => {
try {
return JSON.parse(storage.getItem(BOOT_LOCAL_KEY));
} catch (err) {
Expand All @@ -111,8 +112,6 @@ export const BootDataProvider = ({
getRedirectUri,
getPage,
}: BootDataProviderProps): ReactElement => {
const { hostGranted } = useHostStatus();
const isExtension = checkIsExtension();
const queryClient = useQueryClient();
const preloadFeedsRef = useRef<PreloadFeeds>();
preloadFeedsRef.current = ({ feeds, user }) => {
Expand All @@ -131,15 +130,22 @@ export const BootDataProvider = ({
);
};

const initialData = useMemo(() => {
const [initialLoad, setInitialLoad] = useState<boolean>(null);
const [cachedBootData, setCachedBootData] = useState<Partial<Boot>>();

useEffect(() => {
if (localBootData) {
return localBootData;
setCachedBootData(localBootData);

return;
}

const boot = getLocalBootData();

if (!boot) {
return null;
setCachedBootData(null);

return;
}

if (boot?.settings?.theme) {
Expand All @@ -148,15 +154,17 @@ export const BootDataProvider = ({

preloadFeedsRef.current({ feeds: boot.feeds, user: boot.user });

return boot;
setCachedBootData(boot);
}, [localBootData]);

const logged = initialData?.user as LoggedUser;
const { hostGranted } = useHostStatus();
const isExtension = checkIsExtension();
const logged = cachedBootData?.user as LoggedUser;
const shouldRefetch = !!logged?.providers && !!logged?.id;
const lastAppliedChangeRef = useRef<Partial<BootCacheData>>();

const {
data: bootData,
data: remoteData,
error,
refetch,
isFetched,
Expand All @@ -167,25 +175,24 @@ export const BootDataProvider = ({
queryFn: async () => {
const result = await getBootData(app);
preloadFeedsRef.current({ feeds: result.feeds, user: result.user });
updateLocalBootData(bootData || {}, result);

return result;
},
refetchOnWindowFocus: shouldRefetch,
staleTime: STALE_TIME,
enabled: !isExtension || !!hostGranted,
placeholderData: initialData,
});

const isBootReady = isFetched && !isError && !!bootData;
const loadedFromCache = !!bootData;
const { user, settings, alerts, notifications, squads, geo } = bootData || {};
const isBootReady = isFetched && !isError;
const loadedFromCache = !!cachedBootData;
const { user, settings, alerts, notifications, squads, geo } =
cachedBootData || {};

useRefreshToken(bootData?.accessToken, refetch);
useRefreshToken(remoteData?.accessToken, refetch);
const updatedAtActive = user ? dataUpdatedAt : null;
const updateQueryCache = useCallback(
const updateBootData = useCallback(
(updatedBootData: Partial<BootCacheData>, update = true) => {
const cachedData = getCachedBootOrNull() ?? {};
const cachedData = getCachedOrNull() || {};
const lastAppliedChange = lastAppliedChangeRef.current;
let updatedData = { ...updatedBootData };
if (update) {
Expand All @@ -201,52 +208,51 @@ export const BootDataProvider = ({
}

const updated = updateLocalBootData(cachedData, updatedData);

queryClient.setQueryData<Partial<Boot>>(BOOT_QUERY_KEY, (previous) => {
if (!previous) {
return updated;
}

return { ...previous, ...updated };
});
setCachedBootData(updated);
},
[queryClient],
[],
);

const updateUser = useCallback(
async (newUser: LoggedUser | AnonymousUser) => {
updateQueryCache({ user: newUser });
updateBootData({ user: newUser });
await queryClient.invalidateQueries({
queryKey: generateQueryKey(RequestKey.Profile, newUser),
});
},
[updateQueryCache, queryClient],
[updateBootData, queryClient],
);

const updateSettings = useCallback(
(updatedSettings: Boot['settings']) =>
updateQueryCache({ settings: updatedSettings }),
[updateQueryCache],
(updatedSettings) => updateBootData({ settings: updatedSettings }),
[updateBootData],
);

const updateAlerts = useCallback(
(updatedAlerts: Boot['alerts']) =>
updateQueryCache({ alerts: updatedAlerts }),
[updateQueryCache],
(updatedAlerts) => updateBootData({ alerts: updatedAlerts }),
[updateBootData],
);

const updateExperimentation = useCallback(
(exp: BootCacheData['exp']) => {
updateLocalBootData(bootData, { exp });
updateLocalBootData(cachedBootData, { exp });
},
[bootData],
[cachedBootData],
);

gqlClient.setHeader(
'content-language',
(user as Partial<LoggedUser>)?.language || ContentLanguage.English,
);

useEffect(() => {
if (remoteData) {
setInitialLoad(initialLoad === null);
updateBootData(remoteData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [remoteData]);

if (error) {
return (
<div className="mx-2 flex h-screen items-center justify-center">
Expand All @@ -260,7 +266,7 @@ export const BootDataProvider = ({
app={app}
user={user}
deviceId={deviceId}
experimentation={bootData?.exp}
experimentation={cachedBootData?.exp}
updateExperimentation={updateExperimentation}
>
<AuthContextProvider
Expand All @@ -270,13 +276,13 @@ export const BootDataProvider = ({
getRedirectUri={getRedirectUri}
loadingUser={!dataUpdatedAt || !user}
loadedUserFromCache={loadedFromCache}
visit={bootData?.visit}
visit={remoteData?.visit}
refetchBoot={refetch}
isFetched={isBootReady}
isLegacyLogout={bootData?.isLegacyLogout}
accessToken={bootData?.accessToken}
isLegacyLogout={remoteData?.isLegacyLogout}
accessToken={remoteData?.accessToken}
squads={squads}
isAuthReady={isBootReady}
firstLoad={initialLoad}
geo={geo}
>
<SettingsContextProvider
Expand Down
65 changes: 28 additions & 37 deletions packages/shared/src/hooks/log/useLogContextData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MutableRefObject, useCallback } from 'react';
import { MutableRefObject, useMemo } from 'react';
import { LogEvent, PushToQueueFunc } from './useLogQueue';
import { getCurrentLifecycleState } from '../../lib/lifecycle';
import { Origin } from '../../lib/log';
Expand Down Expand Up @@ -51,42 +51,33 @@ export default function useLogContextData(
durationEventsQueue: MutableRefObject<Map<string, LogEvent>>,
sendBeacon: () => void,
): LogContextData {
const logEvent = useCallback(
(event: LogEvent) => {
pushToQueue([generateEvent(event, sharedPropsRef, getPage())]);
},
[getPage, pushToQueue, sharedPropsRef],
);
const logEventStart = useCallback(
(id, event) => {
if (!durationEventsQueue.current.has(id)) {
durationEventsQueue.current.set(
id,
generateEvent(event, sharedPropsRef, getPage()),
);
}
},
[durationEventsQueue, getPage, sharedPropsRef],
);
const logEventEnd = useCallback(
(id, now = new Date()) => {
const event = durationEventsQueue.current.get(id);
if (event) {
durationEventsQueue.current.delete(id);
event.event_duration = now.getTime() - event.event_timestamp.getTime();
if (window.scrollY > 0 && event.event_name !== 'page inactive') {
event.page_state = 'active';
return useMemo<LogContextData>(
() => ({
logEvent(event: LogEvent) {
pushToQueue([generateEvent(event, sharedPropsRef, getPage())]);
},
logEventStart(id, event) {
if (!durationEventsQueue.current.has(id)) {
durationEventsQueue.current.set(
id,
generateEvent(event, sharedPropsRef, getPage()),
);
}
pushToQueue([event]);
}
},
[durationEventsQueue, pushToQueue],
},
logEventEnd(id, now = new Date()) {
const event = durationEventsQueue.current.get(id);
if (event) {
durationEventsQueue.current.delete(id);
event.event_duration =
now.getTime() - event.event_timestamp.getTime();
if (window.scrollY > 0 && event.event_name !== 'page inactive') {
event.page_state = 'active';
}
pushToQueue([event]);
}
},
sendBeacon,
}),
[sharedPropsRef, getPage, pushToQueue, durationEventsQueue, sendBeacon],
);

return {
logEvent,
logEventStart,
logEventEnd,
sendBeacon,
};
}
Loading

0 comments on commit 6e1db5a

Please sign in to comment.