From d059ffab74536610d8a6fa883bf014dbea125492 Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Wed, 14 Oct 2026 11:52:31 +0300 Subject: [PATCH] APP-3363: Second polish round for Notifications v2 (#11960) Co-authored-by: Claude Opus 5.5 --- src/components/Post/ShowMoreTextButton.tsx | 21 +- .../Notifications/__tests__/PageList.test.ts | 40 +- .../Notifications/__tests__/avatarRow.test.ts | 47 ++ .../Notifications/__tests__/unread.test.ts | 31 +- .../__tests__/useWindowScrollPerPage.test.ts | 121 ++++ .../NotificationItem/Item/Avatar.tsx | 83 ++- .../components/NotificationItem/Item/Root.tsx | 52 +- .../NotificationItem/Item/aggregate.tsx | 161 +----- .../NotificationItem/Item/avatarRow.ts | 62 ++ .../NotificationItem/Item/group.tsx | 541 ++++++++++++++++++ .../components/NotificationItem/Item/index.ts | 2 + .../components/NotificationItem/Item/post.tsx | 99 +++- .../NotificationItem/Item/profile.tsx | 76 +-- .../components/NotificationItem/Item/text.tsx | 18 +- .../NotificationItem/LoadingSkeleton.tsx | 394 +++++++++++++ .../components/NotificationItem/index.tsx | 1 + .../NotificationItem/kinds/aggregate.tsx | 227 ++++---- .../NotificationItem/kinds/follower.tsx | 3 +- .../NotificationItem/kinds/profile.tsx | 185 ++---- .../Notifications/components/PageList.tsx | 41 +- .../components/PagerView/Content.web.tsx | 56 +- .../Notifications/components/RefreshPill.tsx | 46 +- .../Notifications/components/TabPills.tsx | 101 +++- src/screens/Notifications/index.tsx | 87 ++- src/screens/Notifications/unread.ts | 39 +- .../grouped/__fixtures__/index.ts | 70 ++- ...ow-actors.test.ts => group-actors.test.ts} | 96 +++- .../grouped/__tests__/hydrate.test.ts | 73 ++- .../grouped/__tests__/moderate.test.ts | 14 +- .../notifications/grouped/follow-actors.ts | 96 ---- .../notifications/grouped/group-actors.ts | 155 +++++ .../queries/notifications/grouped/hydrate.ts | 54 +- .../queries/notifications/grouped/index.ts | 50 +- .../queries/notifications/grouped/moderate.ts | 13 +- .../queries/notifications/grouped/types.ts | 80 +-- .../screens/DebugMod/GroupedNotifications.tsx | 73 ++- 36 files changed, 2453 insertions(+), 855 deletions(-) create mode 100644 src/screens/Notifications/__tests__/avatarRow.test.ts create mode 100644 src/screens/Notifications/__tests__/useWindowScrollPerPage.test.ts create mode 100644 src/screens/Notifications/components/NotificationItem/Item/avatarRow.ts create mode 100644 src/screens/Notifications/components/NotificationItem/Item/group.tsx create mode 100644 src/screens/Notifications/components/NotificationItem/LoadingSkeleton.tsx rename src/state/queries/notifications/grouped/__tests__/{follow-actors.test.ts => group-actors.test.ts} (68%) delete mode 100644 src/state/queries/notifications/grouped/follow-actors.ts create mode 100644 src/state/queries/notifications/grouped/group-actors.ts diff --git a/src/components/Post/ShowMoreTextButton.tsx b/src/components/Post/ShowMoreTextButton.tsx index 7765fbdd0..80bb485da 100644 --- a/src/components/Post/ShowMoreTextButton.tsx +++ b/src/components/Post/ShowMoreTextButton.tsx @@ -1,5 +1,9 @@ import {useCallback, useMemo} from 'react' -import {LayoutAnimation, type TextStyle} from 'react-native' +import { + type GestureResponderEvent, + LayoutAnimation, + type TextStyle, +} from 'react-native' import {Trans, useLingui} from '@lingui/react/macro' import {HITSLOP_10} from '#/lib/constants' @@ -10,14 +14,19 @@ import {Text} from '#/components/Typography' export function ShowMoreTextButton({ onPress: onPressProp, style, -}: TextStyleProp & {onPress: () => void}) { +}: TextStyleProp & { + onPress: (event: GestureResponderEvent) => void +}) { const t = useTheme() const {t: l} = useLingui() - const onPress = useCallback(() => { - LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) - onPressProp() - }, [onPressProp]) + const onPress = useCallback( + (event: GestureResponderEvent) => { + LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) + onPressProp(event) + }, + [onPressProp], + ) const textStyle = useMemo(() => { return flatten([a.leading_snug, a.text_sm, style]) as TextStyle & { diff --git a/src/screens/Notifications/__tests__/PageList.test.ts b/src/screens/Notifications/__tests__/PageList.test.ts index 4b94c6551..358d512fc 100644 --- a/src/screens/Notifications/__tests__/PageList.test.ts +++ b/src/screens/Notifications/__tests__/PageList.test.ts @@ -1,6 +1,10 @@ import {describe, expect, it, jest} from '@jest/globals' -import {getPlaceholderRow} from '#/screens/Notifications/components/PageList' +import {type NotificationView} from '#/state/queries/notifications/grouped/types' +import { + buildRows, + getPlaceholderRow, +} from '#/screens/Notifications/components/PageList' // The placeholder helper doesn't need the native runtime or analytics setup. jest.mock('#/state/queries/notifications/grouped', () => ({})) @@ -39,3 +43,37 @@ describe('getPlaceholderRow', () => { expect(getPlaceholderRow({isError: true, isEmpty: true}).type).toBe('error') }) }) + +describe('buildRows', () => { + const today = new Date().toISOString() + const lastYear = new Date( + Date.now() - 365 * 24 * 60 * 60 * 1000, + ).toISOString() + + // Only the fields `buildRows` reads + function notification(id: string, indexedAt: string) { + return {id, type: 'like', indexedAt} as unknown as NotificationView + } + + function layout(notifications: NotificationView[]) { + return buildRows(notifications, 'all').map(row => + row.type === 'section' ? row.section : row.key, + ) + } + + it('splits notifications into today and earlier', () => { + expect( + layout([ + notification('a', today), + notification('b', today), + notification('c', lastYear), + ]), + ).toEqual(['today', 'a', 'b', 'earlier', 'c']) + }) + + it('leaves the headers out when nothing happened today', () => { + expect( + layout([notification('a', lastYear), notification('b', lastYear)]), + ).toEqual(['a', 'b']) + }) +}) diff --git a/src/screens/Notifications/__tests__/avatarRow.test.ts b/src/screens/Notifications/__tests__/avatarRow.test.ts new file mode 100644 index 000000000..d34eb53ed --- /dev/null +++ b/src/screens/Notifications/__tests__/avatarRow.test.ts @@ -0,0 +1,47 @@ +import {describe, expect, it} from '@jest/globals' + +import {fitAvatarCount} from '#/screens/Notifications/components/NotificationItem/Item/avatarRow' + +/* + * Each avatar takes 36 (28 and a gap of 8). The toggle takes 32 with just + * the chevron, or 56 with a "+N" chip. + */ +describe('fitAvatarCount', () => { + it('shows everyone, without a chip, when they all fit', () => { + // 6 * 36 + 32 = 248 + expect( + fitAvatarCount({width: 248, resolved: 6, total: 6, hasToggle: true}), + ).toBe(6) + }) + + it('makes room for the chip once everyone no longer fits', () => { + // 247 is too narrow for all 6 and the chevron, and (247 - 56) / 36 = 5.3 + expect( + fitAvatarCount({width: 247, resolved: 6, total: 6, hasToggle: true}), + ).toBe(5) + }) + + it('always leaves room for the chip when some people are unresolved', () => { + // There's room for all 3 profiles, but 17 more people need the chip + expect( + fitAvatarCount({width: 1000, resolved: 3, total: 20, hasToggle: true}), + ).toBe(3) + // (148 - 56) / 36 = 2.5, a phone row beside a thumbnail + expect( + fitAvatarCount({width: 148, resolved: 9, total: 20, hasToggle: true}), + ).toBe(2) + }) + + it('never shows more than fit, even if that means none', () => { + expect( + fitAvatarCount({width: 60, resolved: 9, total: 20, hasToggle: true}), + ).toBe(0) + }) + + it('needs no room for a toggle when there is none', () => { + // A pair named in full: one avatar, 28 wide + expect( + fitAvatarCount({width: 28, resolved: 1, total: 1, hasToggle: false}), + ).toBe(1) + }) +}) diff --git a/src/screens/Notifications/__tests__/unread.test.ts b/src/screens/Notifications/__tests__/unread.test.ts index 50342af48..cb4126992 100644 --- a/src/screens/Notifications/__tests__/unread.test.ts +++ b/src/screens/Notifications/__tests__/unread.test.ts @@ -23,18 +23,18 @@ function load(overrides: Partial = {}): FeedLoad { } describe('nextSeenAt', () => { - it('takes the server seenAt in server mode', () => { + it('takes the server seenAt on a refresh', () => { expect( - nextSeenAt({load: load(), mode: 'server', snapshot: SNAPSHOT}), + nextSeenAt({load: load(), isRefresh: true, snapshot: SNAPSHOT}), ).toEqual(new Date(SERVER_SEEN_AT)) }) - it('moves an existing snapshot to the server seenAt in server mode, so only what arrived since the last load is tinted', () => { + it('moves an existing snapshot to the server seenAt on a refresh, so only what arrived since the last load is tinted', () => { // The previous load marked everything up to SERVER_SEEN_AT as seen const olderSnapshot = new Date(Date.parse(SERVER_SEEN_AT) - 60_000) const next = nextSeenAt({ load: load(), - mode: 'server', + isRefresh: true, snapshot: olderSnapshot, }) expect(next).toEqual(new Date(SERVER_SEEN_AT)) @@ -42,27 +42,28 @@ describe('nextSeenAt', () => { expect(next!.getTime()).toBeLessThan(REQUESTED_AT) }) - it('keeps the snapshot in kept mode, or without a mode', () => { - expect(nextSeenAt({load: load(), mode: 'kept', snapshot: SNAPSHOT})).toBe( - SNAPSHOT, - ) + it("keeps the snapshot for a load that isn't a refresh, e.g. a tab's first", () => { expect( - nextSeenAt({load: load(), mode: undefined, snapshot: SNAPSHOT}), + nextSeenAt({load: load(), isRefresh: false, snapshot: SNAPSHOT}), ).toBe(SNAPSHOT) }) - it('takes the server seenAt when there is no snapshot yet, whatever the mode', () => { - for (const mode of ['server', 'kept', undefined] as const) { - expect(nextSeenAt({load: load(), mode, snapshot: undefined})).toEqual( - new Date(SERVER_SEEN_AT), - ) + it('takes the server seenAt when there is no snapshot yet, refresh or not', () => { + for (const isRefresh of [true, false]) { + expect( + nextSeenAt({load: load(), isRefresh, snapshot: undefined}), + ).toEqual(new Date(SERVER_SEEN_AT)) } }) it('treats a missing or invalid server seenAt as everything seen', () => { for (const seenAt of [undefined, '', 'not a date']) { expect( - nextSeenAt({load: load({seenAt}), mode: 'server', snapshot: undefined}), + nextSeenAt({ + load: load({seenAt}), + isRefresh: true, + snapshot: undefined, + }), ).toEqual(new Date(REQUESTED_AT)) } }) diff --git a/src/screens/Notifications/__tests__/useWindowScrollPerPage.test.ts b/src/screens/Notifications/__tests__/useWindowScrollPerPage.test.ts new file mode 100644 index 000000000..1859e3bb2 --- /dev/null +++ b/src/screens/Notifications/__tests__/useWindowScrollPerPage.test.ts @@ -0,0 +1,121 @@ +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, +} from '@jest/globals' +import {renderHook} from '@testing-library/react-native' + +import {useWindowScrollPerPage} from '#/screens/Notifications/components/PagerView/Content.web' + +let mockIsFocused = true +jest.mock('@react-navigation/native', () => ({ + useIsFocused: () => mockIsFocused, +})) +// The pager's own needs, which the hook doesn't use and can't load here +jest.mock('#/alf', () => ({atoms: {}})) +jest.mock('react-native-reanimated', () => ({})) + +/* + * jest-expo's environment uses the global object as the window, without its + * scrolling or events, so these stand in for them. + */ +const scroller = new EventTarget() +let scrollY = 0 +const scrollTo = jest.fn((options: ScrollToOptions) => { + scrollY = options.top ?? 0 +}) + +beforeAll(() => { + Object.assign(window, { + addEventListener: scroller.addEventListener.bind(scroller), + removeEventListener: scroller.removeEventListener.bind(scroller), + scrollTo, + }) + Object.defineProperty(window, 'scrollY', { + configurable: true, + get: () => scrollY, + }) +}) + +afterAll(() => { + for (const key of [ + 'addEventListener', + 'removeEventListener', + 'scrollTo', + 'scrollY', + ]) { + Reflect.deleteProperty(window, key) + } +}) + +beforeEach(() => { + mockIsFocused = true + scrollY = 0 + scrollTo.mockClear() +}) + +/** + * Scrolls the window to `y`, as the user would. + */ +function scroll(y: number) { + scrollY = y + scroller.dispatchEvent(new Event('scroll')) +} + +function renderPager() { + return renderHook(({page}: {page: number}) => useWindowScrollPerPage(page), { + initialProps: {page: 0}, + }) +} + +describe('useWindowScrollPerPage', () => { + it('leaves the window alone on mount', () => { + renderPager() + expect(scrollTo).not.toHaveBeenCalled() + }) + + it('opens a page for the first time at the top', () => { + const {rerender} = renderPager() + scroll(500) + rerender({page: 1}) + expect(scrollTo).toHaveBeenLastCalledWith({top: 0, behavior: 'instant'}) + }) + + it('puts each page back where it was left', () => { + const {rerender} = renderPager() + scroll(500) + rerender({page: 1}) + scroll(200) + rerender({page: 0}) + expect(scrollTo).toHaveBeenLastCalledWith({top: 500, behavior: 'instant'}) + rerender({page: 1}) + expect(scrollTo).toHaveBeenLastCalledWith({top: 200, behavior: 'instant'}) + }) + + it('keeps the scroll that follows a switch for the page now shown', () => { + const {rerender} = renderPager() + scroll(500) + rerender({page: 1}) + // The browser reports the switch's own scroll afterwards + scroll(scrollY) + rerender({page: 0}) + expect(scrollTo).toHaveBeenLastCalledWith({top: 500, behavior: 'instant'}) + }) + + it('ignores the window scrolling while the screen is out of focus', () => { + const {rerender} = renderPager() + scroll(500) + mockIsFocused = false + rerender({page: 0}) + // Another screen, scrolling the same window + scroll(1500) + mockIsFocused = true + rerender({page: 0}) + rerender({page: 1}) + rerender({page: 0}) + expect(scrollTo).toHaveBeenLastCalledWith({top: 500, behavior: 'instant'}) + }) +}) diff --git a/src/screens/Notifications/components/NotificationItem/Item/Avatar.tsx b/src/screens/Notifications/components/NotificationItem/Item/Avatar.tsx index d9ec17b63..6b65da14d 100644 --- a/src/screens/Notifications/components/NotificationItem/Item/Avatar.tsx +++ b/src/screens/Notifications/components/NotificationItem/Item/Avatar.tsx @@ -5,6 +5,7 @@ import {useModerationOpts} from '#/state/preferences/moderation-opts' import {PreviewableUserAvatar} from '#/view/com/util/UserAvatar' import {atoms as a, useTheme} from '#/alf' import {type Props as SVGIconProps} from '#/components/icons/common' +import * as Skele from '#/components/Skeleton' import type * as bsky from '#/types/bsky' import {useItemBackgroundColor} from './Root' @@ -20,7 +21,10 @@ export type BadgeTone = */ const ACTIVITY_ORANGE = '#F26022' -const AVATAR_SIZE = 40 +/** + * The size of `Item.Avatar`'s avatar, for anything that stands in for it. + */ +export const AVATAR_SIZE = 44 const BADGE_SIZE = 20 /** * The width of the ring around the badge, in the row's background colour, @@ -28,6 +32,21 @@ const BADGE_SIZE = 20 */ const BADGE_RING = 2 +/** + * The space the avatar sits in, with room for the badge to overlap its + * bottom-end corner. + */ +const SLOT_SIZE = { + width: AVATAR_SIZE + 6 + BADGE_RING, + height: AVATAR_SIZE + 4 + BADGE_RING, +} + +/** + * How wide `Item.Avatar` is, for lining things up with the content column + * beside it. + */ +export const AVATAR_SLOT_WIDTH = SLOT_SIZE.width + /** * The primary actor's avatar, with an icon badge overlapping its bottom-end * corner that says what kind of notification this is. Omit `icon` for an @@ -61,10 +80,7 @@ export function Avatar({ return ( @@ -73,27 +89,68 @@ export function Avatar({ profile={profile} moderation={moderation?.ui('avatar')} type={profile.associated?.labeler ? 'labeler' : 'user'} + // It would cover the badge. The red ring still says they're live + hideLiveBadge /> {Icon && ( + /* + * The ring is a padded circle behind the badge rather than a border + * on it. A view's background is drawn under its border too, so it + * would show through the anti-aliased edge of the ring. + */ - + + + )} ) } + +/** + * Stands in for a badged `Avatar` while the row loads, in the same slot, with + * a faint circle where the badge goes. + */ +export function AvatarSkeleton() { + const ringColor = useItemBackgroundColor() + + return ( + + + + + + + ) +} diff --git a/src/screens/Notifications/components/NotificationItem/Item/Root.tsx b/src/screens/Notifications/components/NotificationItem/Item/Root.tsx index a3afcca67..56ea109be 100644 --- a/src/screens/Notifications/components/NotificationItem/Item/Root.tsx +++ b/src/screens/Notifications/components/NotificationItem/Item/Root.tsx @@ -2,6 +2,7 @@ import {createContext, useContext, useState} from 'react' import { type AccessibilityActionEvent, type AccessibilityProps, + type GestureResponderEvent, Pressable, type StyleProp, View, @@ -27,20 +28,27 @@ export function useItemContext() { return useContext(ItemContext) } +/** + * The background colour of a row, tinted while unread. + */ +export function useRowBackgroundColor(isRead: boolean) { + const t = useTheme() + return isRead ? t.atoms.bg.backgroundColor : t.palette.primary_25 +} + /** * The background colour of the enclosing `Item.Root`, tinted while unread, * for parts that have to blend into it. */ export function useItemBackgroundColor() { - const t = useTheme() const {isRead} = useItemContext() - return isRead ? t.atoms.bg.backgroundColor : t.palette.primary_25 + return useRowBackgroundColor(isRead) } /** * A notification row: the avatar column, `Item.Content`, and an optional * `Item.Trailing`, laid out horizontally. Pressing anywhere outside a nested - * control navigates to `href`. + * control navigates to `href`, unless `onPress` handles it instead. * * This is a plain `Pressable` rather than a `Link`, so on web the row isn't * an ``. Rows contain names, rich text links, buttons and menus, none of @@ -52,9 +60,12 @@ export function Root({ label, hint, accessible = true, + accessibilityRole = 'link', + expanded, accessibilityActions, onAccessibilityAction, onBeforePress, + onPress: onPressProp, style, testID, children, @@ -75,16 +86,29 @@ export function Root({ * actions), so that screen readers can reach them individually. */ accessible?: boolean + /** + * `button` for rows that do something other than follow `href` when + * pressed. + */ + accessibilityRole?: 'link' | 'button' + /** + * Whether the row is expanded, for rows that expand. + */ + expanded?: boolean accessibilityActions?: AccessibilityProps['accessibilityActions'] onAccessibilityAction?: (event: AccessibilityActionEvent) => void onBeforePress?: () => void + /** + * Handles presses instead of following `href`, e.g. to expand the row. + */ + onPress?: (event: GestureResponderEvent) => void style?: StyleProp testID?: string children: React.ReactNode }) { - const t = useTheme() + const backgroundColor = useRowBackgroundColor(isRead) const [hover, setHover] = useState(false) - const {onPress} = useLink({to: href, displayText: ''}) + const {onPress: followLink} = useLink({to: href, displayText: ''}) return ( @@ -92,14 +116,19 @@ export function Root({ { + if (onPressProp) { + onPressProp(event) + return + } onBeforePress?.() - onPress(event) + followLink(event) }} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} @@ -107,9 +136,14 @@ export function Root({ a.flex_row, a.align_start, a.gap_lg, + /* + * As a button it's a ` + ) +} + +/** + * The "+N" in an `AvatarRow`, sized to match the avatars. + */ +function OverflowChip({count}: {count: number}) { + const t = useTheme() + const {i18n} = useLingui() + + return ( + + {/* Fixed size, since it has to fit inside the circle */} + + {`+${formatCount(i18n, count)}`} + + + ) +} + +/** + * Points down when the group is collapsed and up when it's expanded. + * + * Swaps icons rather than rotating one, since react-native-svg applies a + * transform on the icon to its contents too, rotating the path out of view. + */ +function ExpandChevron({expanded}: {expanded: boolean}) { + const t = useTheme() + const Icon = expanded ? ChevronUpIcon : ChevronDownIcon + // `sm`, which `fitAvatarCount` allows for as `CHEVRON_SIZE` + return +} diff --git a/src/screens/Notifications/components/NotificationItem/Item/index.ts b/src/screens/Notifications/components/NotificationItem/Item/index.ts index 8d47a5ee3..97c6108a7 100644 --- a/src/screens/Notifications/components/NotificationItem/Item/index.ts +++ b/src/screens/Notifications/components/NotificationItem/Item/index.ts @@ -1,6 +1,8 @@ export * from './aggregate' export * from './Avatar' +export * from './avatarRow' export * from './Expandable' +export * from './group' export * from './media' export * from './post' export * from './profile' diff --git a/src/screens/Notifications/components/NotificationItem/Item/post.tsx b/src/screens/Notifications/components/NotificationItem/Item/post.tsx index cfd8748c3..62059793b 100644 --- a/src/screens/Notifications/components/NotificationItem/Item/post.tsx +++ b/src/screens/Notifications/components/NotificationItem/Item/post.tsx @@ -1,15 +1,17 @@ import {useState} from 'react' -import {View} from 'react-native' +import {type GestureResponderEvent, View} from 'react-native' import {moderatePost, type ModerationDecision} from '@bsky/sdk/moderation' import {RichText as RichTextAPI} from '@bsky/sdk/richtext' import {Trans, useLingui} from '@lingui/react/macro' +import {MAX_POST_LINES} from '#/lib/constants' import {useHaptics} from '#/lib/haptics' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {makeProfileLink} from '#/lib/routes/links' import {forceLTR} from '#/lib/strings/bidi' import {NON_BREAKING_SPACE} from '#/lib/strings/constants' import {sanitizeHandle} from '#/lib/strings/handles' +import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, type Shadow, @@ -35,6 +37,7 @@ import {Link, WebOnlyInlineLinkText} from '#/components/Link' import {ContentHider} from '#/components/moderation/ContentHider' import {PostAlerts} from '#/components/moderation/PostAlerts' import {ExternalEmbed} from '#/components/Post/Embed/ExternalEmbed' +import {ShowMoreTextButton} from '#/components/Post/ShowMoreTextButton' import {PostMenuButton} from '#/components/PostControls/PostMenu' import {ProfileBadges} from '#/components/ProfileBadges' import {ProfileHoverCard} from '#/components/ProfileHoverCard' @@ -155,7 +158,7 @@ export function ContextLine({ + style={[a.flex_1, a.text_sm, a.leading_snug, t.atoms.text]}> {children} @@ -236,7 +239,8 @@ function ReplyContextPost({ 'Shown in place of the text of a post that has no text, only images, video, a link or a quoted post', }) } - const previewStyle = [a.text_md, a.leading_snug, t.atoms.text_contrast_medium] + // Nested text keeps its own size, so each part matches `ContextLine`'s + const previewStyle = [a.text_sm, a.leading_snug, t.atoms.text_contrast_medium] const previewNode = record && preview && !isHidden ? ( replied to: {previewNode} ) : ( - replied to {name}: {previewNode} + replied to {name}: {previewNode} ) } @@ -270,14 +274,15 @@ function ReplyContextPost({ in reply to: {previewNode} ) : ( - in reply to {name}: {previewNode} + in reply to {name}: {previewNode} ) } /** * A post's text and a compact preview of its embed, behind the usual - * moderation hider. Images stand in for the text when there isn't any. + * moderation hider. Images stand in for the text when there isn't any. Long + * text is cut short with a "Show more" button, as in feeds. */ export function PostBody({post}: {post: PostView}) { const moderationOpts = useModerationOpts() @@ -288,11 +293,26 @@ export function PostBody({post}: {post: PostView}) { record && record.text.trim() ? new RichTextAPI({text: record.text, facets: record.facets}) : undefined + /* + * The same rule as posts in feeds: text with `MAX_POST_LINES` or more line + * breaks stops at that many lines until the viewer asks for the rest. Only + * line breaks count, not wrapping. + */ + const [limitLines, setLimitLines] = useState( + () => countLines(richText?.text) >= MAX_POST_LINES, + ) const moderation = moderationOpts ? moderatePost(post, moderationOpts) : undefined const embedPreview = post.embed ? getEmbedPreviewKind(post.embed) : undefined + const onPressShowMore = (event: GestureResponderEvent) => { + // Keep the press from reaching the row, which on web would follow its link + event.preventDefault() + event.stopPropagation() + setLimitLines(false) + } + return ( )} {richText && ( - + // Keeps "Show more" right under the text, without the hider's gap + + + {limitLines && ( + + )} + )} {post.embed && embedPreview && ( /* @@ -412,11 +439,25 @@ function EmbedPreview({ } /** - * Compact preview of a quoted post: author, time and two lines of text. + * Compact preview of a quoted post: author, time and the start of its text. * Pressing it opens the quoted post. Blocked, deleted and detached quotes * collapse to a short muted line, and other record embeds render nothing. */ -export function QuoteCard({embed}: {embed: app.bsky.embed.record.View}) { +export function QuoteCard({ + embed, + numberOfLines = 2, + isMuted = false, +}: { + embed: app.bsky.embed.record.View + /** + * How many lines of the quoted post's text to show. + */ + numberOfLines?: number + /** + * Mutes the quoted post's text, as for a preview of the post. + */ + isMuted?: boolean +}) { const t = useTheme() const {currentAccount} = useSession() const parsed = bsky.post.parseEmbedRecordView(embed) @@ -424,7 +465,13 @@ export function QuoteCard({embed}: {embed: app.bsky.embed.record.View}) { let placeholder: React.ReactNode = null switch (parsed.type) { case 'post': - return + return ( + + ) case 'post_blocked': placeholder = Blocked post break @@ -455,7 +502,15 @@ export function QuoteCard({embed}: {embed: app.bsky.embed.record.View}) { ) } -function QuoteCardPost({view}: {view: app.bsky.embed.record.ViewRecord}) { +function QuoteCardPost({ + view, + numberOfLines, + isMuted, +}: { + view: app.bsky.embed.record.ViewRecord + numberOfLines: number + isMuted: boolean +}) { const t = useTheme() const {t: l} = useLingui() const moderationOpts = useModerationOpts() @@ -551,8 +606,12 @@ function QuoteCardPost({view}: {view: app.bsky.embed.record.ViewRecord}) { authorHandle={view.author.handle} // The whole card is already a link disableLinks - numberOfLines={2} - style={[a.text_md, a.leading_snug, t.atoms.text]} + numberOfLines={numberOfLines} + style={[ + a.text_md, + a.leading_snug, + isMuted ? t.atoms.text_contrast_medium : t.atoms.text, + ]} /> ) : ( -} - /** * How long each row of an `ActorList` takes to fade in, in ms. */ @@ -432,9 +417,28 @@ const ROW_STAGGER = 25 */ const MAX_STAGGERED_ROWS = 8 +/** + * The size of each avatar in an `ActorList`. + */ +const ACTOR_AVATAR_SIZE = 32 + +/** + * How far an `ActorList` insets its people, so that their names line up with + * the row's text above. `Item.Root` puts the text a padding, the avatar slot + * and a gap in from its edge, and each person puts their name an avatar and + * a gap in from theirs. + */ +const ACTOR_LIST_INSET = + tokens.space.lg + + AVATAR_SLOT_WIDTH + + tokens.space.lg - + ACTOR_AVATAR_SIZE - + tokens.space.sm + /** * The expanded list of everyone in a grouped notification, each linking to - * their profile with a follow button. + * their profile with a follow button. Each person spans the full width of + * the row, so their hover does too, and insets their own content. * * Rows fade in one after another as they mount. Rows appended later, e.g. by * "Show more", start a stagger of their own rather than waiting on the rows @@ -479,11 +483,7 @@ export function ActorList({ ? undefined : FadeIn.duration(ROW_FADE_DURATION).delay(step * ROW_STAGGER) }> - + ) })} @@ -514,7 +514,13 @@ export function ShowMoreActorsButton({ disabled={isLoading} hitSlop={HITSLOP_10} onPress={onPress} - style={[a.self_start, a.gap_xs, a.px_lg, a.pt_xs]}> + style={[ + a.self_start, + a.gap_xs, + a.pt_xs, + a.mb_sm, + {marginLeft: ACTOR_LIST_INSET}, + ]}> {({hovered, pressed}) => ( <> {isLoading && ( @@ -544,16 +550,12 @@ export function ShowMoreActorsButton({ export function ActorListItem({ profile, starterPack, - isLast = false, }: { profile: bsky.profile.AnyProfileView starterPack?: bsky.starterPack.AnyStarterPackView - /** - * The last item drops its bottom padding, leaving it to the row. - */ - isLast?: boolean }) { const t = useTheme() + const [hover, setHover] = useState(false) const {t: l} = useLingui() const queryClient = useQueryClient() const moderationOpts = useModerationOpts() @@ -581,30 +583,34 @@ export function ActorListItem({ return ( setHover(true)} + onPointerLeave={() => setHover(false)} style={[ a.flex_row, a.align_center, a.gap_sm, - a.px_lg, - isLast ? a.pt_sm : a.py_sm, + a.py_sm, + a.pr_lg, + {paddingLeft: ACTOR_LIST_INSET}, ]}> + { - // Keep the press from also following the row's link on web - event.stopPropagation() unstableCacheProfileView(queryClient, profile) onPress(event) }} style={[a.flex_1, a.flex_row, a.align_center, a.gap_sm]}> diff --git a/src/screens/Notifications/components/NotificationItem/Item/text.tsx b/src/screens/Notifications/components/NotificationItem/Item/text.tsx index def57a558..7c674e80e 100644 --- a/src/screens/Notifications/components/NotificationItem/Item/text.tsx +++ b/src/screens/Notifications/components/NotificationItem/Item/text.tsx @@ -64,10 +64,17 @@ export function SecondaryText({ /** * Emphasised inline text within `Item.PrimaryText`, e.g. "**3 others**". + * Pass `style` to match smaller text around it, e.g. its size. */ -export function Strong({children}: {children: React.ReactNode}) { +export function Strong({ + children, + style, +}: { + children: React.ReactNode + style?: StyleProp +}) { return ( - + {children} ) @@ -138,7 +145,12 @@ export function Timestamp({date}: {date: string}) { {({timeElapsed}) => ( + style={[ + a.self_start, + a.text_sm, + t.atoms.text_contrast_low, + {color: t.palette.contrast_300}, + ]}> {timeElapsed} )} diff --git a/src/screens/Notifications/components/NotificationItem/LoadingSkeleton.tsx b/src/screens/Notifications/components/NotificationItem/LoadingSkeleton.tsx new file mode 100644 index 000000000..f8745e88e --- /dev/null +++ b/src/screens/Notifications/components/NotificationItem/LoadingSkeleton.tsx @@ -0,0 +1,394 @@ +import { + type DimensionValue, + type StyleProp, + type TextStyle, + View, + type ViewStyle, +} from 'react-native' + +import {type GroupedNotificationsFeed} from '#/state/queries/notifications/grouped/types' +import {atoms as a, useBreakpoints, useTheme} from '#/alf' +import * as Skele from '#/components/Skeleton' +import * as Item from './Item' + +/** + * A kind of skeleton row, after the notifications it stands in for: `group` + * for a like or repost from several people, `reaction` for one from a single + * person or a new post on the Activity tab, `follow`, `reply` (with its + * "replied to" line), and `mention` for mentions and quotes. + */ +type SkeletonKind = 'group' | 'reaction' | 'follow' | 'reply' | 'mention' + +/** + * A believable stretch of a feed with every kind of notification in it, + * cycled to fill the screen. + */ +const MIXED_KINDS: SkeletonKind[] = [ + 'group', + 'reply', + 'follow', + 'reaction', + 'group', + 'mention', + 'follow', +] + +/** + * The kinds of row each tab's skeleton cycles through, so that it looks like + * the tab that's loading. The Followers tab is a list of people instead, see + * `FollowersSkeleton`. + */ +const TAB_KINDS: Record< + Exclude, + SkeletonKind[] +> = { + all: MIXED_KINDS, + 'people-i-follow': MIXED_KINDS, + conversations: ['reply', 'reply', 'mention'], + activity: ['reaction'], +} + +/** + * Enough rows to fill a tall screen. + */ +const ROW_COUNT = 12 + +/** + * Rows on the Followers tab are about half as tall as the others, so it takes + * more of them to fill the screen. + */ +const FOLLOWER_ROW_COUNT = 20 + +/** + * Placeholder rows for a tab of notifications while its first page loads, + * shaped like the rows that tab usually has. They share the real rows' + * padding, avatar slot and line heights, so that the loaded rows don't jump + * when they replace them. + */ +export function LoadingSkeleton({feed}: {feed: GroupedNotificationsFeed}) { + if (feed === 'followers') { + return + } + + const kinds = TAB_KINDS[feed] + const rows: React.ReactNode[] = [] + /* + * Each kind alternates between two variants, counting only its own rows, so + * that no row looks like the last one of its kind. + */ + const counts = new Map() + for (let i = 0; i < ROW_COUNT; i++) { + const kind = kinds[i % kinds.length] + const index = counts.get(kind) ?? 0 + counts.set(kind, index + 1) + rows.push() + } + + return ( + <> + + {rows} + + ) +} + +/** + * Stands in for the "Today" section header, as most feeds open with one. It + * matches the real header's padding and text size, so the rows below don't + * move when it arrives. + */ +function TodayHeaderSkeleton() { + return ( + + + + ) +} + +/** + * Picks the skeleton row for `kind`. + */ +function RowSkeleton({kind, index}: {kind: SkeletonKind; index: number}) { + switch (kind) { + case 'group': + return + case 'reaction': + return + case 'follow': + return + case 'reply': + return + case 'mention': + return + } +} + +/** + * Stands in for a like or repost from several people: their avatars, the + * headline, a preview of the post, and the time. + */ +function GroupSkeleton({index}: {index: number}) { + const even = index % 2 === 0 + + return ( + + + + + + + + + + ) +} + +/** + * Stands in for a like or repost from one person, or a new post on the + * Activity tab, sometimes of a post with images. + */ +function ReactionSkeleton({index}: {index: number}) { + const even = index % 2 === 0 + + return ( + + + + + + + + {even && ( + + + + )} + + ) +} + +/** + * Stands in for a single follow: the headline, a short line of who you have + * in common, the time, and a follow button. + */ +function FollowSkeleton({index}: {index: number}) { + const even = index % 2 === 0 + + return ( + + + + + + + + + + + + ) +} + +/** + * Stands in for a reply, mention or quote: the author, the post, the time, + * and the post's actions. Replies also say what they replied to. + */ +function PostSkeleton({index, isReply}: {index: number; isReply: boolean}) { + const even = index % 2 === 0 + + return ( + + + + + + + + + {isReply && ( + + )} + + + + + + + ) +} + +/** + * The Followers tab's skeleton: its header, then a list of people. + */ +function FollowersSkeleton() { + const {gtMobile} = useBreakpoints() + + return ( + <> + {/* Matches `FollowedYouHeader` */} + + + + {Array.from({length: FOLLOWER_ROW_COUNT}, (_, index) => ( + + ))} + + ) +} + +/** + * Stands in for a `FollowerNotification`: a compact profile row with a + * follow button. + */ +function FollowerSkeleton({ + index, + isBadged, +}: { + index: number + /** + * Whether the avatar has room for a badge, which the rows only have on + * larger screens. + */ + isBadged: boolean +}) { + const even = index % 2 === 0 + + return ( + + {isBadged ? ( + + ) : ( + // The same size as `Item.Avatar`, without its slot + + )} + + + + + + + + + ) +} + +/** + * Lays a skeleton row out like `Item.Root`, without being pressable. + */ +function Row({ + style, + children, +}: { + style?: StyleProp + children: React.ReactNode +}) { + return ( + + {children} + + ) +} + +/** + * Lines of wrapping text, one per width, at the line height of `style`. + * `blend` makes them fainter, for muted or secondary text. + */ +function Lines({ + widths, + blend, + style, +}: { + widths: DimensionValue[] + blend?: boolean + /** + * The real text's size atom, e.g. `a.text_md`. + */ + style: StyleProp +}) { + return ( + + {widths.map((width, index) => ( + + ))} + + ) +} + +/** + * Stands in for `Item.Timestamp`, e.g. "7m ago". + */ +function TimestampSkeleton() { + return +} + +/** + * Stands in for `Item.AvatarRow` and its avatars. With `overflow`, a + * fainter circle at the end stands in for its "+N" chip. + */ +function AvatarRowSkeleton({ + count, + overflow, +}: { + count: number + overflow: boolean +}) { + return ( + + {Array.from({length: count}, (_, index) => ( + + ))} + {overflow && } + + ) +} + +/** + * Stands in for a trailing `Item.InlineImages`. + */ +function ThumbnailSkeleton() { + const t = useTheme() + return ( + + ) +} + +/** + * Stands in for `Item.FollowButton`, about as wide as "Follow back", which is + * what it says for anyone you haven't followed back yet. + */ +function FollowButtonSkeleton() { + return +} + +/** + * Stands in for `Item.PostActions`: the like and reply pills, and the menu. + */ +function PostActionsSkeleton() { + return ( + + + + + + + + ) +} diff --git a/src/screens/Notifications/components/NotificationItem/index.tsx b/src/screens/Notifications/components/NotificationItem/index.tsx index 12bf27779..cc682b4fa 100644 --- a/src/screens/Notifications/components/NotificationItem/index.tsx +++ b/src/screens/Notifications/components/NotificationItem/index.tsx @@ -32,6 +32,7 @@ export { getFollowers, isFollowerNotification, } from './kinds/follower' +export {LoadingSkeleton} from './LoadingSkeleton' /** * Renders one grouped notification, picking the row for its kind. Each kind diff --git a/src/screens/Notifications/components/NotificationItem/kinds/aggregate.tsx b/src/screens/Notifications/components/NotificationItem/kinds/aggregate.tsx index 88d14d8e8..1e5066075 100644 --- a/src/screens/Notifications/components/NotificationItem/kinds/aggregate.tsx +++ b/src/screens/Notifications/components/NotificationItem/kinds/aggregate.tsx @@ -20,14 +20,14 @@ import {type NotificationOf} from '../types' /** * Shared anatomy for likes and reposts of one post: the headline actor's * avatar, the other actors, the primary sentence, a preview of the post, and - * the post's images on the trailing edge. Pressing the row opens the post. + * the post's images on the trailing edge. Pressing the row opens the post, + * and a group expands to list everyone in it. */ function PostReactionRow({ notification, icon, tone, label, - othersHref, children, }: { notification: NotificationOf< @@ -39,10 +39,6 @@ function PostReactionRow({ * Plain-text version of the primary sentence, for screen readers. */ label: string - /** - * Where the "+N" chip in the avatar row goes, if anywhere. - */ - othersHref?: string /** * The primary sentence, as an `Item.PrimaryText`. */ @@ -53,20 +49,14 @@ function PostReactionRow({ const mediaBlurred = Item.usePostMediaBlurred(post) return ( - - {notification.count > 1 && ( - - )} + {children} @@ -80,7 +70,7 @@ function PostReactionRow({ /> )} - + ) } @@ -93,26 +83,31 @@ export function LikeNotification({ notification: NotificationOf<'like'> }) { const {t: l} = useLingui() - const actor = notification.actors[0] - const name = Item.useDisplayName(actor) - const others = notification.count - 1 + const {actor, name, second, secondName, others} = + Item.useGroupNames(notification) return ( 0 - ? l`${name} and ${plural(others, { - one: '# other', - other: '# others', - })} liked your post` - : l`${name} liked your post` + second + ? l`${name} and ${secondName} liked your post` + : others > 0 + ? l`${name} and ${plural(others, { + one: '# other', + other: '# others', + })} liked your post` + : l`${name} liked your post` }> - {others > 0 ? ( + {second ? ( + + and {' '} + liked your post + + ) : others > 0 ? ( and{' '} @@ -139,26 +134,31 @@ export function RepostNotification({ notification: NotificationOf<'repost'> }) { const {t: l} = useLingui() - const actor = notification.actors[0] - const name = Item.useDisplayName(actor) - const others = notification.count - 1 + const {actor, name, second, secondName, others} = + Item.useGroupNames(notification) return ( 0 - ? l`${name} and ${plural(others, { - one: '# other', - other: '# others', - })} reposted your post` - : l`${name} reposted your post` + second + ? l`${name} and ${secondName} reposted your post` + : others > 0 + ? l`${name} and ${plural(others, { + one: '# other', + other: '# others', + })} reposted your post` + : l`${name} reposted your post` }> - {others > 0 ? ( + {second ? ( + + and {' '} + reposted your post + + ) : others > 0 ? ( and{' '} @@ -186,31 +186,31 @@ export function LikeViaRepostNotification({ notification: NotificationOf<'likeViaRepost'> }) { const {t: l} = useLingui() - const actor = notification.actors[0] - const name = Item.useDisplayName(actor) - const others = notification.count - 1 + const {actor, name, second, secondName, others} = + Item.useGroupNames(notification) - /* - * The post's liked-by list also has likes that didn't come via the - * viewer's repost, but it's the closest list there is, and a "+N" that goes - * nowhere looks broken. - */ return ( 0 - ? l`${name} and ${plural(others, { - one: '# other', - other: '# others', - })} liked your repost` - : l`${name} liked your repost` + second + ? l`${name} and ${secondName} liked your repost` + : others > 0 + ? l`${name} and ${plural(others, { + one: '# other', + other: '# others', + })} liked your repost` + : l`${name} liked your repost` }> - {others > 0 ? ( + {second ? ( + + and {' '} + liked your repost + + ) : others > 0 ? ( and{' '} @@ -238,27 +238,31 @@ export function RepostViaRepostNotification({ notification: NotificationOf<'repostViaRepost'> }) { const {t: l} = useLingui() - const actor = notification.actors[0] - const name = Item.useDisplayName(actor) - const others = notification.count - 1 + const {actor, name, second, secondName, others} = + Item.useGroupNames(notification) - // A superset of these people, as in `LikeViaRepostNotification` return ( 0 - ? l`${name} and ${plural(others, { - one: '# other', - other: '# others', - })} reposted your repost` - : l`${name} reposted your repost` + second + ? l`${name} and ${secondName} reposted your repost` + : others > 0 + ? l`${name} and ${plural(others, { + one: '# other', + other: '# others', + })} reposted your repost` + : l`${name} reposted your repost` }> - {others > 0 ? ( + {second ? ( + + and {' '} + reposted your repost + + ) : others > 0 ? ( and{' '} @@ -475,6 +479,8 @@ export function MultiPostRepostViaRepostNotification({ /** * Someone, or a group of people, liked one of the viewer's custom feeds. + * Pressing the row opens the feed, and a group expands to list everyone in + * it. */ export function GeneratorLikeNotification({ notification, @@ -482,37 +488,37 @@ export function GeneratorLikeNotification({ notification: NotificationOf<'generatorLike'> }) { const {t: l} = useLingui() - const {generator, actors} = notification - const actor = actors[0] - const name = Item.useDisplayName(actor) - const others = notification.count - 1 + const {generator} = notification + const {actor, name, second, secondName, others} = + Item.useGroupNames(notification) const feedUri = new AtUri(generator.uri) return ( - 0 - ? l`${name} and ${plural(others, { - one: '# other', - other: '# others', - })} liked your custom feed` - : l`${name} liked your custom feed` + second + ? l`${name} and ${secondName} liked your custom feed` + : others > 0 + ? l`${name} and ${plural(others, { + one: '# other', + other: '# others', + })} liked your custom feed` + : l`${name} liked your custom feed` } testID={`notification-${notification.type}-${notification.id}`}> - {others > 0 && ( - - )} + - {others > 0 ? ( + {second ? ( + + and {' '} + liked your custom feed + + ) : others > 0 ? ( and{' '} @@ -530,59 +536,58 @@ export function GeneratorLikeNotification({ - + ) } /** * New posts from accounts the viewer has subscribed to. A single post opens * that post, otherwise the row opens the activity list with all of them. + * Posts from several authors expand to list the authors. */ export function SubscribedPostNotification({ notification, }: { notification: NotificationOf<'subscribedPost'> }) { - const t = useTheme() const {t: l} = useLingui() const {items, count} = notification // Items are newest first, so this is the post to preview - const [{actor, post}] = items - const name = Item.useDisplayName(actor) - const authors = items - .map(item => item.actor) - .filter( - (author, index, all) => - all.findIndex(other => other.did === author.did) === index, - ) - const others = authors.length - 1 + const [{post}] = items + const {actor, name, second, secondName, others} = + Item.useGroupNames(notification) const hasThumbnails = Item.getPostThumbnails(post.embed).length > 0 const mediaBlurred = Item.usePostMediaBlurred(post) return ( - item.post.uri)) } - isRead={notification.isRead} label={ - others > 0 - ? l`New posts from ${name} and ${plural(others, { - one: '# other', - other: '# others', - })}` - : l`New ${plural(count, {one: 'post', other: 'posts'})} from ${name}` + second + ? l`New posts from ${name} and ${secondName}` + : others > 0 + ? l`New posts from ${name} and ${plural(others, { + one: '# other', + other: '# others', + })}` + : l`New ${plural(count, {one: 'post', other: 'posts'})} from ${name}` } testID={`notification-${notification.type}-${notification.id}`}> - {others > 0 && ( - - )} + - {others > 0 ? ( + {second ? ( + + New posts from and{' '} + + + ) : others > 0 ? ( New posts from and{' '} @@ -596,7 +601,7 @@ export function SubscribedPostNotification({ )} - + {hasThumbnails && ( @@ -608,6 +613,6 @@ export function SubscribedPostNotification({ /> )} - + ) } diff --git a/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx b/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx index 099dc9c7d..ec666c164 100644 --- a/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx +++ b/src/screens/Notifications/components/NotificationItem/kinds/follower.tsx @@ -166,10 +166,11 @@ function PlainAvatar({profile}: {profile: bsky.profile.AnyProfileView}) { return ( ) } diff --git a/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx b/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx index 96916c197..847189265 100644 --- a/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx +++ b/src/screens/Notifications/components/NotificationItem/kinds/profile.tsx @@ -1,5 +1,4 @@ -import {useState} from 'react' -import {type GestureResponderEvent, Pressable, View} from 'react-native' +import {View} from 'react-native' import {plural} from '@lingui/core/macro' import {Plural, Trans, useLingui} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' @@ -7,9 +6,6 @@ import {useQueryClient} from '@tanstack/react-query' import {makeProfileLink} from '#/lib/routes/links' import {type NavigationProp} from '#/lib/routes/types' -import {isNetworkError} from '#/lib/strings/errors' -import {logger} from '#/logger' -import {useFollowActorsQuery} from '#/state/queries/notifications/grouped' import {unstableCacheProfileView} from '#/state/queries/unstable-profile-cache' import {useSession} from '#/state/session' import {atoms as a} from '#/alf' @@ -18,8 +14,6 @@ import { NotificationStarterPackSmall_Filled_Corner0_Rounded as StarterPackIcon, NotificationVerifiedSmall_Filled_Corner0_Rounded as CheckIcon, } from '#/components/icons/Notification' -import * as Toast from '#/components/Toast' -import {useAnalytics} from '#/analytics' import type * as bsky from '#/types/bsky' import * as Item from '../Item' import {type NotificationOf} from '../types' @@ -94,14 +88,13 @@ function SingleFollowNotification({ } /** - * Several follows. Pressing the header expands a list of the followers, each + * Several follows. Pressing the row expands a list of the followers, each * with their own follow button. The list starts with those the API resolved, * and "Show more" loads the rest, though the group may still hold fewer than * `count`. * * The row's own link goes to the viewer's followers list, since that shows - * everyone. It's reached by presses beside the expanded list, and by a screen - * reader action on the header. + * everyone. It's reached by a screen reader action on the row. */ function GroupedFollowNotification({ notification, @@ -109,142 +102,64 @@ function GroupedFollowNotification({ notification: NotificationOf<'follow'> }) { const {t: l} = useLingui() - const ax = useAnalytics() const {currentAccount} = useSession() const navigation = useNavigation() - const [isExpanded, setIsExpanded] = useState(false) - const [actor] = notification.actors - const name = Item.useDisplayName(actor) - const others = notification.count - 1 - - const label = l`${name} and ${plural(others, { - one: '# other', - other: '# others', - })} followed you` - - const onToggleExpanded = (event: GestureResponderEvent) => { - // Keep the press from reaching the row, which on web would follow its link - event.preventDefault() - event.stopPropagation() - if (!isExpanded) { - ax.metric('notifications:bundleExpand', { - notificationType: 'follow', - authorCount: notification.actors.length, - }) - } - setIsExpanded(!isExpanded) - } + const {actor, name, second, secondName, others} = + Item.useGroupNames(notification) return ( - - { + if ( + event.nativeEvent.actionName === 'viewFollowers' && currentAccount - ? [{name: 'viewFollowers', label: l`View all followers`}] - : undefined + ) { + navigation.push('ProfileFollowers', {name: currentAccount.did}) } - onAccessibilityAction={event => { - if ( - event.nativeEvent.actionName === 'viewFollowers' && - currentAccount - ) { - navigation.push('ProfileFollowers', {name: currentAccount.did}) - } - }} - onPress={onToggleExpanded} - style={[a.flex_row, a.align_start, a.gap_md, a.px_lg, a.py_md]}> - {/* The chevron sits at the top, while the text centres on the avatar */} - - - - - - and{' '} - - - {' '} - followed you - - - - - - - - - - - - - - ) -} - -/** - * The expanded list of a grouped follow: the followers it resolved, then any - * loaded since with "Show more", which shows while there are more to load. - * Loaded followers stay in the query cache, so they're still there if the - * list is collapsed and expanded again. - */ -function ExpandedFollowers({ - notification, -}: { - notification: NotificationOf<'follow'> -}) { - const {t: l} = useLingui() - const {actors, hasMore, isFetching, fetchNextPage} = useFollowActorsQuery({ - notification, - }) - - const onShowMore = async () => { - const {error} = await fetchNextPage() - if (!error) return - if (!isNetworkError(error)) { - logger.error('Failed to load more followers', {safeMessage: error}) - } - Toast.show(l`Couldn’t load more followers, please try again`, { - type: 'error', - }) - } - - return ( - - - {hasMore && ( - void onShowMore()} - /> - )} - - + }} + testID={`notification-follow-${notification.id}`}> + + + + + {second ? ( + + and {' '} + followed you + + ) : ( + + and{' '} + + + {' '} + followed you + + )} + + + + ) } diff --git a/src/screens/Notifications/components/PageList.tsx b/src/screens/Notifications/components/PageList.tsx index b24e1f455..7dfd368bf 100644 --- a/src/screens/Notifications/components/PageList.tsx +++ b/src/screens/Notifications/components/PageList.tsx @@ -20,7 +20,6 @@ import { import {useLastUnreadCheck} from '#/state/queries/notifications/unread' import {ErrorMessage} from '#/view/com/util/error/ErrorMessage' import {List, type ListMethods} from '#/view/com/util/List' -import {NotificationFeedLoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder' import {LoadMoreRetryBtn} from '#/view/com/util/LoadMoreRetryBtn' import {MainScrollProvider} from '#/view/com/util/MainScrollProvider' import { @@ -29,14 +28,12 @@ import { type FollowerNotificationView, getFollowers, isFollowerNotification, + LoadingSkeleton, NotificationItem, } from '#/screens/Notifications/components/NotificationItem' import {usePager} from '#/screens/Notifications/components/PagerView' import {RefreshPill} from '#/screens/Notifications/components/RefreshPill' -import { - isRefreshPillVisible, - type SeenAtMode, -} from '#/screens/Notifications/unread' +import {isRefreshPillVisible} from '#/screens/Notifications/unread' import {atoms as a, native, useTheme, web} from '#/alf' import {ButtonText} from '#/components/Button' import {useIsFindContactsFeatureEnabledBasedOnGeolocation} from '#/components/contacts/country-allowlist' @@ -90,7 +87,7 @@ export function PageList({ titleHeight: SharedValue /** * Snapshot of when notifications were last seen, shared by every tab so - * the unread tint doesn't change while the screen is open. + * they all tint the same, until any of them refreshes. */ seenAt?: Date /** @@ -105,7 +102,7 @@ export function PageList({ * Refetches the feed's first page, then updates the screen's `seenAt` * snapshot from it. */ - refresh: (feed: GroupedNotificationsFeed, mode: SeenAtMode) => Promise + refresh: (feed: GroupedNotificationsFeed) => Promise /** * Called when loading what's new after the tab button or a pill was * pressed starts, and again when it settles, successfully or not. @@ -170,7 +167,7 @@ export function PageList({ /* * Pressing the Notifications tab button, the selected tab pill, or the * "Refresh" pill scrolls the visible tab back to the top and loads anything - * new, keeping the unread tint. It always asks the server, as the unread + * new, clearing the unread state as pull-to-refresh does. It always asks the server, as the unread * count only updates on a poll and may not know about new notifications * yet. */ @@ -178,7 +175,7 @@ export function PageList({ const loadLatest = () => { listRef.current?.scrollToOffset({animated: IS_NATIVE, offset: 0}) onLoadingLatestChange?.(true) - void refresh(feed, 'kept').finally(() => onLoadingLatestChange?.(false)) + void refresh(feed).finally(() => onLoadingLatestChange?.(false)) } const onSoftReset = useEffectEvent(loadLatest) useEffect(() => { @@ -208,7 +205,7 @@ export function PageList({ const onRefresh = async () => { setIsPTRing(true) try { - await refresh(feed, 'server') + await refresh(feed) } catch (err) { logger.error('Failed to refresh grouped notifications', { safeMessage: err, @@ -261,7 +258,7 @@ export function PageList({ /> ) case 'loading': - return + return case 'empty': return ( // Centred in the space between the header and the bottom bar @@ -367,7 +364,7 @@ export function getPlaceholderRow({ * today the headers are left out entirely, per the designs. The Followers tab * is laid out differently, see `buildFollowerRows`. */ -function buildRows( +export function buildRows( notifications: NotificationView[], feed: GroupedNotificationsFeed, ): Row[] { @@ -391,11 +388,7 @@ function buildRows( rows.push({type: 'section', key: 'section-earlier', section: 'earlier'}) addedEarlier = true } - rows.push({ - type: 'notification', - key: notification.id, - notification, - }) + rows.push({type: 'notification', key: notification.id, notification}) } return rows } @@ -424,11 +417,7 @@ function buildFollowerRows(notifications: NotificationView[]): Row[] { }) } } else { - rows.push({ - type: 'notification', - key: notification.id, - notification, - }) + rows.push({type: 'notification', key: notification.id, notification}) } } return rows @@ -444,7 +433,13 @@ function SectionHeader({section}: {section: 'today' | 'earlier'}) { a.px_lg, section === 'today' ? a.py_sm - : [a.border_t, a.pt_md, a.pb_sm, t.atoms.border_contrast_low], + : [ + a.mt_md, + a.border_t, + a.pt_md, + a.pb_sm, + t.atoms.border_contrast_low, + ], ]}> {section === 'today' diff --git a/src/screens/Notifications/components/PagerView/Content.web.tsx b/src/screens/Notifications/components/PagerView/Content.web.tsx index 0380ae5ab..c59550d00 100644 --- a/src/screens/Notifications/components/PagerView/Content.web.tsx +++ b/src/screens/Notifications/components/PagerView/Content.web.tsx @@ -1,6 +1,15 @@ -import {Activity, Children, useEffect, useId, useRef, useState} from 'react' +import { + Activity, + Children, + useEffect, + useId, + useLayoutEffect, + useRef, + useState, +} from 'react' import {type StyleProp, View, type ViewStyle} from 'react-native' import {ReduceMotion, withTiming} from 'react-native-reanimated' +import {useIsFocused} from '@react-navigation/native' import {atoms as a} from '#/alf' import {usePagerContext} from './context' @@ -29,6 +38,7 @@ export function Content({ const [visitedPages, setVisitedPages] = useState( () => new Set([selectedPage]), ) + useWindowScrollPerPage(selectedPage) useEffect(() => { if (selectedPage !== previousPage.current) { @@ -72,3 +82,47 @@ export function Content({ ) } + +/** + * Gives each page its own scroll position. The pages all scroll the window, + * and a hidden page keeps its DOM, so switching pages swaps the content under + * a window that stays where it was: the page would open at the offset the + * last one was left at, cut short to its own height. Instead, the offset is + * kept for each page as it's scrolled, and put back when the page is shown + * again. A page shown for the first time opens at the top. + */ +export function useWindowScrollPerPage(selectedPage: number) { + const isFocused = useIsFocused() + const scrollYs = useRef(new Map()) + /** + * The page the window's offset belongs to, which changes as soon as a + * switch commits, so the scroll that follows is kept for the page now + * shown. + */ + const shownPage = useRef(selectedPage) + + /* + * Kept as the page scrolls rather than read on a switch, as by the time a + * switch commits, the old page is hidden and the window may already have + * been cut short to fit the new one. + */ + useEffect(() => { + // Other screens scroll the window too + if (!isFocused) return + const onScroll = () => { + scrollYs.current.set(shownPage.current, window.scrollY) + } + window.addEventListener('scroll', onScroll, {passive: true}) + return () => window.removeEventListener('scroll', onScroll) + }, [isFocused]) + + // Before paint, so the new page is never seen at the old one's offset + useLayoutEffect(() => { + if (selectedPage === shownPage.current) return + shownPage.current = selectedPage + window.scrollTo({ + top: scrollYs.current.get(selectedPage) ?? 0, + behavior: 'instant', + }) + }, [selectedPage]) +} diff --git a/src/screens/Notifications/components/RefreshPill.tsx b/src/screens/Notifications/components/RefreshPill.tsx index 21538e894..f80ebfdf1 100644 --- a/src/screens/Notifications/components/RefreshPill.tsx +++ b/src/screens/Notifications/components/RefreshPill.tsx @@ -8,8 +8,9 @@ import {useLingui} from '@lingui/react/macro' import {HITSLOP_20} from '#/lib/constants' import {useHomeHeaderMode} from '#/view/com/util/MainScrollProvider' import {atoms as a} from '#/alf' +import * as Layout from '#/components/Layout' import {NewPostsPill} from '#/components/NewPostsPill' -import {IS_LIQUID_GLASS} from '#/env' +import {IS_LIQUID_GLASS, IS_WEB} from '#/env' /** * Space between the bottom edge of the header and the pill. @@ -20,10 +21,11 @@ const HEADER_GAP = 16 * A full-width strip whose top edge sits on the header's bottom edge. It * clips, so the pill slides out from behind that edge, and back behind it. * The bottom padding keeps the pill's hit slop inside the clip. The strip - * itself takes no touches. + * itself takes no touches. On web the page scrolls with the document, so + * the strip is fixed to the window, as the header is. */ const strip = [ - a.absolute, + a.fixed, a.overflow_hidden, a.z_10, { @@ -36,9 +38,10 @@ const strip = [ ] /** - * The "Refresh" pill on a Notifications tab, beneath the header. It follows - * the header as the title hides on scroll, coming to rest under the tab pills - * that stay. Render it in a tab, after its list. + * The "Refresh" pill on a Notifications tab, beneath the header, centred on + * the content column. It follows the header as the title hides on scroll, + * coming to rest under the tab pills that stay. The web header doesn't hide, + * so there it stays put. Render it in a tab, after its list. */ export function RefreshPill({ visible, @@ -67,26 +70,29 @@ export function RefreshPill({ const follow = useAnimatedStyle(() => ({ transform: [ { - translateY: - headerHeight + mode.get() * (pinnedHeight - titleHeight.get()), + translateY: IS_WEB + ? headerHeight + : headerHeight + mode.get() * (pinnedHeight - titleHeight.get()), }, ], })) return ( - + + + ) } diff --git a/src/screens/Notifications/components/TabPills.tsx b/src/screens/Notifications/components/TabPills.tsx index 3e17faa9a..09ac75756 100644 --- a/src/screens/Notifications/components/TabPills.tsx +++ b/src/screens/Notifications/components/TabPills.tsx @@ -10,6 +10,7 @@ import { } from 'react-native' import Animated, { interpolate, + interpolateColor, type SharedValue, useAnimatedStyle, useDerivedValue, @@ -18,7 +19,8 @@ import {useLingui} from '@lingui/react/macro' import {DraggableScrollView} from '#/view/com/pager/DraggableScrollView' import {BlockDrawerGesture} from '#/view/shell/BlockDrawerGesture' -import {atoms as a, tokens, useTheme, utils, web} from '#/alf' +import {atoms as a, tokens, useAlf, useTheme, utils, web} from '#/alf' +import {normalizeTextStyles} from '#/alf/typography' import {Button, ButtonIcon} from '#/components/Button' import { ArrowLeft_Stroke2_Corner0_Rounded as ArrowLeft, @@ -116,6 +118,18 @@ export function TabPills({ right: canScrollRight, width: gutterWidth + pillHeight + tokens.space.md, }) + /* + * The active pill is a light grey under the usual text colour in the light + * theme. In the dark themes (dim and dark) it's the highest contrast colour + * instead, under inverted text. + */ + const isDarkScheme = t.scheme === 'dark' + const indicatorColor = isDarkScheme + ? t.palette.contrast_1000 + : t.palette.contrast_50 + const activeLabelColor = isDarkScheme + ? t.atoms.text_inverted.color + : t.atoms.text.color const cleanupRef = useRef<(() => void) | null>(null) const isContinuouslyScrollingRef = useRef(false) @@ -268,8 +282,9 @@ export function TabPills({ )} {tabOffsets.map((layout, index) => ( @@ -292,15 +307,14 @@ export function TabPills({ height: layout.height, }, ]}> - - {tabs[index].label} - + ))} @@ -460,6 +474,69 @@ function getEdgeMask({ return `linear-gradient(to right, ${start}, ${end})` } +/** + * A tab's label, drawn over the pills. Its colour follows the sliding + * indicator rather than the selected tab, so a label reads on whatever is + * under it while the indicator moves, e.g. mid-swipe, or as it passes the tabs + * in between after a tap. + */ +function PillLabel({ + label, + index, + lastIndex, + dragProgress, + activeColor, + inactiveColor, +}: { + label: string + index: number + /** + * The indicator stops at the last tab, so the colour does too. + */ + lastIndex: number + dragProgress: SharedValue + activeColor: string + inactiveColor: string +}) { + const {fonts, flags} = useAlf() + /* + * Reanimated can't animate our `Text`, so this is React Native's text, + * animated, with the styles `Text` would give the label. Unselectable `Text` + * renders React Native's text too, so the label measures the same as the + * hidden one that sizes its pill. + */ + const textStyle = normalizeTextStyles( + [a.text_sm, a.leading_snug, a.font_medium], + { + fontScale: fonts.scaleMultiplier, + fontFamily: fonts.family, + flags, + }, + ) + const colorStyle = useAnimatedStyle(() => { + const progress = Math.min(Math.max(dragProgress.get(), 0), lastIndex) + return { + /* + * Fully active with the indicator on this tab, fading to inactive as the + * indicator moves a whole tab away. Halfway there, the label sits about + * half on the pill and half off it, so that colour has to read on both. + * A plain RGB blend keeps it midway in lightness, where the default + * gamma-corrected one leans towards the lighter end. Labels the + * indicator isn't moving between stay put, so only two update at once. + */ + color: interpolateColor( + Math.abs(progress - index), + [0, 1], + [activeColor, inactiveColor], + 'RGB', + {gamma: 1}, + ), + } + }) + + return {label} +} + function PillIndicator({ layouts, dragProgress, diff --git a/src/screens/Notifications/index.tsx b/src/screens/Notifications/index.tsx index 6a87eb578..48ed14b57 100644 --- a/src/screens/Notifications/index.tsx +++ b/src/screens/Notifications/index.tsx @@ -10,11 +10,7 @@ import Animated, { import {useSafeAreaInsets} from 'react-native-safe-area-context' import {LinearGradient} from 'expo-linear-gradient' import {Trans, useLingui} from '@lingui/react/macro' -import { - useFocusEffect, - useIsFocused, - useNavigation, -} from '@react-navigation/native' +import {useFocusEffect, useIsFocused} from '@react-navigation/native' import {useQueryClient} from '@tanstack/react-query' import {type AnyAppReturn, onAnyAppReturn} from '#/lib/appState' @@ -43,7 +39,6 @@ import { type FeedLoad, getMarkReadAt, nextSeenAt, - type SeenAtMode, } from '#/screens/Notifications/unread' import {atoms as a, useBreakpoints, useTheme, utils} from '#/alf' import {ButtonIcon} from '#/components/Button' @@ -53,7 +48,7 @@ import * as Layout from '#/components/Layout' import {Link} from '#/components/Link' import {Loader} from '#/components/Loader' import {useAnalytics} from '#/analytics' -import {IS_LIQUID_GLASS, IS_WEB} from '#/env' +import {IS_INTERNAL, IS_LIQUID_GLASS, IS_WEB} from '#/env' type Props = NativeStackScreenProps< NotificationsTabNavigatorParams, @@ -62,9 +57,9 @@ type Props = NativeStackScreenProps< export function NotificationsScreen(props: Props) { const ax = useAnalytics() - const isNewNotificationsEnabled = ax.features.enabled( - ax.features.NotificationsV2Enable, - ) + // Dev and TestFlight builds always get it, so it's dogfooded before rollout + const isNewNotificationsEnabled = + IS_INTERNAL || ax.features.enabled(ax.features.NotificationsV2Enable) if (isNewNotificationsEnabled) { return @@ -110,13 +105,13 @@ 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, mode: SeenAtMode) => { + const checkLatest = (feed: GroupedNotificationsFeed) => { // 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 { - void refresh(feed, mode) + void refresh(feed) } } useReturnToScreen({ @@ -160,8 +155,12 @@ function NewNotificationsScreenInner() { // Web reports the page it starts on, too if (feed === activeFeed.current) return activeFeed.current = feed - // As in v1, switching to a tab checks it for anything new - checkLatest(feed, 'kept') + /* + * Switching tabs only checks for anything new, which the "Refresh" + * pill offers, so flicking between tabs neither reloads them nor + * clears what's tinted + */ + void unreadApi.checkUnread() }} onTabPressed={showHeader} onPageScrollStateChanged={state => { @@ -246,10 +245,10 @@ function NewNotificationsScreenInner() { * update it. * * Each feed's first load takes the snapshot from the server if there isn't - * one yet. From then on, the feed's loads come from `refresh`, which updates - * the snapshot according to its `SeenAtMode`. Only fresh loads count: a page - * cached from before the screen mounted, or a refresh that failed, never - * moves the snapshot or marks anything as seen. + * one yet. From then on, the feed's loads come from `refresh`, which takes + * the snapshot from the server, clearing what was tinted before. Only fresh + * loads count: a page cached from before the screen mounted, or a refresh + * that failed, never moves the snapshot or marks anything as seen. */ function useSessionSeenAt() { const queryClient = useQueryClient() @@ -267,8 +266,8 @@ function useSessionSeenAt() { */ const latestRefreshes = useRef(new Map()) - const applyLoad = (load: FeedLoad, mode: SeenAtMode | undefined) => { - setSeenAt(snapshot => nextSeenAt({load, mode, snapshot})) + const applyLoad = (load: FeedLoad, isRefresh: boolean) => { + setSeenAt(snapshot => nextSeenAt({load, isRefresh, snapshot})) const markReadAt = getMarkReadAt(load) if (markReadAt) { void unreadApi.markAllRead({seenAt: markReadAt}) @@ -281,15 +280,19 @@ function useSessionSeenAt() { ) => { if (handledFeeds.current.has(feed) || page.requestedAt < mountedAt) return handledFeeds.current.add(feed) - applyLoad({feed, ...page}, undefined) + applyLoad({feed, ...page}, false) } /** - * Refetches the first page of a feed, then updates the snapshot from it. - * Refreshing any other feed refreshes "All" behind it, so what's new is - * marked as seen. + * Refetches the first page of a feed, then takes the snapshot from it. + * Refreshing any other feed refreshes "All" behind it, which leaves the + * snapshot alone but marks what's new as seen, so a refresh on any tab + * clears the unread state. */ - const refresh = async (feed: GroupedNotificationsFeed, mode?: SeenAtMode) => { + const refresh = async ( + feed: GroupedNotificationsFeed, + {isBehind = false}: {isBehind?: boolean} = {}, + ) => { handledFeeds.current.add(feed) const request = {} latestRefreshes.current.set(feed, request) @@ -299,9 +302,9 @@ function useSessionSeenAt() { const page = getGroupedNotificationsTop(queryClient, feed) // A failed refetch leaves the old page in place if (!page || page.requestedAt < startedAt) return - applyLoad({feed, ...page}, mode) + applyLoad({feed, ...page}, !isBehind) if (feed !== 'all') { - void refresh('all') + void refresh('all', {isBehind: true}) } } @@ -316,10 +319,9 @@ function useSessionSeenAt() { * share sheet, only peeks with `peekLatest`, so the list stays as it is and * the "Refresh" pill offers anything new. * - * - From a screen pushed within the Notifications tab (e.g. a post), the - * unread tint is kept as it was, and anything new is tinted too. - * - After switching to another tab or leaving the app, the tint is taken - * from the server again, so only what arrived meanwhile is tinted. + * As in v1, coming back from a screen pushed within the Notifications tab + * (e.g. a post) refreshes too, unless the user is partway down the list. So + * what was tinted before is cleared, having been seen. */ function useReturnToScreen({ activeFeed, @@ -327,32 +329,17 @@ function useReturnToScreen({ peekLatest, }: { activeFeed: React.RefObject - checkLatest: (feed: GroupedNotificationsFeed, mode: SeenAtMode) => void + checkLatest: (feed: GroupedNotificationsFeed) => void /** * Asks the server for anything new without loading it, which offers the * "Refresh" pill if there is. */ peekLatest: () => void }) { - const navigation = useNavigation() const isFocused = useIsFocused() - /* - * The tab navigator's own blur means the user switched tabs, rather than - * pushing a screen within this tab's stack. Web's flat navigator has no tab - * level, so there only leaving the app counts. - */ - const hasLeft = useRef(false) - useEffect(() => { - return navigation.getParent()?.addListener('blur', () => { - hasLeft.current = true - }) - }, [navigation]) - const onReturn = useEffectEvent(() => { - const mode = hasLeft.current ? 'server' : 'kept' - hasLeft.current = false - checkLatest(activeFeed.current, mode) + checkLatest(activeFeed.current) }) // Mounting counts, as the cache can outlive the screen @@ -365,7 +352,6 @@ function useReturnToScreen({ }, [isFocused]) const onLeftApp = useEffectEvent(() => { - hasLeft.current = true if (isFocused) { onReturn() } @@ -484,7 +470,8 @@ function NotificationsHeader({ variant="ghost" color="secondary" shape="round" - style={[a.justify_center]}> + // Ghost buttons fill with the screen colour, which shows on the see-through header + style={[a.justify_center, a.bg_transparent]}> ({actor: p.did})), + ] + .map(p => p.did) + .concat(UNRESOLVED_LIKER_DIDS) + .map(did => ({actor: did})), }, }, { @@ -549,6 +562,7 @@ export function createGroupedNotificationsFixture( }, }, { + // Two people, so the row names both id: 'repost-via-repost-bronco', isRead: true, indexedAt: ago(5 * HOUR), @@ -560,6 +574,38 @@ export function createGroupedNotificationsFixture( items: [{actor: danielle.did}, {actor: lena.did}], }, }, + { + /* + * A large group with only three profiles in `relatedViews`, as when + * most of the accounts are gone, so the avatar row runs out early. + */ + id: 'like-photos', + isRead: true, + indexedAt: ago(6 * HOUR), + count: 20, + kind: { + $type: `${$group}#likeGroup`, + post: photosPost.uri, + items: [theo.did, ines.did, omar.did] + .concat(fakeDids('photo-liker', 17)) + .map(did => ({actor: did})), + }, + }, + { + /* + * Two people, but the second has no profile in `relatedViews`, so the + * row falls back to "1 other". + */ + id: 'repost-photos', + isRead: true, + indexedAt: ago(7 * HOUR), + count: 2, + kind: { + $type: `${$group}#repostGroup`, + post: photosPost.uri, + items: [{actor: priya.did}, {actor: 'did:plc:ghost3'}], + }, + }, { id: 'multi-post-like-rafael', isRead: true, @@ -725,6 +771,17 @@ export function createGroupedNotificationsFixture( items: [{actor: sofia.did, starterPack: scicommPack.uri}], }, }, + { + // Two people, so the row names both + id: 'follow-pair', + isRead: true, + indexedAt: ago(2 * DAY + 4 * HOUR), + count: 2, + kind: { + $type: `${$group}#followGroup`, + items: [{actor: jonas.did}, {actor: lena.did}], + }, + }, { id: 'follow-single', isRead: true, @@ -1069,6 +1126,17 @@ function blockUri(): AtUriString { return `at://${VIEWER_DID}/app.bsky.graph.block/blockeduser` } +/** + * `count` made-up DIDs, e.g. `did:plc:liker1` onwards, for actors without a + * profile in `relatedViews`. + */ +function fakeDids(prefix: string, count: number): DidString[] { + return Array.from( + {length: count}, + (_, i): DidString => `did:plc:${prefix}${i + 1}`, + ) +} + /** * A stable, obviously fake CID. Nothing in the client verifies these. */ diff --git a/src/state/queries/notifications/grouped/__tests__/follow-actors.test.ts b/src/state/queries/notifications/grouped/__tests__/group-actors.test.ts similarity index 68% rename from src/state/queries/notifications/grouped/__tests__/follow-actors.test.ts rename to src/state/queries/notifications/grouped/__tests__/group-actors.test.ts index f749f9ce6..0690ba430 100644 --- a/src/state/queries/notifications/grouped/__tests__/follow-actors.test.ts +++ b/src/state/queries/notifications/grouped/__tests__/group-actors.test.ts @@ -5,16 +5,19 @@ import {describe, expect, it} from '@jest/globals' import { createGroupedNotificationsFixture, UNRESOLVED_FOLLOWER_DIDS, + UNRESOLVED_LIKER_DIDS, VIEWER_DID, } from '#/state/queries/notifications/grouped/__fixtures__' import { - createFollowActorsPage, - FOLLOW_ACTORS_PAGE_SIZE, - type FollowActorsPage, + createGroupActorsPage, getNextActorDids, + getNotificationGroup, getUnresolvedActorDids, + GROUP_ACTORS_PAGE_SIZE, + type GroupActorsPage, + type GroupNotificationView, selectLoadedActors, -} from '#/state/queries/notifications/grouped/follow-actors' +} from '#/state/queries/notifications/grouped/group-actors' import {hydratePage} from '#/state/queries/notifications/grouped/hydrate' import {moderateNotification} from '#/state/queries/notifications/grouped/moderate' import {type NotificationView} from '#/state/queries/notifications/grouped/types' @@ -65,16 +68,16 @@ function profile( return {did, handle: `${did.slice(8)}.bsky.social`, ...overrides} } -function page(requested: DidString[], returned = requested): FollowActorsPage { - return createFollowActorsPage( +function page(requested: DidString[], returned = requested): GroupActorsPage { + return createGroupActorsPage( requested, returned.map(did => profile(did)), ) } /** - * Works on notification actors and on followers loaded with "Show more", - * which are basic and detailed views respectively. + * Works on notification actors and on actors loaded with "Show more", which + * are basic and detailed views respectively. */ function hideableOffense< T extends Pick, @@ -88,6 +91,60 @@ function hideableOffense< return {...actor, labels: [label]} } +function group(id: string): GroupNotificationView { + const notification = PAGE.notifications.find(n => n.id === id) + switch (notification?.type) { + case 'like': + case 'repost': + case 'likeViaRepost': + case 'repostViaRepost': + case 'generatorLike': + case 'follow': + case 'subscribedPost': + return notification + default: + throw new Error(`Expected ${id} to be a group notification`) + } +} + +describe('getNotificationGroup', () => { + it('counts everyone in the group, resolved or not', () => { + const like = getNotificationGroup(group('like-photos')) + expect(like.actors.map(actor => actor.did)).toEqual([ + 'did:plc:theo', + 'did:plc:ines', + 'did:plc:omar', + ]) + expect(like.actorDids).toHaveLength(20) + expect(like.count).toBe(20) + }) + + it('counts a pair whose second profile did not resolve', () => { + const repost = getNotificationGroup(group('repost-photos')) + expect(repost.actors).toHaveLength(1) + expect(repost.count).toBe(2) + }) + + it('counts subscribed post authors, once each, rather than posts', () => { + const oneAuthor = getNotificationGroup(group('subscribed-danielle')) + expect(oneAuthor.actors.map(actor => actor.did)).toEqual([ + 'did:plc:danielleyuhan', + ]) + expect(oneAuthor.count).toBe(1) + + const threeAuthors = getNotificationGroup(group('subscribed-many')) + expect(threeAuthors.actors.map(actor => actor.did)).toEqual([ + 'did:plc:michaelblack', + 'did:plc:rafael', + 'did:plc:darrin', + ]) + expect(threeAuthors.actorDids).toEqual( + threeAuthors.actors.map(actor => actor.did), + ) + expect(threeAuthors.count).toBe(3) + }) +}) + describe('getUnresolvedActorDids', () => { it('is the group’s DIDs without a resolved profile', () => { expect(getUnresolvedActorDids(followMany())).toEqual( @@ -95,6 +152,12 @@ describe('getUnresolvedActorDids', () => { ) }) + it('works the same for groups of other kinds', () => { + const like = PAGE.notifications.find(n => n.id === 'like-fungus') + if (like?.type !== 'like') throw new Error('No like-fungus group') + expect(getUnresolvedActorDids(like)).toEqual(UNRESOLVED_LIKER_DIDS) + }) + it('is empty when every follower resolved', () => { const notification = PAGE.notifications.find(n => n.id === 'follow-single') if (notification?.type !== 'follow') throw new Error('No follow-single') @@ -118,7 +181,7 @@ describe('getNextActorDids', () => { it('starts with the first page of unresolved DIDs', () => { const unresolved = dids(60) expect(getNextActorDids(unresolved, [])).toEqual( - unresolved.slice(0, FOLLOW_ACTORS_PAGE_SIZE), + unresolved.slice(0, GROUP_ACTORS_PAGE_SIZE), ) }) @@ -151,12 +214,13 @@ describe('getNextActorDids', () => { }) }) -describe('createFollowActorsPage', () => { +describe('createGroupActorsPage', () => { it('orders profiles as requested and drops missing ones', () => { const [a, b, c] = dids(3) - expect(createFollowActorsPage([a, b, c], [profile(c), profile(a)])).toEqual( - {dids: [a, b, c], profiles: [profile(a), profile(c)]}, - ) + expect(createGroupActorsPage([a, b, c], [profile(c), profile(a)])).toEqual({ + dids: [a, b, c], + profiles: [profile(a), profile(c)], + }) }) }) @@ -176,7 +240,7 @@ describe('selectLoadedActors', () => { }) const muted = profile(c, {viewer: {muted: true}}) const pages = [ - createFollowActorsPage([a, b, c], [profile(a), blocked, muted]), + createGroupActorsPage([a, b, c], [profile(a), blocked, muted]), ] expect( selectLoadedActors(pages, [a, b, c], MODERATION_OPTS).map(p => p.did), @@ -193,7 +257,7 @@ describe('selectLoadedActors', () => { }) expect( selectLoadedActors( - [createFollowActorsPage([a], [followed])], + [createGroupActorsPage([a], [followed])], [a], MODERATION_OPTS, ), @@ -203,7 +267,7 @@ describe('selectLoadedActors', () => { it('hides hideable offenses without moderation opts', () => { const [a, b] = dids(2) const pages = [ - createFollowActorsPage([a, b], [profile(a), hideableOffense(profile(b))]), + createGroupActorsPage([a, b], [profile(a), hideableOffense(profile(b))]), ] expect( selectLoadedActors(pages, [a, b], undefined).map(p => p.did), diff --git a/src/state/queries/notifications/grouped/__tests__/hydrate.test.ts b/src/state/queries/notifications/grouped/__tests__/hydrate.test.ts index 82756c866..6dd3e1f8e 100644 --- a/src/state/queries/notifications/grouped/__tests__/hydrate.test.ts +++ b/src/state/queries/notifications/grouped/__tests__/hydrate.test.ts @@ -5,6 +5,7 @@ import {describe, expect, it} from '@jest/globals' import { createGroupedNotificationsFixture, UNRESOLVED_FOLLOWER_DIDS, + UNRESOLVED_LIKER_DIDS, VIEWER_DID, } from '#/state/queries/notifications/grouped/__fixtures__' import {hydratePage} from '#/state/queries/notifications/grouped/hydrate' @@ -209,6 +210,10 @@ describe('hydratePage', () => { for (const actor of like.actors) { expect(actor).toBe(related(res, actor.did)) } + expect(like.actorDids).toEqual([ + ...like.actors.map(actor => actor.did), + ...UNRESOLVED_LIKER_DIDS, + ]) }) it('maps a single like', () => { @@ -839,27 +844,65 @@ describe('hydratePage', () => { ) }) - describe('follow actor DIDs', () => { - function follow(actors: DidString[]) { - return narrow( - hydrateKind({ - $type: `${NS}#followGroup`, - items: actors.map(actor => ({actor})), - }), - 'follow', - ) + describe('actor DIDs', () => { + /** + * A group of each kind from several actors, with the given actors. + */ + function groups(actors: DidString[]) { + const items = actors.map(actor => ({actor})) + return hydrateKinds( + {$type: `${NS}#likeGroup`, post: FUNGUS_POST, items}, + {$type: `${NS}#repostGroup`, post: FUNGUS_POST, items}, + { + $type: `${NS}#likeViaRepostGroup`, + post: FUNGUS_POST, + viaRepost: VIA_REPOST, + items, + }, + { + $type: `${NS}#repostViaRepostGroup`, + post: FUNGUS_POST, + viaRepost: VIA_REPOST, + items, + }, + {$type: `${NS}#generatorLikeGroup`, generator: FUNGI_FEED, items}, + {$type: `${NS}#followGroup`, items}, + ).notifications.map(notification => { + if (!('actorDids' in notification)) { + throw new Error(`Expected ${notification.type} to have actor DIDs`) + } + return notification + }) } + it('covers every kind from several actors', () => { + expect(groups([DANIELLE]).map(n => n.type)).toEqual([ + 'like', + 'repost', + 'likeViaRepost', + 'repostViaRepost', + 'generatorLike', + 'follow', + ]) + }) + it('keeps unresolved DIDs, in order, alongside the resolved actors', () => { - const {actors, actorDids} = follow([GHOST, DANIELLE, MICHAEL]) - expect(actors.map(actor => actor.did)).toEqual([DANIELLE, MICHAEL]) - expect(actorDids).toEqual([GHOST, DANIELLE, MICHAEL]) + for (const {actors, actorDids} of groups([GHOST, DANIELLE, MICHAEL])) { + expect(actors.map(actor => actor.did)).toEqual([DANIELLE, MICHAEL]) + expect(actorDids).toEqual([GHOST, DANIELLE, MICHAEL]) + } }) it('drops duplicates and the viewer', () => { - expect( - follow([DANIELLE, VIEWER_DID, GHOST, DANIELLE, GHOST]).actorDids, - ).toEqual([DANIELLE, GHOST]) + for (const {actorDids} of groups([ + DANIELLE, + VIEWER_DID, + GHOST, + DANIELLE, + GHOST, + ])) { + expect(actorDids).toEqual([DANIELLE, GHOST]) + } }) }) diff --git a/src/state/queries/notifications/grouped/__tests__/moderate.test.ts b/src/state/queries/notifications/grouped/__tests__/moderate.test.ts index 8c0049fcc..9f8d44dda 100644 --- a/src/state/queries/notifications/grouped/__tests__/moderate.test.ts +++ b/src/state/queries/notifications/grouped/__tests__/moderate.test.ts @@ -110,7 +110,11 @@ describe('moderateNotification', () => { {...like, actors: [danielle, blocked(michael), ...rest]}, ARGS, ) - expect(result).toEqual({...like, actors: [danielle, ...rest]}) + expect(result).toEqual({ + ...like, + actors: [danielle, ...rest], + actorDids: like.actorDids.filter(did => did !== michael.did), + }) expect(result?.count).toBe(like.count) }) @@ -124,7 +128,7 @@ describe('moderateNotification', () => { expect(result?.type === 'follow' && result.actors[0]).toBe(second) }) - it('removes hidden followers from the DIDs left to load', () => { + it('removes hidden actors from the DIDs left to load', () => { const follow = get('follow-many', 'follow') const [first, ...rest] = follow.actors const result = moderateNotification( @@ -163,7 +167,11 @@ describe('moderateNotification', () => { {...like, actors: [hideableOffense(danielle), ...rest]}, {...ARGS, moderationOpts: undefined}, ) - expect(result).toEqual({...like, actors: rest}) + expect(result).toEqual({ + ...like, + actors: rest, + actorDids: like.actorDids.filter(did => did !== danielle.did), + }) }) }) diff --git a/src/state/queries/notifications/grouped/follow-actors.ts b/src/state/queries/notifications/grouped/follow-actors.ts deleted file mode 100644 index 432ffee9b..000000000 --- a/src/state/queries/notifications/grouped/follow-actors.ts +++ /dev/null @@ -1,96 +0,0 @@ -import {type DidString} from '@atproto/syntax' -import {type ModerationOpts} from '@bsky/sdk/moderation' - -import {isActorHidden} from '#/state/queries/notifications/grouped/moderate' -import {type NotificationView} from '#/state/queries/notifications/grouped/types' -import {type app} from '#/lexicons' - -type ProfileView = app.bsky.actor.defs.ProfileViewDetailed -type FollowNotificationView = Extract - -/** - * How many followers "Show more" loads at once, the most - * `app.bsky.actor.getProfiles` accepts. - */ -export const FOLLOW_ACTORS_PAGE_SIZE = 25 - -/** - * One page of a follow group's followers, loaded beyond those its - * notification resolved. - */ -export type FollowActorsPage = { - /** - * Every DID requested, including any that didn't come back, e.g. deleted - * or taken down accounts, so that they're never requested again. - */ - dids: DidString[] - /** - * The profiles that came back, in the order they were requested. - */ - profiles: ProfileView[] -} - -/** - * The followers in a follow group that hydration couldn't resolve, newest - * first. - */ -export function getUnresolvedActorDids( - notification: FollowNotificationView, -): DidString[] { - const resolved = new Set(notification.actors.map(actor => actor.did)) - return notification.actorDids.filter(did => !resolved.has(did)) -} - -/** - * The DIDs for the next page: the first unresolved ones that no page has - * requested yet. Empty once every one has been. - */ -export function getNextActorDids( - unresolvedDids: DidString[], - pages: FollowActorsPage[], -): DidString[] { - const requested = new Set(pages.flatMap(page => page.dids)) - return unresolvedDids - .filter(did => !requested.has(did)) - .slice(0, FOLLOW_ACTORS_PAGE_SIZE) -} - -/** - * Builds a page from a `getProfiles` response, putting the profiles back in - * the order requested. - */ -export function createFollowActorsPage( - dids: DidString[], - profiles: ProfileView[], -): FollowActorsPage { - const byDid = new Map(profiles.map(profile => [profile.did, profile])) - return { - dids, - profiles: dids.flatMap(did => { - const profile = byDid.get(did) - return profile ? [profile] : [] - }), - } -} - -/** - * The loaded followers to show, in order, with the same list-time moderation - * as the notification's own actors. Only those still unresolved in the - * notification are kept, so none repeat its actors even if it has changed - * since they loaded. - */ -export function selectLoadedActors( - pages: FollowActorsPage[], - unresolvedDids: DidString[], - moderationOpts: ModerationOpts | undefined, -): ProfileView[] { - const unresolved = new Set(unresolvedDids) - const seen = new Set() - return pages - .flatMap(page => page.profiles) - .filter(profile => { - if (!unresolved.has(profile.did) || seen.has(profile.did)) return false - seen.add(profile.did) - return !isActorHidden(profile, moderationOpts) - }) -} diff --git a/src/state/queries/notifications/grouped/group-actors.ts b/src/state/queries/notifications/grouped/group-actors.ts new file mode 100644 index 000000000..222a8b06d --- /dev/null +++ b/src/state/queries/notifications/grouped/group-actors.ts @@ -0,0 +1,155 @@ +import {type DidString} from '@atproto/syntax' +import {type ModerationOpts} from '@bsky/sdk/moderation' + +import {isActorHidden} from '#/state/queries/notifications/grouped/moderate' +import { + type ActorGroup, + type NonEmptyArray, + type NotificationView, +} from '#/state/queries/notifications/grouped/types' +import {type app} from '#/lexicons' + +type ProfileView = app.bsky.actor.defs.ProfileViewDetailed + +/** + * A notification that can be from a group of people, e.g. everyone who liked + * a post. + */ +export type GroupNotificationView = Extract< + NotificationView, + { + type: + | 'like' + | 'repost' + | 'likeViaRepost' + | 'repostViaRepost' + | 'generatorLike' + | 'follow' + | 'subscribedPost' + } +> + +/** + * The people in a group notification. + */ +export type NotificationGroup = ActorGroup & { + /** + * How many people the group is from, including any without a resolved + * profile. + */ + count: number +} + +/** + * Everyone in a group notification, with the actors it resolved first. + * + * A subscribed post group lists each author once. It only has the authors + * whose profile and post both resolved, and its `count` counts posts, so + * those authors are everyone. + */ +export function getNotificationGroup( + notification: GroupNotificationView, +): NotificationGroup { + if (notification.type !== 'subscribedPost') { + const {actors, actorDids, count} = notification + return {actors, actorDids, count} + } + const [first, ...rest] = notification.items + const actors: NonEmptyArray = [ + first.actor, + ] + for (const {actor} of rest) { + if (!actors.some(other => other.did === actor.did)) { + actors.push(actor) + } + } + return { + actors, + actorDids: actors.map(actor => actor.did), + count: actors.length, + } +} + +/** + * How many actors "Show more" loads at once, the most + * `app.bsky.actor.getProfiles` accepts. + */ +export const GROUP_ACTORS_PAGE_SIZE = 25 + +/** + * One page of a group's actors, loaded beyond those its notification + * resolved. + */ +export type GroupActorsPage = { + /** + * Every DID requested, including any that didn't come back, e.g. deleted + * or taken down accounts, so that they're never requested again. + */ + dids: DidString[] + /** + * The profiles that came back, in the order they were requested. + */ + profiles: ProfileView[] +} + +/** + * The actors in a group that hydration couldn't resolve, newest first. + */ +export function getUnresolvedActorDids(group: ActorGroup): DidString[] { + const resolved = new Set(group.actors.map(actor => actor.did)) + return group.actorDids.filter(did => !resolved.has(did)) +} + +/** + * The DIDs for the next page: the first unresolved ones that no page has + * requested yet. Empty once every one has been. + */ +export function getNextActorDids( + unresolvedDids: DidString[], + pages: GroupActorsPage[], +): DidString[] { + const requested = new Set(pages.flatMap(page => page.dids)) + return unresolvedDids + .filter(did => !requested.has(did)) + .slice(0, GROUP_ACTORS_PAGE_SIZE) +} + +/** + * Builds a page from a `getProfiles` response, putting the profiles back in + * the order requested. + */ +export function createGroupActorsPage( + dids: DidString[], + profiles: ProfileView[], +): GroupActorsPage { + const byDid = new Map(profiles.map(profile => [profile.did, profile])) + return { + dids, + profiles: dids.flatMap(did => { + const profile = byDid.get(did) + return profile ? [profile] : [] + }), + } +} + +/** + * The loaded actors to show, in order, with the same list-time moderation as + * the notification's own actors. Only those still unresolved in the + * notification are kept, so none repeat its actors even if it has changed + * since they loaded. + */ +export function selectLoadedActors( + pages: GroupActorsPage[], + unresolvedDids: DidString[], + moderationOpts: ModerationOpts | undefined, +): ProfileView[] { + const unresolved = new Set(unresolvedDids) + const seen = new Set() + return pages + .flatMap(page => page.profiles) + .filter(profile => { + if (!unresolved.has(profile.did) || seen.has(profile.did)) return false + seen.add(profile.did) + return !isActorHidden(profile, moderationOpts) + }) +} diff --git a/src/state/queries/notifications/grouped/hydrate.ts b/src/state/queries/notifications/grouped/hydrate.ts index 43f998eea..080d4f7bf 100644 --- a/src/state/queries/notifications/grouped/hydrate.ts +++ b/src/state/queries/notifications/grouped/hydrate.ts @@ -1,6 +1,7 @@ import {type DidString} from '@atproto/syntax' import { + type ActorGroup, type GroupedNotificationsPage, isNonEmpty, type NonEmptyArray, @@ -111,41 +112,41 @@ function hydrateGroup( if (bsky.isType(defs.likeGroup, kind)) { const post = resolvePost(kind.post, ctx) - const actors = resolveActors(kind.items, ctx) - if (!post || !actors) return - return {...base, type: 'like', post, actors} + const group = resolveActorGroup(kind.items, ctx) + if (!post || !group) return + return {...base, type: 'like', post, ...group} } if (bsky.isType(defs.repostGroup, kind)) { const post = resolvePost(kind.post, ctx) - const actors = resolveActors(kind.items, ctx) - if (!post || !actors) return - return {...base, type: 'repost', post, actors} + const group = resolveActorGroup(kind.items, ctx) + if (!post || !group) return + return {...base, type: 'repost', post, ...group} } if (bsky.isType(defs.likeViaRepostGroup, kind)) { const post = resolvePost(kind.post, ctx) - const actors = resolveActors(kind.items, ctx) - if (!post || !actors) return + const group = resolveActorGroup(kind.items, ctx) + if (!post || !group) return return { ...base, type: 'likeViaRepost', post, viaRepost: kind.viaRepost, - actors, + ...group, } } if (bsky.isType(defs.repostViaRepostGroup, kind)) { const post = resolvePost(kind.post, ctx) - const actors = resolveActors(kind.items, ctx) - if (!post || !actors) return + const group = resolveActorGroup(kind.items, ctx) + if (!post || !group) return return { ...base, type: 'repostViaRepost', post, viaRepost: kind.viaRepost, - actors, + ...group, } } @@ -170,9 +171,8 @@ function hydrateGroup( } if (bsky.isType(defs.followGroup, kind)) { - const actors = resolveActors(kind.items, ctx) - if (!actors) return - const actorDids = uniqueActorDids(kind.items, ctx) + const group = resolveActorGroup(kind.items, ctx) + if (!group) return /* * Only attribute the group to a starter pack when every follow came via * the same one, otherwise "via " would be wrong for some actors. @@ -183,8 +183,8 @@ function hydrateGroup( ? ctx.starterPacks.get(packUri) : undefined return starterPack - ? {...base, type: 'follow', actors, actorDids, starterPack} - : {...base, type: 'follow', actors, actorDids} + ? {...base, type: 'follow', ...group, starterPack} + : {...base, type: 'follow', ...group} } if (bsky.isType(defs.subscribedPostGroup, kind)) { @@ -201,9 +201,9 @@ function hydrateGroup( if (bsky.isType(defs.generatorLikeGroup, kind)) { const generator = ctx.generators.get(kind.generator) - const actors = resolveActors(kind.items, ctx) - if (!generator || !actors) return - return {...base, type: 'generatorLike', generator, actors} + const group = resolveActorGroup(kind.items, ctx) + if (!generator || !group) return + return {...base, type: 'generatorLike', generator, ...group} } if (bsky.isType(defs.replyNotification, kind)) { @@ -306,6 +306,20 @@ function resolveMultiPost( return {actor, posts} } +/** + * Resolves the actors of a group from several people, keeping every DID + * alongside the profiles so the rest can be loaded later. Undefined if no + * actor resolves. + */ +function resolveActorGroup( + items: {actor: DidString}[], + ctx: Context, +): ActorGroup | undefined { + const actors = resolveActors(items, ctx) + if (!actors) return + return {actors, actorDids: uniqueActorDids(items, ctx)} +} + /** * Resolves each item's actor, skipping unresolved ones and duplicates. The * first resolved actor is the group's primary actor. diff --git a/src/state/queries/notifications/grouped/index.ts b/src/state/queries/notifications/grouped/index.ts index 6c4401a64..7b4b57e02 100644 --- a/src/state/queries/notifications/grouped/index.ts +++ b/src/state/queries/notifications/grouped/index.ts @@ -8,18 +8,19 @@ import { import {useModerationOpts} from '#/state/preferences/moderation-opts' import {STALE} from '#/state/queries' import { - createFollowActorsPage, - type FollowActorsPage, + createGroupActorsPage, getNextActorDids, getUnresolvedActorDids, + type GroupActorsPage, selectLoadedActors, -} from '#/state/queries/notifications/grouped/follow-actors' +} from '#/state/queries/notifications/grouped/group-actors' import {hydratePage} from '#/state/queries/notifications/grouped/hydrate' import { moderateNotification, type NotificationModerationArgs, } from '#/state/queries/notifications/grouped/moderate' import { + type ActorGroup, type GroupedNotificationsFeed, type GroupedNotificationsPage, type NotificationView, @@ -37,6 +38,7 @@ import {app} from '#/lexicons' import type * as bsky from '#/types/bsky' export type { + ActorGroup, GroupedNotificationsFeed, GroupedNotificationsPage, NotificationView, @@ -237,39 +239,41 @@ function selectNotification( return isRead === moderated.isRead ? moderated : {...moderated, isRead} } -const followActorsQueryKeyRoot = 'follow-actors' +const groupActorsQueryKeyRoot = 'group-actors' -export const createFollowActorsQueryKey = (args: {notificationId: string}) => - createQueryKey(followActorsQueryKeyRoot, args) +export const createGroupActorsQueryKey = (args: {notificationId: string}) => + createQueryKey(groupActorsQueryKeyRoot, args) /** - * The followers in a grouped follow notification beyond the profiles it - * resolved, loaded a page at a time with `app.bsky.actor.getProfiles` for - * "Show more". Nothing loads until `fetchNextPage` is called, and loaded - * pages are kept rather than refetched. + * The actors in a grouped notification beyond the profiles it resolved, + * loaded a page at a time with `app.bsky.actor.getProfiles` for "Show more". + * Nothing loads until `fetchNextPage` is called, and loaded pages are kept + * rather than refetched. * * Returns the loaded `actors` to show, moderated as the notification's own - * actors are, and whether any followers are left to request (`hasMore`). + * actors are, and whether any actors are left to request (`hasMore`). */ -export function useFollowActorsQuery({ - notification, +export function useGroupActorsQuery({ + notificationId, + group, }: { - notification: Extract + notificationId: string + group: ActorGroup }) { const client = useAppviewClient() const moderationOpts = useModerationOpts() - const unresolvedDids = getUnresolvedActorDids(notification) + const unresolvedDids = getUnresolvedActorDids(group) const {data, isFetching, fetchNextPage} = useInfiniteQuery({ // Even the first page waits for `fetchNextPage` enabled: false, staleTime: STALE.INFINITY, - queryKey: createFollowActorsQueryKey({notificationId: notification.id}), - async queryFn({pageParam}): Promise { + queryKey: createGroupActorsQueryKey({notificationId}), + async queryFn({pageParam}): Promise { const res = await client.call(app.bsky.actor.getProfiles, { actors: pageParam, }) - return createFollowActorsPage(pageParam, res.profiles) + return createGroupActorsPage(pageParam, res.profiles) }, initialPageParam: getNextActorDids(unresolvedDids, []), getNextPageParam(_lastPage, pages) { @@ -407,11 +411,11 @@ export function* findAllProfilesInQueryData( } } } - // Followers loaded by "Show more", so their follow buttons update too - const followActorsDatas = queryClient.getQueriesData< - InfiniteData - >({queryKey: [followActorsQueryKeyRoot]}) - for (const [_queryKey, queryData] of followActorsDatas) { + // Actors loaded by "Show more", so their follow buttons update too + const groupActorsDatas = queryClient.getQueriesData< + InfiniteData + >({queryKey: [groupActorsQueryKeyRoot]}) + for (const [_queryKey, queryData] of groupActorsDatas) { for (const page of queryData?.pages ?? []) { for (const profile of page.profiles) { if (profile.did === did) { diff --git a/src/state/queries/notifications/grouped/moderate.ts b/src/state/queries/notifications/grouped/moderate.ts index 1e6bc950c..65cd677ae 100644 --- a/src/state/queries/notifications/grouped/moderate.ts +++ b/src/state/queries/notifications/grouped/moderate.ts @@ -14,7 +14,7 @@ import {app} from '#/lexicons' import * as bsky from '#/types/bsky' /** - * Notification actors are basic views, but followers loaded with "Show more" + * Notification actors are basic views, but actors loaded with "Show more" * come from `getProfiles`, which returns detailed ones. */ type ProfileView = @@ -55,15 +55,7 @@ export function moderateNotification( case 'repost': case 'likeViaRepost': case 'repostViaRepost': - case 'generatorLike': { - const actors = notification.actors.filter( - actor => !isActorHidden(actor, moderationOpts), - ) - if (actors.length === notification.actors.length) return notification - if (!isNonEmpty(actors)) return undefined - // `count` stays as the server's total, hidden actors included. - return {...notification, actors} - } + case 'generatorLike': case 'follow': { const hiddenDids = new Set( notification.actors @@ -75,6 +67,7 @@ export function moderateNotification( actor => !hiddenDids.has(actor.did), ) if (!isNonEmpty(actors)) return undefined + // `count` stays as the server's total, hidden actors included. return { ...notification, actors, diff --git a/src/state/queries/notifications/grouped/types.ts b/src/state/queries/notifications/grouped/types.ts index cc7b645bb..d8bdce16d 100644 --- a/src/state/queries/notifications/grouped/types.ts +++ b/src/state/queries/notifications/grouped/types.ts @@ -44,6 +44,25 @@ type Base = { count: number } +/** + * The people in a group of notifications from different actors, e.g. + * everyone who liked a post. + */ +export type ActorGroup = { + /** + * The actors with a profile in `relatedViews`, newest first. The first is + * the group's primary actor. + */ + actors: NonEmptyArray + /** + * Every actor in the group, newest first, including those without a + * profile in `relatedViews`. A superset of the DIDs in `actors`, so the + * rest can be loaded on demand. List-time moderation removes hidden + * actors from both. May still be fewer than `count`. + */ + actorDids: DidString[] +} + /** * A notification group from `getGroupedNotifications`, with every DID and * at-uri resolved against the page's `relatedViews`. @@ -52,7 +71,7 @@ type Base = { * post and profile shadows are keyed by object identity. */ export type NotificationView = - | (Base & {type: 'like'; post: PostView; actors: NonEmptyArray}) + | (Base & ActorGroup & {type: 'like'; post: PostView}) | (Base & { type: 'multiPostLike' actor: ProfileView @@ -81,47 +100,32 @@ export type NotificationView = actor: ProfileView posts: NonEmptyArray }) - | (Base & { - type: 'repost' - post: PostView - actors: NonEmptyArray - }) - | (Base & { - type: 'likeViaRepost' - post: PostView - viaRepost: string - actors: NonEmptyArray - }) - | (Base & { - type: 'repostViaRepost' - post: PostView - viaRepost: string - actors: NonEmptyArray - }) - | (Base & { - type: 'follow' - actors: NonEmptyArray - /** - * Every follower in the group, newest first, including those without a - * profile in `relatedViews`. A superset of the DIDs in `actors`, so the - * rest can be loaded on demand. List-time moderation removes hidden - * actors from both. May still be fewer than `count`. - */ - actorDids: DidString[] - /** - * Only set when every follow in the group came via the same pack. - */ - starterPack?: StarterPackView - }) + | (Base & ActorGroup & {type: 'repost'; post: PostView}) + | (Base & + ActorGroup & { + type: 'likeViaRepost' + post: PostView + viaRepost: string + }) + | (Base & + ActorGroup & { + type: 'repostViaRepost' + post: PostView + viaRepost: string + }) + | (Base & + ActorGroup & { + type: 'follow' + /** + * Only set when every follow in the group came via the same pack. + */ + starterPack?: StarterPackView + }) | (Base & { type: 'subscribedPost' items: NonEmptyArray<{actor: ProfileView; post: PostView}> }) - | (Base & { - type: 'generatorLike' - generator: GeneratorView - actors: NonEmptyArray - }) + | (Base & ActorGroup & {type: 'generatorLike'; generator: GeneratorView}) | (Base & {type: 'reply'; post: PostView; parent: ParentPost}) | (Base & {type: 'quote'; post: PostView; parent?: ParentPost}) | (Base & {type: 'mention'; post: PostView; parent?: ParentPost}) diff --git a/src/view/screens/DebugMod/GroupedNotifications.tsx b/src/view/screens/DebugMod/GroupedNotifications.tsx index f8c5412b4..b548e09bf 100644 --- a/src/view/screens/DebugMod/GroupedNotifications.tsx +++ b/src/view/screens/DebugMod/GroupedNotifications.tsx @@ -1,5 +1,6 @@ import {useState} from 'react' import {View} from 'react-native' +import {type DidString} from '@atproto/syntax' import {type ModerationOpts} from '@bsky/sdk/moderation' import {moderateNotification} from '#/state/queries/notifications/grouped/moderate' @@ -127,8 +128,9 @@ export function GroupedNotifications({ target wrote the post. Embed labels go on the quoted post.

- Groups add Carol and Dave, who are never moderated, so hiding the - target trims the group rather than dropping it. + Groups add Carol, and Dave in groups of three or more, who are never + moderated, so hiding the target trims the group rather than dropping + it.

{profile.did === currentAccount?.did && (

@@ -260,12 +262,28 @@ function createMockNotifications({ groupPosition === 'first' ? [target, carolActor, daveActor] : [carolActor, target, daveActor] + const pair: NonEmptyArray = + groupPosition === 'first' ? [target, carolActor] : [carolActor, target] const base = (id: string, count = 1) => ({ id, isRead: false, indexedAt, count, }) + /** + * The actors of a group, every one of them resolved unless `unresolved` + * adds more without a profile, as when the API only hydrates some. + */ + const actorGroup = (actors: NonEmptyArray, unresolved = 0) => ({ + actors, + actorDids: [ + ...actors.map(actor => actor.did), + ...Array.from( + {length: unresolved}, + (_, i): DidString => `did:plc:unresolved${i + 1}`, + ), + ], + }) const postLabels = (on: LabelTarget, author: {did: string}, rkey: string) => labelsFor(on, { authorDid: author.did, @@ -361,7 +379,17 @@ function createMockNotifications({ ...base('like'), type: 'like', post: likedPost, - actors: [target], + ...actorGroup([target]), + }, + }, + { + title: 'Like', + subtitle: 'two people, named', + notification: { + ...base('like-pair', pair.length), + type: 'like', + post: likedPost, + ...actorGroup(pair), }, }, { @@ -371,7 +399,17 @@ function createMockNotifications({ ...base('like-group', group.length), type: 'like', post: likedPost, - actors: group, + ...actorGroup(group), + }, + }, + { + title: 'Like', + subtitle: 'large group, few profiles resolved', + notification: { + ...base('like-sparse', 20), + type: 'like', + post: likedPost, + ...actorGroup(group, 17), }, }, { @@ -381,7 +419,7 @@ function createMockNotifications({ ...base('repost'), type: 'repost', post: likedPost, - actors: [target], + ...actorGroup([target]), }, }, { @@ -391,7 +429,7 @@ function createMockNotifications({ ...base('repost-group', group.length), type: 'repost', post: likedPost, - actors: group, + ...actorGroup(group), }, }, { @@ -402,7 +440,7 @@ function createMockNotifications({ type: 'likeViaRepost', post: repostedPost, viaRepost, - actors: group, + ...actorGroup(group), }, }, { @@ -413,7 +451,7 @@ function createMockNotifications({ type: 'repostViaRepost', post: repostedPost, viaRepost, - actors: group, + ...actorGroup(group), }, }, { @@ -463,7 +501,7 @@ function createMockNotifications({ ...base('generator-like', group.length), type: 'generatorLike', generator, - actors: group, + ...actorGroup(group), }, }, { @@ -532,18 +570,25 @@ function createMockNotifications({ notification: { ...base('follow'), type: 'follow', - actors: [target], - actorDids: [target.did], + ...actorGroup([target]), + }, + }, + { + title: 'Follow', + subtitle: 'two people, named', + notification: { + ...base('follow-pair', pair.length), + type: 'follow', + ...actorGroup(pair), }, }, { title: 'Follow', - subtitle: 'grouped, expandable', + subtitle: 'multiple actors', notification: { ...base('follow-group', group.length), type: 'follow', - actors: group, - actorDids: group.map(actor => actor.did), + ...actorGroup(group), }, }, { -- knotmirror 0.0.1