diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx index ce54243fba..79f789d582 100644 --- a/packages/shared/src/hooks/post/useViewPost.spec.tsx +++ b/packages/shared/src/hooks/post/useViewPost.spec.tsx @@ -1,6 +1,12 @@ import React from 'react'; -import type { ReactNode } from 'react'; -import { act, renderHook, waitFor } from '@testing-library/react'; +import type { ComponentProps, ReactNode } from 'react'; +import { + act, + render, + renderHook, + screen, + waitFor, +} from '@testing-library/react'; import { QueryClient, useQuery } from '@tanstack/react-query'; import { GrowthBook } from '@growthbook/growthbook-react'; import nock from 'nock'; @@ -13,7 +19,12 @@ import { VIEW_POST_MUTATION } from '../../graphql/posts'; import { REQUEST_PROTOCOL_KEY } from '../../graphql/common'; import { generateQueryKey, RequestKey } from '../../lib/query'; import { DayOfWeek } from '../../lib/date'; +import { dateFormatInTimezone } from '../../lib/timezones'; import { readStreakViewQueue } from '../../lib/streakViewQueue'; +import { getStreakCelebratedKey } from '../../lib/streakDailyCelebration'; +import type { ToastNotification } from '../useToastNotification'; +import { TOAST_NOTIF_KEY } from '../useToastNotification'; +import { LogEvent, TargetType } from '../../lib/log'; import { STREAK_REFETCH_RETRY_DELAY_MS, useViewPost } from './useViewPost'; const user = { ...loggedUser, timezone: 'Europe/Amsterdam' }; @@ -46,30 +57,51 @@ const renderViewPost = ({ client, requestMethod, flag = true, + celebrationFlag = false, isCompanion = false, + initialStreak = streak, + alerts, + log, + settings, }: { client: QueryClient; requestMethod: jest.Mock; flag?: boolean; + celebrationFlag?: boolean; isCompanion?: boolean; + initialStreak?: UserStreak; + alerts?: ComponentProps['alerts']; + log?: ComponentProps['log']; + settings?: ComponentProps['settings']; }) => { client.setQueryData(REQUEST_PROTOCOL_KEY, { requestMethod, isCompanion }); const gb = new GrowthBook({ - features: { streak_optimistic_view: { defaultValue: flag } }, + features: { + streak_optimistic_view: { defaultValue: flag }, + streak_daily_celebration: { defaultValue: celebrationFlag }, + }, }); + const getFeatureValue = jest.spyOn(gb, 'getFeatureValue'); const wrapper = ({ children }: { children: ReactNode }) => ( - + {children} ); - return renderHook( + const view = renderHook( () => { // the streak query the post page shell already has in cache useQuery({ queryKey: streakKey, queryFn: getReadingStreak, - initialData: streak, + initialData: initialStreak, staleTime: Infinity, }); @@ -77,6 +109,8 @@ const renderViewPost = ({ }, { wrapper }, ); + + return { ...view, getFeatureValue }; }; describe('useViewPost', () => { @@ -310,4 +344,258 @@ describe('useViewPost', () => { expect(client.getQueryData(streakKey)).toEqual(streak); expect(readStreakViewQueue()).toEqual([]); }); + + describe('daily celebration toast', () => { + // 5 -> 6: not a milestone (the API raises the milestone modal on + // Fibonacci days), so the daily toast is the one that celebrates it + const dayFive: UserStreak = { ...streak, current: 5, max: 5 }; + const daySix: UserStreak = { + ...dayFive, + current: 6, + max: 6, + total: 21, + lastViewAt: new Date(), + }; + const requestMethod = () => + jest.fn().mockResolvedValue({ viewPost: { _: true } }); + const getToast = () => + client.getQueryData(TOAST_NOTIF_KEY); + + it('should toast once on the first counted read of the day', async () => { + const logEvent = jest.fn(); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + initialStreak: dayFive, + log: { logEvent }, + }); + + await act(async () => { + await result.current('p1'); + }); + + render(<>{getToast()?.message}); + expect(screen.getByText('Day 6! See you tomorrow.')).toBeInTheDocument(); + expect(logEvent).toHaveBeenCalledTimes(1); + expect(logEvent).toHaveBeenCalledWith({ + event_name: LogEvent.Impression, + target_type: TargetType.StreakDailyCelebration, + target_id: 6, + }); + expect(localStorage.getItem(getStreakCelebratedKey(user.id))).toBe( + dateFormatInTimezone(new Date(), 'yyyy-MM-dd', user.timezone), + ); + + // a second first-view the same day (replay, second tab) stays quiet + client.setQueryData(TOAST_NOTIF_KEY, null); + client.setQueryData(streakKey, dayFive); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + + await act(async () => { + await result.current('p2'); + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 6, + }), + ); + expect(getToast()).toBeNull(); + expect(logEvent).toHaveBeenCalledTimes(1); + }); + + it('should not toast when the milestone modal is due', async () => { + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + initialStreak: dayFive, + alerts: { alerts: { showStreakMilestone: true } }, + }); + + await act(async () => { + await result.current('p1'); + }); + + expect(getToast()).toBeFalsy(); + expect(localStorage.getItem(getStreakCelebratedKey(user.id))).toBeNull(); + }); + + it('should leave milestone days to the milestone modal', async () => { + // 7 -> 8 is a Fibonacci day: the API flags showStreakMilestone for it + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: serverStreak } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + }); + + await act(async () => { + await result.current('p1'); + }); + + expect(getToast()).toBeFalsy(); + }); + + describe('when the refetch still has the pre-view streak', () => { + // the newView worker has not credited the read yet, so userStreak + // returns yesterday's 7 although this read makes it 8 + const mockPreViewStreak = () => + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: streak } }, + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('should not toast the stale count on a milestone day', async () => { + mockPreViewStreak(); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + flag: false, + celebrationFlag: true, + }); + + await act(async () => { + await result.current('p1'); + }); + + // 8 is a milestone, so the toast stays quiet instead of "Day 7!" + expect(nock.isDone()).toBe(true); + expect(getToast()).toBeFalsy(); + expect( + localStorage.getItem(getStreakCelebratedKey(user.id)), + ).toBeNull(); + }); + + it('should not toast the stale count after the retry is stale too', async () => { + jest.useFakeTimers({ advanceTimers: true }); + mockPreViewStreak(); + mockPreViewStreak(); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + }); + + const promise = result.current('p1'); + await waitFor(() => expect(nock.pendingMocks()).toHaveLength(1)); + await act(async () => { + await jest.advanceTimersByTimeAsync(STREAK_REFETCH_RETRY_DELAY_MS); + await promise; + }); + + expect(nock.isDone()).toBe(true); + expect(getToast()).toBeFalsy(); + }); + + it('should toast the count this read lands on', async () => { + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: dayFive } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + flag: false, + celebrationFlag: true, + initialStreak: dayFive, + }); + + await act(async () => { + await result.current('p1'); + }); + + render(<>{getToast()?.message}); + expect( + screen.getByText('Day 6! See you tomorrow.'), + ).toBeInTheDocument(); + }); + }); + + it('should not evaluate the flag for users who opted out of streaks', async () => { + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result, getFeatureValue } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + initialStreak: dayFive, + settings: { optOutReadingStreak: true }, + }); + + await act(async () => { + await result.current('p1'); + }); + + expect(getToast()).toBeFalsy(); + expect( + getFeatureValue.mock.calls.some( + ([id]) => id === 'streak_daily_celebration', + ), + ).toBe(false); + }); + + it('should not evaluate the flag while settings are loading', async () => { + const { getFeatureValue } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + settings: { loadedSettings: false }, + }); + + await act(() => Promise.resolve()); + expect( + getFeatureValue.mock.calls.some( + ([id]) => id === 'streak_daily_celebration', + ), + ).toBe(false); + }); + + it('should not toast when the flag is off', async () => { + const logEvent = jest.fn(); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + initialStreak: dayFive, + log: { logEvent }, + }); + + await act(async () => { + await result.current('p1'); + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 6, + }), + ); + expect(getToast()).toBeFalsy(); + expect(logEvent).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index 1ef41edb1e..5b13178ab8 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -13,6 +13,7 @@ import { isFinalViewRejection, } from '../../lib/streakViewQueue'; import { includesThisRead } from '../../lib/userStreak'; +import { useStreakDailyCelebration } from '../streaks/useStreakDailyCelebration'; // The API credits the view in a worker after the mutation resolves, so the // first refetch can miss it. Give the worker this long before asking again. @@ -27,6 +28,9 @@ interface ViewPostContext { previousStreak?: UserStreak; optimisticStreak?: UserStreak; shouldRefetchStreak: boolean; + // the count this view should land on, used when the refetch fails or + // has not caught up with the view yet + nextStreak?: number; } export const useViewPost = (): UseMutateAsyncFunction< @@ -42,6 +46,7 @@ export const useViewPost = (): UseMutateAsyncFunction< feature: featureStreakOptimisticView, shouldEvaluate: !!user, }); + const celebrateStreakDay = useStreakDailyCelebration(); const streakKey = generateQueryKey(RequestKey.UserStreak, user); const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user); const { mutateAsync: onSendViewPost } = useMutation< @@ -62,9 +67,10 @@ export const useViewPost = (): UseMutateAsyncFunction< user!.timezone, ); const shouldRefetchStreak = isNewStreak || isFirstViewToday; + const nextStreak = streak ? streak.current + 1 : undefined; if (!isOptimisticView || !shouldRefetchStreak || !streak) { - return { shouldRefetchStreak }; + return { shouldRefetchStreak, nextStreak }; } const current = streak.current + 1; @@ -77,7 +83,12 @@ export const useViewPost = (): UseMutateAsyncFunction< }; client.setQueryData(streakKey, optimisticStreak); - return { previousStreak: streak, optimisticStreak, shouldRefetchStreak }; + return { + previousStreak: streak, + optimisticStreak, + shouldRefetchStreak, + nextStreak, + }; }, onSuccess: async (_, __, context) => { if (!context.shouldRefetchStreak) { @@ -85,24 +96,31 @@ export const useViewPost = (): UseMutateAsyncFunction< } const { optimisticStreak } = context; - const refetchStreak = async (): Promise => { + // Resolves with the refetched streak only when it already counts this + // view: the API credits it in a worker, so it can still be the + // pre-view streak. + const refetchStreak = async (): Promise => { await client.refetchQueries({ queryKey: streakKey }); + const refetched = client.getQueryData(streakKey); return includesThisRead( - client.getQueryData(streakKey), + refetched, user?.timezone, - optimisticStreak?.current, - ); + optimisticStreak?.current ?? context.nextStreak, + ) + ? refetched + : undefined; }; - const isCounted = await refetchStreak(); + let countedStreak = await refetchStreak(); // A refetch that still has the pre-view streak would undo the // optimistic bump, so keep the bump and ask once more after a moment. - if (optimisticStreak && !isCounted) { + if (optimisticStreak && !countedStreak) { client.setQueryData(streakKey, optimisticStreak); await wait(STREAK_REFETCH_RETRY_DELAY_MS); + countedStreak = await refetchStreak(); - if (!(await refetchStreak())) { + if (!countedStreak) { client.setQueryData(streakKey, optimisticStreak); } } @@ -110,6 +128,8 @@ export const useViewPost = (): UseMutateAsyncFunction< // just mark the query as stale await client.invalidateQueries({ queryKey: readKey }); + celebrateStreakDay(countedStreak?.current ?? context.nextStreak); + return null; }, onError: (error, id, context) => { diff --git a/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx b/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx new file mode 100644 index 0000000000..6f335f411a --- /dev/null +++ b/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx @@ -0,0 +1,84 @@ +import React, { useCallback, useContext } from 'react'; +import { useAuthContext } from '../../contexts/AuthContext'; +import { useAlertsContext } from '../../contexts/AlertContext'; +import SettingsContext from '../../contexts/SettingsContext'; +import { useLogContext } from '../../contexts/LogContext'; +import { useToastNotification } from '../useToastNotification'; +import { useRequestProtocol } from '../useRequestProtocol'; +import { useConditionalFeature } from '../useConditionalFeature'; +import { featureStreakDailyCelebration } from '../../lib/featureManagement'; +import { LogEvent, TargetType } from '../../lib/log'; +import { + hasCelebratedStreakToday, + isStreakMilestone, + markStreakCelebrated, +} from '../../lib/streakDailyCelebration'; +import { ReadingStreakIcon } from '../../components/icons/ReadingStreak'; +import { IconSize } from '../../components/Icon'; + +export const getStreakDailyCelebrationCopy = (current: number): string => + `Day ${current}! See you tomorrow.`; + +// Toasts "Day n! See you tomorrow." once per local day, after the first read +// that extended the streak. Milestone days leave the stage to the milestone +// modal, and the companion never shows it: it has no streak in its cache, so +// every read there looks like the first of the day. +export const useStreakDailyCelebration = (): ((current?: number) => void) => { + const { user } = useAuthContext(); + const { isCompanion } = useRequestProtocol(); + const { alerts } = useAlertsContext(); + const { optOutReadingStreak, loadedSettings } = useContext(SettingsContext); + const { displayToast } = useToastNotification(); + const { logEvent } = useLogContext(); + const isStreaksEnabled = loadedSettings && !optOutReadingStreak; + // Users who opted out of streaks (or whose settings are still loading) can + // never see the toast, so keep them out of the experiment. + const { value: isEnabled } = useConditionalFeature({ + feature: featureStreakDailyCelebration, + shouldEvaluate: !!user && !isCompanion && isStreaksEnabled, + }); + const showStreakMilestone = alerts?.showStreakMilestone; + + return useCallback( + (current?: number) => { + if ( + !isEnabled || + isCompanion || + !user || + !isStreaksEnabled || + !current || + showStreakMilestone || + isStreakMilestone(current) || + hasCelebratedStreakToday(user.id, user.timezone) + ) { + return; + } + + markStreakCelebrated(user.id, user.timezone); + displayToast( + + + {getStreakDailyCelebrationCopy(current)} + , + ); + logEvent({ + event_name: LogEvent.Impression, + target_type: TargetType.StreakDailyCelebration, + target_id: current, + }); + }, + [ + displayToast, + isCompanion, + isEnabled, + isStreaksEnabled, + logEvent, + showStreakMilestone, + user, + ], + ); +}; diff --git a/packages/shared/src/lib/featureManagement.ts b/packages/shared/src/lib/featureManagement.ts index 796bf777ea..eba39e95a8 100644 --- a/packages/shared/src/lib/featureManagement.ts +++ b/packages/shared/src/lib/featureManagement.ts @@ -109,6 +109,12 @@ export const featureStreakOptimisticView = new Feature( false, ); +// daily "streak extended" toast on the first counted read of a local day +export const featureStreakDailyCelebration = new Feature( + 'streak_daily_celebration', + false, +); + export const briefCardFeedFeature = new Feature( 'brief_card_feed', isDevelopment, diff --git a/packages/shared/src/lib/log.ts b/packages/shared/src/lib/log.ts index 98e62cc235..1e6af79555 100644 --- a/packages/shared/src/lib/log.ts +++ b/packages/shared/src/lib/log.ts @@ -785,6 +785,7 @@ export enum TargetType { StreaksMilestone = 'streaks milestone', StreakRecover = 'streak restore', StreakFreezePurchase = 'streak freeze purchase', + StreakDailyCelebration = 'streak daily celebration', PromotionCard = 'promotion_card', PromotionalBanner = 'promotion_banner', MarketingCtaPopover = 'promotion_popover', diff --git a/packages/shared/src/lib/streakDailyCelebration.ts b/packages/shared/src/lib/streakDailyCelebration.ts new file mode 100644 index 0000000000..13384e8b56 --- /dev/null +++ b/packages/shared/src/lib/streakDailyCelebration.ts @@ -0,0 +1,51 @@ +import { generateStorageKey, StorageTopic } from './storage'; +import { storageWrapper } from './storageWrapper'; +import { dateFormatInTimezone } from './timezones'; + +const STREAK_DAY_FORMAT = 'yyyy-MM-dd'; + +export const getStreakCelebratedKey = (userId: string): string => + generateStorageKey(StorageTopic.Streak, 'celebrated', userId); + +const isPerfectSquare = (num: number): boolean => { + const root = Math.floor(Math.sqrt(num)); + return root * root === num; +}; + +const isFibonacci = (num: number): boolean => { + const square = 5 * num * num; + return isPerfectSquare(square + 4) || isPerfectSquare(square - 4); +}; + +// Mirrors the API's milestone rule (workers/newView.ts), which raises +// alerts.showStreakMilestone for the milestone modal on these days. +export const isStreakMilestone = (current: number): boolean => + current > 1 && isFibonacci(current); + +export const hasCelebratedStreakToday = ( + userId: string, + timezone?: string, +): boolean => { + try { + return ( + storageWrapper.getItem(getStreakCelebratedKey(userId)) === + dateFormatInTimezone(new Date(), STREAK_DAY_FORMAT, timezone) + ); + } catch { + return false; + } +}; + +export const markStreakCelebrated = ( + userId: string, + timezone?: string, +): void => { + try { + storageWrapper.setItem( + getStreakCelebratedKey(userId), + dateFormatInTimezone(new Date(), STREAK_DAY_FORMAT, timezone), + ); + } catch { + // ignore storage quota / privacy-mode failures + } +}; diff --git a/packages/shared/tailwind.config.ts b/packages/shared/tailwind.config.ts index c6e4ec986b..a313969c36 100644 --- a/packages/shared/tailwind.config.ts +++ b/packages/shared/tailwind.config.ts @@ -375,6 +375,14 @@ export default { 'color-mix(in srgb, var(--theme-accent-bacon-default) 28%, transparent)', }, }, + // Daily streak toast: the flame pops in with the same strike + rebound + // as the rail tile's earn pop, then rests at its normal size. + 'streak-toast-pop': { + '0%': { transform: 'scale(0.6)', opacity: '0' }, + '45%': { transform: 'scale(1.3)', opacity: '1' }, + '70%': { transform: 'scale(0.95)' }, + '100%': { transform: 'scale(1)' }, + }, // The search palette: the scrim and panel fade in, and the list fades // in again every time its scope changes (it is keyed on the scope). // Opacity only: a transform left by `both` would make the scrolling @@ -420,6 +428,8 @@ export default { 'streak-border-pulse': 'streak-border-pulse 2.2s ease-in-out infinite', 'streak-earn-border': 'streak-earn-border 0.6s ease-out both', 'streak-earn-fill': 'streak-earn-fill 0.6s ease-out both', + 'streak-toast-pop': + 'streak-toast-pop 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) both', 'mascot-bob': 'mascot-bob 4s ease-in-out infinite', }, },