about summary refs log tree commit diff
path: root/src/components/FeedCard.tsx
blob: f94692e5bd002c57f389bf948026a5875a215dab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import React from 'react'
import {type GestureResponderEvent, View} from 'react-native'
import {
  type AppBskyFeedDefs,
  type AppBskyGraphDefs,
  AtUri,
  RichText as RichTextApi,
} from '@atproto/api'
import {msg, Plural, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query'

import {sanitizeHandle} from '#/lib/strings/handles'
import {logger} from '#/logger'
import {precacheFeedFromGeneratorView} from '#/state/queries/feed'
import {
  useAddSavedFeedsMutation,
  usePreferencesQuery,
  useRemoveFeedMutation,
} from '#/state/queries/preferences'
import {useSession} from '#/state/session'
import * as Toast from '#/view/com/util/Toast'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, useTheme} from '#/alf'
import {
  Button,
  ButtonIcon,
  type ButtonProps,
  ButtonText,
} from '#/components/Button'
import {Pin_Stroke2_Corner0_Rounded as PinIcon} from '#/components/icons/Pin'
import {Link as InternalLink, type LinkProps} from '#/components/Link'
import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt'
import {RichText, type RichTextProps} from '#/components/RichText'
import {Text} from '#/components/Typography'
import type * as bsky from '#/types/bsky'
import {Trash_Stroke2_Corner0_Rounded as TrashIcon} from './icons/Trash'

type Props = {
  view: AppBskyFeedDefs.GeneratorView
  onPress?: () => void
}

export function Default(props: Props) {
  const {view} = props
  return (
    <Link {...props}>
      <Outer>
        <Header>
          <Avatar src={view.avatar} />
          <TitleAndByline title={view.displayName} creator={view.creator} />
          <SaveButton view={view} pin />
        </Header>
        <Description description={view.description} />
        <Likes count={view.likeCount || 0} />
      </Outer>
    </Link>
  )
}

export function Link({
  view,
  children,
  ...props
}: Props & Omit<LinkProps, 'to' | 'label'>) {
  const queryClient = useQueryClient()

  const href = React.useMemo(() => {
    return createProfileFeedHref({feed: view})
  }, [view])

  React.useEffect(() => {
    precacheFeedFromGeneratorView(queryClient, view)
  }, [view, queryClient])

  return (
    <InternalLink
      label={view.displayName}
      to={href}
      style={[a.flex_col]}
      {...props}>
      {children}
    </InternalLink>
  )
}

export function Outer({children}: {children: React.ReactNode}) {
  return <View style={[a.w_full, a.gap_sm]}>{children}</View>
}

export function Header({children}: {children: React.ReactNode}) {
  return <View style={[a.flex_row, a.align_center, a.gap_sm]}>{children}</View>
}

export type AvatarProps = {src: string | undefined; size?: number}

export function Avatar({src, size = 40}: AvatarProps) {
  return <UserAvatar type="algo" size={size} avatar={src} />
}

export function AvatarPlaceholder({size = 40}: Omit<AvatarProps, 'src'>) {
  const t = useTheme()
  return (
    <View
      style={[
        t.atoms.bg_contrast_25,
        {
          width: size,
          height: size,
          borderRadius: 8,
        },
      ]}
    />
  )
}

export function TitleAndByline({
  title,
  creator,
}: {
  title: string
  creator?: bsky.profile.AnyProfileView
}) {
  const t = useTheme()

  return (
    <View style={[a.flex_1]}>
      <Text
        emoji
        style={[a.text_md, a.font_bold, a.leading_snug]}
        numberOfLines={1}>
        {title}
      </Text>
      {creator && (
        <Text
          style={[a.leading_snug, t.atoms.text_contrast_medium]}
          numberOfLines={1}>
          <Trans>Feed by {sanitizeHandle(creator.handle, '@')}</Trans>
        </Text>
      )}
    </View>
  )
}

export function TitleAndBylinePlaceholder({creator}: {creator?: boolean}) {
  const t = useTheme()

  return (
    <View style={[a.flex_1, a.gap_xs]}>
      <View
        style={[
          a.rounded_xs,
          t.atoms.bg_contrast_50,
          {
            width: '60%',
            height: 14,
          },
        ]}
      />

      {creator && (
        <View
          style={[
            a.rounded_xs,
            t.atoms.bg_contrast_25,
            {
              width: '40%',
              height: 10,
            },
          ]}
        />
      )}
    </View>
  )
}

export function Description({
  description,
  ...rest
}: {description?: string} & Partial<RichTextProps>) {
  const rt = React.useMemo(() => {
    if (!description) return
    const rt = new RichTextApi({text: description || ''})
    rt.detectFacetsWithoutResolution()
    return rt
  }, [description])
  if (!rt) return null
  return <RichText value={rt} style={[a.leading_snug]} disableLinks {...rest} />
}

export function DescriptionPlaceholder() {
  const t = useTheme()
  return (
    <View style={[a.gap_xs]}>
      <View
        style={[a.rounded_xs, a.w_full, t.atoms.bg_contrast_50, {height: 12}]}
      />
      <View
        style={[a.rounded_xs, a.w_full, t.atoms.bg_contrast_50, {height: 12}]}
      />
      <View
        style={[
          a.rounded_xs,
          a.w_full,
          t.atoms.bg_contrast_50,
          {height: 12, width: 100},
        ]}
      />
    </View>
  )
}

export function Likes({count}: {count: number}) {
  const t = useTheme()
  return (
    <Text style={[a.text_sm, t.atoms.text_contrast_medium]}>
      <Trans>
        Liked by <Plural value={count || 0} one="# user" other="# users" />
      </Trans>
    </Text>
  )
}

export function SaveButton({
  view,
  pin,
  ...props
}: {
  view: AppBskyFeedDefs.GeneratorView | AppBskyGraphDefs.ListView
  pin?: boolean
  text?: boolean
} & Partial<ButtonProps>) {
  const {hasSession} = useSession()
  if (!hasSession) return null
  return <SaveButtonInner view={view} pin={pin} {...props} />
}

function SaveButtonInner({
  view,
  pin,
  text = true,
  ...buttonProps
}: {
  view: AppBskyFeedDefs.GeneratorView | AppBskyGraphDefs.ListView
  pin?: boolean
  text?: boolean
} & Partial<ButtonProps>) {
  const {_} = useLingui()
  const {data: preferences} = usePreferencesQuery()
  const {isPending: isAddSavedFeedPending, mutateAsync: saveFeeds} =
    useAddSavedFeedsMutation()
  const {isPending: isRemovePending, mutateAsync: removeFeed} =
    useRemoveFeedMutation()

  const uri = view.uri
  const type = view.uri.includes('app.bsky.feed.generator') ? 'feed' : 'list'

  const savedFeedConfig = React.useMemo(() => {
    return preferences?.savedFeeds?.find(feed => feed.value === uri)
  }, [preferences?.savedFeeds, uri])
  const removePromptControl = Prompt.usePromptControl()
  const isPending = isAddSavedFeedPending || isRemovePending

  const toggleSave = React.useCallback(
    async (e: GestureResponderEvent) => {
      e.preventDefault()
      e.stopPropagation()

      try {
        if (savedFeedConfig) {
          await removeFeed(savedFeedConfig)
        } else {
          await saveFeeds([
            {
              type,
              value: uri,
              pinned: pin || false,
            },
          ])
        }
        Toast.show(_(msg({message: 'Feeds updated!', context: 'toast'})))
      } catch (err: any) {
        logger.error(err, {message: `FeedCard: failed to update feeds`, pin})
        Toast.show(_(msg`Failed to update feeds`), 'xmark')
      }
    },
    [_, pin, saveFeeds, removeFeed, uri, savedFeedConfig, type],
  )

  const onPrompRemoveFeed = React.useCallback(
    async (e: GestureResponderEvent) => {
      e.preventDefault()
      e.stopPropagation()

      removePromptControl.open()
    },
    [removePromptControl],
  )

  return (
    <>
      <Button
        disabled={isPending}
        label={_(msg`Add this feed to your feeds`)}
        size="small"
        variant="solid"
        color={savedFeedConfig ? 'secondary' : 'primary'}
        onPress={savedFeedConfig ? onPrompRemoveFeed : toggleSave}
        {...buttonProps}>
        {savedFeedConfig ? (
          <>
            {isPending ? (
              <ButtonIcon size="md" icon={Loader} />
            ) : (
              !text && <ButtonIcon size="md" icon={TrashIcon} />
            )}
            {text && (
              <ButtonText>
                <Trans>Unpin Feed</Trans>
              </ButtonText>
            )}
          </>
        ) : (
          <>
            <ButtonIcon size="md" icon={isPending ? Loader : PinIcon} />
            {text && (
              <ButtonText>
                <Trans>Pin Feed</Trans>
              </ButtonText>
            )}
          </>
        )}
      </Button>

      <Prompt.Basic
        control={removePromptControl}
        title={_(msg`Remove from your feeds?`)}
        description={_(
          msg`Are you sure you want to remove this from your feeds?`,
        )}
        onConfirm={toggleSave}
        confirmButtonCta={_(msg`Remove`)}
        confirmButtonColor="negative"
      />
    </>
  )
}

export function createProfileFeedHref({
  feed,
}: {
  feed: AppBskyFeedDefs.GeneratorView
}) {
  const urip = new AtUri(feed.uri)
  const handleOrDid = feed.creator.handle || feed.creator.did
  return `/profile/${handleOrDid}/feed/${urip.rkey}`
}