diff --git a/src/components/NewPostsPill/index.tsx b/src/components/NewPostsPill/index.tsx new file mode 100644 index 000000000..da1bcb5d7 --- /dev/null +++ b/src/components/NewPostsPill/index.tsx @@ -0,0 +1,323 @@ +import {useEffect, useEffectEvent, useId, useState} from 'react' +import {AppState, type StyleProp, View, type ViewStyle} from 'react-native' +import Animated, { + Easing, + useAnimatedStyle, + useReducedMotion, + useSharedValue, + withTiming, +} from 'react-native-reanimated' +import Svg, {Circle, Defs, G, Image, Mask} from 'react-native-svg' +import {plural} from '@lingui/core/macro' +import {Trans, useLingui} from '@lingui/react/macro' + +import {HITSLOP_20} from '#/lib/constants' +import {PressableScale} from '#/lib/custom-animations/PressableScale' +import {atoms as a, useTheme} from '#/alf' +import {GlassView, IS_GLASS_AVAILABLE} from '#/components/GlassView' +import {useInteractionState} from '#/components/hooks/useInteractionState' +import {ArrowTop_Stroke2_Corner0_Rounded as ArrowTopIcon} from '#/components/icons/Arrow' +import { + newPostsPillLeadsUp, + newPostsPillPresentation, + type NewPostsPillVariant, +} from '#/components/NewPostsPill/presentation' +import {SubtleHover} from '#/components/SubtleHover' +import {Text} from '#/components/Typography' + +export type {NewPostsPillVariant} + +/** Only authors whose avatars are safe to display should be supplied. */ +export type NewPostsPillAuthor = { + did: string + avatar?: string +} + +const PILL_HEIGHT = 32 +const FACEPILE_PILL_HEIGHT = 40 +const AVATAR_SIZE = 24 +const AVATAR_OVERLAP = 7 +const FACE_GAP = 2 +const ANIMATION_DURATION = 200 +const PILL_TRAVEL = 56 +const NO_AUTHORS: NewPostsPillAuthor[] = [] + +/** + * A floating capsule's content and lifecycle, independent of feed data, metrics, + * and header positioning. The parent positions it beneath its own header. + * Exiting pills stay mounted for the slide, but are immediately inert. + */ +export function NewPostsPill({ + visible, + variant = 'newPosts', + count = 0, + authors = NO_AUTHORS, + showArrow, + text, + label, + style, + testID = 'newPostsPill', + onPress, +}: { + visible: boolean + variant?: NewPostsPillVariant + /** Number of eligible rendered posts, or 0 if only existence is known. */ + count?: number + authors?: NewPostsPillAuthor[] + /** Independent of fetch mode: a List refresh, for example, points up. */ + showArrow?: boolean + /** Optional translated visual wording for a surface or long-label fixture. */ + text?: string + /** Accessible action label; defaults to localized variant/count wording. */ + label?: string + /** The parent can provide positioning without coupling this to a header. */ + style?: StyleProp + testID?: string + onPress: () => void +}) { + const t = useTheme() + const {t: l} = useLingui() + const reducedMotion = useReducedMotion() + const { + state: hovered, + onIn: onHoverIn, + onOut: onHoverOut, + } = useInteractionState() + + /* Glass disappears after a genuine background return on supported iOS. */ + const [glassGeneration, setGlassGeneration] = useState(0) + const rebuildGlass = useEffectEvent(() => { + if (IS_GLASS_AVAILABLE) setGlassGeneration(generation => generation + 1) + }) + useEffect(() => { + let wasBackgrounded = AppState.currentState === 'background' + const subscription = AppState.addEventListener('change', next => { + if (next === 'background') { + wasBackgrounded = true + } else if (next === 'active' && wasBackgrounded) { + wasBackgrounded = false + rebuildGlass() + } + }) + return () => subscription.remove() + }, []) + + /* Translate only: opacity animations stop the native glass from rendering. */ + const travel = useSharedValue(-PILL_TRAVEL) + useEffect(() => { + travel.set( + reducedMotion + ? visible + ? 0 + : -PILL_TRAVEL + : withTiming(visible ? 0 : -PILL_TRAVEL, { + duration: ANIMATION_DURATION, + easing: visible ? Easing.out(Easing.quad) : Easing.in(Easing.quad), + }), + ) + }, [visible, reducedMotion, travel]) + const slide = useAnimatedStyle(() => ({ + transform: [{translateY: travel.get()}], + })) + + const [isMounted, setIsMounted] = useState(visible) + useEffect(() => { + if (visible) { + setIsMounted(true) + return + } + const timeout = setTimeout( + () => setIsMounted(false), + reducedMotion ? 0 : ANIMATION_DURATION, + ) + return () => clearTimeout(timeout) + }, [visible, reducedMotion]) + + /* Keep the offered content unchanged as it slides out. */ + const [retained, setRetained] = useState({ + variant, + count, + authors, + showArrow, + text, + label, + }) + useEffect(() => { + if (visible) setRetained({variant, count, authors, showArrow, text, label}) + }, [visible, variant, count, authors, showArrow, text, label]) + const content = visible + ? {variant, count, authors, showArrow, text, label} + : retained + + const faces = content.authors.filter(author => author.avatar).slice(0, 3) + const presentation = newPostsPillPresentation({ + variant: content.variant, + count: content.count, + faceCount: faces.length, + }) + const hasArrow = content.showArrow ?? newPostsPillLeadsUp(content.variant) + const defaultLabel = + content.variant === 'scrollToTop' + ? l`Scroll to top` + : content.variant === 'new' + ? l({ + message: 'Load new notifications', + comment: 'Accessible action on the notification list pill.', + }) + : content.variant === 'newPostsToFetch' || content.count === 0 + ? l`Load new posts` + : plural(content.count, { + one: 'Load # new post', + other: 'Load # new posts', + }) + + if (!isMounted) return null + + return ( + + + + + + + + {hasArrow && ( + + )} + {presentation === 'facepile' ? ( + + ) : presentation === 'generic' ? ( + + {content.text ?? New posts} + + ) : presentation === 'new' ? ( + + {content.text ?? ( + + New + + )} + + ) : null} + + + + + + ) +} + +function PillLabelText({children}: {children: React.ReactNode}) { + const t = useTheme() + return ( + + {children} + + ) +} + +/** SVG masks leave actual transparent gaps between the faces over glass. */ +function Facepile({authors}: {authors: NewPostsPillAuthor[]}) { + const t = useTheme() + const instance = useId().replace(/[^a-zA-Z0-9]/g, '') + const radius = AVATAR_SIZE / 2 + const step = AVATAR_SIZE - AVATAR_OVERLAP + const width = AVATAR_SIZE + (authors.length - 1) * step + + return ( + + + {authors.map((author, index) => ( + + + {index > 0 && ( + + )} + + ))} + + {authors.map((author, index) => ( + + + + + ))} + + ) +} diff --git a/src/components/NewPostsPill/presentation.test.ts b/src/components/NewPostsPill/presentation.test.ts new file mode 100644 index 000000000..459603f29 --- /dev/null +++ b/src/components/NewPostsPill/presentation.test.ts @@ -0,0 +1,53 @@ +import { + newPostsPillLeadsUp, + newPostsPillPresentation, +} from '#/components/NewPostsPill/presentation' + +describe('newPostsPillPresentation', () => { + it('shows faces only with four or more known posts and a usable avatar', () => { + expect( + newPostsPillPresentation({variant: 'newPosts', count: 4, faceCount: 3}), + ).toBe('facepile') + expect( + newPostsPillPresentation({variant: 'newPosts', count: 3, faceCount: 3}), + ).toBe('generic') + expect( + newPostsPillPresentation({variant: 'newPosts', count: 40, faceCount: 0}), + ).toBe('generic') + expect( + newPostsPillPresentation({variant: 'newPosts', count: 0, faceCount: 0}), + ).toBe('generic') + }) + + it('does not turn an existence-only check into a facepile', () => { + expect( + newPostsPillPresentation({ + variant: 'newPostsToFetch', + count: 40, + faceCount: 3, + }), + ).toBe('generic') + }) + + it('keeps notifications and plain scrolling distinct from post offers', () => { + expect( + newPostsPillPresentation({variant: 'new', count: 0, faceCount: 0}), + ).toBe('new') + expect( + newPostsPillPresentation({ + variant: 'scrollToTop', + count: 0, + faceCount: 0, + }), + ).toBeNull() + }) +}) + +describe('newPostsPillLeadsUp', () => { + it('points up by default for loaded posts and plain scrolling', () => { + expect(newPostsPillLeadsUp('newPosts')).toBe(true) + expect(newPostsPillLeadsUp('scrollToTop')).toBe(true) + expect(newPostsPillLeadsUp('newPostsToFetch')).toBe(false) + expect(newPostsPillLeadsUp('new')).toBe(false) + }) +}) diff --git a/src/components/NewPostsPill/presentation.ts b/src/components/NewPostsPill/presentation.ts new file mode 100644 index 000000000..d9d8d4530 --- /dev/null +++ b/src/components/NewPostsPill/presentation.ts @@ -0,0 +1,30 @@ +/** The content offered by a pill; the caller owns what pressing it does. */ +export type NewPostsPillVariant = + 'newPosts' | 'newPostsToFetch' | 'new' | 'scrollToTop' + +/** The usual arrow treatment. A surface may override it independently. */ +export function newPostsPillLeadsUp(variant: NewPostsPillVariant): boolean { + return variant === 'newPosts' || variant === 'scrollToTop' +} + +/** A facepile needs a known group of posts and at least one usable avatar. */ +export function newPostsPillPresentation({ + variant, + count, + faceCount, +}: { + variant: NewPostsPillVariant + count: number + faceCount: number +}): 'generic' | 'facepile' | 'new' | null { + switch (variant) { + case 'scrollToTop': + return null + case 'new': + return 'new' + case 'newPostsToFetch': + return 'generic' + case 'newPosts': + return count >= 4 && faceCount > 0 ? 'facepile' : 'generic' + } +} diff --git a/src/view/screens/Storybook/NewPostsPill.tsx b/src/view/screens/Storybook/NewPostsPill.tsx new file mode 100644 index 000000000..b05b23c35 --- /dev/null +++ b/src/view/screens/Storybook/NewPostsPill.tsx @@ -0,0 +1,252 @@ +import {useState} from 'react' +import {Image as RNImage, ScrollView, View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {atoms as a, ThemeProvider, useAlf, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import { + NewPostsPill as Pill, + type NewPostsPillAuthor, + type NewPostsPillVariant, +} from '#/components/NewPostsPill' +import {Text} from '#/components/Typography' + +const avatars: NewPostsPillAuthor[] = [ + { + did: 'storybook:one', + avatar: RNImage.resolveAssetSource(require('../../../../assets/kawaii.png')) + ?.uri, + }, + { + did: 'storybook:two', + avatar: RNImage.resolveAssetSource( + require('../../../../assets/icons/community/germ_logo.webp'), + )?.uri, + }, + { + did: 'storybook:three', + avatar: RNImage.resolveAssetSource( + require('../../../../assets/kawaii_smol.png'), + )?.uri, + }, +] + +const cases: { + name: string + variant?: NewPostsPillVariant + count?: number + authors?: NewPostsPillAuthor[] + showArrow?: boolean +}[] = [ + {name: 'Loaded, count unknown', count: 0}, + {name: 'Loaded, one post', count: 1, authors: avatars}, + {name: 'Loaded, three posts', count: 3, authors: avatars}, + {name: 'Four posts, one face', count: 4, authors: avatars.slice(0, 1)}, + {name: 'Many posts, two faces', count: 40, authors: avatars.slice(0, 2)}, + {name: 'Many posts, three faces', count: 40, authors: avatars}, + {name: 'Many posts, no faces', count: 40}, + { + name: 'Missing avatar', + count: 4, + authors: [{did: 'storybook:missing'}, ...avatars.slice(0, 1)], + }, + { + name: 'Broken avatar', + count: 4, + authors: [ + ...avatars.slice(0, 1), + {did: 'storybook:broken', avatar: 'https://example.invalid/x.png'}, + ], + }, + {name: 'Fetch new posts', variant: 'newPostsToFetch'}, + {name: 'List refresh points up', variant: 'newPostsToFetch', showArrow: true}, + {name: 'Notifications', variant: 'new'}, + {name: 'Scroll to top', variant: 'scrollToTop'}, +] + +/** Offline fixtures: no feed, account, pager, or analytics provider required. */ +export function NewPostsPill() { + const t = useTheme() + const {t: l} = useLingui() + const {fonts} = useAlf() + const [visible, setVisible] = useState(true) + const [presses, setPresses] = useState(0) + + return ( + + New posts pill + + Static cases use bundled images. Background and resume the app while the + interactive facepile is visible to check the glass rebuild without + reloading the faces. Turn on Reduce Motion in device settings to check + the non-animated path. + + + + + + + + + {cases.map(({name, ...props}) => ( + + {name} + setPresses(n => n + 1)} /> + + ))} + + + Themes + + {(['light', 'dim', 'dark'] as const).map(theme => ( + + + + ))} + + + Long translated wording + + setPresses(n => n + 1)} + /> + + + Show, hide, re-show, press during exit + + + + Presses: {presses} + + + setPresses(n => n + 1)} + /> + + + Scrollable header placement + + + ) +} + +function ThemeCase({name}: {name: string}) { + const t = useTheme() + return ( + + {name} + {}} /> + + ) +} + +function HeaderFixture() { + const t = useTheme() + const [scrollY, setScrollY] = useState(0) + const [header, setHeader] = useState<'home' | 'pager' | 'web'>('home') + const expandedHeight = header === 'home' ? 96 : header === 'pager' ? 76 : 80 + const pinnedHeight = header === 'home' ? 48 : header === 'pager' ? 44 : 40 + const headerHeight = Math.max(pinnedHeight, expandedHeight - scrollY) + + return ( + + + {(['home', 'pager', 'web'] as const).map(value => ( + + ))} + + + setScrollY(event.nativeEvent.contentOffset.y)}> + + {Array.from({length: 12}, (_, index) => ( + + Example post {index + 1} + + ))} + + + {header} header + + {}} + /> + + + ) +} diff --git a/src/view/screens/Storybook/Storybook.tsx b/src/view/screens/Storybook/Storybook.tsx index 1583e923f..633022bf4 100644 --- a/src/view/screens/Storybook/Storybook.tsx +++ b/src/view/screens/Storybook/Storybook.tsx @@ -21,6 +21,7 @@ import {Forms} from './Forms' import {Icons} from './Icons' import {Links} from './Links' import {Menus} from './Menus' +import {NewPostsPill} from './NewPostsPill' import {Settings} from './Settings' import {Shadows} from './Shadows' import {Spacing} from './Spacing' @@ -122,6 +123,7 @@ export default function Storybook() { +