about summary refs log tree commit diff
path: root/src/components/dialogs/MutedWords.tsx
blob: dcdaccea3e31e2d3a0a712795b33e37234e439bf (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
import React from 'react'
import {Keyboard, View} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {AppBskyActorDefs, sanitizeMutedWordValue} from '@atproto/api'

import {
  usePreferencesQuery,
  useUpsertMutedWordsMutation,
  useRemoveMutedWordMutation,
} from '#/state/queries/preferences'
import {isNative} from '#/platform/detection'
import {
  atoms as a,
  useTheme,
  useBreakpoints,
  ViewStyleProp,
  web,
  native,
} from '#/alf'
import {Text} from '#/components/Typography'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import {PlusLarge_Stroke2_Corner0_Rounded as Plus} from '#/components/icons/Plus'
import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
import {Hashtag_Stroke2_Corner0_Rounded as Hashtag} from '#/components/icons/Hashtag'
import {PageText_Stroke2_Corner0_Rounded as PageText} from '#/components/icons/PageText'
import {Divider} from '#/components/Divider'
import {Loader} from '#/components/Loader'
import {logger} from '#/logger'
import * as Dialog from '#/components/Dialog'
import * as Toggle from '#/components/forms/Toggle'
import * as Prompt from '#/components/Prompt'

import {useGlobalDialogsControlContext} from '#/components/dialogs/Context'

export function MutedWordsDialog() {
  const {mutedWordsDialogControl: control} = useGlobalDialogsControlContext()
  return (
    <Dialog.Outer control={control}>
      <Dialog.Handle />
      <MutedWordsInner control={control} />
    </Dialog.Outer>
  )
}

function MutedWordsInner({}: {control: Dialog.DialogOuterProps['control']}) {
  const t = useTheme()
  const {_} = useLingui()
  const {gtMobile} = useBreakpoints()
  const {
    isLoading: isPreferencesLoading,
    data: preferences,
    error: preferencesError,
  } = usePreferencesQuery()
  const {isPending, mutateAsync: addMutedWord} = useUpsertMutedWordsMutation()
  const [field, setField] = React.useState('')
  const [options, setOptions] = React.useState(['content'])
  const [error, setError] = React.useState('')

  const submit = React.useCallback(async () => {
    const sanitizedValue = sanitizeMutedWordValue(field)
    const targets = ['tag', options.includes('content') && 'content'].filter(
      Boolean,
    ) as AppBskyActorDefs.MutedWord['targets']

    if (!sanitizedValue || !targets.length) {
      setField('')
      setError(_(msg`Please enter a valid word, tag, or phrase to mute`))
      return
    }

    try {
      // send raw value and rely on SDK as sanitization source of truth
      await addMutedWord([{value: field, targets}])
      setField('')
    } catch (e: any) {
      logger.error(`Failed to save muted word`, {message: e.message})
      setError(e.message)
    }
  }, [_, field, options, addMutedWord, setField])

  return (
    <Dialog.ScrollableInner label={_(msg`Manage your muted words and tags`)}>
      <View onTouchStart={Keyboard.dismiss}>
        <Text
          style={[a.text_md, a.font_bold, a.pb_sm, t.atoms.text_contrast_high]}>
          <Trans>Add muted words and tags</Trans>
        </Text>
        <Text style={[a.pb_lg, a.leading_snug, t.atoms.text_contrast_medium]}>
          <Trans>
            Posts can be muted based on their text, their tags, or both.
          </Trans>
        </Text>

        <View style={[a.pb_lg]}>
          <Dialog.Input
            autoCorrect={false}
            autoCapitalize="none"
            autoComplete="off"
            label={_(msg`Enter a word or tag`)}
            placeholder={_(msg`Enter a word or tag`)}
            value={field}
            onChangeText={value => {
              if (error) {
                setError('')
              }
              setField(value)
            }}
            onSubmitEditing={submit}
          />

          <Toggle.Group
            label={_(msg`Toggle between muted word options.`)}
            type="radio"
            values={options}
            onChange={setOptions}>
            <View
              style={[
                a.pt_sm,
                a.py_sm,
                a.flex_row,
                a.align_center,
                a.gap_sm,
                a.flex_wrap,
              ]}>
              <Toggle.Item
                label={_(msg`Mute this word in post text and tags`)}
                name="content"
                style={[a.flex_1, !gtMobile && [a.w_full, a.flex_0]]}>
                <TargetToggle>
                  <View style={[a.flex_row, a.align_center, a.gap_sm]}>
                    <Toggle.Radio />
                    <Toggle.Label>
                      <Trans>Mute in text & tags</Trans>
                    </Toggle.Label>
                  </View>
                  <PageText size="sm" />
                </TargetToggle>
              </Toggle.Item>

              <Toggle.Item
                label={_(msg`Mute this word in tags only`)}
                name="tag"
                style={[a.flex_1, !gtMobile && [a.w_full, a.flex_0]]}>
                <TargetToggle>
                  <View style={[a.flex_row, a.align_center, a.gap_sm]}>
                    <Toggle.Radio />
                    <Toggle.Label>
                      <Trans>Mute in tags only</Trans>
                    </Toggle.Label>
                  </View>
                  <Hashtag size="sm" />
                </TargetToggle>
              </Toggle.Item>

              <Button
                disabled={isPending || !field}
                label={_(msg`Add mute word for configured settings`)}
                size="small"
                color="primary"
                variant="solid"
                style={[!gtMobile && [a.w_full, a.flex_0]]}
                onPress={submit}>
                <ButtonText>
                  <Trans>Add</Trans>
                </ButtonText>
                <ButtonIcon icon={isPending ? Loader : Plus} />
              </Button>
            </View>
          </Toggle.Group>

          {error && (
            <View
              style={[
                a.mb_lg,
                a.flex_row,
                a.rounded_sm,
                a.p_md,
                a.mb_xs,
                t.atoms.bg_contrast_25,
                {
                  backgroundColor: t.palette.negative_400,
                },
              ]}>
              <Text
                style={[
                  a.italic,
                  {color: t.palette.white},
                  native({marginTop: 2}),
                ]}>
                {error}
              </Text>
            </View>
          )}

          <Text
            style={[
              a.pt_xs,
              a.text_sm,
              a.italic,
              a.leading_snug,
              t.atoms.text_contrast_medium,
            ]}>
            <Trans>
              We recommend avoiding common words that appear in many posts,
              since it can result in no posts being shown.
            </Trans>
          </Text>
        </View>

        <Divider />

        <View style={[a.pt_2xl]}>
          <Text
            style={[
              a.text_md,
              a.font_bold,
              a.pb_md,
              t.atoms.text_contrast_high,
            ]}>
            <Trans>Your muted words</Trans>
          </Text>

          {isPreferencesLoading ? (
            <Loader />
          ) : preferencesError || !preferences ? (
            <View
              style={[a.py_md, a.px_lg, a.rounded_md, t.atoms.bg_contrast_25]}>
              <Text style={[a.italic, t.atoms.text_contrast_high]}>
                <Trans>
                  We're sorry, but we weren't able to load your muted words at
                  this time. Please try again.
                </Trans>
              </Text>
            </View>
          ) : preferences.mutedWords.length ? (
            [...preferences.mutedWords]
              .reverse()
              .map((word, i) => (
                <MutedWordRow
                  key={word.value + i}
                  word={word}
                  style={[i % 2 === 0 && t.atoms.bg_contrast_25]}
                />
              ))
          ) : (
            <View
              style={[a.py_md, a.px_lg, a.rounded_md, t.atoms.bg_contrast_25]}>
              <Text style={[a.italic, t.atoms.text_contrast_high]}>
                <Trans>You haven't muted any words or tags yet</Trans>
              </Text>
            </View>
          )}
        </View>

        {isNative && <View style={{height: 20}} />}
      </View>

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

function MutedWordRow({
  style,
  word,
}: ViewStyleProp & {word: AppBskyActorDefs.MutedWord}) {
  const t = useTheme()
  const {_} = useLingui()
  const {isPending, mutateAsync: removeMutedWord} = useRemoveMutedWordMutation()
  const control = Prompt.usePromptControl()

  const remove = React.useCallback(async () => {
    control.close()
    removeMutedWord(word)
  }, [removeMutedWord, word, control])

  return (
    <>
      <Prompt.Basic
        control={control}
        title={_(msg`Are you sure?`)}
        description={_(
          msg`This will delete ${word.value} from your muted words. You can always add it back later.`,
        )}
        onConfirm={remove}
        confirmButtonCta={_(msg`Remove`)}
        confirmButtonColor="negative"
      />

      <View
        style={[
          a.py_md,
          a.px_lg,
          a.flex_row,
          a.align_center,
          a.justify_between,
          a.rounded_md,
          a.gap_md,
          style,
        ]}>
        <Text
          style={[
            a.flex_1,
            a.leading_snug,
            a.w_full,
            a.font_bold,
            t.atoms.text_contrast_high,
            web({
              overflowWrap: 'break-word',
              wordBreak: 'break-word',
            }),
          ]}>
          {word.value}
        </Text>

        <View style={[a.flex_row, a.align_center, a.justify_end, a.gap_sm]}>
          {word.targets.map(target => (
            <View
              key={target}
              style={[a.py_xs, a.px_sm, a.rounded_sm, t.atoms.bg_contrast_100]}>
              <Text
                style={[a.text_xs, a.font_bold, t.atoms.text_contrast_medium]}>
                {target === 'content' ? _(msg`text`) : _(msg`tag`)}
              </Text>
            </View>
          ))}

          <Button
            label={_(msg`Remove mute word from your list`)}
            size="tiny"
            shape="round"
            variant="ghost"
            color="secondary"
            onPress={() => control.open()}
            style={[a.ml_sm]}>
            <ButtonIcon icon={isPending ? Loader : X} />
          </Button>
        </View>
      </View>
    </>
  )
}

function TargetToggle({children}: React.PropsWithChildren<{}>) {
  const t = useTheme()
  const ctx = Toggle.useItemContext()
  const {gtMobile} = useBreakpoints()
  return (
    <View
      style={[
        a.flex_row,
        a.align_center,
        a.justify_between,
        a.gap_xs,
        a.flex_1,
        a.py_sm,
        a.px_sm,
        gtMobile && a.px_md,
        a.rounded_sm,
        t.atoms.bg_contrast_50,
        (ctx.hovered || ctx.focused) && t.atoms.bg_contrast_100,
        ctx.selected && [
          {
            backgroundColor:
              t.name === 'light' ? t.palette.primary_50 : t.palette.primary_975,
          },
        ],
        ctx.disabled && {
          opacity: 0.8,
        },
      ]}>
      {children}
    </View>
  )
}