about summary refs log tree commit diff
path: root/src/components/dialogs/nudges/TenMillion/index.tsx
blob: e110ed1ffb516e2426828aeea46a75981df7b3b2 (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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import React from 'react'
import {View} from 'react-native'
import ViewShot from 'react-native-view-shot'
import {Image} from 'expo-image'
import {moderateProfile} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'

import {networkRetry} from '#/lib/async/retry'
import {getCanvas} from '#/lib/canvas'
import {shareUrl} from '#/lib/sharing'
import {sanitizeDisplayName} from '#/lib/strings/display-names'
import {sanitizeHandle} from '#/lib/strings/handles'
import {isNative} from '#/platform/detection'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useProfileQuery} from '#/state/queries/profile'
import {useAgent, useSession} from '#/state/session'
import {useComposerControls} from 'state/shell'
import {formatCount} from '#/view/com/util/numeric/format'
// import {UserAvatar} from '#/view/com/util/UserAvatar'
import {Logomark} from '#/view/icons/Logomark'
import {
  atoms as a,
  ThemeProvider,
  tokens,
  useBreakpoints,
  useTheme,
} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
import {useContext} from '#/components/dialogs/nudges'
import {OnePercent} from '#/components/dialogs/nudges/TenMillion/icons/OnePercent'
import {PointOnePercent} from '#/components/dialogs/nudges/TenMillion/icons/PointOnePercent'
import {TenPercent} from '#/components/dialogs/nudges/TenMillion/icons/TenPercent'
import {Divider} from '#/components/Divider'
import {GradientFill} from '#/components/GradientFill'
import {ArrowOutOfBox_Stroke2_Corner0_Rounded as Share} from '#/components/icons/ArrowOutOfBox'
import {Download_Stroke2_Corner0_Rounded as Download} from '#/components/icons/Download'
import {Image_Stroke2_Corner0_Rounded as ImageIcon} from '#/components/icons/Image'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
// import {TwentyFivePercent} from '#/components/dialogs/nudges/TenMillion/icons/TwentyFivePercent'

const DEBUG = false
const RATIO = 8 / 10
const WIDTH = 2000
const HEIGHT = WIDTH * RATIO

function getFontSize(count: number) {
  const length = count.toString().length
  if (length < 7) {
    return 80
  } else if (length < 5) {
    return 100
  } else {
    return 70
  }
}

function getPercentBadge(percent: number) {
  if (percent <= 0.001) {
    return PointOnePercent
  } else if (percent <= 0.01) {
    return OnePercent
  } else if (percent <= 0.1) {
    return TenPercent
  }
  // else if (percent <= 0.25) {
  //   return TwentyFivePercent
  // }
  return null
}

function Frame({children}: {children: React.ReactNode}) {
  return (
    <View
      style={[
        a.relative,
        a.w_full,
        a.overflow_hidden,
        {
          paddingTop: '80%',
        },
      ]}>
      {children}
    </View>
  )
}

export function TenMillion() {
  const {hasSession} = useSession()
  return hasSession ? <TenMillionInner /> : null
}

export function TenMillionInner() {
  const t = useTheme()
  const lightTheme = useTheme('light')
  const {_, i18n} = useLingui()
  const {controls} = useContext()
  const {gtMobile} = useBreakpoints()
  const {openComposer} = useComposerControls()
  const {currentAccount} = useSession()
  const {isLoading: isProfileLoading, data: profile} = useProfileQuery({
    did: currentAccount!.did,
  })
  const moderationOpts = useModerationOpts()
  const moderation = React.useMemo(() => {
    return profile && moderationOpts
      ? moderateProfile(profile, moderationOpts)
      : undefined
  }, [profile, moderationOpts])
  const [uri, setUri] = React.useState<string | null>(null)
  const [userNumber, setUserNumber] = React.useState<number>(0)
  const [error, setError] = React.useState('')

  const isLoadingData =
    isProfileLoading || !moderation || !profile || !userNumber
  const isLoadingImage = !uri

  const percent = userNumber / 10_000_000
  const Badge = getPercentBadge(percent)

  const agent = useAgent()
  React.useEffect(() => {
    async function fetchUserNumber() {
      if (agent.session?.accessJwt) {
        const res = await fetch(
          `https://bsky.social/xrpc/com.atproto.temp.getSignupNumber`,
          {
            headers: {
              Authorization: `Bearer ${agent.session.accessJwt}`,
            },
          },
        )

        if (!res.ok) {
          throw new Error('Network request failed')
        }

        const data = await res.json()

        if (data.number) {
          setUserNumber(data.number)
        }
      }
    }

    networkRetry(3, fetchUserNumber).catch(() => {
      setError(
        _(
          msg`Oh no! We couldn't fetch your user number. Rest assured, we're glad you're here ❤️`,
        ),
      )
    })
  }, [
    _,
    agent.session?.accessJwt,
    setUserNumber,
    controls.tenMillion,
    setError,
  ])

  const sharePost = () => {
    if (uri) {
      controls.tenMillion.close(() => {
        setTimeout(() => {
          openComposer({
            text: '10 milly, babyyy',
            imageUris: [
              {
                uri,
                width: WIDTH,
                height: HEIGHT,
              },
            ],
          })
        }, 1e3)
      })
    }
  }

  const onNativeShare = () => {
    if (uri) {
      controls.tenMillion.close(() => {
        shareUrl(uri)
      })
    }
  }

  const download = async () => {
    if (uri) {
      const canvas = await getCanvas(uri)
      const imgHref = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream')
      const link = document.createElement('a')
      link.setAttribute('download', `Bluesky 10M Users.png`)
      link.setAttribute('href', imgHref)
      link.click()
    }
  }

  const imageRef = React.useRef<ViewShot>(null)
  // const captureInProgress = React.useRef(false)
  // const [cavasRelayout, setCanvasRelayout] = React.useState('key')
  // const onCanvasReady = async () => {
  //   if (
  //     imageRef.current &&
  //     imageRef.current.capture &&
  //     !captureInProgress.current
  //   ) {
  //     captureInProgress.current = true
  //     setCanvasRelayout('updated')
  //   }
  // }
  const onCanvasLayout = async () => {
    if (
      imageRef.current &&
      imageRef.current.capture // &&
      // cavasRelayout === 'updated'
    ) {
      const uri = await imageRef.current.capture()
      setUri(uri)
    }
  }

  const canvas = isLoadingData ? null : (
    <View
      style={[
        a.absolute,
        a.overflow_hidden,
        DEBUG
          ? {
              width: 600,
              height: 600 * RATIO,
            }
          : {
              width: 1,
              height: 1,
            },
      ]}>
      <View style={{width: 600}}>
        <ThemeProvider theme="light">
          <Frame>
            <ViewShot
              ref={imageRef}
              options={{width: WIDTH, height: HEIGHT}}
              style={[a.absolute, a.inset_0]}>
              <View
                // key={cavasRelayout}
                onLayout={onCanvasLayout}
                style={[
                  a.absolute,
                  a.inset_0,
                  a.align_center,
                  a.justify_center,
                  {
                    top: -1,
                    bottom: -1,
                    left: -1,
                    right: -1,
                    paddingVertical: 48,
                    paddingHorizontal: 48,
                  },
                ]}>
                <GradientFill gradient={tokens.gradients.bonfire} />

                <View
                  style={[
                    a.flex_1,
                    a.w_full,
                    a.align_center,
                    a.justify_center,
                    a.rounded_md,
                    {
                      backgroundColor: 'white',
                      shadowRadius: 32,
                      shadowOpacity: 0.1,
                      elevation: 24,
                      shadowColor: tokens.gradients.bonfire.values[0][1],
                    },
                  ]}>
                  <View
                    style={[
                      a.absolute,
                      a.px_xl,
                      a.py_xl,
                      {
                        top: 0,
                        left: 0,
                      },
                    ]}>
                    <Logomark fill={t.palette.primary_500} width={36} />
                  </View>

                  {/* Centered content */}
                  <View
                    style={[
                      {
                        paddingBottom: isNative ? 0 : 24,
                      },
                    ]}>
                    <Text
                      style={[
                        a.text_md,
                        a.font_bold,
                        a.text_center,
                        a.pb_sm,
                        lightTheme.atoms.text_contrast_medium,
                      ]}>
                      <Trans>
                        Celebrating {formatCount(i18n, 10000000)} users
                      </Trans>{' '}
                      🎉
                    </Text>
                    <View style={[a.flex_row, a.align_start]}>
                      <Text
                        style={[
                          a.absolute,
                          {
                            color: t.palette.primary_500,
                            fontSize: 32,
                            fontWeight: '900',
                            width: 32,
                            top: isNative ? -10 : 0,
                            left: 0,
                            transform: [
                              {
                                translateX: -16,
                              },
                            ],
                          },
                        ]}>
                        #
                      </Text>
                      <Text
                        style={[
                          a.relative,
                          a.text_center,
                          {
                            fontStyle: 'italic',
                            fontSize: getFontSize(userNumber),
                            lineHeight: getFontSize(userNumber),
                            fontWeight: '900',
                            letterSpacing: -2,
                          },
                        ]}>
                        {i18n.number(userNumber)}
                      </Text>
                    </View>

                    {Badge && (
                      <View
                        style={[
                          a.absolute,
                          {
                            width: 64,
                            height: 64,
                            top: isNative ? 75 : 85,
                            right: '5%',
                            transform: [
                              {
                                rotate: '8deg',
                              },
                            ],
                          },
                        ]}>
                        <Badge fill={t.palette.primary_500} />
                      </View>
                    )}
                  </View>
                  {/* End centered content */}

                  <View
                    style={[
                      a.absolute,
                      a.px_xl,
                      a.py_xl,
                      {
                        bottom: 0,
                        left: 0,
                        right: 0,
                      },
                    ]}>
                    <View style={[a.flex_row, a.align_center, a.gap_sm]}>
                      {/*
                      <UserAvatar
                        size={36}
                        avatar={profile.avatar}
                        moderation={moderation.ui('avatar')}
                        onLoad={onCanvasReady}
                      />
                        */}
                      <View style={[a.gap_2xs, a.flex_1]}>
                        <Text style={[a.text_sm, a.font_bold, a.leading_tight]}>
                          {sanitizeDisplayName(
                            profile.displayName ||
                              sanitizeHandle(profile.handle),
                            moderation.ui('displayName'),
                          )}
                        </Text>
                        <View style={[a.flex_row, a.justify_between]}>
                          <Text
                            style={[
                              a.text_sm,
                              a.font_semibold,
                              ,
                              a.leading_tight,
                              lightTheme.atoms.text_contrast_medium,
                            ]}>
                            {sanitizeHandle(profile.handle, '@')}
                          </Text>

                          {profile.createdAt && (
                            <Text
                              style={[
                                a.text_sm,
                                a.font_semibold,
                                ,
                                a.leading_tight,
                                lightTheme.atoms.text_contrast_low,
                              ]}>
                              <Trans>
                                Joined{' '}
                                {i18n.date(profile.createdAt, {
                                  dateStyle: 'long',
                                })}
                              </Trans>
                            </Text>
                          )}
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            </ViewShot>
          </Frame>
        </ThemeProvider>
      </View>
    </View>
  )

  return (
    <Dialog.Outer control={controls.tenMillion}>
      <Dialog.ScrollableInner
        label={_(msg`Ten Million`)}
        style={[
          {
            padding: 0,
            paddingTop: 0,
          },
        ]}>
        <View
          style={[
            a.rounded_md,
            a.overflow_hidden,
            isNative && {
              borderTopLeftRadius: 40,
              borderTopRightRadius: 40,
            },
          ]}>
          <Frame>
            <View
              style={[a.absolute, a.inset_0, a.align_center, a.justify_center]}>
              <GradientFill gradient={tokens.gradients.bonfire} />
              {error ? (
                <View>
                  <Text
                    style={[
                      a.text_md,
                      a.leading_snug,
                      a.text_center,
                      a.pb_md,
                      {
                        maxWidth: 300,
                      },
                    ]}>
                    (╯°□°)╯︵ ┻━┻
                  </Text>
                  <Text
                    style={[
                      a.text_xl,
                      a.font_bold,
                      a.leading_snug,
                      a.text_center,
                      {
                        maxWidth: 300,
                      },
                    ]}>
                    {error}
                  </Text>
                </View>
              ) : isLoadingData || isLoadingImage ? (
                <Loader size="xl" fill="white" />
              ) : (
                <Image
                  accessibilityIgnoresInvertColors
                  source={{uri}}
                  style={[a.w_full, a.h_full]}
                />
              )}
            </View>
          </Frame>

          {canvas}

          <View style={[gtMobile ? a.p_2xl : a.p_xl]}>
            <Text
              style={[
                a.text_5xl,
                a.leading_tight,
                a.pb_lg,
                {
                  fontWeight: '900',
                },
              ]}>
              Thanks for being an early part of Bluesky.
            </Text>

            <Text style={[a.leading_snug, a.text_lg, a.pb_xl]}>
              <Trans>
                We're rebuilding the social internet together. Congratulations,
                we're glad you're here.
              </Trans>{' '}
            </Text>

            <Divider />

            <View
              style={[
                a.flex_row,
                a.align_center,
                a.justify_end,
                a.gap_md,
                a.pt_xl,
              ]}>
              <Text style={[a.text_md, a.italic, t.atoms.text_contrast_medium]}>
                Brag a little!
              </Text>

              <Button
                disabled={isLoadingImage}
                label={
                  isNative
                    ? _(msg`Share image externally`)
                    : _(msg`Download image`)
                }
                size="large"
                variant="solid"
                color="secondary"
                shape="square"
                onPress={isNative ? onNativeShare : download}>
                <ButtonIcon icon={isNative ? Share : Download} />
              </Button>
              <Button
                disabled={isLoadingImage}
                label={_(msg`Share image in post`)}
                size="large"
                variant="solid"
                color="primary"
                onPress={sharePost}>
                <ButtonText>{_(msg`Share`)}</ButtonText>
                <ButtonIcon position="right" icon={ImageIcon} />
              </Button>
            </View>
          </View>
        </View>

        <Dialog.Close />
      </Dialog.ScrollableInner>
    </Dialog.Outer>
  )
}