about summary refs log tree commit diff
path: root/src/components/dialogs/PostInteractionSettingsDialog.tsx
blob: 63b640d9fe715738f6e4a76694763a8881ed66ba (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
575
576
import React from 'react'
import {StyleProp, View, ViewStyle} from 'react-native'
import {AppBskyFeedDefs, AppBskyFeedPostgate, AtUri} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query'
import isEqual from 'lodash.isequal'

import {logger} from '#/logger'
import {STALE} from '#/state/queries'
import {useMyListsQuery} from '#/state/queries/my-lists'
import {
  createPostgateQueryKey,
  getPostgateRecord,
  usePostgateQuery,
  useWritePostgateMutation,
} from '#/state/queries/postgate'
import {
  createPostgateRecord,
  embeddingRules,
} from '#/state/queries/postgate/util'
import {
  createThreadgateViewQueryKey,
  getThreadgateView,
  ThreadgateAllowUISetting,
  threadgateViewToAllowUISetting,
  useSetThreadgateAllowMutation,
  useThreadgateViewQuery,
} from '#/state/queries/threadgate'
import {useAgent, useSession} from '#/state/session'
import * as Toast from '#/view/com/util/Toast'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
import {Divider} from '#/components/Divider'
import * as Toggle from '#/components/forms/Toggle'
import {Check_Stroke2_Corner0_Rounded as Check} from '#/components/icons/Check'
import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfo} from '#/components/icons/CircleInfo'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'

export type PostInteractionSettingsFormProps = {
  canSave?: boolean
  onSave: () => void
  isSaving?: boolean

  postgate: AppBskyFeedPostgate.Record
  onChangePostgate: (v: AppBskyFeedPostgate.Record) => void

  threadgateAllowUISettings: ThreadgateAllowUISetting[]
  onChangeThreadgateAllowUISettings: (v: ThreadgateAllowUISetting[]) => void

  replySettingsDisabled?: boolean
}

export function PostInteractionSettingsControlledDialog({
  control,
  ...rest
}: PostInteractionSettingsFormProps & {
  control: Dialog.DialogControlProps
}) {
  const t = useTheme()
  const {_} = useLingui()

  return (
    <Dialog.Outer control={control}>
      <Dialog.Handle />
      <Dialog.ScrollableInner
        label={_(msg`Edit post interaction settings`)}
        style={[{maxWidth: 500}, a.w_full]}>
        <View style={[a.gap_md]}>
          <Header />
          <PostInteractionSettingsForm {...rest} />
          <Text
            style={[
              a.pt_sm,
              a.text_sm,
              a.leading_snug,
              t.atoms.text_contrast_medium,
            ]}>
            <Trans>
              You can set default interaction settings in{' '}
              <Text style={[a.font_bold, t.atoms.text_contrast_medium]}>
                Settings &rarr; Moderation &rarr; Interaction settings
              </Text>
              .
            </Trans>
          </Text>
        </View>
        <Dialog.Close />
      </Dialog.ScrollableInner>
    </Dialog.Outer>
  )
}

export function Header() {
  return (
    <View style={[a.gap_md, a.pb_sm]}>
      <Text style={[a.text_2xl, a.font_bold]}>
        <Trans>Post interaction settings</Trans>
      </Text>
      <Text style={[a.text_md, a.pb_xs]}>
        <Trans>Customize who can interact with this post.</Trans>
      </Text>
      <Divider />
    </View>
  )
}

export type PostInteractionSettingsDialogProps = {
  control: Dialog.DialogControlProps
  /**
   * URI of the post to edit the interaction settings for. Could be a root post
   * or could be a reply.
   */
  postUri: string
  /**
   * The URI of the root post in the thread. Used to determine if the viewer
   * owns the threadgate record and can therefore edit it.
   */
  rootPostUri: string
  /**
   * Optional initial {@link AppBskyFeedDefs.ThreadgateView} to use if we
   * happen to have one before opening the settings dialog.
   */
  initialThreadgateView?: AppBskyFeedDefs.ThreadgateView
}

export function PostInteractionSettingsDialog(
  props: PostInteractionSettingsDialogProps,
) {
  return (
    <Dialog.Outer control={props.control}>
      <Dialog.Handle />
      <PostInteractionSettingsDialogControlledInner {...props} />
    </Dialog.Outer>
  )
}

export function PostInteractionSettingsDialogControlledInner(
  props: PostInteractionSettingsDialogProps,
) {
  const {_} = useLingui()
  const {currentAccount} = useSession()
  const [isSaving, setIsSaving] = React.useState(false)

  const {data: threadgateViewLoaded, isLoading: isLoadingThreadgate} =
    useThreadgateViewQuery({postUri: props.rootPostUri})
  const {data: postgate, isLoading: isLoadingPostgate} = usePostgateQuery({
    postUri: props.postUri,
  })

  const {mutateAsync: writePostgateRecord} = useWritePostgateMutation()
  const {mutateAsync: setThreadgateAllow} = useSetThreadgateAllowMutation()

  const [editedPostgate, setEditedPostgate] =
    React.useState<AppBskyFeedPostgate.Record>()
  const [editedAllowUISettings, setEditedAllowUISettings] =
    React.useState<ThreadgateAllowUISetting[]>()

  const isLoading = isLoadingThreadgate || isLoadingPostgate
  const threadgateView = threadgateViewLoaded || props.initialThreadgateView
  const isThreadgateOwnedByViewer = React.useMemo(() => {
    return currentAccount?.did === new AtUri(props.rootPostUri).host
  }, [props.rootPostUri, currentAccount?.did])

  const postgateValue = React.useMemo(() => {
    return (
      editedPostgate || postgate || createPostgateRecord({post: props.postUri})
    )
  }, [postgate, editedPostgate, props.postUri])
  const allowUIValue = React.useMemo(() => {
    return (
      editedAllowUISettings || threadgateViewToAllowUISetting(threadgateView)
    )
  }, [threadgateView, editedAllowUISettings])

  const onSave = React.useCallback(async () => {
    if (!editedPostgate && !editedAllowUISettings) {
      props.control.close()
      return
    }

    setIsSaving(true)

    try {
      const requests = []

      if (editedPostgate) {
        requests.push(
          writePostgateRecord({
            postUri: props.postUri,
            postgate: editedPostgate,
          }),
        )
      }

      if (editedAllowUISettings && isThreadgateOwnedByViewer) {
        requests.push(
          setThreadgateAllow({
            postUri: props.rootPostUri,
            allow: editedAllowUISettings,
          }),
        )
      }

      await Promise.all(requests)

      props.control.close()
    } catch (e: any) {
      logger.error(`Failed to save post interaction settings`, {
        source: 'PostInteractionSettingsDialogControlledInner',
        safeMessage: e.message,
      })
      Toast.show(
        _(
          msg`There was an issue. Please check your internet connection and try again.`,
        ),
        'xmark',
      )
    } finally {
      setIsSaving(false)
    }
  }, [
    _,
    props.postUri,
    props.rootPostUri,
    props.control,
    editedPostgate,
    editedAllowUISettings,
    setIsSaving,
    writePostgateRecord,
    setThreadgateAllow,
    isThreadgateOwnedByViewer,
  ])

  return (
    <Dialog.ScrollableInner
      label={_(msg`Edit post interaction settings`)}
      style={[{maxWidth: 500}, a.w_full]}>
      <View style={[a.gap_md]}>
        <Header />

        {isLoading ? (
          <View style={[a.flex_1, a.py_4xl, a.align_center, a.justify_center]}>
            <Loader size="xl" />
          </View>
        ) : (
          <PostInteractionSettingsForm
            replySettingsDisabled={!isThreadgateOwnedByViewer}
            isSaving={isSaving}
            onSave={onSave}
            postgate={postgateValue}
            onChangePostgate={setEditedPostgate}
            threadgateAllowUISettings={allowUIValue}
            onChangeThreadgateAllowUISettings={setEditedAllowUISettings}
          />
        )}
      </View>
    </Dialog.ScrollableInner>
  )
}

export function PostInteractionSettingsForm({
  canSave = true,
  onSave,
  isSaving,
  postgate,
  onChangePostgate,
  threadgateAllowUISettings,
  onChangeThreadgateAllowUISettings,
  replySettingsDisabled,
}: PostInteractionSettingsFormProps) {
  const t = useTheme()
  const {_} = useLingui()
  const {data: lists} = useMyListsQuery('curate')
  const [quotesEnabled, setQuotesEnabled] = React.useState(
    !(
      postgate.embeddingRules &&
      postgate.embeddingRules.find(
        v => v.$type === embeddingRules.disableRule.$type,
      )
    ),
  )

  const onPressAudience = (setting: ThreadgateAllowUISetting) => {
    // remove boolean values
    let newSelected: ThreadgateAllowUISetting[] =
      threadgateAllowUISettings.filter(
        v => v.type !== 'nobody' && v.type !== 'everybody',
      )
    // toggle
    const i = newSelected.findIndex(v => isEqual(v, setting))
    if (i === -1) {
      newSelected.push(setting)
    } else {
      newSelected.splice(i, 1)
    }
    if (newSelected.length === 0) {
      newSelected.push({type: 'everybody'})
    }

    onChangeThreadgateAllowUISettings(newSelected)
  }

  const onChangeQuotesEnabled = React.useCallback(
    (enabled: boolean) => {
      setQuotesEnabled(enabled)
      onChangePostgate(
        createPostgateRecord({
          ...postgate,
          embeddingRules: enabled ? [] : [embeddingRules.disableRule],
        }),
      )
    },
    [setQuotesEnabled, postgate, onChangePostgate],
  )

  const noOneCanReply = !!threadgateAllowUISettings.find(
    v => v.type === 'nobody',
  )

  return (
    <View>
      <View style={[a.flex_1, a.gap_md]}>
        <View style={[a.gap_lg]}>
          <View style={[a.gap_sm]}>
            <Text style={[a.font_bold, a.text_lg]}>
              <Trans>Quote settings</Trans>
            </Text>

            <Toggle.Item
              name="quoteposts"
              type="checkbox"
              label={
                quotesEnabled
                  ? _(msg`Click to disable quote posts of this post.`)
                  : _(msg`Click to enable quote posts of this post.`)
              }
              value={quotesEnabled}
              onChange={onChangeQuotesEnabled}
              style={[a.justify_between, a.pt_xs]}>
              <Text style={[t.atoms.text_contrast_medium]}>
                <Trans>Allow quote posts</Trans>
              </Text>
              <Toggle.Switch />
            </Toggle.Item>
          </View>

          <Divider />

          {replySettingsDisabled && (
            <View
              style={[
                a.px_md,
                a.py_sm,
                a.rounded_sm,
                a.flex_row,
                a.align_center,
                a.gap_sm,
                t.atoms.bg_contrast_25,
              ]}>
              <CircleInfo fill={t.atoms.text_contrast_low.color} />
              <Text
                style={[
                  a.flex_1,
                  a.leading_snug,
                  t.atoms.text_contrast_medium,
                ]}>
                <Trans>
                  Reply settings are chosen by the author of the thread
                </Trans>
              </Text>
            </View>
          )}

          <View
            style={[
              a.gap_sm,
              {
                opacity: replySettingsDisabled ? 0.3 : 1,
              },
            ]}>
            <Text style={[a.font_bold, a.text_lg]}>
              <Trans>Reply settings</Trans>
            </Text>

            <Text style={[a.pt_sm, t.atoms.text_contrast_medium]}>
              <Trans>Allow replies from:</Trans>
            </Text>

            <View style={[a.flex_row, a.gap_sm]}>
              <Selectable
                label={_(msg`Everybody`)}
                isSelected={
                  !!threadgateAllowUISettings.find(v => v.type === 'everybody')
                }
                onPress={() =>
                  onChangeThreadgateAllowUISettings([{type: 'everybody'}])
                }
                style={{flex: 1}}
                disabled={replySettingsDisabled}
              />
              <Selectable
                label={_(msg`Nobody`)}
                isSelected={noOneCanReply}
                onPress={() =>
                  onChangeThreadgateAllowUISettings([{type: 'nobody'}])
                }
                style={{flex: 1}}
                disabled={replySettingsDisabled}
              />
            </View>

            {!noOneCanReply && (
              <>
                <Text style={[a.pt_sm, t.atoms.text_contrast_medium]}>
                  <Trans>Or combine these options:</Trans>
                </Text>

                <View style={[a.gap_sm]}>
                  <Selectable
                    label={_(msg`Mentioned users`)}
                    isSelected={
                      !!threadgateAllowUISettings.find(
                        v => v.type === 'mention',
                      )
                    }
                    onPress={() => onPressAudience({type: 'mention'})}
                    disabled={replySettingsDisabled}
                  />
                  <Selectable
                    label={_(msg`Users you follow`)}
                    isSelected={
                      !!threadgateAllowUISettings.find(
                        v => v.type === 'following',
                      )
                    }
                    onPress={() => onPressAudience({type: 'following'})}
                    disabled={replySettingsDisabled}
                  />
                  <Selectable
                    label={_(msg`Your followers`)}
                    isSelected={
                      !!threadgateAllowUISettings.find(
                        v => v.type === 'followers',
                      )
                    }
                    onPress={() => onPressAudience({type: 'followers'})}
                    disabled={replySettingsDisabled}
                  />
                  {lists && lists.length > 0
                    ? lists.map(list => (
                        <Selectable
                          key={list.uri}
                          label={_(msg`Users in "${list.name}"`)}
                          isSelected={
                            !!threadgateAllowUISettings.find(
                              v => v.type === 'list' && v.list === list.uri,
                            )
                          }
                          onPress={() =>
                            onPressAudience({type: 'list', list: list.uri})
                          }
                          disabled={replySettingsDisabled}
                        />
                      ))
                    : // No loading states to avoid jumps for the common case (no lists)
                      null}
                </View>
              </>
            )}
          </View>
        </View>
      </View>

      <Button
        disabled={!canSave || isSaving}
        label={_(msg`Save`)}
        onPress={onSave}
        color="primary"
        size="large"
        variant="solid"
        style={a.mt_xl}>
        <ButtonText>{_(msg`Save`)}</ButtonText>
        {isSaving && <ButtonIcon icon={Loader} position="right" />}
      </Button>
    </View>
  )
}

function Selectable({
  label,
  isSelected,
  onPress,
  style,
  disabled,
}: {
  label: string
  isSelected: boolean
  onPress: () => void
  style?: StyleProp<ViewStyle>
  disabled?: boolean
}) {
  const t = useTheme()
  return (
    <Button
      disabled={disabled}
      onPress={onPress}
      label={label}
      accessibilityRole="checkbox"
      aria-checked={isSelected}
      accessibilityState={{
        checked: isSelected,
      }}
      style={a.flex_1}>
      {({hovered, focused}) => (
        <View
          style={[
            a.flex_1,
            a.flex_row,
            a.align_center,
            a.justify_between,
            a.rounded_sm,
            a.p_md,
            {minHeight: 40}, // for consistency with checkmark icon visible or not
            t.atoms.bg_contrast_50,
            (hovered || focused) && t.atoms.bg_contrast_100,
            isSelected && {
              backgroundColor: t.palette.primary_100,
            },
            style,
          ]}>
          <Text style={[a.text_sm, isSelected && a.font_bold]}>{label}</Text>
          {isSelected ? (
            <Check size="sm" fill={t.palette.primary_500} />
          ) : (
            <View />
          )}
        </View>
      )}
    </Button>
  )
}

export function usePrefetchPostInteractionSettings({
  postUri,
  rootPostUri,
}: {
  postUri: string
  rootPostUri: string
}) {
  const queryClient = useQueryClient()
  const agent = useAgent()

  return React.useCallback(async () => {
    try {
      await Promise.all([
        queryClient.prefetchQuery({
          queryKey: createPostgateQueryKey(postUri),
          queryFn: () => getPostgateRecord({agent, postUri}),
          staleTime: STALE.SECONDS.THIRTY,
        }),
        queryClient.prefetchQuery({
          queryKey: createThreadgateViewQueryKey(rootPostUri),
          queryFn: () => getThreadgateView({agent, postUri: rootPostUri}),
          staleTime: STALE.SECONDS.THIRTY,
        }),
      ])
    } catch (e: any) {
      logger.error(`Failed to prefetch post interaction settings`, {
        safeMessage: e.message,
      })
    }
  }, [queryClient, agent, postUri, rootPostUri])
}