From 717b8a812a207a8fac33185773ee48502772ca71 Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Thu, 12 Nov 2026 16:07:00 +0200 Subject: [PATCH] feat(streak): toast the day's streak on the first counted read The milestone modal is the only streak celebration today, and it only fires on Fibonacci days. The daily moment, the read that actually extended the streak, had no feedback beyond the rail tile's 700 ms ring pop, which is off-screen on the post page. Behind the streak_daily_celebration flag (default off), useViewPost now shows a "Day {n}! See you tomorrow." toast with the streak flame after the first counted read of a local day. It reuses the first-view decision already made in onMutate, waits for the streak refetch and takes n from the server value, falling back to the count the optimistic update aimed for when the refetch failed. The flame pops in with a keyframe gated on motion-safe. The toast stays away on days the milestone modal takes over: when alerts.showStreakMilestone is already set, or when the refetched count is a milestone by the API's own rule (Fibonacci and above 1, mirrored in lib/streakDailyCelebration.ts), since the alert only reaches the client on the next boot. It is also skipped when streaks are opted out and in the extension companion, which has no streak in its cache and would treat every read as the first of the day. A per-user localStorage marker (dailydev:streak:celebrated:) holding the local date in the profile timezone keeps it to one toast a day, so an optimistic replay or a second tab does not toast twice. The toast logs an impression with target type `streak daily celebration` and the count as target_id. Co-Authored-By: Claude Fable 5.1 --- .../src/hooks/post/useViewPost.spec.tsx | 172 +++++++++++++++++- packages/shared/src/hooks/post/useViewPost.ts | 16 +- .../streaks/useStreakDailyCelebration.tsx | 82 +++++++++ packages/shared/src/lib/featureManagement.ts | 6 + packages/shared/src/lib/log.ts | 1 + .../shared/src/lib/streakDailyCelebration.ts | 51 ++++++ packages/shared/tailwind.config.ts | 10 + 7 files changed, 331 insertions(+), 7 deletions(-) create mode 100644 packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx create mode 100644 packages/shared/src/lib/streakDailyCelebration.ts diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx index cc47be0493..b113c61add 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 { useViewPost } from './useViewPost'; const user = { ...loggedUser, timezone: 'Europe/Amsterdam' }; @@ -44,19 +55,37 @@ const renderViewPost = ({ client, requestMethod, flag = true, + celebrationFlag = false, isCompanion = false, + initialStreak = streak, + alerts, + log, }: { client: QueryClient; requestMethod: jest.Mock; flag?: boolean; + celebrationFlag?: boolean; isCompanion?: boolean; + initialStreak?: UserStreak; + alerts?: ComponentProps['alerts']; + log?: ComponentProps['log']; }) => { 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 wrapper = ({ children }: { children: ReactNode }) => ( - + {children} ); @@ -67,7 +96,7 @@ const renderViewPost = ({ useQuery({ queryKey: streakKey, queryFn: getReadingStreak, - initialData: streak, + initialData: initialStreak, staleTime: Infinity, }); @@ -212,4 +241,137 @@ 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(); + }); + + 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 21dfb56034..539593f9d1 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -12,10 +12,13 @@ import { enqueueStreakView, isGraphQLRejection, } from '../../lib/streakViewQueue'; +import { useStreakDailyCelebration } from '../streaks/useStreakDailyCelebration'; interface ViewPostContext { previousStreak?: UserStreak; shouldRefetchStreak: boolean; + // the count this view should land on, used when the refetch fails + nextStreak?: number; } export const useViewPost = (): UseMutateAsyncFunction< @@ -31,6 +34,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< @@ -51,9 +55,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; @@ -65,7 +70,7 @@ export const useViewPost = (): UseMutateAsyncFunction< lastViewAt: new Date(), }); - return { previousStreak: streak, shouldRefetchStreak }; + return { previousStreak: streak, shouldRefetchStreak, nextStreak }; }, onSuccess: async (_, __, context) => { if (context.shouldRefetchStreak) { @@ -73,6 +78,13 @@ export const useViewPost = (): UseMutateAsyncFunction< // just mark the query as stale await client.invalidateQueries({ queryKey: readKey }); + + const refetched = client.getQueryState(streakKey); + celebrateStreakDay( + refetched?.status === 'success' + ? refetched.data?.current + : context.nextStreak, + ); } return null; diff --git a/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx b/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx new file mode 100644 index 0000000000..c813a5aa50 --- /dev/null +++ b/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx @@ -0,0 +1,82 @@ +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 { value: isEnabled } = useConditionalFeature({ + feature: featureStreakDailyCelebration, + shouldEvaluate: !!user && !isCompanion, + }); + const isStreaksEnabled = loadedSettings && !optOutReadingStreak; + 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 712cedb5dd..ad7bbf9bb8 100644 --- a/packages/shared/src/lib/featureManagement.ts +++ b/packages/shared/src/lib/featureManagement.ts @@ -107,6 +107,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 055c08b7d4..375f426425 100644 --- a/packages/shared/src/lib/log.ts +++ b/packages/shared/src/lib/log.ts @@ -783,6 +783,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', }, },