Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946import { useCallback, useLayoutEffect, useMemo, useReducer, useRef, useState,} from 'react'import {LayoutAnimation, type TextInput, View} from 'react-native'import {moderateProfile, type ModerationOpts} from '@atproto/api'import {Plural, Trans, useLingui} from '@lingui/react/macro'
import {MAX_GROUP_NAME_GRAPHEME_LENGTH} from '#/lib/constants'import {sanitizeDisplayName} from '#/lib/strings/display-names'import {sanitizeHandle} from '#/lib/strings/handles'import {isOverMaxGraphemeCount} from '#/lib/strings/helpers'import {useModerationOpts} from '#/state/preferences/moderation-opts'import {useActorAutocompleteQuery} from '#/state/queries/actor-autocomplete'import {useChatActorStatusQuery} from '#/state/queries/messages/get-status'import {useProfileFollowsQuery} from '#/state/queries/profile-follows'import {useSession} from '#/state/session'import {type ListMethods} from '#/view/com/util/List'import {android, atoms as a, native, useTheme, web} from '#/alf'import {Button, ButtonIcon, ButtonText} from '#/components/Button'import * as Dialog from '#/components/Dialog'import {canBeAddedToGroup, canBeMessaged} from '#/components/dms/util'import * as TextField from '#/components/forms/TextField'import * as Toggle from '#/components/forms/Toggle'import { ArrowLeft_Stroke2_Corner0_Rounded as ArrowLeftIcon, ArrowRight_Stroke2_Corner0_Rounded as ArrowRightIcon,} from '#/components/icons/Arrow'import {ChevronRight_Stroke2_Corner0_Rounded as ChevronRightIcon} from '#/components/icons/Chevron'import {PersonGroup_Stroke2_Corner2_Rounded as PersonGroupIcon} from '#/components/icons/Person'import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/Times'import * as ProfileCard from '#/components/ProfileCard'import * as Prompt from '#/components/Prompt'import {Text} from '#/components/Typography'import {IS_NATIVE, IS_WEB} from '#/env'import type * as bsky from '#/types/bsky'import {ChatProfileTabs} from './ChatProfileTabs'import {EmptyMemberList} from './components/EmptyMemberList'import {GroupChatProfileCard} from './components/GroupChatProfileCard'import {ProfileCardSkeleton} from './components/ProfileCardSkeleton'import {UserLabel} from './components/UserLabel'import {UserSearchInput} from './components/UserSearchInput'
type NewGroupChatItem = { type: 'newGroupChat' key: string}
type LabelItem = { type: 'label' key: string message: string}
type ProfileItem = { type: 'profile' key: string profile: bsky.profile.AnyProfileView}
type EmptyItem = { type: 'empty' key: string message: string}
type PlaceholderItem = { type: 'placeholder' key: string}
type ErrorItem = { type: 'error' key: string}
type Item = | NewGroupChatItem | LabelItem | ProfileItem | EmptyItem | PlaceholderItem | ErrorItem
enum ChatState { NEW_CHAT, NEW_GROUP_CHAT, GROUP_NAME,}
export type State = { chatState: ChatState screenTitle: string groupChatDids: string[] groupChatProfiles: bsky.profile.AnyProfileView[] groupName: string searchText: string}
export type Action = | { type: 'startNewGroupChat' screenTitle: string } | { type: 'setDids' groupChatDids: string[] groupChatProfiles: bsky.profile.AnyProfileView[] } | { type: 'removeDids' groupChatDids: string[] groupChatProfiles: bsky.profile.AnyProfileView[] } | { type: 'startNameGroup' screenTitle: string } | { type: 'nameGroup' groupName: string } | { type: 'goBackFromNewGroupChat' screenTitle: string } | { type: 'goBackFromGroupName' screenTitle: string } | { type: 'setSearchText' searchText: string }
function reducer(state: State, action: Action): State { switch (action.type) { case 'startNewGroupChat': { return { ...state, chatState: ChatState.NEW_GROUP_CHAT, screenTitle: action.screenTitle, groupChatDids: [], groupChatProfiles: [], groupName: '', } } case 'setDids': { return { ...state, groupChatDids: action.groupChatDids, groupChatProfiles: action.groupChatProfiles, searchText: '', } } case 'removeDids': { return { ...state, groupChatDids: action.groupChatDids, groupChatProfiles: action.groupChatProfiles, } } case 'startNameGroup': { return { ...state, chatState: ChatState.GROUP_NAME, screenTitle: action.screenTitle, searchText: '', } } case 'nameGroup': { return { ...state, groupName: action.groupName, } } case 'goBackFromNewGroupChat': { return { ...state, chatState: ChatState.NEW_CHAT, screenTitle: action.screenTitle, groupChatDids: [], groupChatProfiles: [], groupName: '', searchText: '', } } case 'goBackFromGroupName': { return { ...state, chatState: ChatState.NEW_GROUP_CHAT, screenTitle: action.screenTitle, groupName: '', } } case 'setSearchText': { return { ...state, searchText: action.searchText, } } }}
export function InitiateChatFlow({ title, onSelectChat, onSelectGroupChat, startInGroupChat = false,}: { title: string onSelectChat: (did: string) => void onSelectGroupChat: (dids: string[], groupName: string) => void startInGroupChat?: boolean}) { const t = useTheme() const {t: l} = useLingui() const moderationOpts = useModerationOpts() const control = Dialog.useDialogContext() const [headerHeight, setHeaderHeight] = useState(0) const [footerHeight, setFooterHeight] = useState(0) const listRef = useRef<ListMethods>(null) const {currentAccount} = useSession() const inputRef = useRef<TextInput>(null) const accountTooNewPromptControl = Dialog.useDialogControl()
const {data: chatStatus} = useChatActorStatusQuery() const canCreateGroups = chatStatus?.canCreateGroups ?? true const groupMemberLimit = chatStatus?.groupMemberLimit
const [ { chatState, screenTitle, groupChatDids, groupChatProfiles, groupName, searchText, }, dispatch, ] = useReducer(reducer, { chatState: startInGroupChat ? ChatState.NEW_GROUP_CHAT : ChatState.NEW_CHAT, screenTitle: startInGroupChat ? l`New group chat` : title, groupChatDids: [], groupChatProfiles: [], groupName: '', searchText: '', })
const { data: results, isError, isFetching, } = useActorAutocompleteQuery(searchText, true, 12) const {data: follows} = useProfileFollowsQuery(currentAccount?.did)
const newGroupChatTitle = l`New group chat` const groupNameTitle = l`Group name`
const onRemoveDid = useCallback( (did: string) => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) dispatch({ type: 'removeDids', groupChatDids: groupChatDids.filter(d => d !== did), groupChatProfiles: groupChatProfiles.filter( profile => profile.did !== did, ), }) }, [groupChatDids, groupChatProfiles], )
const items = useMemo(() => { let _items: Item[] = [] const checker = chatState === ChatState.NEW_GROUP_CHAT ? canBeAddedToGroup : canBeMessaged
if (isError) { _items.push({ type: 'empty', key: 'empty', message: l`We’re having network issues, try again`, }) } else if (chatState === ChatState.GROUP_NAME) { _items = groupChatProfiles.map(profile => ({ type: 'profile', key: profile.did, profile, })) _items.unshift({ type: 'label', key: 'members', message: l`New group chat with:`, }) } else if (searchText.length) { if (results?.length) { for (const profile of results) { if (profile.did === currentAccount?.did) continue _items.push({ type: 'profile', key: profile.did, profile, }) }
_items = _items.sort(item => { return item.type === 'profile' && checker(item.profile) ? -1 : 1 }) } } else { const placeholders: Item[] = Array(10) .fill(0) .map((__, i) => ({ type: 'placeholder', key: i + '', }))
if (follows) { for (const page of follows.pages) { for (const profile of page.follows) { if (!checker(profile)) continue _items.push({ type: 'profile', key: profile.did, profile, }) } } } else { _items.push(...placeholders) } }
if ( searchText === '' && _items.length > 0 && (chatState === ChatState.NEW_CHAT || chatState === ChatState.NEW_GROUP_CHAT) ) { _items.unshift({ type: 'label', key: 'suggested', message: l`Suggested`, }) }
if (chatState === ChatState.NEW_CHAT && searchText === '') { _items.unshift({type: 'newGroupChat', key: 'newGroupChat'}) }
return _items }, [ isError, chatState, searchText, l, groupChatProfiles, results, currentAccount?.did, follows, ])
if (searchText && !isFetching && !items.length && !isError) { items.push({type: 'empty', key: 'empty', message: l`No results`}) }
const handlePressBack = useCallback(() => { switch (chatState) { case ChatState.NEW_CHAT: control.close() break case ChatState.NEW_GROUP_CHAT: LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) dispatch({type: 'goBackFromNewGroupChat', screenTitle: title}) break case ChatState.GROUP_NAME: LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) dispatch({type: 'goBackFromGroupName', screenTitle: newGroupChatTitle}) break } }, [chatState, control, newGroupChatTitle, title])
const handlePressNewGroupChat = useCallback(() => { if (!canCreateGroups) { accountTooNewPromptControl.open() return } LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) dispatch({type: 'startNewGroupChat', screenTitle: newGroupChatTitle}) }, [accountTooNewPromptControl, canCreateGroups, newGroupChatTitle])
const handlePressNext = useCallback(() => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) dispatch({type: 'startNameGroup', screenTitle: groupNameTitle}) }, [groupNameTitle])
const handlePressConfirm = useCallback(() => { onSelectGroupChat(groupChatDids, groupName) }, [groupChatDids, groupName, onSelectGroupChat])
const setGroupName = (newGroupName: string) => { dispatch({type: 'nameGroup', groupName: newGroupName}) }
const renderItems = useCallback( ({item}: {item: Item}) => { switch (item.type) { case 'newGroupChat': { return ( <NewGroupChatButton key={item.key} onPress={handlePressNewGroupChat} dimmed={!canCreateGroups} /> ) } case 'label': { return <UserLabel key={item.key} message={item.message} /> } case 'profile': { switch (chatState) { case ChatState.NEW_CHAT: return ( <DefaultProfileCard key={item.key} profile={item.profile} moderationOpts={moderationOpts!} onPress={onSelectChat} /> ) case ChatState.NEW_GROUP_CHAT: return ( <GroupChatProfileCard key={item.key} profile={item.profile} moderationOpts={moderationOpts!} /> ) case ChatState.GROUP_NAME: return ( <GroupChatMemberProfileCard key={item.key} profile={item.profile} moderationOpts={moderationOpts!} /> ) } } case 'placeholder': { return <ProfileCardSkeleton key={item.key} /> } case 'empty': { return <EmptyMemberList key={item.key} message={item.message} /> } default: return null } }, [ canCreateGroups, chatState, handlePressNewGroupChat, moderationOpts, onSelectChat, ], )
useLayoutEffect(() => { if (IS_WEB) { setImmediate(() => { inputRef?.current?.focus() }) } }, [])
const groupNameTooLong = isOverMaxGraphemeCount({ text: groupName, maxCount: MAX_GROUP_NAME_GRAPHEME_LENGTH, })
let buttonLabel = l`Continue to group name` let buttonText = l`Next` let handleButtonPress = handlePressNext let showButton = chatState === ChatState.NEW_GROUP_CHAT && groupChatProfiles.length > 0 let isButtonDisabled = !showButton switch (chatState) { case ChatState.GROUP_NAME: buttonLabel = l`Create group chat` buttonText = l`Create` handleButtonPress = handlePressConfirm showButton = true isButtonDisabled = groupName === '' || groupNameTooLong break }
const showChatProfileTabs = chatState === ChatState.NEW_GROUP_CHAT && groupChatProfiles.length > 0
const listHeader = useMemo( () => ( <View onLayout={evt => setHeaderHeight(evt.nativeEvent.layout.height)}> <View style={[ a.relative, web(a.pt_lg), native(a.pt_4xl), android({ borderTopLeftRadius: a.rounded_md.borderRadius, borderTopRightRadius: a.rounded_md.borderRadius, }), a.px_lg, chatState !== ChatState.GROUP_NAME ? a.pb_xs : a.pb_lg, chatState !== ChatState.GROUP_NAME && a.border_b, t.atoms.border_contrast_low, t.atoms.bg, ]}> <View style={[ a.flex_row, a.gap_sm, a.relative, a.align_center, a.justify_between, ]}> {IS_NATIVE ? ( <Button label={l`Back`} size="large" shape="round" variant="ghost" color="secondary" style={[native([a.absolute, a.z_20])]} onPress={handlePressBack}> <ButtonIcon icon={ArrowLeftIcon} size="lg" /> </Button> ) : null} <Text style={[ a.flex_grow, a.z_10, a.text_lg, a.font_bold, a.leading_tight, t.atoms.text_contrast_high, a.text_center, a.px_5xl, ]}> {screenTitle} </Text> {IS_WEB ? ( <Button label={l`Close`} size="small" shape="round" variant="ghost" color="secondary" style={[a.absolute, a.z_20, {right: -4}]} onPress={() => control.close()}> <ButtonIcon icon={XIcon} size="md" /> </Button> ) : showButton ? ( <Button label={buttonLabel} size="small" color="primary" style={[ native([ a.absolute, a.z_20, { right: 8, }, ]), ]} disabled={isButtonDisabled} onPress={handleButtonPress}> <ButtonText>{buttonText}</ButtonText> </Button> ) : null} </View> <View style={[web(a.pt_xs), native(a.pt_md)]}> {chatState === ChatState.GROUP_NAME ? ( <View style={[a.w_full, a.relative, web(a.pt_md), native(a.pt_xl)]}> <TextField.Root isInvalid={groupNameTooLong}> <TextField.Input label={l`Group name`} value={groupName} returnKeyType="next" keyboardAppearance={t.scheme} selectTextOnFocus={IS_NATIVE} autoFocus={false} accessibilityRole="text" clearButtonMode="while-editing" autoCorrect={false} autoComplete="off" autoCapitalize="none" onChangeText={setGroupName} onSubmitEditing={ isButtonDisabled ? undefined : handleButtonPress } /> </TextField.Root> {groupNameTooLong ? ( <Text style={[ a.text_sm, a.mt_xs, a.font_semi_bold, {color: t.palette.negative_400}, ]}> <Trans> Group name is too long.{' '} <Plural value={MAX_GROUP_NAME_GRAPHEME_LENGTH} other="The maximum number of characters is #." /> </Trans> </Text> ) : null} </View> ) : ( <UserSearchInput inputRef={inputRef} value={searchText} onChangeText={text => { dispatch({type: 'setSearchText', searchText: text}) listRef.current?.scrollToOffset({offset: 0, animated: false}) }} onEscape={control.close} /> )} </View> </View> {showChatProfileTabs ? ( <View style={[a.pb_sm, a.pt_md, t.atoms.bg]}> <ChatProfileTabs testID="newGroupChatMembers" profiles={groupChatProfiles} onRemove={onRemoveDid} /> </View> ) : null} </View> ), [ chatState, t.atoms.border_contrast_low, t.atoms.bg, t.atoms.text_contrast_high, t.scheme, l, handlePressBack, screenTitle, showButton, buttonLabel, isButtonDisabled, handleButtonPress, buttonText, groupName, groupNameTooLong, t.palette.negative_400, searchText, control, showChatProfileTabs, groupChatProfiles, onRemoveDid, ], )
const setGroupChatMembers = (dids: string[]) => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
const added = dids.filter(d => !groupChatDids.includes(d)) const removed = groupChatDids.filter(d => !dids.includes(d)) const newDids = [ ...groupChatDids.filter(d => !removed.includes(d)), ...added, ]
const kept = groupChatProfiles.filter(p => dids.includes(p.did)) const keptDids = new Set(kept.map(p => p.did)) const addedProfiles = items .filter( (item): item is ProfileItem => item.type === 'profile' && dids.includes(item.profile.did) && !keptDids.has(item.profile.did), ) .map(item => item.profile) .sort((a, b) => dids.indexOf(a.did) - dids.indexOf(b.did))
dispatch({ type: 'setDids', groupChatDids: newDids, groupChatProfiles: [...kept, ...addedProfiles], }) }
return ( <Toggle.Group values={groupChatDids} onChange={setGroupChatMembers} type="checkbox" maxSelections={ // groupMemberLimit counts the creator, who is added implicitly, so // reserve one slot for them groupMemberLimit ? groupMemberLimit - 1 : undefined } label={ chatState === ChatState.NEW_GROUP_CHAT ? l`Select group chat members` : l`Start chat` } style={web([a.contents])}> <Prompt.Basic control={accountTooNewPromptControl} title={l`Your account is too new`} description={l`Your account must be at least 7 days old to create a new group chat.`} confirmButtonCta={l`Okay`} onConfirm={() => {}} showCancel={false} /> <Dialog.InnerFlatList ref={listRef} data={items} renderItem={renderItems} ListHeaderComponent={listHeader} stickyHeaderIndices={[0]} keyExtractor={(item: Item) => item.key} style={[ web([a.py_0, {height: '100vh', maxHeight: 600}, a.px_0]), native({height: '100%'}), ]} webInnerContentContainerStyle={[a.py_0, {paddingBottom: footerHeight}]} webInnerStyle={[a.py_0, {maxWidth: 500, minWidth: 200}]} scrollIndicatorInsets={{top: headerHeight, bottom: footerHeight}} keyboardDismissMode="on-drag" footer={ IS_WEB && chatState !== ChatState.NEW_CHAT ? ( <Dialog.FlatListFooter onLayout={evt => setFooterHeight(evt.nativeEvent.layout.height)}> <View style={[a.flex_row, a.align_center, a.justify_between]}> <Button label={l`Back`} size="small" color="secondary" onPress={handlePressBack}> <ButtonIcon icon={ArrowLeftIcon} size="md" /> <ButtonText> {' '} <Trans>Back</Trans> </ButtonText> </Button> <Button label={buttonLabel} size="small" color="primary" disabled={isButtonDisabled} onPress={handleButtonPress}> <ButtonText>{buttonText} </ButtonText> {chatState !== ChatState.GROUP_NAME ? ( <ButtonIcon icon={ArrowRightIcon} size="md" /> ) : null} </Button> </View> </Dialog.FlatListFooter> ) : null } /> </Toggle.Group> )}
function NewGroupChatButton({ onPress, dimmed = false,}: { onPress: () => void dimmed?: boolean}) { const t = useTheme() const {t: l} = useLingui()
return ( <Button label={l({ message: 'New group chat', context: 'action', comment: 'Button used to create a new group chat.', })} onPress={onPress}> {({hovered, pressed, focused}) => ( <View style={[ a.px_lg, a.py_md, a.flex_row, a.flex_1, a.justify_between, a.align_center, a.gap_sm, pressed || focused || hovered ? t.atoms.bg_contrast_25 : t.atoms.bg, dimmed && {opacity: 0.5}, ]}> <View style={[ a.rounded_full, a.justify_center, a.align_center, { backgroundColor: t.palette.contrast_50, padding: 12, }, ]}> <PersonGroupIcon size="md" fill={t.palette.contrast_1000} /> </View> <View style={[a.flex_grow]}> <Text style={[a.text_md, a.font_medium, a.leading_snug, t.atoms.text]}> <Trans context="action" comment="Button used to create a new group chat."> New group chat </Trans> </Text> </View> <ChevronRightIcon size="md" fill={t.palette.contrast_1000} /> </View> )} </Button> )}
function DefaultProfileCard({ profile, moderationOpts, onPress,}: { profile: bsky.profile.AnyProfileView moderationOpts: ModerationOpts onPress: (did: string) => void}) { const t = useTheme() const {t: l} = useLingui() const enabled = canBeMessaged(profile) const moderation = moderateProfile(profile, moderationOpts) const handle = sanitizeHandle(profile.handle, '@') const displayName = sanitizeDisplayName( profile.displayName || sanitizeHandle(profile.handle), moderation.ui('displayName'), )
const handleOnPress = useCallback(() => { onPress(profile.did) }, [onPress, profile.did])
return ( <Button disabled={!enabled} label={l`Start chat with ${displayName}`} onPress={handleOnPress}> {({hovered, pressed, focused}) => ( <View style={[ a.flex_1, a.py_sm, a.px_lg, !enabled ? {opacity: 0.5} : pressed || focused || hovered ? t.atoms.bg_contrast_25 : t.atoms.bg, ]}> <ProfileCard.Header> <ProfileCard.Avatar profile={profile} moderationOpts={moderationOpts} size={44} disabledPreview /> <View style={[a.flex_1]}> <ProfileCard.Name profile={profile} moderationOpts={moderationOpts} /> {enabled ? ( <ProfileCard.Handle profile={profile} /> ) : ( <Text style={[a.leading_snug, t.atoms.text_contrast_high]} numberOfLines={2}> <Trans>{handle} can’t be messaged</Trans> </Text> )} </View> </ProfileCard.Header> </View> )} </Button> )}
function GroupChatMemberProfileCard({ profile, moderationOpts,}: { profile: bsky.profile.AnyProfileView moderationOpts: ModerationOpts}) { const t = useTheme() const enabled = canBeAddedToGroup(profile) const handle = sanitizeHandle(profile.handle, '@')
return ( <View style={[a.flex_1, a.py_sm, a.px_lg, t.atoms.bg]}> <ProfileCard.Header> <ProfileCard.Avatar profile={profile} moderationOpts={moderationOpts} size={44} disabledPreview /> <View style={[a.flex_1]}> <ProfileCard.Name profile={profile} moderationOpts={moderationOpts} /> {enabled ? ( <ProfileCard.Handle profile={profile} /> ) : ( <Text style={[a.leading_snug, t.atoms.text_contrast_high]} numberOfLines={2}> <Trans>{handle} can’t be added</Trans> </Text> )} </View> </ProfileCard.Header> </View> )}