From 8fc7dfd87106af6869a1a10ba2eda89cc0e60efc Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Wed, 14 Oct 2026 11:52:31 +0300 Subject: [PATCH] APP-3377: Add Notifications v2 metrics (#11965) Co-authored-by: Claude Opus 5.5 --- src/analytics/metrics/types.ts | 91 ++++++ .../__tests__/refreshPillMetrics.test.ts | 263 ++++++++++++++++++ .../Notifications/__tests__/tabTaps.test.ts | 34 +++ .../NotificationItem/Item/profile.tsx | 8 +- .../NotificationItem/kinds/follower.tsx | 5 +- .../NotificationItem/kinds/profile.tsx | 7 +- .../Notifications/components/PageList.tsx | 25 +- src/screens/Notifications/index.tsx | 63 ++++- .../Notifications/refreshPillMetrics.ts | 203 ++++++++++++++ src/screens/Notifications/tabTaps.ts | 30 ++ 10 files changed, 706 insertions(+), 23 deletions(-) create mode 100644 src/screens/Notifications/__tests__/refreshPillMetrics.test.ts create mode 100644 src/screens/Notifications/__tests__/tabTaps.test.ts create mode 100644 src/screens/Notifications/refreshPillMetrics.ts create mode 100644 src/screens/Notifications/tabTaps.ts diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index ab2e8b0a8..275af1755 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -6,6 +6,7 @@ import {type Platform} from 'react-native' import {type NotificationReason} from '#/lib/hooks/useNotificationHandler' import {type VideoCompressSkipReason} from '#/lib/media/video/types' +import {type GroupedNotificationsFeed} from '#/state/queries/notifications/grouped/types' import {type NotificationType} from '#/state/queries/notifications/types' import {type FeedDescriptor} from '#/state/queries/post-feed' import {type LiveEventFeedMetricContext} from '#/features/liveEvents/types' @@ -60,6 +61,90 @@ export type Events = { notificationType: NotificationType authorCount: number } + /** + * A tab of the Notifications screen came into view: the tab it's on when + * the screen gains focus, which includes mounting, and each tab the user + * switches to. A switch is logged once, as the pager settles on the new + * tab. + */ + 'notifications:tabDisplayed': { + tab: GroupedNotificationsFeed + /** The tab's position in the tab pills, from 0. */ + index: number + /** + * - `focus`: the screen gained focus, or mounted, on the tab. Web mounts + * the screen on every visit. + * - `tap`: the user pressed the tab's pill. + * - `swipe`: the user swiped the pager to the tab, which only native + * does. + */ + reason: 'focus' | 'tap' | 'swipe' + } + /** + * A tab of the Notifications screen started loading its newest + * notifications, in place of what it shows. Not the tab's first load or a + * retry of it, nor a check that only asks whether there's anything new, as + * a quick return to the app or a switch between tabs does, or any return + * while the user is partway down the tab. Nor the refresh of "All" that + * refreshing any other tab sets off behind it. + */ + 'notifications:refresh': { + tab: GroupedNotificationsFeed + /** + * - `pullToRefresh`: the user pulled the tab down. + * - `softReset`: the user pressed Notifications in the app's navigation, + * or the tab's own pill, while already on the tab. + * - `pill`: the user pressed the "Refresh" pill. + * - `focus`: the screen came back into view, e.g. from a post opened + * from it, or mounted with the tab already loaded, as web's does on + * every visit. + * - `significantReturn`: the user came back to the app after a while + * away, with the screen in view. + * - `pushOpened`: the user opened a push notification with the screen in + * view. + */ + reason: + | 'pullToRefresh' + | 'softReset' + | 'pill' + | 'focus' + | 'significantReturn' + | 'pushOpened' + } + /** + * The "Refresh" pill came into view on a Notifications tab, offering what an + * unread check found that the tab hasn't loaded. Only while the tab is the + * one in view, on the focused screen, with the app in the foreground, and + * again each time it comes back into view still up. One hide follows each. + */ + 'notifications:refreshPill:impression': { + tab: GroupedNotificationsFeed + } + /** + * The user pressed the pill, which loads the tab's newest notifications. + */ + 'notifications:refreshPill:press': { + tab: GroupedNotificationsFeed + /** How long since it came into view. */ + shownMs: number + } + /** The pill went, after it came into view. */ + 'notifications:refreshPill:hide': { + tab: GroupedNotificationsFeed + /** + * - `pressed`: the user pressed it. + * - `left`: the tab went out of view: the user switched tab, opened + * another screen, or left the app, or the screen closed, as web's does + * on every navigation away. + * - `refreshed`: the tab started loading its newest notifications some + * other way, e.g. a pull-to-refresh. + * - `gone`: a later unread check found nothing new for the tab to load, + * e.g. once the notifications were seen somewhere else. + */ + reason: 'pressed' | 'left' | 'refreshed' | 'gone' + /** How long it was in view. */ + shownMs: number + } 'state:background': {} 'state:foreground': {} 'router:navigate': { @@ -551,6 +636,9 @@ export type Events = { | 'FindContacts' | 'GroupChat' | 'NotificationExpandedProfileCard' + | 'NotificationFollowRow' + | 'NotificationFollowersTabRow' + | 'NotificationContactMatchRow' } 'profile:followers:view': { contextProfileDid: string @@ -665,6 +753,9 @@ export type Events = { | 'FindContacts' | 'GroupChat' | 'NotificationExpandedProfileCard' + | 'NotificationFollowRow' + | 'NotificationFollowersTabRow' + | 'NotificationContactMatchRow' } 'chat:create': { logContext: diff --git a/src/screens/Notifications/__tests__/refreshPillMetrics.test.ts b/src/screens/Notifications/__tests__/refreshPillMetrics.test.ts new file mode 100644 index 000000000..a98c292f2 --- /dev/null +++ b/src/screens/Notifications/__tests__/refreshPillMetrics.test.ts @@ -0,0 +1,263 @@ +import {afterEach, beforeEach, describe, expect, it, jest} from '@jest/globals' +import {act, renderHook} from '@testing-library/react-native' + +import { + IMPRESSION_DELAY_MS, + refreshPillHideReason, + useRefreshPillMetrics, +} from '#/screens/Notifications/refreshPillMetrics' + +/** + * The app state the hook reads, for tests to send the app to the background. + */ +let mockAppState = 'active' +jest.mock('#/lib/appState', () => ({ + useAppState: () => mockAppState, +})) + +describe('refreshPillHideReason', () => { + const SHOWN_TOP = 1000 + + it('is left once the tab is out of view, whatever else happened', () => { + expect( + refreshPillHideReason({ + isInView: false, + isFetchingTop: true, + topRequestedAt: SHOWN_TOP + 1, + shownTopRequestedAt: SHOWN_TOP, + }), + ).toBe('left') + }) + + it('is refreshed while the tab fetches its top, or once a newer top is in', () => { + expect( + refreshPillHideReason({ + isInView: true, + isFetchingTop: true, + topRequestedAt: SHOWN_TOP, + shownTopRequestedAt: SHOWN_TOP, + }), + ).toBe('refreshed') + expect( + refreshPillHideReason({ + isInView: true, + isFetchingTop: false, + topRequestedAt: SHOWN_TOP + 1, + shownTopRequestedAt: SHOWN_TOP, + }), + ).toBe('refreshed') + }) + + it('is gone when the tab still has the top it showed over, or none', () => { + expect( + refreshPillHideReason({ + isInView: true, + isFetchingTop: false, + topRequestedAt: SHOWN_TOP, + shownTopRequestedAt: SHOWN_TOP, + }), + ).toBe('gone') + expect( + refreshPillHideReason({ + isInView: true, + isFetchingTop: false, + topRequestedAt: undefined, + shownTopRequestedAt: SHOWN_TOP, + }), + ).toBe('gone') + }) +}) + +describe('useRefreshPillMetrics', () => { + type Props = Parameters[0] + const T0 = new Date('2026-10-12T12:00:00.000Z').getTime() + const TOP = {requestedAt: T0 - 60_000} + const SHOWN = {isInView: true, visible: true} + const HIDDEN = {isInView: true, visible: false} + + function setup(initial: Partial = {}) { + const metric = jest.fn() + const onPress = jest.fn() + let props: Props = { + metric, + tab: 'all', + isInView: true, + visible: false, + top: TOP, + isFetchingTop: false, + onPress, + ...initial, + } + const hook = renderHook((p: Props) => useRefreshPillMetrics(p), { + initialProps: props, + }) + const update = (next: Partial) => { + props = {...props, ...next} + hook.rerender(props) + } + const press = () => act(() => hook.result.current()) + const reported = () => + metric.mock.calls.map(([event, payload]) => [event, payload]) + return {hook, onPress, update, press, reported} + } + + beforeEach(() => { + mockAppState = 'active' + jest.useFakeTimers() + jest.setSystemTime(T0) + }) + afterEach(() => { + jest.useRealTimers() + }) + + it('reports an impression as it shows, and a press and hide when pressed', () => { + const {onPress, update, press, reported} = setup() + + update(SHOWN) + jest.advanceTimersByTime(2000) + press() + jest.advanceTimersByTime(500) + update({...HIDDEN, isFetchingTop: true}) + + expect(onPress).toHaveBeenCalledTimes(1) + expect(reported()).toEqual([ + ['notifications:refreshPill:impression', {tab: 'all'}], + ['notifications:refreshPill:press', {tab: 'all', shownMs: 2000}], + [ + 'notifications:refreshPill:hide', + {tab: 'all', reason: 'pressed', shownMs: 2500}, + ], + ]) + }) + + it('says the tab was refreshed when it loads its top some other way', () => { + const {update, reported} = setup() + + update(SHOWN) + jest.advanceTimersByTime(1000) + update({...HIDDEN, isFetchingTop: true}) + + expect(reported()).toEqual([ + ['notifications:refreshPill:impression', {tab: 'all'}], + [ + 'notifications:refreshPill:hide', + {tab: 'all', reason: 'refreshed', shownMs: 1000}, + ], + ]) + }) + + it('says it was gone when a check takes it down', () => { + const {update, reported} = setup() + + update(SHOWN) + jest.advanceTimersByTime(1000) + update(HIDDEN) + + expect(reported()).toEqual([ + ['notifications:refreshPill:impression', {tab: 'all'}], + [ + 'notifications:refreshPill:hide', + {tab: 'all', reason: 'gone', shownMs: 1000}, + ], + ]) + }) + + it("doesn't count one that goes straight away, e.g. as the app comes back and refreshes", () => { + const {update, reported} = setup() + + update(SHOWN) + jest.advanceTimersByTime(IMPRESSION_DELAY_MS - 1) + update({...HIDDEN, isFetchingTop: true}) + jest.advanceTimersByTime(1000) + + expect(reported()).toEqual([]) + }) + + it('counts one pressed before it would have counted', () => { + const {onPress, update, press, reported} = setup() + + update(SHOWN) + jest.advanceTimersByTime(100) + press() + update({...HIDDEN, isFetchingTop: true}) + jest.advanceTimersByTime(1000) + + expect(onPress).toHaveBeenCalledTimes(1) + expect(reported()).toEqual([ + ['notifications:refreshPill:impression', {tab: 'all'}], + ['notifications:refreshPill:press', {tab: 'all', shownMs: 100}], + [ + 'notifications:refreshPill:hide', + {tab: 'all', reason: 'pressed', shownMs: 100}, + ], + ]) + }) + + it('counts each time it comes back into view still up', () => { + const {update, reported} = setup() + + update(SHOWN) + jest.advanceTimersByTime(1000) + update({isInView: false, visible: false}) + jest.advanceTimersByTime(5000) + update(SHOWN) + jest.advanceTimersByTime(IMPRESSION_DELAY_MS) + + expect(reported()).toEqual([ + ['notifications:refreshPill:impression', {tab: 'all'}], + [ + 'notifications:refreshPill:hide', + {tab: 'all', reason: 'left', shownMs: 1000}, + ], + ['notifications:refreshPill:impression', {tab: 'all'}], + ]) + }) + + it('only counts it while the app is in the foreground', () => { + mockAppState = 'background' + const {update, reported} = setup() + + update(SHOWN) + expect(reported()).toEqual([]) + + mockAppState = 'active' + update({}) + jest.advanceTimersByTime(3000) + mockAppState = 'background' + update({}) + + expect(reported()).toEqual([ + ['notifications:refreshPill:impression', {tab: 'all'}], + [ + 'notifications:refreshPill:hide', + {tab: 'all', reason: 'left', shownMs: 3000}, + ], + ]) + }) + + it('ends a showing as the tab unmounts', () => { + const {hook, update, reported} = setup() + + update(SHOWN) + jest.advanceTimersByTime(4000) + hook.unmount() + + expect(reported()).toEqual([ + ['notifications:refreshPill:impression', {tab: 'all'}], + [ + 'notifications:refreshPill:hide', + {tab: 'all', reason: 'left', shownMs: 4000}, + ], + ]) + }) + + it('reports nothing for a pill that never showed, but still presses it', () => { + const {hook, onPress, press, reported} = setup() + + press() + hook.unmount() + + expect(onPress).toHaveBeenCalledTimes(1) + expect(reported()).toEqual([]) + }) +}) diff --git a/src/screens/Notifications/__tests__/tabTaps.test.ts b/src/screens/Notifications/__tests__/tabTaps.test.ts new file mode 100644 index 000000000..73ceff91e --- /dev/null +++ b/src/screens/Notifications/__tests__/tabTaps.test.ts @@ -0,0 +1,34 @@ +import {describe, expect, it} from '@jest/globals' + +import {createTabTaps} from '#/screens/Notifications/tabTaps' + +describe('createTabTaps', () => { + it('counts a page selected after its pill was tapped as a tap, once', () => { + const taps = createTabTaps() + taps.tap(2, 0) + expect(taps.take(2, 300)).toBe(true) + expect(taps.take(2, 400)).toBe(false) + }) + + it('counts a swipe to a page that was never tapped as a swipe', () => { + expect(createTabTaps().take(1, 0)).toBe(false) + }) + + it('counts every page tapped in quick succession, if they come in order', () => { + const taps = createTabTaps() + taps.tap(1, 0) + taps.tap(2, 50) + expect(taps.take(1, 300)).toBe(true) + expect(taps.take(2, 600)).toBe(true) + }) + + it("doesn't let a tap the pager skipped over make a later swipe look like a tap", () => { + const taps = createTabTaps() + taps.tap(1, 0) + taps.tap(2, 50) + // The pager went straight to the last one + expect(taps.take(2, 300)).toBe(true) + // A swipe back to the first, a while later + expect(taps.take(1, 10_000)).toBe(false) + }) +}) diff --git a/src/screens/Notifications/components/NotificationItem/Item/profile.tsx b/src/screens/Notifications/components/NotificationItem/Item/profile.tsx index 1a4db4cd4..cf5709a23 100644 --- a/src/screens/Notifications/components/NotificationItem/Item/profile.tsx +++ b/src/screens/Notifications/components/NotificationItem/Item/profile.tsx @@ -119,10 +119,14 @@ function PillButton({ */ export function FollowButton({ profile, - logContext = 'ProfileCard', + logContext, }: { profile: bsky.profile.AnyProfileView - logContext?: FollowLogContext + /** + * Which row the button is in, for the follow and unfollow metrics, e.g. + * `NotificationFollowRow`. + */ + logContext: FollowLogContext }) { const {currentAccount, hasSession} = useSession() if (!hasSession || profile.did === currentAccount?.did) return null diff --git a/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx b/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx index ec666c164..9e96b7244 100644 --- a/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx +++ b/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx @@ -147,7 +147,10 @@ export function FollowerNotification({ {secondLine} - + ) diff --git a/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx b/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx index 847189265..4a33238b3 100644 --- a/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx +++ b/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx @@ -81,7 +81,7 @@ function SingleFollowNotification({ - + ) @@ -345,7 +345,10 @@ export function ContactMatchNotification({ - + ) diff --git a/src/screens/Notifications/components/PageList.tsx b/src/screens/Notifications/components/PageList.tsx index 7dfd368bf..22d603152 100644 --- a/src/screens/Notifications/components/PageList.tsx +++ b/src/screens/Notifications/components/PageList.tsx @@ -33,6 +33,7 @@ import { } from '#/screens/Notifications/components/NotificationItem' import {usePager} from '#/screens/Notifications/components/PagerView' import {RefreshPill} from '#/screens/Notifications/components/RefreshPill' +import {useRefreshPillMetrics} from '#/screens/Notifications/refreshPillMetrics' import {isRefreshPillVisible} from '#/screens/Notifications/unread' import {atoms as a, native, useTheme, web} from '#/alf' import {ButtonText} from '#/components/Button' @@ -117,6 +118,7 @@ export function PageList({ onEmptyChange?: (isEmpty: boolean) => void }) { const {t: l} = useLingui() + const ax = useAnalytics() const initialNumToRender = useInitialNumToRender() const trackPostView = usePostViewTracking('Notifications') const isScreenFocused = useIsFocused() @@ -172,24 +174,36 @@ export function PageList({ * yet. */ const listRef = useRef(null) - const loadLatest = () => { + const loadLatest = (reason: 'softReset' | 'pill') => { + ax.metric('notifications:refresh', {tab: feed, reason}) listRef.current?.scrollToOffset({animated: IS_NATIVE, offset: 0}) onLoadingLatestChange?.(true) void refresh(feed).finally(() => onLoadingLatestChange?.(false)) } - const onSoftReset = useEffectEvent(loadLatest) + const onSoftReset = useEffectEvent(() => loadLatest('softReset')) useEffect(() => { if (!isScreenFocused || !isActive) return return listenSoftReset(() => onSoftReset()) }, [isScreenFocused, isActive]) + const isInView = isScreenFocused && isActive + const isFetchingTop = isFetching && !isFetchingNextPage const lastUnreadCheck = useLastUnreadCheck() const showRefreshPill = isRefreshPillVisible({ feed, - isActive: isScreenFocused && isActive, + isActive: isInView, check: lastUnreadCheck, top, - isFetchingTop: isFetching && !isFetchingNextPage, + isFetchingTop, + }) + const onPressRefreshPill = useRefreshPillMetrics({ + metric: ax.metric, + tab: feed, + isInView, + visible: showRefreshPill, + top, + isFetchingTop, + onPress: () => loadLatest('pill'), }) let rows: Row[] @@ -203,6 +217,7 @@ export function PageList({ } const onRefresh = async () => { + ax.metric('notifications:refresh', {tab: feed, reason: 'pullToRefresh'}) setIsPTRing(true) try { await refresh(feed) @@ -333,7 +348,7 @@ export function PageList({ visible={showRefreshPill} headerHeight={headerOffset} titleHeight={titleHeight} - onPress={loadLatest} + onPress={onPressRefreshPill} /> ) diff --git a/src/screens/Notifications/index.tsx b/src/screens/Notifications/index.tsx index 48ed14b57..2a86efb9c 100644 --- a/src/screens/Notifications/index.tsx +++ b/src/screens/Notifications/index.tsx @@ -14,6 +14,7 @@ import {useFocusEffect, useIsFocused} from '@react-navigation/native' import {useQueryClient} from '@tanstack/react-query' import {type AnyAppReturn, onAnyAppReturn} from '#/lib/appState' +import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import { type NativeStackScreenProps, type NotificationsTabNavigatorParams, @@ -35,6 +36,7 @@ import {NotificationsScreen as LegacyNotificationsScreen} from '#/view/screens/N import {PageList} from '#/screens/Notifications/components/PageList' import * as Pager from '#/screens/Notifications/components/PagerView' import {TabPills} from '#/screens/Notifications/components/TabPills' +import {createTabTaps} from '#/screens/Notifications/tabTaps' import { type FeedLoad, getMarkReadAt, @@ -47,7 +49,7 @@ import {SettingsGear2_Stroke2_Corner0_Rounded as SettingsIcon} from '#/component import * as Layout from '#/components/Layout' import {Link} from '#/components/Link' import {Loader} from '#/components/Loader' -import {useAnalytics} from '#/analytics' +import {type Metrics, useAnalytics} from '#/analytics' import {IS_INTERNAL, IS_LIQUID_GLASS, IS_WEB} from '#/env' type Props = NativeStackScreenProps< @@ -55,6 +57,8 @@ type Props = NativeStackScreenProps< 'Notifications' > +type RefreshReason = Metrics['notifications:refresh']['reason'] + export function NotificationsScreen(props: Props) { const ax = useAnalytics() // Dev and TestFlight builds always get it, so it's dogfooded before rollout @@ -80,6 +84,7 @@ export function NewNotificationsScreen({}: Props) { function NewNotificationsScreenInner() { const {t: l} = useLingui() + const ax = useAnalytics() const headerMode = useHomeHeaderMode() const initialHeaderOffset = useHeaderOffset() const [headerOffset, setHeaderOffset] = useState(initialHeaderOffset) @@ -105,12 +110,16 @@ function NewNotificationsScreenInner() { * refreshes the feed, unless the user is partway down it, in which case * only the unread check runs, so the list doesn't move under them. */ - const checkLatest = (feed: GroupedNotificationsFeed) => { + const checkLatest = ( + feed: GroupedNotificationsFeed, + reason: RefreshReason, + ) => { // Not loaded yet, so its first load is on the way if (!getGroupedNotificationsTop(queryClient, feed)) return if (scrolledDownFeeds.current.has(feed)) { void unreadApi.checkUnread() } else { + ax.metric('notifications:refresh', {tab: feed, reason}) void refresh(feed) } } @@ -148,13 +157,35 @@ function NewNotificationsScreenInner() { }, [showHeader]), ) + const logTabDisplayed = ( + page: number, + reason: Metrics['notifications:tabDisplayed']['reason'], + ) => { + ax.metric('notifications:tabDisplayed', { + tab: tabs[page].key, + index: page, + reason, + }) + } + useFocusEffect( + useNonReactiveCallback(() => { + logTabDisplayed( + tabs.findIndex(tab => tab.key === activeFeed.current), + 'focus', + ) + }), + ) + const [tabTaps] = useState(createTabTaps) + return ( { const feed = tabs[page].key + const isTap = tabTaps.take(page) // Web reports the page it starts on, too if (feed === activeFeed.current) return activeFeed.current = feed + logTabDisplayed(page, isTap ? 'tap' : 'swipe') /* * Switching tabs only checks for anything new, which the "Refresh" * pill offers, so flicking between tabs neither reloads them nor @@ -188,6 +219,8 @@ function NewNotificationsScreenInner() { // Re-pressing the current tab scrolls it to the top if (page === selectedPage) { emitSoftReset() + } else { + tabTaps.tap(page) } selectPage(page) }} @@ -329,7 +362,7 @@ function useReturnToScreen({ peekLatest, }: { activeFeed: React.RefObject - checkLatest: (feed: GroupedNotificationsFeed) => void + checkLatest: (feed: GroupedNotificationsFeed, reason: RefreshReason) => void /** * Asks the server for anything new without loading it, which offers the * "Refresh" pill if there is. @@ -338,27 +371,29 @@ function useReturnToScreen({ }) { const isFocused = useIsFocused() - const onReturn = useEffectEvent(() => { - checkLatest(activeFeed.current) + const onReturn = useEffectEvent((reason: RefreshReason) => { + checkLatest(activeFeed.current, reason) }) // Mounting counts, as the cache can outlive the screen const wasFocused = useRef(false) useEffect(() => { if (isFocused && !wasFocused.current) { - onReturn() + onReturn('focus') } wasFocused.current = isFocused }, [isFocused]) - const onLeftApp = useEffectEvent(() => { - if (isFocused) { - onReturn() - } - }) + const onLeftApp = useEffectEvent( + (reason: 'significantReturn' | 'pushOpened') => { + if (isFocused) { + onReturn(reason) + } + }, + ) const onAppReturn = useEffectEvent((appReturn: AnyAppReturn) => { if (appReturn.isSignificant) { - onLeftApp() + onLeftApp('significantReturn') } else if (isFocused) { peekLatest() } @@ -369,7 +404,9 @@ function useReturnToScreen({ * Opening a push leaves the app too, even when it never went to the * background, e.g. from Notification Center on iOS. */ - const unlistenPush = listenPushNotificationOpened(() => onLeftApp()) + const unlistenPush = listenPushNotificationOpened(() => + onLeftApp('pushOpened'), + ) return () => { returns.remove() unlistenPush() diff --git a/src/screens/Notifications/refreshPillMetrics.ts b/src/screens/Notifications/refreshPillMetrics.ts new file mode 100644 index 000000000..b1a3007bb --- /dev/null +++ b/src/screens/Notifications/refreshPillMetrics.ts @@ -0,0 +1,203 @@ +import {useEffect, useEffectEvent, useRef} from 'react' + +import {useAppState} from '#/lib/appState' +import { + type GroupedNotificationsFeed, + type LoadedGroupedNotificationsPage, +} from '#/state/queries/notifications/grouped' +import {type AnalyticsContextType, type Metrics} from '#/analytics' + +/* + * Metrics for the "Refresh" pill on a Notifications tab (see `RefreshPill`): + * when it shows, when it's pressed, and why it goes, named and shaped like + * Following's new posts pill. Counts, durations and enums only, never the + * notifications or who they're from. + */ + +/** + * Why the pill went, after it showed. + */ +export type RefreshPillHideReason = + Metrics['notifications:refreshPill:hide']['reason'] + +/** + * How long the pill has to stay up to count. One that goes sooner was never + * really seen, e.g. one still up from before the app went to the background, + * which the refresh on coming back takes down straight away. + */ +export const IMPRESSION_DELAY_MS = 250 + +/** + * Why the pill went without the user pressing it: `left` if the tab is out of + * view, `refreshed` if the tab is fetching its first page or has fetched it + * again since the pill showed, otherwise `gone`. + */ +export function refreshPillHideReason({ + isInView, + isFetchingTop, + topRequestedAt, + shownTopRequestedAt, +}: { + isInView: boolean + isFetchingTop: boolean + /** + * When the tab's first page was requested, if it has one. + */ + topRequestedAt: number | undefined + /** + * When the tab's first page was requested, as the pill showed. + */ + shownTopRequestedAt: number +}): RefreshPillHideReason { + if (!isInView) return 'left' + if ( + isFetchingTop || + (topRequestedAt !== undefined && topRequestedAt > shownTopRequestedAt) + ) { + return 'refreshed' + } + return 'gone' +} + +/** + * The pill from showing to going. + */ +type Showing = { + /** When it showed. */ + shownAt: number + /** When the tab's first page was requested, as it showed. */ + topRequestedAt: number + /** Whether the user has pressed it. */ + isPressed: boolean + /** Whether its impression has been reported. */ + isCounted: boolean + /** Reports its impression once it has stayed up long enough. */ + timer: ReturnType +} + +/** + * Reports the "Refresh" pill's impressions, presses and hides on one tab, and + * returns `onPress` wrapped to report presses. + * + * An impression is each time the pill comes into view and stays up for + * `IMPRESSION_DELAY_MS`, or is pressed sooner. It's only in view while the tab + * is the one in view, on the focused screen, with the app in the foreground. + * Every impression ends in one hide, so a pill that's still up when the user + * comes back to the tab counts again, and one that goes before it counts + * reports nothing. + */ +export function useRefreshPillMetrics({ + metric, + tab, + isInView, + visible, + top, + isFetchingTop, + onPress, +}: { + metric: AnalyticsContextType['metric'] + tab: GroupedNotificationsFeed + /** + * Whether the tab is the one in view, on the focused screen. + */ + isInView: boolean + /** + * Whether the pill is up, which it only is while `isInView`. + */ + visible: boolean + /** + * The tab's first page, once loaded. + */ + top: Pick | undefined + /** + * Whether the tab is fetching its first page, rather than a later one. + */ + isFetchingTop: boolean + onPress: () => void +}): () => void { + const isForeground = useAppState() !== 'background' + const isShown = visible && isForeground + const showing = useRef(undefined) + const topRequestedAt = top?.requestedAt + + const count = (current: Showing) => { + if (current.isCounted) return + clearTimeout(current.timer) + current.isCounted = true + metric('notifications:refreshPill:impression', {tab}) + } + + /** + * Ends a showing, reporting its hide if it was counted. + */ + const end = (current: Showing, reason: RefreshPillHideReason) => { + showing.current = undefined + clearTimeout(current.timer) + if (!current.isCounted) return + metric('notifications:refreshPill:hide', { + tab, + reason: current.isPressed ? 'pressed' : reason, + shownMs: Date.now() - current.shownAt, + }) + } + + useEffect(() => { + const current = showing.current + if (isShown && !current && topRequestedAt !== undefined) { + const next: Showing = { + shownAt: Date.now(), + topRequestedAt, + isPressed: false, + isCounted: false, + timer: setTimeout(() => count(next), IMPRESSION_DELAY_MS), + } + showing.current = next + } else if (!isShown && current) { + end( + current, + refreshPillHideReason({ + isInView: isInView && isForeground, + isFetchingTop, + topRequestedAt, + shownTopRequestedAt: current.topRequestedAt, + }), + ) + } + }, [ + count, + end, + isShown, + isInView, + isForeground, + isFetchingTop, + topRequestedAt, + ]) + + /* + * The tab's effects going ends a showing too: when the screen closes, and + * on web, when the user switches away from the tab, which hides it. + */ + const onEffectsGone = useEffectEvent(() => { + const current = showing.current + if (current) { + end(current, 'left') + } + }) + useEffect(() => { + return () => onEffectsGone() + }, []) + + return () => { + const current = showing.current + if (current) { + // Pressed before it counted, so it was seen after all + count(current) + current.isPressed = true + metric('notifications:refreshPill:press', { + tab, + shownMs: Date.now() - current.shownAt, + }) + } + onPress() + } +} diff --git a/src/screens/Notifications/tabTaps.ts b/src/screens/Notifications/tabTaps.ts new file mode 100644 index 000000000..c1be1d135 --- /dev/null +++ b/src/screens/Notifications/tabTaps.ts @@ -0,0 +1,30 @@ +/** + * How long after a tab pill is tapped the pager selecting its page still + * counts as the tap's doing. On iOS the pager reports the page once it has + * animated there. + */ +const TAP_WINDOW_MS = 2000 + +/** + * Tells tab pill taps apart from swipes, as both end in the pager selecting a + * page. Pills tapped in quick succession can have several on the way, and + * the pager may skip straight to the last, so a tap only counts for a short + * while: one whose page was skipped can't make a later swipe there look like + * a tap. + */ +export function createTabTaps() { + const tappedAt = new Map() + return { + tap(page: number, now = Date.now()) { + tappedAt.set(page, now) + }, + /** + * Whether the pager selecting `page` was down to a tap. + */ + take(page: number, now = Date.now()) { + const at = tappedAt.get(page) + tappedAt.delete(page) + return at !== undefined && now - at <= TAP_WINDOW_MS + }, + } +} -- knotmirror 0.0.1