diff --git a/packages/extension/src/newtab/App.tsx b/packages/extension/src/newtab/App.tsx index 28341e93d8..24fe27f9fb 100644 --- a/packages/extension/src/newtab/App.tsx +++ b/packages/extension/src/newtab/App.tsx @@ -37,6 +37,7 @@ import { useCheckCoresRole } from '@dailydotdev/shared/src/hooks/useCheckCoresRo import { ShortcutsProvider } from '@dailydotdev/shared/src/features/shortcuts/contexts/ShortcutsProvider'; import { useCheckLocation } from '@dailydotdev/shared/src/hooks/useCheckLocation'; import { useEnsureUserTimezone } from '@dailydotdev/shared/src/hooks/useEnsureUserTimezone'; +import { useStreakViewQueue } from '@dailydotdev/shared/src/hooks/streaks/useStreakViewQueue'; import { useScrollbarWidth } from '@dailydotdev/shared/src/hooks/useScrollbarWidth'; import { ErrorBoundary } from '@dailydotdev/shared/src/components/ErrorBoundary'; import { ExtensionContextProvider } from '../contexts/ExtensionContext'; @@ -121,6 +122,7 @@ function InternalApp(): ReactElement { useCheckLocation(); useEnsureUserTimezone(); useCheckCoresRole(); + useStreakViewQueue(); useEffect(() => { if (routeChangedCallbackRef.current && isPageReady) { diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx new file mode 100644 index 0000000000..59f33c19bc --- /dev/null +++ b/packages/shared/src/hooks/post/useViewPost.spec.tsx @@ -0,0 +1,674 @@ +import React from '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'; +import { subDays } from 'date-fns'; +import { TestBootProvider } from '../../../__tests__/helpers/boot'; +import { mockGraphQL } from '../../../__tests__/helpers/graphql'; +import loggedUser from '../../../__tests__/fixture/loggedUser'; +import type { UserStreak } from '../../graphql/users'; +import { getReadingStreak, USER_STREAK_QUERY } from '../../graphql/users'; +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' }; +const streakKey = generateQueryKey(RequestKey.UserStreak, user); +const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000); + +const streak: UserStreak = { + max: 7, + total: 20, + current: 7, + weekStart: DayOfWeek.Monday, + lastViewAt: yesterday, + freezesAvailable: 0, +}; + +const serverStreak: UserStreak = { + ...streak, + current: 8, + max: 8, + total: 21, + lastViewAt: new Date(), +}; + +const graphqlError = (code: string) => ({ + response: { data: null, errors: [{ message: 'no', extensions: { code } }] }, +}); +const networkError = new TypeError('Failed to fetch'); + +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 }, + streak_daily_celebration: { defaultValue: celebrationFlag }, + }, + }); + const getFeatureValue = jest.spyOn(gb, 'getFeatureValue'); + const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + + ); + + const view = renderHook( + () => { + // the streak query the post page shell already has in cache + useQuery({ + queryKey: streakKey, + queryFn: getReadingStreak, + initialData: initialStreak, + staleTime: Infinity, + }); + + return useViewPost(); + }, + { wrapper }, + ); + + return { ...view, getFeatureValue }; +}; + +describe('useViewPost', () => { + let client: QueryClient; + + beforeEach(() => { + nock.cleanAll(); + localStorage.clear(); + client = new QueryClient(); + }); + + it('should bump the cached streak before the response and keep it after success', async () => { + let resolve: (value: unknown) => void; + const requestMethod = jest.fn( + () => + new Promise((res) => { + resolve = res; + }), + ); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: serverStreak } }, + }); + const { result } = renderViewPost({ client, requestMethod }); + + const promise = result.current('p1'); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + }), + ); + expect(requestMethod).toHaveBeenCalledWith(VIEW_POST_MUTATION, { + id: 'p1', + }); + + await act(async () => { + resolve!({ viewPost: { _: true } }); + await promise; + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + lastViewAt: serverStreak.lastViewAt.toISOString(), + }), + ); + expect(readStreakViewQueue()).toEqual([]); + }); + + it.each(['NOT_FOUND', 'FORBIDDEN', 'UNAUTHENTICATED'])( + 'should roll the streak back when the API rejects the view with %s', + async (code) => { + const error = graphqlError(code); + const requestMethod = jest.fn().mockRejectedValue(error); + const { result } = renderViewPost({ client, requestMethod }); + + await expect(result.current('p1')).rejects.toBe(error); + + expect(client.getQueryData(streakKey)).toEqual(streak); + expect(readStreakViewQueue()).toEqual([]); + }, + ); + + it('should keep the streak and queue the view on a transient GraphQL error', async () => { + const error = graphqlError('RATE_LIMITED'); + const requestMethod = jest.fn().mockRejectedValue(error); + const { result } = renderViewPost({ client, requestMethod }); + + await expect(result.current('p1')).rejects.toBe(error); + + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + }); + expect(readStreakViewQueue()).toEqual([ + expect.objectContaining({ postId: 'p1', userId: user.id }), + ]); + }); + + describe('when the refetch runs before the API credited the view', () => { + // the newView worker has not written the streak yet, so userStreak still + // returns yesterday's value + const mockPreViewStreak = () => + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: streak } }, + }); + + beforeEach(() => { + jest.useFakeTimers({ advanceTimers: true }); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('should keep the optimistic streak and take the retry once it is up to date', async () => { + mockPreViewStreak(); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: { ...serverStreak, current: 9 } } }, + }); + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + const { result } = renderViewPost({ client, requestMethod }); + + let done = false; + const promise = result.current('p1').then(() => { + done = true; + }); + + await waitFor(() => expect(nock.pendingMocks()).toHaveLength(1)); + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + }); + expect(done).toBe(false); + + await act(async () => { + await jest.advanceTimersByTimeAsync(STREAK_REFETCH_RETRY_DELAY_MS); + await promise; + }); + + expect(nock.isDone()).toBe(true); + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 9, + }); + }); + + // a re-read of a post viewed in the past week: newView skips it, so the + // streak never moves + it('should put the server streak back when the retry is still stale', async () => { + mockPreViewStreak(); + mockPreViewStreak(); + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + const { result } = renderViewPost({ client, requestMethod }); + + 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(client.getQueryData(streakKey)).toMatchObject({ + current: 7, + total: 20, + max: 7, + }); + }); + }); + + it('should queue the view and keep the streak when the request never reaches the API', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ client, requestMethod }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + }); + expect(readStreakViewQueue()).toEqual([ + expect.objectContaining({ + postId: 'p1', + userId: user.id, + timezone: 'Europe/Amsterdam', + }), + ]); + }); + + it('should not persist the queue from the companion', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ + client, + requestMethod, + isCompanion: true, + }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + expect(readStreakViewQueue()).toEqual([]); + }); + + it('should only update the streak from the response when the flag is off', async () => { + let resolve: (value: unknown) => void; + const requestMethod = jest.fn( + () => + new Promise((res) => { + resolve = res; + }), + ); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: serverStreak } }, + }); + const { result } = renderViewPost({ client, requestMethod, flag: false }); + + const promise = result.current('p1'); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(client.getQueryData(streakKey)).toEqual(streak); + + await act(async () => { + resolve!({ viewPost: { _: true } }); + await promise; + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + }), + ); + }); + + it('should not queue a dropped view when the flag is off', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ client, requestMethod, flag: false }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + expect(client.getQueryData(streakKey)).toEqual(streak); + expect(readStreakViewQueue()).toEqual([]); + }); + + it('should not bump the streak from the companion', async () => { + const requestMethod = jest.fn(() => new Promise(() => {})); + const { result } = renderViewPost({ + client, + requestMethod, + isCompanion: true, + }); + + result.current('p1'); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(client.getQueryData(streakKey)).toEqual(streak); + }); + + it('should not bump a streak last read before yesterday', async () => { + const lastRead = { ...streak, lastViewAt: subDays(new Date(), 3) }; + const requestMethod = jest.fn(() => new Promise(() => {})); + const { result } = renderViewPost({ + client, + requestMethod, + initialStreak: lastRead, + }); + + result.current('p1'); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(client.getQueryData(streakKey)).toEqual(lastRead); + }); + + it('should bump a reset streak to one', async () => { + const reset = { + ...streak, + current: 0, + lastViewAt: subDays(new Date(), 3), + }; + const requestMethod = jest.fn(() => new Promise(() => {})); + const { result } = renderViewPost({ + client, + requestMethod, + initialStreak: reset, + }); + + result.current('p1'); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 1, + total: 21, + max: 7, + }), + ); + }); + + it('should not queue a dropped view when today is already counted', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ + client, + requestMethod, + initialStreak: serverStreak, + }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + 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, or skipped it (a + // post viewed in the past week), so userStreak still returns day 5 + const mockPreViewStreak = () => + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: dayFive } }, + }); + const renderAndView = async ( + props: Partial[0]> = {}, + ) => { + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + initialStreak: dayFive, + ...props, + }); + + 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; + }); + }; + + beforeEach(() => { + jest.useFakeTimers({ advanceTimers: true }); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it.each([ + ['on', true], + ['off', false], + ])( + 'should not toast a read the API never counted with optimistic view %s', + async (_, flag) => { + mockPreViewStreak(); + mockPreViewStreak(); + + await renderAndView({ flag }); + + expect(nock.isDone()).toBe(true); + expect(getToast()).toBeFalsy(); + expect( + localStorage.getItem(getStreakCelebratedKey(user.id)), + ).toBeNull(); + }, + ); + + it('should not toast a guessed count after a gap', async () => { + mockPreViewStreak(); + mockPreViewStreak(); + + await renderAndView({ + initialStreak: { ...dayFive, lastViewAt: subDays(new Date(), 3) }, + }); + + expect(nock.isDone()).toBe(true); + expect(getToast()).toBeFalsy(); + }); + + it('should toast once the retry confirms the read', async () => { + mockPreViewStreak(); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + + await renderAndView({ flag: false }); + + expect(nock.isDone()).toBe(true); + 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 1d41cf3570..1636399dde 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -1,25 +1,74 @@ import type { UseMutateAsyncFunction } from '@tanstack/react-query'; import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { subDays } from 'date-fns'; import { VIEW_POST_MUTATION } from '../../graphql/posts'; import { generateQueryKey, RequestKey } from '../../lib/query'; import { useAuthContext } from '../../contexts/AuthContext'; import type { UserStreak } from '../../graphql/users'; import { isSameDayInTimezone } from '../../lib/timezones'; import { useRequestProtocol } from '../useRequestProtocol'; +import { useConditionalFeature } from '../useConditionalFeature'; +import { featureStreakOptimisticView } from '../../lib/featureManagement'; +import { + enqueueStreakView, + 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. +export const STREAK_REFETCH_RETRY_DELAY_MS = 2000; + +// After a longer gap the API decides (off days, freezes, a reset) +const canBumpStreak = ( + streak: UserStreak, + timezone?: string, + now: Date = new Date(), +): boolean => + !streak.lastViewAt || + streak.current === 0 || + isSameDayInTimezone(new Date(streak.lastViewAt), subDays(now, 1), timezone); + +const wait = (ms: number) => + new Promise((resolve) => { + setTimeout(resolve, ms); + }); + +interface ViewPostContext { + previousStreak?: UserStreak; + optimisticStreak?: UserStreak; + shouldRefetchStreak: boolean; + // the count this view should land on, to recognize a refetch that already + // includes it + nextStreak?: number; +} export const useViewPost = (): UseMutateAsyncFunction< unknown, unknown, - string + string, + ViewPostContext > => { const client = useQueryClient(); - const { requestMethod } = useRequestProtocol(); + const { requestMethod, isCompanion } = useRequestProtocol(); const { user } = useAuthContext(); + const { value: isOptimisticView } = useConditionalFeature({ + feature: featureStreakOptimisticView, + shouldEvaluate: !!user && !isCompanion, + }); + const isOptimistic = isOptimisticView && !isCompanion; + const celebrateStreakDay = useStreakDailyCelebration(); const streakKey = generateQueryKey(RequestKey.UserStreak, user); const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user); - const { mutateAsync: onSendViewPost } = useMutation({ + const { mutateAsync: onSendViewPost } = useMutation< + unknown, + unknown, + string, + ViewPostContext + >({ mutationFn: (id: string) => requestMethod(VIEW_POST_MUTATION, { id }), - onSuccess: async () => { + onMutate: () => { const streak = client.getQueryData(streakKey); const isNewStreak = !streak?.lastViewAt; const isFirstViewToday = @@ -29,16 +78,100 @@ export const useViewPost = (): UseMutateAsyncFunction< new Date(), user!.timezone, ); + const shouldRefetchStreak = isNewStreak || isFirstViewToday; + const nextStreak = + streak && canBumpStreak(streak, user?.timezone) + ? streak.current + 1 + : undefined; + + if (!isOptimistic || !shouldRefetchStreak || nextStreak === undefined) { + return { shouldRefetchStreak, nextStreak }; + } + + const optimisticStreak: UserStreak = { + ...streak!, + current: nextStreak, + total: streak!.total + 1, + max: Math.max(streak!.max, nextStreak), + lastViewAt: new Date(), + }; + client.setQueryData(streakKey, optimisticStreak); + + return { + previousStreak: streak, + optimisticStreak, + shouldRefetchStreak, + nextStreak, + }; + }, + onSuccess: async (_, __, context) => { + if (!context.shouldRefetchStreak) { + return null; + } - if (isNewStreak || isFirstViewToday) { + const { optimisticStreak } = context; + // 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); - // just mark the query as stale - await client.invalidateQueries({ queryKey: readKey }); + return includesThisRead( + refetched, + user?.timezone, + optimisticStreak?.current ?? context.nextStreak, + ) + ? refetched + : undefined; + }; + let countedStreak = await refetchStreak(); + + // The worker may not have credited the view yet: keep the optimistic + // bump and ask once more after a moment. A retry that is still stale + // means the API skipped the view (it ignores a post the user viewed in + // the past week), so the server value it returned stays. + if (!countedStreak) { + if (optimisticStreak) { + client.setQueryData(streakKey, optimisticStreak); + } + await wait(STREAK_REFETCH_RETRY_DELAY_MS); + countedStreak = await refetchStreak(); } + // just mark the query as stale + await client.invalidateQueries({ queryKey: readKey }); + + // only a count the API confirmed: a guess could celebrate a day that + // never counted and suppress the toast for the read that does + celebrateStreakDay(countedStreak?.current); + return null; }, + onError: (error, id, context) => { + if (!isOptimistic) { + return; + } + + if (isFinalViewRejection(error)) { + if (context?.previousStreak) { + client.setQueryData(streakKey, context.previousStreak); + } + + return; + } + + if (!context?.shouldRefetchStreak) { + return; + } + + enqueueStreakView({ + postId: id, + userId: user!.id, + at: Date.now(), + timezone: user?.timezone, + }); + }, }); return onSendViewPost; 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/hooks/streaks/useStreakViewQueue.spec.tsx b/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx new file mode 100644 index 0000000000..d79faf90e8 --- /dev/null +++ b/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx @@ -0,0 +1,236 @@ +import React from 'react'; +import type { ReactNode } from 'react'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClient } from '@tanstack/react-query'; +import { GrowthBook } from '@growthbook/growthbook-react'; +import { TestBootProvider } from '../../../__tests__/helpers/boot'; +import loggedUser from '../../../__tests__/fixture/loggedUser'; +import { VIEW_POST_MUTATION } from '../../graphql/posts'; +import { REQUEST_PROTOCOL_KEY } from '../../graphql/common'; +import type { QueuedStreakView } from '../../lib/streakViewQueue'; +import { + enqueueStreakView, + readStreakViewQueue, +} from '../../lib/streakViewQueue'; +import { useStreakViewQueue } from './useStreakViewQueue'; + +const user = { ...loggedUser, timezone: 'Europe/Amsterdam' }; +const DAY = 24 * 60 * 60 * 1000; + +const queued = ( + postId: string, + overrides: Partial = {}, +): QueuedStreakView => ({ + postId, + userId: user.id, + at: Date.now(), + timezone: user.timezone, + ...overrides, +}); + +const renderQueue = ({ + client, + requestMethod, + flag = true, + isCompanion = false, +}: { + client: QueryClient; + requestMethod: jest.Mock; + flag?: boolean; + isCompanion?: boolean; +}) => { + client.setQueryData(REQUEST_PROTOCOL_KEY, { requestMethod, isCompanion }); + const gb = new GrowthBook({ + features: { streak_optimistic_view: { defaultValue: flag } }, + }); + const getFeatureValue = jest.spyOn(gb, 'getFeatureValue'); + const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + + ); + + const view = renderHook(() => useStreakViewQueue(), { wrapper }); + const hasEvaluatedFlag = () => + getFeatureValue.mock.calls.some(([id]) => id === 'streak_optimistic_view'); + + return { ...view, hasEvaluatedFlag }; +}; + +const goOnline = () => + act(() => { + window.dispatchEvent(new Event('online')); + }); + +describe('useStreakViewQueue', () => { + let client: QueryClient; + + beforeEach(() => { + localStorage.clear(); + client = new QueryClient(); + }); + + it('should replay the queued view once on reconnect and clear it', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + renderQueue({ client, requestMethod }); + expect(requestMethod).not.toHaveBeenCalled(); + + enqueueStreakView(queued('p1')); + goOnline(); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + expect(requestMethod).toHaveBeenCalledWith(VIEW_POST_MUTATION, { + id: 'p1', + }); + + goOnline(); + await act(() => Promise.resolve()); + expect(requestMethod).toHaveBeenCalledTimes(1); + }); + + it('should replay the queue on app load', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + }); + + it('should drop a view from a previous local day without sending it', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('old', { at: Date.now() - 2 * DAY })); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + expect(requestMethod).toHaveBeenCalledWith(VIEW_POST_MUTATION, { + id: 'p1', + }); + }); + + it('should keep the queue when the replay fails on the network', async () => { + const requestMethod = jest + .fn() + .mockRejectedValue(new TypeError('Failed to fetch')); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(readStreakViewQueue()).toHaveLength(1); + }); + + it('should drop a view the API can never count', async () => { + const requestMethod = jest.fn().mockRejectedValue({ + response: { + errors: [{ message: 'no', extensions: { code: 'NOT_FOUND' } }], + }, + }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + }); + + it('should keep a view when the API fails with a transient GraphQL error', async () => { + const requestMethod = jest.fn().mockRejectedValue({ + response: { + errors: [ + { message: 'slow down', extensions: { code: 'RATE_LIMITED' } }, + ], + }, + }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(readStreakViewQueue()).toHaveLength(1); + }); + + it('should drop a view from just before midnight once the local day changed', async () => { + jest.useFakeTimers({ now: new Date('2026-01-13T00:10:00+01:00') }); + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView( + queued('late', { at: new Date('2026-01-12T23:50:00+01:00').getTime() }), + ); + + try { + renderQueue({ client, requestMethod }); + await act(() => Promise.resolve()); + await act(() => Promise.resolve()); + + expect(requestMethod).not.toHaveBeenCalled(); + expect(readStreakViewQueue()).toEqual([]); + } finally { + jest.useRealTimers(); + } + }); + + it('should leave views queued by another user alone', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1', { userId: 'someone-else' })); + + renderQueue({ client, requestMethod }); + + await act(() => Promise.resolve()); + expect(requestMethod).not.toHaveBeenCalled(); + expect(readStreakViewQueue()).toHaveLength(1); + }); + + it('should never evaluate the flag for a user with an empty queue', async () => { + const requestMethod = jest.fn(); + const { hasEvaluatedFlag } = renderQueue({ client, requestMethod }); + goOnline(); + + await act(() => Promise.resolve()); + expect(hasEvaluatedFlag()).toBe(false); + expect(requestMethod).not.toHaveBeenCalled(); + }); + + it('should drain queued views without reading the flag', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1')); + + const { hasEvaluatedFlag } = renderQueue({ + client, + requestMethod, + flag: false, + }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + expect(hasEvaluatedFlag()).toBe(false); + }); + + it('should not replay from the companion', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod, isCompanion: true }); + + await act(() => Promise.resolve()); + expect(requestMethod).not.toHaveBeenCalled(); + expect(readStreakViewQueue()).toHaveLength(1); + }); +}); diff --git a/packages/shared/src/hooks/streaks/useStreakViewQueue.ts b/packages/shared/src/hooks/streaks/useStreakViewQueue.ts new file mode 100644 index 0000000000..185ef9ed0a --- /dev/null +++ b/packages/shared/src/hooks/streaks/useStreakViewQueue.ts @@ -0,0 +1,71 @@ +import { useEffect } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { useAuthContext } from '../../contexts/AuthContext'; +import { useRequestProtocol } from '../useRequestProtocol'; +import { VIEW_POST_MUTATION } from '../../graphql/posts'; +import { generateQueryKey, RequestKey } from '../../lib/query'; +import { drainStreakViewQueue } from '../../lib/streakViewQueue'; + +// Replays post views that a flaky connection dropped (see useViewPost), on +// app load and whenever the browser comes back online. +// +// It deliberately does not read streak_optimistic_view: this mounts for every +// signed-in user on every load, and evaluating the flag here would enrol +// people who never open a post. Only useViewPost with the flag on fills the +// queue, so draining whatever is queued stays scoped to the treatment arm, and +// a user with an empty queue does no work beyond one storage read. +export const useStreakViewQueue = (): void => { + const client = useQueryClient(); + const { user } = useAuthContext(); + const { requestMethod, isCompanion } = useRequestProtocol(); + const userId = user?.id; + + useEffect(() => { + if (!userId || isCompanion) { + return undefined; + } + + let isDraining = false; + let shouldDrainAgain = false; + const drain = async () => { + if (isDraining) { + shouldDrainAgain = true; + return; + } + + isDraining = true; + + try { + const sent = await drainStreakViewQueue({ + userId, + sendView: (id) => requestMethod(VIEW_POST_MUTATION, { id }), + }); + + if (sent > 0) { + const streakUser = { id: userId }; + await client.invalidateQueries({ + queryKey: generateQueryKey(RequestKey.UserStreak, streakUser), + }); + await client.invalidateQueries({ + queryKey: generateQueryKey( + RequestKey.ReadingStreak30Days, + streakUser, + ), + }); + } + } finally { + isDraining = false; + + if (shouldDrainAgain) { + shouldDrainAgain = false; + drain(); + } + } + }; + + drain(); + window.addEventListener('online', drain); + + return () => window.removeEventListener('online', drain); + }, [client, isCompanion, requestMethod, userId]); +}; diff --git a/packages/shared/src/lib/featureManagement.ts b/packages/shared/src/lib/featureManagement.ts index 3c3eba338d..2609c691ed 100644 --- a/packages/shared/src/lib/featureManagement.ts +++ b/packages/shared/src/lib/featureManagement.ts @@ -110,6 +110,19 @@ export const featureGtaViFreezeDay = new Feature('gta_vi_freeze_day', false); export const featureGtaViTheme = new Feature('gta_vi_theme', false); +// count the read on open: optimistic streak bump plus a retry queue for views +// dropped by a flaky connection +export const featureStreakOptimisticView = new Feature( + 'streak_optimistic_view', + 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 06b6a3ad29..35a81a5ac8 100644 --- a/packages/shared/src/lib/log.ts +++ b/packages/shared/src/lib/log.ts @@ -786,6 +786,7 @@ export enum TargetType { StreaksMilestone = 'streaks milestone', StreakRecover = 'streak restore', StreakFreezePurchase = 'streak freeze purchase', + StreakDailyCelebration = 'streak daily celebration', StreakReminderOptOut = 'streak reminder opt out', StreakResetReason = 'streak reset reason', StreakSoftBreak = 'streak soft break', diff --git a/packages/shared/src/lib/storage.ts b/packages/shared/src/lib/storage.ts index 30765a0912..175b8a5d2b 100644 --- a/packages/shared/src/lib/storage.ts +++ b/packages/shared/src/lib/storage.ts @@ -6,6 +6,7 @@ export enum StorageTopic { Onboarding = 'onboarding', Comment = 'comment', Settings = 'settings', + Streak = 'streak', } export const APP_KEY_PREFIX = 'dailydev'; 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/src/lib/streakViewQueue.spec.ts b/packages/shared/src/lib/streakViewQueue.spec.ts new file mode 100644 index 0000000000..00c0436d8a --- /dev/null +++ b/packages/shared/src/lib/streakViewQueue.spec.ts @@ -0,0 +1,77 @@ +import { + isFinalViewRejection, + isStreakViewCreditable, +} from './streakViewQueue'; + +const tz = 'Europe/Amsterdam'; +// CET (UTC+1), no DST in January +const at = new Date('2026-01-12T21:30:00+01:00'); + +const graphqlError = (code?: string) => ({ + response: { + data: null, + errors: [{ message: 'no', ...(code && { extensions: { code } }) }], + }, +}); + +describe('isStreakViewCreditable', () => { + it('should credit a view from the same local day', () => { + expect( + isStreakViewCreditable(at, new Date('2026-01-12T23:59:00+01:00'), tz), + ).toBe(true); + }); + + it('should drop a view from the previous local day, even just after midnight', () => { + // the API would credit the replay to 00:10, so the read would land on + // the wrong day + expect( + isStreakViewCreditable(at, new Date('2026-01-13T00:10:00+01:00'), tz), + ).toBe(false); + }); + + it('should drop a view older than a day', () => { + expect( + isStreakViewCreditable(at, new Date('2026-01-14T12:00:00+01:00'), tz), + ).toBe(false); + }); + + it('should use the profile timezone for the day boundary', () => { + // 14:30Z is 23:30 in Tokyo and 15:30 in Amsterdam; at 18:30Z Tokyo is on + // the next day while Amsterdam is still on the same one + expect( + isStreakViewCreditable( + new Date('2026-01-13T14:30:00Z'), + new Date('2026-01-13T18:30:00Z'), + 'Asia/Tokyo', + ), + ).toBe(false); + expect( + isStreakViewCreditable( + new Date('2026-01-13T14:30:00Z'), + new Date('2026-01-13T18:30:00Z'), + tz, + ), + ).toBe(true); + }); +}); + +describe('isFinalViewRejection', () => { + it.each(['NOT_FOUND', 'FORBIDDEN', 'UNAUTHENTICATED'])( + 'should treat %s as final', + (code) => { + expect(isFinalViewRejection(graphqlError(code))).toBe(true); + }, + ); + + it.each(['RATE_LIMITED', 'UNEXPECTED', 'INTERNAL_SERVER_ERROR', undefined])( + 'should not treat a %s GraphQL error as final', + (code) => { + expect(isFinalViewRejection(graphqlError(code))).toBe(false); + }, + ); + + it('should not treat a network failure as final', () => { + expect(isFinalViewRejection(new TypeError('Failed to fetch'))).toBe(false); + expect(isFinalViewRejection(undefined)).toBe(false); + }); +}); diff --git a/packages/shared/src/lib/streakViewQueue.ts b/packages/shared/src/lib/streakViewQueue.ts new file mode 100644 index 0000000000..f720f51e29 --- /dev/null +++ b/packages/shared/src/lib/streakViewQueue.ts @@ -0,0 +1,154 @@ +import type { ResponseError } from '../graphql/common'; +import { ApiError } from '../graphql/common'; +import { generateStorageKey, StorageTopic } from './storage'; +import { storageWrapper } from './storageWrapper'; +import { isSameDayInTimezone } from './timezones'; + +export interface QueuedStreakView { + postId: string; + userId: string; + at: number; + timezone?: string; +} + +export const STREAK_VIEW_QUEUE_KEY = generateStorageKey( + StorageTopic.Streak, + 'pendingViews', +); + +export const readStreakViewQueue = (): QueuedStreakView[] => { + try { + const raw = storageWrapper.getItem(STREAK_VIEW_QUEUE_KEY); + const parsed = raw ? JSON.parse(raw) : []; + + if (!Array.isArray(parsed)) { + return []; + } + + return parsed.filter( + (item): item is QueuedStreakView => + !!item && + typeof item.postId === 'string' && + typeof item.userId === 'string' && + typeof item.at === 'number', + ); + } catch { + return []; + } +}; + +const writeStreakViewQueue = (queue: QueuedStreakView[]): void => { + try { + if (queue.length) { + storageWrapper.setItem(STREAK_VIEW_QUEUE_KEY, JSON.stringify(queue)); + } else { + storageWrapper.removeItem(STREAK_VIEW_QUEUE_KEY); + } + } catch { + // ignore storage quota / privacy-mode failures + } +}; + +const isSameView = (a: QueuedStreakView, b: Pick) => + a.postId === b.postId; + +export const enqueueStreakView = (view: QueuedStreakView): void => { + const queue = readStreakViewQueue(); + + if (queue.some((item) => isSameView(item, view))) { + return; + } + + writeStreakViewQueue([...queue, view]); +}; + +export const removeStreakView = ( + view: Pick, +): void => { + writeStreakViewQueue( + readStreakViewQueue().filter((item) => !isSameView(item, view)), + ); +}; + +// Codes that mean the API will never count this view (the post is gone, the +// user cannot see it, or the session is not valid). Anything else, including +// other GraphQL errors such as rate limiting or a failed publish, is treated +// like a dropped connection and the view is kept for a retry. +// Read when called, not at module load: graphql/common sits in an import +// cycle with this file, so ApiError can still be undefined at load time. +const getFinalViewRejectionCodes = (): string[] => [ + ApiError.NotFound, + ApiError.Forbidden, + ApiError.Unauthenticated, +]; + +export const isFinalViewRejection = (error: unknown): boolean => { + const errors = (error as Partial)?.response?.errors; + const finalCodes = getFinalViewRejectionCodes(); + + return ( + Array.isArray(errors) && + errors.some((item) => finalCodes.includes(item?.extensions?.code as string)) + ); +}; + +// viewPost takes no read time: the API credits a replayed view to the moment +// it arrives. Only a view from the same local day lands on the day it was +// read, so anything older is dropped instead of sent. +export const isStreakViewCreditable = ( + at: Date, + now: Date, + timezone?: string, +): boolean => isSameDayInTimezone(at, now, timezone); + +interface DrainStreakViewQueueProps { + userId: string; + sendView: (postId: string) => Promise; + now?: Date; +} + +const sendQueuedViews = async ( + views: QueuedStreakView[], + sendView: DrainStreakViewQueueProps['sendView'], + now: Date, + sent = 0, +): Promise => { + if (!views.length) { + return sent; + } + + const [view, ...rest] = views; + + if (!isStreakViewCreditable(new Date(view.at), now, view.timezone)) { + removeStreakView(view); + return sendQueuedViews(rest, sendView, now, sent); + } + + try { + await sendView(view.postId); + } catch (error) { + if (isFinalViewRejection(error)) { + removeStreakView(view); + return sendQueuedViews(rest, sendView, now, sent); + } + + // still offline or a transient API error, keep the rest for the next drain + return sent; + } + + removeStreakView(view); + return sendQueuedViews(rest, sendView, now, sent + 1); +}; + +// Replays the views queued for this user, oldest first, and resolves with how +// many the API accepted. +export const drainStreakViewQueue = ({ + userId, + sendView, + now = new Date(), +}: DrainStreakViewQueueProps): Promise => + sendQueuedViews( + readStreakViewQueue().filter((view) => view.userId === userId), + sendView, + now, + ); diff --git a/packages/shared/src/lib/userStreak.spec.ts b/packages/shared/src/lib/userStreak.spec.ts new file mode 100644 index 0000000000..b5f29077de --- /dev/null +++ b/packages/shared/src/lib/userStreak.spec.ts @@ -0,0 +1,76 @@ +import { hasStreakViewToday, includesThisRead } from './userStreak'; + +const tz = 'Europe/Amsterdam'; +// CET (UTC+1), no DST in January +const now = new Date('2026-01-13T00:30:00+01:00'); + +describe('hasStreakViewToday', () => { + it('should be true when lastViewAt is today in the profile timezone', () => { + expect( + hasStreakViewToday( + { lastViewAt: new Date('2026-01-13T00:05:00+01:00') }, + tz, + now, + ), + ).toBe(true); + }); + + it('should be false when lastViewAt is the previous local day', () => { + expect( + hasStreakViewToday( + { lastViewAt: new Date('2026-01-12T23:50:00+01:00') }, + tz, + now, + ), + ).toBe(false); + }); + + it('should accept a serialized lastViewAt', () => { + expect( + hasStreakViewToday( + { + lastViewAt: '2026-01-12T23:10:00.000Z' as unknown as Date, + }, + tz, + now, + ), + ).toBe(true); + }); + + it('should be false without a streak or lastViewAt', () => { + expect(hasStreakViewToday(undefined, tz, now)).toBe(false); + expect( + hasStreakViewToday({ lastViewAt: undefined as unknown as Date }, tz, now), + ).toBe(false); + }); +}); + +describe('includesThisRead', () => { + // A 00:30 read the API's grace window credited to yesterday + const credited = { + lastViewAt: new Date('2026-01-12T23:59:59.999+01:00'), + current: 6, + }; + + it('should accept a grace-credited read whose count matches the expected one', () => { + expect(includesThisRead(credited, tz, 6, now)).toBe(true); + }); + + it('should reject the pre-view streak', () => { + expect(includesThisRead({ ...credited, current: 5 }, tz, 6, now)).toBe( + false, + ); + }); + + it('should fall back to the lastViewAt check without an expected count', () => { + expect(includesThisRead(credited, tz, undefined, now)).toBe(false); + expect( + includesThisRead( + { lastViewAt: new Date('2026-01-13T00:05:00+01:00'), current: 6 }, + tz, + undefined, + now, + ), + ).toBe(true); + }); +}); diff --git a/packages/shared/src/lib/userStreak.ts b/packages/shared/src/lib/userStreak.ts new file mode 100644 index 0000000000..5a3009d690 --- /dev/null +++ b/packages/shared/src/lib/userStreak.ts @@ -0,0 +1,27 @@ +import type { UserStreak } from '../graphql/users'; +import { isSameDayInTimezone } from './timezones'; + +// The API credits a view asynchronously (viewPost only publishes it, and the +// newView worker writes the streak), so a userStreak read right after the +// mutation can still be the pre-view streak. It includes today's read only +// once its lastViewAt falls on today in the profile timezone. +export const hasStreakViewToday = ( + streak: Pick | undefined | null, + timezone?: string, + now: Date = new Date(), +): boolean => + !!streak?.lastViewAt && + isSameDayInTimezone(new Date(streak.lastViewAt), now, timezone); + +// Whether a refetched streak already includes the read we just sent. Besides +// a lastViewAt today, a count that already matches the one we expect counts +// too: when the API's grace window credits an early-morning read to +// yesterday, lastViewAt lands on yesterday and never looks like today. +export const includesThisRead = ( + streak: Pick | undefined | null, + timezone?: string, + expectedCurrent?: number, + now: Date = new Date(), +): boolean => + hasStreakViewToday(streak, timezone, now) || + (expectedCurrent !== undefined && streak?.current === expectedCurrent); 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', }, }, diff --git a/packages/webapp/pages/_app.tsx b/packages/webapp/pages/_app.tsx index 6076a190d1..a9fc54e7af 100644 --- a/packages/webapp/pages/_app.tsx +++ b/packages/webapp/pages/_app.tsx @@ -59,6 +59,7 @@ import { } from '@dailydotdev/shared/src/lib/ios'; import { useCheckLocation } from '@dailydotdev/shared/src/hooks/useCheckLocation'; import { useEnsureUserTimezone } from '@dailydotdev/shared/src/hooks/useEnsureUserTimezone'; +import { useStreakViewQueue } from '@dailydotdev/shared/src/hooks/streaks/useStreakViewQueue'; import { useSlackShareReturn } from '@dailydotdev/shared/src/hooks/integrations/slack/useSlackShareButton'; import Seo, { defaultSeo, defaultSeoTitle, robotsProps } from '../next-seo'; import useWebappVersion from '../hooks/useWebappVersion'; @@ -170,6 +171,7 @@ function InternalApp({ Component, pageProps, router }: AppProps): ReactElement { useCheckCoresRole(); useCheckLocation(); useEnsureUserTimezone(); + useStreakViewQueue(); useSlackShareReturn(); useEffect(() => {