Add first round of labeling tools (#467)

* Rework notifications to sync locally in full and give users better control

* Fix positioning of load more btn on web

* Improve behavior of load more notifications btn

* Fix to post rendering

* Fix notification fetch abort condition

* Add start of post-hiding by labels

* Create a standard postcontainer and improve show/hide UI on posts

* Add content hiding to expanded post form

* Improve label rendering to give more context to users when appropriate

* Fix rendering bug

* Add user/profile labeling

* Implement content filtering preferences

* Filter notifications by content prefs

* Update test-pds config

* Bump deps
zio/stable
Paul Frazee 2023-04-12 18:26:38 -07:00 committed by GitHub
parent a20d034ba5
commit 2fed6c4021
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 1292 additions and 530 deletions

View File

@ -79,6 +79,8 @@ export async function createServer(
maxSubscriptionBuffer: 200, maxSubscriptionBuffer: 200,
repoBackfillLimitMs: HOUR, repoBackfillLimitMs: HOUR,
userInviteInterval: 1, userInviteInterval: 1,
labelerDid: 'did:example:labeler',
labelerKeywords: {},
}) })
const db = const db =

View File

@ -21,7 +21,7 @@
"e2e:run": "detox test --configuration ios.sim.debug --take-screenshots all" "e2e:run": "detox test --configuration ios.sim.debug --take-screenshots all"
}, },
"dependencies": { "dependencies": {
"@atproto/api": "0.2.5", "@atproto/api": "0.2.6",
"@bam.tech/react-native-image-resizer": "^3.0.4", "@bam.tech/react-native-image-resizer": "^3.0.4",
"@expo/webpack-config": "^18.0.1", "@expo/webpack-config": "^18.0.1",
"@fortawesome/fontawesome-svg-core": "^6.1.1", "@fortawesome/fontawesome-svg-core": "^6.1.1",
@ -123,7 +123,7 @@
"zod": "^3.20.2" "zod": "^3.20.2"
}, },
"devDependencies": { "devDependencies": {
"@atproto/pds": "^0.1.3", "@atproto/pds": "^0.1.4",
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",
"@babel/preset-env": "^7.20.0", "@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.20.0", "@babel/runtime": "^7.20.0",

View File

@ -0,0 +1,50 @@
import {LabelPreferencesModel} from 'state/models/ui/preferences'
export interface LabelValGroup {
id: keyof LabelPreferencesModel | 'illegal' | 'unknown'
title: string
values: string[]
}
export const ILLEGAL_LABEL_GROUP: LabelValGroup = {
id: 'illegal',
title: 'Illegal Content',
values: ['csam', 'dmca-violation', 'nudity-nonconsentual'],
}
export const UNKNOWN_LABEL_GROUP: LabelValGroup = {
id: 'unknown',
title: 'Unknown Label',
values: [],
}
export const CONFIGURABLE_LABEL_GROUPS: Record<
keyof LabelPreferencesModel,
LabelValGroup
> = {
nsfw: {
id: 'nsfw',
title: 'Sexual Content',
values: ['porn', 'nudity', 'sexual'],
},
gore: {
id: 'gore',
title: 'Violent / Bloody',
values: ['gore', 'self-harm', 'torture'],
},
hate: {
id: 'hate',
title: 'Political Hate-Groups',
values: ['icon-kkk', 'icon-nazi', 'icon-confederate'],
},
spam: {
id: 'spam',
title: 'Spam',
values: ['spam'],
},
impersonation: {
id: 'impersonation',
title: 'Impersonation',
values: ['impersonation'],
},
}

View File

@ -0,0 +1,19 @@
import {
LabelValGroup,
CONFIGURABLE_LABEL_GROUPS,
ILLEGAL_LABEL_GROUP,
UNKNOWN_LABEL_GROUP,
} from './const'
export function getLabelValueGroup(labelVal: string): LabelValGroup {
let id: keyof typeof CONFIGURABLE_LABEL_GROUPS
for (id in CONFIGURABLE_LABEL_GROUPS) {
if (ILLEGAL_LABEL_GROUP.values.includes(labelVal)) {
return ILLEGAL_LABEL_GROUP
}
if (CONFIGURABLE_LABEL_GROUPS[id].values.includes(labelVal)) {
return CONFIGURABLE_LABEL_GROUPS[id]
}
}
return UNKNOWN_LABEL_GROUP
}

View File

@ -1,6 +1,7 @@
import {makeAutoObservable, runInAction} from 'mobx' import {makeAutoObservable, runInAction} from 'mobx'
import {PickedMedia} from 'lib/media/picker' import {PickedMedia} from 'lib/media/picker'
import { import {
ComAtprotoLabelDefs,
AppBskyActorGetProfile as GetProfile, AppBskyActorGetProfile as GetProfile,
AppBskyActorProfile, AppBskyActorProfile,
RichText, RichText,
@ -41,6 +42,7 @@ export class ProfileModel {
followersCount: number = 0 followersCount: number = 0
followsCount: number = 0 followsCount: number = 0
postsCount: number = 0 postsCount: number = 0
labels?: ComAtprotoLabelDefs.Label[] = undefined
viewer = new ProfileViewerModel() viewer = new ProfileViewerModel()
// added data // added data
@ -210,6 +212,7 @@ export class ProfileModel {
this.followersCount = res.data.followersCount || 0 this.followersCount = res.data.followersCount || 0
this.followsCount = res.data.followsCount || 0 this.followsCount = res.data.followsCount || 0
this.postsCount = res.data.postsCount || 0 this.postsCount = res.data.postsCount || 0
this.labels = res.data.labels
if (res.data.viewer) { if (res.data.viewer) {
Object.assign(this.viewer, res.data.viewer) Object.assign(this.viewer, res.data.viewer)
this.rootStore.me.follows.hydrate(this.did, res.data.viewer.following) this.rootStore.me.follows.hydrate(this.did, res.data.viewer.following)

View File

@ -6,6 +6,7 @@ import {
AppBskyFeedRepost, AppBskyFeedRepost,
AppBskyFeedLike, AppBskyFeedLike,
AppBskyGraphFollow, AppBskyGraphFollow,
ComAtprotoLabelDefs,
} from '@atproto/api' } from '@atproto/api'
import AwaitLock from 'await-lock' import AwaitLock from 'await-lock'
import {bundleAsync} from 'lib/async/bundle' import {bundleAsync} from 'lib/async/bundle'
@ -20,6 +21,8 @@ const MS_2DAY = MS_1HR * 48
let _idCounter = 0 let _idCounter = 0
type CondFn = (notif: ListNotifications.Notification) => boolean
export interface GroupedNotification extends ListNotifications.Notification { export interface GroupedNotification extends ListNotifications.Notification {
additional?: ListNotifications.Notification[] additional?: ListNotifications.Notification[]
} }
@ -47,6 +50,7 @@ export class NotificationsFeedItemModel {
record?: SupportedRecord record?: SupportedRecord
isRead: boolean = false isRead: boolean = false
indexedAt: string = '' indexedAt: string = ''
labels?: ComAtprotoLabelDefs.Label[]
additional?: NotificationsFeedItemModel[] additional?: NotificationsFeedItemModel[]
// additional data // additional data
@ -71,6 +75,7 @@ export class NotificationsFeedItemModel {
this.record = this.toSupportedRecord(v.record) this.record = this.toSupportedRecord(v.record)
this.isRead = v.isRead this.isRead = v.isRead
this.indexedAt = v.indexedAt this.indexedAt = v.indexedAt
this.labels = v.labels
if (v.additional?.length) { if (v.additional?.length) {
this.additional = [] this.additional = []
for (const add of v.additional) { for (const add of v.additional) {
@ -83,6 +88,27 @@ export class NotificationsFeedItemModel {
} }
} }
get numUnreadInGroup(): number {
if (this.additional?.length) {
return (
this.additional.reduce(
(acc, notif) => acc + notif.numUnreadInGroup,
0,
) + (this.isRead ? 0 : 1)
)
}
return this.isRead ? 0 : 1
}
markGroupRead() {
if (this.additional?.length) {
for (const notif of this.additional) {
notif.markGroupRead()
}
}
this.isRead = true
}
get isLike() { get isLike() {
return this.reason === 'like' return this.reason === 'like'
} }
@ -192,7 +218,6 @@ export class NotificationsFeedModel {
hasLoaded = false hasLoaded = false
error = '' error = ''
loadMoreError = '' loadMoreError = ''
params: ListNotifications.QueryParams
hasMore = true hasMore = true
loadMoreCursor?: string loadMoreCursor?: string
@ -201,25 +226,21 @@ export class NotificationsFeedModel {
// data // data
notifications: NotificationsFeedItemModel[] = [] notifications: NotificationsFeedItemModel[] = []
queuedNotifications: undefined | ListNotifications.Notification[] = undefined
unreadCount = 0 unreadCount = 0
// this is used to help trigger push notifications // this is used to help trigger push notifications
mostRecentNotificationUri: string | undefined mostRecentNotificationUri: string | undefined
constructor( constructor(public rootStore: RootStoreModel) {
public rootStore: RootStoreModel,
params: ListNotifications.QueryParams,
) {
makeAutoObservable( makeAutoObservable(
this, this,
{ {
rootStore: false, rootStore: false,
params: false,
mostRecentNotificationUri: false, mostRecentNotificationUri: false,
}, },
{autoBind: true}, {autoBind: true},
) )
this.params = params
} }
get hasContent() { get hasContent() {
@ -234,6 +255,10 @@ export class NotificationsFeedModel {
return this.hasLoaded && !this.hasContent return this.hasLoaded && !this.hasContent
} }
get hasNewLatest() {
return this.queuedNotifications && this.queuedNotifications?.length > 0
}
// public api // public api
// = // =
@ -258,19 +283,17 @@ export class NotificationsFeedModel {
* Load for first render * Load for first render
*/ */
setup = bundleAsync(async (isRefreshing: boolean = false) => { setup = bundleAsync(async (isRefreshing: boolean = false) => {
this.rootStore.log.debug('NotificationsModel:setup', {isRefreshing}) this.rootStore.log.debug('NotificationsModel:refresh', {isRefreshing})
if (isRefreshing) {
this.isRefreshing = true // set optimistically for UI
}
await this.lock.acquireAsync() await this.lock.acquireAsync()
try { try {
this._xLoading(isRefreshing) this._xLoading(isRefreshing)
try { try {
const params = Object.assign({}, this.params, { const res = await this._fetchUntil(notif => notif.isRead, {
limit: PAGE_SIZE, breakAt: 'page',
}) })
const res = await this.rootStore.agent.listNotifications(params)
await this._replaceAll(res) await this._replaceAll(res)
this._setQueued(undefined)
this._countUnread()
this._xIdle() this._xIdle()
} catch (e: any) { } catch (e: any) {
this._xIdle(e) this._xIdle(e)
@ -284,9 +307,65 @@ export class NotificationsFeedModel {
* Reset and load * Reset and load
*/ */
async refresh() { async refresh() {
this.isRefreshing = true // set optimistically for UI
return this.setup(true) return this.setup(true)
} }
/**
* Sync the next set of notifications to show
* returns true if the number changed
*/
syncQueue = bundleAsync(async () => {
this.rootStore.log.debug('NotificationsModel:syncQueue')
await this.lock.acquireAsync()
try {
const res = await this._fetchUntil(
notif =>
this.notifications.length
? isEq(notif, this.notifications[0])
: notif.isRead,
{breakAt: 'record'},
)
this._setQueued(res.data.notifications)
this._countUnread()
} catch (e) {
this.rootStore.log.error('NotificationsModel:syncQueue failed', {e})
} finally {
this.lock.release()
}
})
/**
*
*/
processQueue = bundleAsync(async () => {
this.rootStore.log.debug('NotificationsModel:processQueue')
if (!this.queuedNotifications) {
return
}
this.isRefreshing = true
await this.lock.acquireAsync()
try {
runInAction(() => {
this.mostRecentNotificationUri = this.queuedNotifications?.[0].uri
})
const itemModels = await this._processNotifications(
this.queuedNotifications,
)
this._setQueued(undefined)
runInAction(() => {
this.notifications = itemModels.concat(this.notifications)
})
} catch (e) {
this.rootStore.log.error('NotificationsModel:processQueue failed', {e})
} finally {
runInAction(() => {
this.isRefreshing = false
})
this.lock.release()
}
})
/** /**
* Load more posts to the end of the notifications * Load more posts to the end of the notifications
*/ */
@ -294,15 +373,14 @@ export class NotificationsFeedModel {
if (!this.hasMore) { if (!this.hasMore) {
return return
} }
this.lock.acquireAsync() await this.lock.acquireAsync()
try { try {
this._xLoading() this._xLoading()
try { try {
const params = Object.assign({}, this.params, { const res = await this.rootStore.agent.listNotifications({
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: this.loadMoreCursor, cursor: this.loadMoreCursor,
}) })
const res = await this.rootStore.agent.listNotifications(params)
await this._appendAll(res) await this._appendAll(res)
this._xIdle() this._xIdle()
} catch (e: any) { } catch (e: any) {
@ -325,101 +403,37 @@ export class NotificationsFeedModel {
return this.loadMore() return this.loadMore()
} }
/** // unread notification in-place
* Load more posts at the start of the notifications
*/
loadLatest = bundleAsync(async () => {
if (this.notifications.length === 0 || this.unreadCount > PAGE_SIZE) {
return this.refresh()
}
this.lock.acquireAsync()
try {
this._xLoading()
try {
const res = await this.rootStore.agent.listNotifications({
limit: PAGE_SIZE,
})
await this._prependAll(res)
this._xIdle()
} catch (e: any) {
this._xIdle() // don't bubble the error to the user
this.rootStore.log.error('NotificationsView: Failed to load latest', {
params: this.params,
e,
})
}
} finally {
this.lock.release()
}
})
/**
* Update content in-place
*/
update = bundleAsync(async () => {
await this.lock.acquireAsync()
try {
if (!this.notifications.length) {
return
}
this._xLoading()
let numToFetch = this.notifications.length
let cursor
try {
do {
const res: ListNotifications.Response =
await this.rootStore.agent.listNotifications({
cursor,
limit: Math.min(numToFetch, 100),
})
if (res.data.notifications.length === 0) {
break // sanity check
}
this._updateAll(res)
numToFetch -= res.data.notifications.length
cursor = res.data.cursor
} while (cursor && numToFetch > 0)
this._xIdle()
} catch (e: any) {
this._xIdle() // don't bubble the error to the user
this.rootStore.log.error('NotificationsView: Failed to update', {
params: this.params,
e,
})
}
} finally {
this.lock.release()
}
})
// unread notification apis
// = // =
async update() {
/** const promises = []
* Get the current number of unread notifications for (const item of this.notifications) {
* returns true if the number changed if (item.additionalPost) {
*/ promises.push(item.additionalPost.update())
loadUnreadCount = bundleAsync(async () => { }
const old = this.unreadCount }
const res = await this.rootStore.agent.countUnreadNotifications() await Promise.all(promises).catch(e => {
runInAction(() => { this.rootStore.log.error(
this.unreadCount = res.data.count 'Uncaught failure during notifications update()',
}) e,
this.rootStore.emitUnreadNotifications(this.unreadCount) )
return this.unreadCount !== old
}) })
}
/** /**
* Update read/unread state * Update read/unread state
*/ */
async markAllRead() { async markAllUnqueuedRead() {
try { try {
this.unreadCount = 0
this.rootStore.emitUnreadNotifications(0)
for (const notif of this.notifications) { for (const notif of this.notifications) {
notif.isRead = true notif.markGroupRead()
}
this._countUnread()
if (this.notifications[0]) {
await this.rootStore.agent.updateSeenNotifications(
this.notifications[0].indexedAt,
)
} }
await this.rootStore.agent.updateSeenNotifications()
} catch (e: any) { } catch (e: any) {
this.rootStore.log.warn('Failed to update notifications read state', e) this.rootStore.log.warn('Failed to update notifications read state', e)
} }
@ -472,6 +486,40 @@ export class NotificationsFeedModel {
// helper functions // helper functions
// = // =
async _fetchUntil(
condFn: CondFn,
{breakAt}: {breakAt: 'page' | 'record'},
): Promise<ListNotifications.Response> {
const accRes: ListNotifications.Response = {
success: true,
headers: {},
data: {cursor: undefined, notifications: []},
}
for (let i = 0; i <= 10; i++) {
const res = await this.rootStore.agent.listNotifications({
limit: PAGE_SIZE,
cursor: accRes.data.cursor,
})
accRes.data.cursor = res.data.cursor
let pageIsDone = false
for (const notif of res.data.notifications) {
if (condFn(notif)) {
if (breakAt === 'record') {
return accRes
} else {
pageIsDone = true
}
}
accRes.data.notifications.push(notif)
}
if (pageIsDone || res.data.notifications.length < PAGE_SIZE) {
return accRes
}
}
return accRes
}
async _replaceAll(res: ListNotifications.Response) { async _replaceAll(res: ListNotifications.Response) {
if (res.data.notifications[0]) { if (res.data.notifications[0]) {
this.mostRecentNotificationUri = res.data.notifications[0].uri this.mostRecentNotificationUri = res.data.notifications[0].uri
@ -482,25 +530,7 @@ export class NotificationsFeedModel {
async _appendAll(res: ListNotifications.Response, replace = false) { async _appendAll(res: ListNotifications.Response, replace = false) {
this.loadMoreCursor = res.data.cursor this.loadMoreCursor = res.data.cursor
this.hasMore = !!this.loadMoreCursor this.hasMore = !!this.loadMoreCursor
const promises = [] const itemModels = await this._processNotifications(res.data.notifications)
const itemModels: NotificationsFeedItemModel[] = []
for (const item of groupNotifications(res.data.notifications)) {
const itemModel = new NotificationsFeedItemModel(
this.rootStore,
`item-${_idCounter++}`,
item,
)
if (itemModel.needsAdditionalData) {
promises.push(itemModel.fetchAdditionalData())
}
itemModels.push(itemModel)
}
await Promise.all(promises).catch(e => {
this.rootStore.log.error(
'Uncaught failure during notifications-view _appendAll()',
e,
)
})
runInAction(() => { runInAction(() => {
if (replace) { if (replace) {
this.notifications = itemModels this.notifications = itemModels
@ -510,16 +540,18 @@ export class NotificationsFeedModel {
}) })
} }
async _prependAll(res: ListNotifications.Response) { async _processNotifications(
items: ListNotifications.Notification[],
): Promise<NotificationsFeedItemModel[]> {
const promises = [] const promises = []
const itemModels: NotificationsFeedItemModel[] = [] const itemModels: NotificationsFeedItemModel[] = []
const dedupedNotifs = res.data.notifications.filter( items = items.filter(item => {
n1 => return (
!this.notifications.find( this.rootStore.preferences.getLabelPreference(item.labels).pref !==
n2 => isEq(n1, n2) || n2.additional?.find(n3 => isEq(n1, n3)), 'hide'
),
) )
for (const item of groupNotifications(dedupedNotifs)) { })
for (const item of groupNotifications(items)) {
const itemModel = new NotificationsFeedItemModel( const itemModel = new NotificationsFeedItemModel(
this.rootStore, this.rootStore,
`item-${_idCounter++}`, `item-${_idCounter++}`,
@ -532,22 +564,27 @@ export class NotificationsFeedModel {
} }
await Promise.all(promises).catch(e => { await Promise.all(promises).catch(e => {
this.rootStore.log.error( this.rootStore.log.error(
'Uncaught failure during notifications-view _prependAll()', 'Uncaught failure during notifications _processNotifications()',
e, e,
) )
}) })
runInAction(() => { return itemModels
this.notifications = itemModels.concat(this.notifications)
})
} }
_updateAll(res: ListNotifications.Response) { _setQueued(queued: undefined | ListNotifications.Notification[]) {
for (const item of res.data.notifications) { this.queuedNotifications = queued
const existingItem = this.notifications.find(item2 => isEq(item, item2))
if (existingItem) {
existingItem.copy(item, true)
} }
_countUnread() {
let unread = 0
for (const notif of this.notifications) {
unread += notif.numUnreadInGroup
} }
if (this.queuedNotifications) {
unread += this.queuedNotifications.length
}
this.unreadCount = unread
this.rootStore.emitUnreadNotifications(unread)
} }
} }

View File

@ -119,7 +119,7 @@ export class MeModel {
await this.fetchProfile() await this.fetchProfile()
await this.fetchInviteCodes() await this.fetchInviteCodes()
} }
await this.notifications.loadUnreadCount() await this.notifications.syncQueue()
} }
async fetchProfile() { async fetchProfile() {

View File

@ -1,11 +1,33 @@
import {makeAutoObservable} from 'mobx' import {makeAutoObservable} from 'mobx'
import {getLocales} from 'expo-localization' import {getLocales} from 'expo-localization'
import {isObj, hasProp} from 'lib/type-guards' import {isObj, hasProp} from 'lib/type-guards'
import {ComAtprotoLabelDefs} from '@atproto/api'
import {getLabelValueGroup} from 'lib/labeling/helpers'
import {
LabelValGroup,
UNKNOWN_LABEL_GROUP,
ILLEGAL_LABEL_GROUP,
} from 'lib/labeling/const'
const deviceLocales = getLocales() const deviceLocales = getLocales()
export type LabelPreference = 'show' | 'warn' | 'hide'
export class LabelPreferencesModel {
nsfw: LabelPreference = 'warn'
gore: LabelPreference = 'hide'
hate: LabelPreference = 'hide'
spam: LabelPreference = 'hide'
impersonation: LabelPreference = 'warn'
constructor() {
makeAutoObservable(this, {}, {autoBind: true})
}
}
export class PreferencesModel { export class PreferencesModel {
_contentLanguages: string[] | undefined _contentLanguages: string[] | undefined
contentLabels = new LabelPreferencesModel()
constructor() { constructor() {
makeAutoObservable(this, {}, {autoBind: true}) makeAutoObservable(this, {}, {autoBind: true})
@ -22,6 +44,7 @@ export class PreferencesModel {
serialize() { serialize() {
return { return {
contentLanguages: this._contentLanguages, contentLanguages: this._contentLanguages,
contentLabels: this.contentLabels,
} }
} }
@ -34,6 +57,46 @@ export class PreferencesModel {
) { ) {
this._contentLanguages = v.contentLanguages this._contentLanguages = v.contentLanguages
} }
if (hasProp(v, 'contentLabels') && typeof v.contentLabels === 'object') {
Object.assign(this.contentLabels, v.contentLabels)
} }
} }
} }
setContentLabelPref(
key: keyof LabelPreferencesModel,
value: LabelPreference,
) {
this.contentLabels[key] = value
}
getLabelPreference(labels: ComAtprotoLabelDefs.Label[] | undefined): {
pref: LabelPreference
desc: LabelValGroup
} {
let res: {pref: LabelPreference; desc: LabelValGroup} = {
pref: 'show',
desc: UNKNOWN_LABEL_GROUP,
}
if (!labels?.length) {
return res
}
for (const label of labels) {
const group = getLabelValueGroup(label.val)
if (group.id === 'illegal') {
return {pref: 'hide', desc: ILLEGAL_LABEL_GROUP}
} else if (group.id === 'unknown') {
continue
}
let pref = this.contentLabels[group.id]
if (pref === 'hide') {
res.pref = 'hide'
res.desc = group
} else if (pref === 'warn' && res.pref === 'show') {
res.pref = 'warn'
res.desc = group
}
}
return res
}
}

View File

@ -65,6 +65,10 @@ export interface InviteCodesModal {
name: 'invite-codes' name: 'invite-codes'
} }
export interface ContentFilteringSettingsModal {
name: 'content-filtering-settings'
}
export type Modal = export type Modal =
| ConfirmModal | ConfirmModal
| EditProfileModal | EditProfileModal
@ -77,6 +81,7 @@ export type Modal =
| ChangeHandleModal | ChangeHandleModal
| WaitlistModal | WaitlistModal
| InviteCodesModal | InviteCodesModal
| ContentFilteringSettingsModal
interface LightboxModel {} interface LightboxModel {}

View File

@ -31,6 +31,7 @@ export const SuggestedFollows = ({
handle={item.handle} handle={item.handle}
displayName={item.displayName} displayName={item.displayName}
avatar={item.avatar} avatar={item.avatar}
labels={item.labels}
noBg noBg
noBorder noBorder
description={ description={

View File

@ -0,0 +1,185 @@
import React from 'react'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import {observer} from 'mobx-react-lite'
import {useStores} from 'state/index'
import {LabelPreference} from 'state/models/ui/preferences'
import {s, colors, gradients} from 'lib/styles'
import {Text} from '../util/text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {CONFIGURABLE_LABEL_GROUPS} from 'lib/labeling/const'
export const snapPoints = [500]
export function Component({}: {}) {
const store = useStores()
const pal = usePalette('default')
const onPressDone = React.useCallback(() => {
store.shell.closeModal()
}, [store])
return (
<View testID="reportPostModal" style={[pal.view, styles.container]}>
<Text style={[pal.text, styles.title]}>Content Filtering</Text>
<ContentLabelPref group="nsfw" />
<ContentLabelPref group="gore" />
<ContentLabelPref group="hate" />
<ContentLabelPref group="spam" />
<ContentLabelPref group="impersonation" />
<View style={s.flex1} />
<TouchableOpacity testID="sendReportBtn" onPress={onPressDone}>
<LinearGradient
colors={[gradients.blueLight.start, gradients.blueLight.end]}
start={{x: 0, y: 0}}
end={{x: 1, y: 1}}
style={[styles.btn]}>
<Text style={[s.white, s.bold, s.f18]}>Done</Text>
</LinearGradient>
</TouchableOpacity>
</View>
)
}
const ContentLabelPref = observer(
({group}: {group: keyof typeof CONFIGURABLE_LABEL_GROUPS}) => {
const store = useStores()
const pal = usePalette('default')
return (
<View style={[styles.contentLabelPref, pal.border]}>
<Text type="md-medium" style={[pal.text]}>
{CONFIGURABLE_LABEL_GROUPS[group].title}
</Text>
<SelectGroup
current={store.preferences.contentLabels[group]}
onChange={v => store.preferences.setContentLabelPref(group, v)}
/>
</View>
)
},
)
function SelectGroup({
current,
onChange,
}: {
current: LabelPreference
onChange: (v: LabelPreference) => void
}) {
return (
<View style={styles.selectableBtns}>
<SelectableBtn
current={current}
value="hide"
label="Hide"
left
onChange={onChange}
/>
<SelectableBtn
current={current}
value="warn"
label="Warn"
onChange={onChange}
/>
<SelectableBtn
current={current}
value="show"
label="Show"
right
onChange={onChange}
/>
</View>
)
}
function SelectableBtn({
current,
value,
label,
left,
right,
onChange,
}: {
current: string
value: LabelPreference
label: string
left?: boolean
right?: boolean
onChange: (v: LabelPreference) => void
}) {
const pal = usePalette('default')
const palPrimary = usePalette('inverted')
return (
<TouchableOpacity
style={[
styles.selectableBtn,
left && styles.selectableBtnLeft,
right && styles.selectableBtnRight,
pal.border,
current === value ? palPrimary.view : pal.view,
]}
onPress={() => onChange(value)}>
<Text style={current === value ? palPrimary.text : pal.text}>
{label}
</Text>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingHorizontal: 10,
paddingBottom: 40,
},
title: {
textAlign: 'center',
fontWeight: 'bold',
fontSize: 24,
marginBottom: 12,
},
description: {
paddingHorizontal: 2,
marginBottom: 10,
},
contentLabelPref: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingTop: 10,
paddingLeft: 4,
marginBottom: 10,
borderTopWidth: 1,
},
selectableBtns: {
flexDirection: 'row',
},
selectableBtn: {
flexDirection: 'row',
justifyContent: 'center',
borderWidth: 1,
borderLeftWidth: 0,
paddingHorizontal: 10,
paddingVertical: 10,
},
selectableBtnLeft: {
borderTopLeftRadius: 8,
borderBottomLeftRadius: 8,
borderLeftWidth: 1,
},
selectableBtnRight: {
borderTopRightRadius: 8,
borderBottomRightRadius: 8,
},
btn: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
borderRadius: 32,
padding: 14,
backgroundColor: colors.gray1,
},
})

View File

@ -1,9 +1,10 @@
import React, {useRef, useEffect} from 'react' import React, {useRef, useEffect} from 'react'
import {View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import BottomSheet from '@gorhom/bottom-sheet' import BottomSheet from '@gorhom/bottom-sheet'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {createCustomBackdrop} from '../util/BottomSheetCustomBackdrop' import {createCustomBackdrop} from '../util/BottomSheetCustomBackdrop'
import {usePalette} from 'lib/hooks/usePalette'
import * as ConfirmModal from './Confirm' import * as ConfirmModal from './Confirm'
import * as EditProfileModal from './EditProfile' import * as EditProfileModal from './EditProfile'
@ -15,8 +16,7 @@ import * as DeleteAccountModal from './DeleteAccount'
import * as ChangeHandleModal from './ChangeHandle' import * as ChangeHandleModal from './ChangeHandle'
import * as WaitlistModal from './Waitlist' import * as WaitlistModal from './Waitlist'
import * as InviteCodesModal from './InviteCodes' import * as InviteCodesModal from './InviteCodes'
import {usePalette} from 'lib/hooks/usePalette' import * as ContentFilteringSettingsModal from './ContentFilteringSettings'
import {StyleSheet} from 'react-native'
const DEFAULT_SNAPPOINTS = ['90%'] const DEFAULT_SNAPPOINTS = ['90%']
@ -77,6 +77,9 @@ export const ModalsContainer = observer(function ModalsContainer() {
} else if (activeModal?.name === 'invite-codes') { } else if (activeModal?.name === 'invite-codes') {
snapPoints = InviteCodesModal.snapPoints snapPoints = InviteCodesModal.snapPoints
element = <InviteCodesModal.Component /> element = <InviteCodesModal.Component />
} else if (activeModal?.name === 'content-filtering-settings') {
snapPoints = ContentFilteringSettingsModal.snapPoints
element = <ContentFilteringSettingsModal.Component />
} else { } else {
return <View /> return <View />
} }

View File

@ -17,6 +17,7 @@ import * as CropImageModal from './crop-image/CropImage.web'
import * as ChangeHandleModal from './ChangeHandle' import * as ChangeHandleModal from './ChangeHandle'
import * as WaitlistModal from './Waitlist' import * as WaitlistModal from './Waitlist'
import * as InviteCodesModal from './InviteCodes' import * as InviteCodesModal from './InviteCodes'
import * as ContentFilteringSettingsModal from './ContentFilteringSettings'
export const ModalsContainer = observer(function ModalsContainer() { export const ModalsContainer = observer(function ModalsContainer() {
const store = useStores() const store = useStores()
@ -75,6 +76,8 @@ function Modal({modal}: {modal: ModalIface}) {
element = <WaitlistModal.Component /> element = <WaitlistModal.Component />
} else if (modal.name === 'invite-codes') { } else if (modal.name === 'invite-codes') {
element = <InviteCodesModal.Component /> element = <InviteCodesModal.Component />
} else if (modal.name === 'content-filtering-settings') {
element = <ContentFilteringSettingsModal.Component />
} else { } else {
return null return null
} }

View File

@ -45,7 +45,6 @@ export const Feed = observer(function Feed({
const onRefresh = React.useCallback(async () => { const onRefresh = React.useCallback(async () => {
try { try {
await view.refresh() await view.refresh()
await view.markAllRead()
} catch (err) { } catch (err) {
view.rootStore.log.error('Failed to refresh notifications feed', err) view.rootStore.log.error('Failed to refresh notifications feed', err)
} }

View File

@ -8,7 +8,7 @@ import {
View, View,
} from 'react-native' } from 'react-native'
import {AppBskyEmbedImages} from '@atproto/api' import {AppBskyEmbedImages} from '@atproto/api'
import {AtUri} from '@atproto/api' import {AtUri, ComAtprotoLabelDefs} from '@atproto/api'
import { import {
FontAwesomeIcon, FontAwesomeIcon,
FontAwesomeIconStyle, FontAwesomeIconStyle,
@ -38,6 +38,7 @@ interface Author {
handle: string handle: string
displayName?: string displayName?: string
avatar?: string avatar?: string
labels?: ComAtprotoLabelDefs.Label[]
} }
export const FeedItem = observer(function FeedItem({ export const FeedItem = observer(function FeedItem({
@ -129,6 +130,7 @@ export const FeedItem = observer(function FeedItem({
handle: item.author.handle, handle: item.author.handle,
displayName: item.author.displayName, displayName: item.author.displayName,
avatar: item.author.avatar, avatar: item.author.avatar,
labels: item.author.labels,
}, },
] ]
if (item.additional?.length) { if (item.additional?.length) {
@ -138,6 +140,7 @@ export const FeedItem = observer(function FeedItem({
handle: item2.author.handle, handle: item2.author.handle,
displayName: item2.author.displayName, displayName: item2.author.displayName,
avatar: item2.author.avatar, avatar: item2.author.avatar,
labels: item.author.labels,
})), })),
) )
} }
@ -255,7 +258,11 @@ function CondensedAuthorsList({
href={authors[0].href} href={authors[0].href}
title={`@${authors[0].handle}`} title={`@${authors[0].handle}`}
asAnchor> asAnchor>
<UserAvatar size={35} avatar={authors[0].avatar} /> <UserAvatar
size={35}
avatar={authors[0].avatar}
hasWarning={!!authors[0].labels?.length}
/>
</Link> </Link>
</View> </View>
) )
@ -264,7 +271,11 @@ function CondensedAuthorsList({
<View style={styles.avis}> <View style={styles.avis}>
{authors.slice(0, MAX_AUTHORS).map(author => ( {authors.slice(0, MAX_AUTHORS).map(author => (
<View key={author.href} style={s.mr5}> <View key={author.href} style={s.mr5}>
<UserAvatar size={35} avatar={author.avatar} /> <UserAvatar
size={35}
avatar={author.avatar}
hasWarning={!!author.labels?.length}
/>
</View> </View>
))} ))}
{authors.length > MAX_AUTHORS ? ( {authors.length > MAX_AUTHORS ? (
@ -317,7 +328,11 @@ function ExpandedAuthorsList({
style={styles.expandedAuthor} style={styles.expandedAuthor}
asAnchor> asAnchor>
<View style={styles.expandedAuthorAvi}> <View style={styles.expandedAuthorAvi}>
<UserAvatar size={35} avatar={author.avatar} /> <UserAvatar
size={35}
avatar={author.avatar}
hasWarning={!!author.labels?.length}
/>
</View> </View>
<View style={s.flex1}> <View style={s.flex1}>
<Text <Text

View File

@ -53,6 +53,7 @@ export const PostLikedBy = observer(function ({uri}: {uri: string}) {
handle={item.actor.handle} handle={item.actor.handle}
displayName={item.actor.displayName} displayName={item.actor.displayName}
avatar={item.actor.avatar} avatar={item.actor.avatar}
labels={item.actor.labels}
isFollowedBy={!!item.actor.viewer?.followedBy} isFollowedBy={!!item.actor.viewer?.followedBy}
/> />
) )

View File

@ -64,6 +64,7 @@ export const PostRepostedBy = observer(function PostRepostedBy({
handle={item.handle} handle={item.handle}
displayName={item.displayName} displayName={item.displayName}
avatar={item.avatar} avatar={item.avatar}
labels={item.labels}
isFollowedBy={!!item.viewer?.followedBy} isFollowedBy={!!item.viewer?.followedBy}
/> />
) )

View File

@ -22,7 +22,8 @@ import {useStores} from 'state/index'
import {PostMeta} from '../util/PostMeta' import {PostMeta} from '../util/PostMeta'
import {PostEmbeds} from '../util/post-embeds' import {PostEmbeds} from '../util/post-embeds'
import {PostCtrls} from '../util/PostCtrls' import {PostCtrls} from '../util/PostCtrls'
import {PostMutedWrapper} from '../util/PostMuted' import {PostHider} from '../util/moderation/PostHider'
import {ContentHider} from '../util/moderation/ContentHider'
import {ErrorMessage} from '../util/error/ErrorMessage' import {ErrorMessage} from '../util/error/ErrorMessage'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
@ -137,7 +138,11 @@ export const PostThreadItem = observer(function PostThreadItem({
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<Link href={authorHref} title={authorTitle} asAnchor> <Link href={authorHref} title={authorTitle} asAnchor>
<UserAvatar size={52} avatar={item.post.author.avatar} /> <UserAvatar
size={52}
avatar={item.post.author.avatar}
hasWarning={!!item.post.author.labels?.length}
/>
</Link> </Link>
</View> </View>
<View style={styles.layoutContent}> <View style={styles.layoutContent}>
@ -193,9 +198,15 @@ export const PostThreadItem = observer(function PostThreadItem({
</View> </View>
</View> </View>
<View style={[s.pl10, s.pr10, s.pb10]}> <View style={[s.pl10, s.pr10, s.pb10]}>
<ContentHider
isMuted={item.post.author.viewer?.muted === true}
labels={item.post.labels}>
{item.richText?.text ? ( {item.richText?.text ? (
<View <View
style={[styles.postTextContainer, styles.postTextLargeContainer]}> style={[
styles.postTextContainer,
styles.postTextLargeContainer,
]}>
<RichText <RichText
type="post-text-lg" type="post-text-lg"
richText={item.richText} richText={item.richText}
@ -204,6 +215,7 @@ export const PostThreadItem = observer(function PostThreadItem({
</View> </View>
) : undefined} ) : undefined}
<PostEmbeds embed={item.post.embed} style={s.mb10} /> <PostEmbeds embed={item.post.embed} style={s.mb10} />
</ContentHider>
{item._isHighlightedPost && hasEngagement ? ( {item._isHighlightedPost && hasEngagement ? (
<View style={[styles.expandedInfo, pal.border]}> <View style={[styles.expandedInfo, pal.border]}>
{item.post.repostCount ? ( {item.post.repostCount ? (
@ -270,13 +282,13 @@ export const PostThreadItem = observer(function PostThreadItem({
) )
} else { } else {
return ( return (
<PostMutedWrapper isMuted={item.post.author.viewer?.muted === true}> <>
<Link <PostHider
testID={`postThreadItem-by-${item.post.author.handle}`} testID={`postThreadItem-by-${item.post.author.handle}`}
style={[styles.outer, {borderTopColor: pal.colors.border}, pal.view]}
href={itemHref} href={itemHref}
title={itemTitle} style={[styles.outer, {borderColor: pal.colors.border}, pal.view]}
noFeedback> isMuted={item.post.author.viewer?.muted === true}
labels={item.post.labels}>
{item._showParentReplyLine && ( {item._showParentReplyLine && (
<View <View
style={[ style={[
@ -296,17 +308,25 @@ export const PostThreadItem = observer(function PostThreadItem({
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<Link href={authorHref} title={authorTitle} asAnchor> <Link href={authorHref} title={authorTitle} asAnchor>
<UserAvatar size={52} avatar={item.post.author.avatar} /> <UserAvatar
size={52}
avatar={item.post.author.avatar}
hasWarning={!!item.post.author.labels?.length}
/>
</Link> </Link>
</View> </View>
<View style={styles.layoutContent}> <View style={styles.layoutContent}>
<PostMeta <PostMeta
authorHandle={item.post.author.handle} authorHandle={item.post.author.handle}
authorDisplayName={item.post.author.displayName} authorDisplayName={item.post.author.displayName}
authorHasWarning={!!item.post.author.labels?.length}
timestamp={item.post.indexedAt} timestamp={item.post.indexedAt}
postHref={itemHref} postHref={itemHref}
did={item.post.author.did} did={item.post.author.did}
/> />
<ContentHider
labels={item.post.labels}
containerStyle={styles.contentHider}>
{item.richText?.text ? ( {item.richText?.text ? (
<View style={styles.postTextContainer}> <View style={styles.postTextContainer}>
<RichText <RichText
@ -318,6 +338,7 @@ export const PostThreadItem = observer(function PostThreadItem({
</View> </View>
) : undefined} ) : undefined}
<PostEmbeds embed={item.post.embed} style={s.mb10} /> <PostEmbeds embed={item.post.embed} style={s.mb10} />
</ContentHider>
<PostCtrls <PostCtrls
itemUri={itemUri} itemUri={itemUri}
itemCid={itemCid} itemCid={itemCid}
@ -345,7 +366,7 @@ export const PostThreadItem = observer(function PostThreadItem({
/> />
</View> </View>
</View> </View>
</Link> </PostHider>
{item._hasMore ? ( {item._hasMore ? (
<Link <Link
style={[ style={[
@ -364,7 +385,7 @@ export const PostThreadItem = observer(function PostThreadItem({
/> />
</Link> </Link>
) : undefined} ) : undefined}
</PostMutedWrapper> </>
) )
} }
}) })
@ -433,6 +454,9 @@ const styles = StyleSheet.create({
paddingHorizontal: 0, paddingHorizontal: 0,
paddingBottom: 10, paddingBottom: 10,
}, },
contentHider: {
marginTop: 4,
},
expandedInfo: { expandedInfo: {
flexDirection: 'row', flexDirection: 'row',
padding: 10, padding: 10,

View File

@ -7,17 +7,22 @@ import {
View, View,
ViewStyle, ViewStyle,
} from 'react-native' } from 'react-native'
import {AppBskyFeedPost as FeedPost} from '@atproto/api'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import Clipboard from '@react-native-clipboard/clipboard' import Clipboard from '@react-native-clipboard/clipboard'
import {AtUri} from '@atproto/api' import {AtUri} from '@atproto/api'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome' import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {PostThreadModel} from 'state/models/content/post-thread' import {
PostThreadModel,
PostThreadItemModel,
} from 'state/models/content/post-thread'
import {Link} from '../util/Link' import {Link} from '../util/Link'
import {UserInfoText} from '../util/UserInfoText' import {UserInfoText} from '../util/UserInfoText'
import {PostMeta} from '../util/PostMeta' import {PostMeta} from '../util/PostMeta'
import {PostEmbeds} from '../util/post-embeds' import {PostEmbeds} from '../util/post-embeds'
import {PostCtrls} from '../util/PostCtrls' import {PostCtrls} from '../util/PostCtrls'
import {PostMutedWrapper} from '../util/PostMuted' import {PostHider} from '../util/moderation/PostHider'
import {ContentHider} from '../util/moderation/ContentHider'
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'
import {RichText} from '../util/text/RichText' import {RichText} from '../util/text/RichText'
import * as Toast from '../util/Toast' import * as Toast from '../util/Toast'
@ -61,7 +66,11 @@ export const Post = observer(function Post({
// loading // loading
// = // =
if (!view || view.isLoading || view.params.uri !== uri) { if (
!view ||
(!view.hasContent && view.isLoading) ||
view.params.uri !== uri
) {
return ( return (
<View style={pal.view}> <View style={pal.view}>
<ActivityIndicator /> <ActivityIndicator />
@ -84,8 +93,34 @@ export const Post = observer(function Post({
// loaded // loaded
// = // =
const item = view.thread
const record = view.thread.postRecord return (
<PostLoaded
item={view.thread}
record={view.thread.postRecord}
setDeleted={setDeleted}
showReplyLine={showReplyLine}
style={style}
/>
)
})
const PostLoaded = observer(
({
item,
record,
setDeleted,
showReplyLine,
style,
}: {
item: PostThreadItemModel
record: FeedPost.Record
setDeleted: (v: boolean) => void
showReplyLine?: boolean
style?: StyleProp<ViewStyle>
}) => {
const pal = usePalette('default')
const store = useStores()
const itemUri = item.post.uri const itemUri = item.post.uri
const itemCid = item.post.cid const itemCid = item.post.cid
@ -99,7 +134,7 @@ export const Post = observer(function Post({
const urip = new AtUri(record.reply.parent?.uri || record.reply.root.uri) const urip = new AtUri(record.reply.parent?.uri || record.reply.root.uri)
replyAuthorDid = urip.hostname replyAuthorDid = urip.hostname
} }
const onPressReply = () => { const onPressReply = React.useCallback(() => {
store.shell.openComposer({ store.shell.openComposer({
replyTo: { replyTo: {
uri: item.post.uri, uri: item.post.uri,
@ -112,27 +147,34 @@ export const Post = observer(function Post({
}, },
}, },
}) })
} }, [store, item, record])
const onPressToggleRepost = () => {
const onPressToggleRepost = React.useCallback(() => {
return item return item
.toggleRepost() .toggleRepost()
.catch(e => store.log.error('Failed to toggle repost', e)) .catch(e => store.log.error('Failed to toggle repost', e))
} }, [item, store])
const onPressToggleLike = () => {
const onPressToggleLike = React.useCallback(() => {
return item return item
.toggleLike() .toggleLike()
.catch(e => store.log.error('Failed to toggle like', e)) .catch(e => store.log.error('Failed to toggle like', e))
} }, [item, store])
const onCopyPostText = () => {
const onCopyPostText = React.useCallback(() => {
Clipboard.setString(record.text) Clipboard.setString(record.text)
Toast.show('Copied to clipboard') Toast.show('Copied to clipboard')
} }, [record])
const onOpenTranslate = () => {
const onOpenTranslate = React.useCallback(() => {
Linking.openURL( Linking.openURL(
encodeURI(`https://translate.google.com/#auto|en|${record?.text || ''}`), encodeURI(
`https://translate.google.com/#auto|en|${record?.text || ''}`,
),
) )
} }, [record])
const onDeletePost = () => {
const onDeletePost = React.useCallback(() => {
item.delete().then( item.delete().then(
() => { () => {
setDeleted(true) setDeleted(true)
@ -143,26 +185,30 @@ export const Post = observer(function Post({
Toast.show('Failed to delete post, please try again') Toast.show('Failed to delete post, please try again')
}, },
) )
} }, [item, setDeleted, store])
return ( return (
<PostMutedWrapper isMuted={item.post.author.viewer?.muted === true}> <PostHider
<Link
style={[styles.outer, pal.view, pal.border, style]}
href={itemHref} href={itemHref}
title={itemTitle} style={[styles.outer, pal.view, pal.border, style]}
noFeedback> isMuted={item.post.author.viewer?.muted === true}
labels={item.post.labels}>
{showReplyLine && <View style={styles.replyLine} />} {showReplyLine && <View style={styles.replyLine} />}
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<Link href={authorHref} title={authorTitle} asAnchor> <Link href={authorHref} title={authorTitle} asAnchor>
<UserAvatar size={52} avatar={item.post.author.avatar} /> <UserAvatar
size={52}
avatar={item.post.author.avatar}
hasWarning={!!item.post.author.labels?.length}
/>
</Link> </Link>
</View> </View>
<View style={styles.layoutContent}> <View style={styles.layoutContent}>
<PostMeta <PostMeta
authorHandle={item.post.author.handle} authorHandle={item.post.author.handle}
authorDisplayName={item.post.author.displayName} authorDisplayName={item.post.author.displayName}
authorHasWarning={!!item.post.author.labels?.length}
timestamp={item.post.indexedAt} timestamp={item.post.indexedAt}
postHref={itemHref} postHref={itemHref}
did={item.post.author.did} did={item.post.author.did}
@ -185,6 +231,9 @@ export const Post = observer(function Post({
/> />
</View> </View>
)} )}
<ContentHider
labels={item.post.labels}
containerStyle={styles.contentHider}>
{item.richText?.text ? ( {item.richText?.text ? (
<View style={styles.postTextContainer}> <View style={styles.postTextContainer}>
<RichText <RichText
@ -195,6 +244,7 @@ export const Post = observer(function Post({
</View> </View>
) : undefined} ) : undefined}
<PostEmbeds embed={item.post.embed} style={s.mb10} /> <PostEmbeds embed={item.post.embed} style={s.mb10} />
</ContentHider>
<PostCtrls <PostCtrls
itemUri={itemUri} itemUri={itemUri}
itemCid={itemCid} itemCid={itemCid}
@ -222,10 +272,10 @@ export const Post = observer(function Post({
/> />
</View> </View>
</View> </View>
</Link> </PostHider>
</PostMutedWrapper> )
},
) )
})
const styles = StyleSheet.create({ const styles = StyleSheet.create({
outer: { outer: {
@ -257,4 +307,7 @@ const styles = StyleSheet.create({
borderLeftWidth: 2, borderLeftWidth: 2,
borderLeftColor: colors.gray2, borderLeftColor: colors.gray2,
}, },
contentHider: {
marginTop: 4,
},
}) })

View File

@ -14,7 +14,8 @@ import {UserInfoText} from '../util/UserInfoText'
import {PostMeta} from '../util/PostMeta' import {PostMeta} from '../util/PostMeta'
import {PostCtrls} from '../util/PostCtrls' import {PostCtrls} from '../util/PostCtrls'
import {PostEmbeds} from '../util/post-embeds' import {PostEmbeds} from '../util/post-embeds'
import {PostMutedWrapper} from '../util/PostMuted' import {PostHider} from '../util/moderation/PostHider'
import {ContentHider} from '../util/moderation/ContentHider'
import {RichText} from '../util/text/RichText' import {RichText} from '../util/text/RichText'
import * as Toast from '../util/Toast' import * as Toast from '../util/Toast'
import {UserAvatar} from '../util/UserAvatar' import {UserAvatar} from '../util/UserAvatar'
@ -59,7 +60,7 @@ export const FeedItem = observer(function ({
return urip.hostname return urip.hostname
}, [record?.reply]) }, [record?.reply])
const onPressReply = () => { const onPressReply = React.useCallback(() => {
track('FeedItem:PostReply') track('FeedItem:PostReply')
store.shell.openComposer({ store.shell.openComposer({
replyTo: { replyTo: {
@ -73,29 +74,34 @@ export const FeedItem = observer(function ({
}, },
}, },
}) })
} }, [item, track, record, store])
const onPressToggleRepost = () => {
const onPressToggleRepost = React.useCallback(() => {
track('FeedItem:PostRepost') track('FeedItem:PostRepost')
return item return item
.toggleRepost() .toggleRepost()
.catch(e => store.log.error('Failed to toggle repost', e)) .catch(e => store.log.error('Failed to toggle repost', e))
} }, [track, item, store])
const onPressToggleLike = () => {
const onPressToggleLike = React.useCallback(() => {
track('FeedItem:PostLike') track('FeedItem:PostLike')
return item return item
.toggleLike() .toggleLike()
.catch(e => store.log.error('Failed to toggle like', e)) .catch(e => store.log.error('Failed to toggle like', e))
} }, [track, item, store])
const onCopyPostText = () => {
const onCopyPostText = React.useCallback(() => {
Clipboard.setString(record?.text || '') Clipboard.setString(record?.text || '')
Toast.show('Copied to clipboard') Toast.show('Copied to clipboard')
} }, [record])
const onOpenTranslate = React.useCallback(() => { const onOpenTranslate = React.useCallback(() => {
Linking.openURL( Linking.openURL(
encodeURI(`https://translate.google.com/#auto|en|${record?.text || ''}`), encodeURI(`https://translate.google.com/#auto|en|${record?.text || ''}`),
) )
}, [record]) }, [record])
const onDeletePost = () => {
const onDeletePost = React.useCallback(() => {
track('FeedItem:PostDelete') track('FeedItem:PostDelete')
item.delete().then( item.delete().then(
() => { () => {
@ -107,7 +113,7 @@ export const FeedItem = observer(function ({
Toast.show('Failed to delete post, please try again') Toast.show('Failed to delete post, please try again')
}, },
) )
} }, [track, item, setDeleted, store])
if (!record || deleted) { if (!record || deleted) {
return <View /> return <View />
@ -127,13 +133,12 @@ export const FeedItem = observer(function ({
] ]
return ( return (
<PostMutedWrapper isMuted={isMuted}> <PostHider
<Link
testID={`feedItem-by-${item.post.author.handle}`} testID={`feedItem-by-${item.post.author.handle}`}
style={outerStyles} style={outerStyles}
href={itemHref} href={itemHref}
title={itemTitle} isMuted={isMuted}
noFeedback> labels={item.post.labels}>
{isThreadChild && ( {isThreadChild && (
<View <View
style={[styles.topReplyLine, {borderColor: pal.colors.replyLine}]} style={[styles.topReplyLine, {borderColor: pal.colors.replyLine}]}
@ -174,8 +179,7 @@ export const FeedItem = observer(function ({
lineHeight={1.2} lineHeight={1.2}
numberOfLines={1} numberOfLines={1}
text={sanitizeDisplayName( text={sanitizeDisplayName(
item.reasonRepost.by.displayName || item.reasonRepost.by.displayName || item.reasonRepost.by.handle,
item.reasonRepost.by.handle,
)} )}
href={`/profile/${item.reasonRepost.by.handle}`} href={`/profile/${item.reasonRepost.by.handle}`}
/> />
@ -185,13 +189,18 @@ export const FeedItem = observer(function ({
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<Link href={authorHref} title={item.post.author.handle} asAnchor> <Link href={authorHref} title={item.post.author.handle} asAnchor>
<UserAvatar size={52} avatar={item.post.author.avatar} /> <UserAvatar
size={52}
avatar={item.post.author.avatar}
hasWarning={!!item.post.author.labels?.length}
/>
</Link> </Link>
</View> </View>
<View style={styles.layoutContent}> <View style={styles.layoutContent}>
<PostMeta <PostMeta
authorHandle={item.post.author.handle} authorHandle={item.post.author.handle}
authorDisplayName={item.post.author.displayName} authorDisplayName={item.post.author.displayName}
authorHasWarning={!!item.post.author.labels?.length}
timestamp={item.post.indexedAt} timestamp={item.post.indexedAt}
postHref={itemHref} postHref={itemHref}
did={item.post.author.did} did={item.post.author.did}
@ -218,6 +227,9 @@ export const FeedItem = observer(function ({
/> />
</View> </View>
)} )}
<ContentHider
labels={item.post.labels}
containerStyle={styles.contentHider}>
{item.richText?.text ? ( {item.richText?.text ? (
<View style={styles.postTextContainer}> <View style={styles.postTextContainer}>
<RichText <RichText
@ -228,6 +240,7 @@ export const FeedItem = observer(function ({
</View> </View>
) : undefined} ) : undefined}
<PostEmbeds embed={item.post.embed} style={styles.embed} /> <PostEmbeds embed={item.post.embed} style={styles.embed} />
</ContentHider>
<PostCtrls <PostCtrls
style={styles.ctrls} style={styles.ctrls}
itemUri={itemUri} itemUri={itemUri}
@ -256,8 +269,7 @@ export const FeedItem = observer(function ({
/> />
</View> </View>
</View> </View>
</Link> </PostHider>
</PostMutedWrapper>
) )
}) })
@ -320,6 +332,9 @@ const styles = StyleSheet.create({
flexWrap: 'wrap', flexWrap: 'wrap',
paddingBottom: 4, paddingBottom: 4,
}, },
contentHider: {
marginTop: 4,
},
embed: { embed: {
marginBottom: 6, marginBottom: 6,
}, },

View File

@ -1,7 +1,7 @@
import React from 'react' import React from 'react'
import {StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {AppBskyActorDefs} from '@atproto/api' import {AppBskyActorDefs, ComAtprotoLabelDefs} from '@atproto/api'
import {Link} from '../util/Link' import {Link} from '../util/Link'
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'
import {UserAvatar} from '../util/UserAvatar' import {UserAvatar} from '../util/UserAvatar'
@ -17,6 +17,7 @@ export function ProfileCard({
displayName, displayName,
avatar, avatar,
description, description,
labels,
isFollowedBy, isFollowedBy,
noBg, noBg,
noBorder, noBorder,
@ -28,6 +29,7 @@ export function ProfileCard({
displayName?: string displayName?: string
avatar?: string avatar?: string
description?: string description?: string
labels: ComAtprotoLabelDefs.Label[] | undefined
isFollowedBy?: boolean isFollowedBy?: boolean
noBg?: boolean noBg?: boolean
noBorder?: boolean noBorder?: boolean
@ -50,7 +52,7 @@ export function ProfileCard({
asAnchor> asAnchor>
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<UserAvatar size={40} avatar={avatar} /> <UserAvatar size={40} avatar={avatar} hasWarning={!!labels?.length} />
</View> </View>
<View style={styles.layoutContent}> <View style={styles.layoutContent}>
<Text <Text
@ -114,6 +116,7 @@ export const ProfileCardWithFollowBtn = observer(
displayName, displayName,
avatar, avatar,
description, description,
labels,
isFollowedBy, isFollowedBy,
noBg, noBg,
noBorder, noBorder,
@ -124,6 +127,7 @@ export const ProfileCardWithFollowBtn = observer(
displayName?: string displayName?: string
avatar?: string avatar?: string
description?: string description?: string
labels: ComAtprotoLabelDefs.Label[] | undefined
isFollowedBy?: boolean isFollowedBy?: boolean
noBg?: boolean noBg?: boolean
noBorder?: boolean noBorder?: boolean
@ -138,6 +142,7 @@ export const ProfileCardWithFollowBtn = observer(
displayName={displayName} displayName={displayName}
avatar={avatar} avatar={avatar}
description={description} description={description}
labels={labels}
isFollowedBy={isFollowedBy} isFollowedBy={isFollowedBy}
noBg={noBg} noBg={noBg}
noBorder={noBorder} noBorder={noBorder}

View File

@ -67,6 +67,7 @@ export const ProfileFollowers = observer(function ProfileFollowers({
handle={item.handle} handle={item.handle}
displayName={item.displayName} displayName={item.displayName}
avatar={item.avatar} avatar={item.avatar}
labels={item.labels}
isFollowedBy={!!item.viewer?.followedBy} isFollowedBy={!!item.viewer?.followedBy}
/> />
) )

View File

@ -64,6 +64,7 @@ export const ProfileFollows = observer(function ProfileFollows({
handle={item.handle} handle={item.handle}
displayName={item.displayName} displayName={item.displayName}
avatar={item.avatar} avatar={item.avatar}
labels={item.labels}
isFollowedBy={!!item.viewer?.followedBy} isFollowedBy={!!item.viewer?.followedBy}
/> />
) )

View File

@ -27,6 +27,7 @@ import {Text} from '../util/text/Text'
import {RichText} from '../util/text/RichText' import {RichText} from '../util/text/RichText'
import {UserAvatar} from '../util/UserAvatar' import {UserAvatar} from '../util/UserAvatar'
import {UserBanner} from '../util/UserBanner' import {UserBanner} from '../util/UserBanner'
import {ProfileHeaderLabels} from '../util/moderation/ProfileHeaderLabels'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {useAnalytics} from 'lib/analytics' import {useAnalytics} from 'lib/analytics'
import {NavigationProp} from 'lib/routes/types' import {NavigationProp} from 'lib/routes/types'
@ -320,6 +321,7 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoaded({
richText={view.descriptionRichText} richText={view.descriptionRichText}
/> />
) : undefined} ) : undefined}
<ProfileHeaderLabels labels={view.labels} />
{view.viewer.muted ? ( {view.viewer.muted ? (
<View <View
testID="profileHeaderMutedNotice" testID="profileHeaderMutedNotice"
@ -348,7 +350,11 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoaded({
onPress={onPressAvi}> onPress={onPressAvi}>
<View <View
style={[pal.view, {borderColor: pal.colors.background}, styles.avi]}> style={[pal.view, {borderColor: pal.colors.background}, styles.avi]}>
<UserAvatar size={80} avatar={view.avatar} /> <UserAvatar
size={80}
avatar={view.avatar}
hasWarning={!!view.labels?.length}
/>
</View> </View>
</TouchableWithoutFeedback> </TouchableWithoutFeedback>
</View> </View>

View File

@ -101,6 +101,7 @@ const Profiles = observer(({model}: {model: SearchUIModel}) => {
displayName={item.displayName} displayName={item.displayName}
avatar={item.avatar} avatar={item.avatar}
description={item.description} description={item.description}
labels={item.labels}
/> />
))} ))}
<View style={s.footerSpacer} /> <View style={s.footerSpacer} />

View File

@ -10,7 +10,8 @@ import {useStores} from 'state/index'
const HITSLOP = {left: 20, top: 20, right: 20, bottom: 20} const HITSLOP = {left: 20, top: 20, right: 20, bottom: 20}
export const LoadLatestBtn = observer(({onPress}: {onPress: () => void}) => { export const LoadLatestBtn = observer(
({onPress, label}: {onPress: () => void; label: string}) => {
const store = useStores() const store = useStores()
const safeAreaInsets = useSafeAreaInsets() const safeAreaInsets = useSafeAreaInsets()
return ( return (
@ -29,12 +30,13 @@ export const LoadLatestBtn = observer(({onPress}: {onPress: () => void}) => {
end={{x: 1, y: 1}} end={{x: 1, y: 1}}
style={styles.loadLatestInner}> style={styles.loadLatestInner}>
<Text type="md-bold" style={styles.loadLatestText}> <Text type="md-bold" style={styles.loadLatestText}>
Load new posts Load new {label}
</Text> </Text>
</LinearGradient> </LinearGradient>
</TouchableOpacity> </TouchableOpacity>
) )
}) },
)
const styles = StyleSheet.create({ const styles = StyleSheet.create({
loadLatest: { loadLatest: {

View File

@ -6,7 +6,13 @@ import {UpIcon} from 'lib/icons'
const HITSLOP = {left: 20, top: 20, right: 20, bottom: 20} const HITSLOP = {left: 20, top: 20, right: 20, bottom: 20}
export const LoadLatestBtn = ({onPress}: {onPress: () => void}) => { export const LoadLatestBtn = ({
onPress,
label,
}: {
onPress: () => void
label: string
}) => {
const pal = usePalette('default') const pal = usePalette('default')
return ( return (
<TouchableOpacity <TouchableOpacity
@ -15,7 +21,7 @@ export const LoadLatestBtn = ({onPress}: {onPress: () => void}) => {
hitSlop={HITSLOP}> hitSlop={HITSLOP}>
<Text type="md-bold" style={pal.text}> <Text type="md-bold" style={pal.text}>
<UpIcon size={16} strokeWidth={1} style={[pal.text, styles.icon]} /> <UpIcon size={16} strokeWidth={1} style={[pal.text, styles.icon]} />
Load new posts Load new {label}
</Text> </Text>
</TouchableOpacity> </TouchableOpacity>
) )
@ -25,7 +31,9 @@ const styles = StyleSheet.create({
loadLatest: { loadLatest: {
flexDirection: 'row', flexDirection: 'row',
position: 'absolute', position: 'absolute',
left: 'calc(50vw - 80px)', left: '50vw',
// @ts-ignore web only -prf
transform: 'translateX(-50%)',
top: 30, top: 30,
shadowColor: '#000', shadowColor: '#000',
shadowOpacity: 0.2, shadowOpacity: 0.2,

View File

@ -15,6 +15,7 @@ interface PostMetaOpts {
authorAvatar?: string authorAvatar?: string
authorHandle: string authorHandle: string
authorDisplayName: string | undefined authorDisplayName: string | undefined
authorHasWarning: boolean
postHref: string postHref: string
timestamp: string timestamp: string
did?: string did?: string
@ -93,7 +94,11 @@ export const PostMeta = observer(function (opts: PostMetaOpts) {
<View style={styles.meta}> <View style={styles.meta}>
{typeof opts.authorAvatar !== 'undefined' && ( {typeof opts.authorAvatar !== 'undefined' && (
<View style={[styles.metaItem, styles.avatar]}> <View style={[styles.metaItem, styles.avatar]}>
<UserAvatar avatar={opts.authorAvatar} size={16} /> <UserAvatar
avatar={opts.authorAvatar}
size={16}
hasWarning={opts.authorHasWarning}
/>
</View> </View>
)} )}
<View style={[styles.metaItem, styles.maxWidth]}> <View style={[styles.metaItem, styles.maxWidth]}>

View File

@ -1,50 +0,0 @@
import React from 'react'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {usePalette} from 'lib/hooks/usePalette'
import {Text} from './text/Text'
export function PostMutedWrapper({
isMuted,
children,
}: React.PropsWithChildren<{isMuted?: boolean}>) {
const pal = usePalette('default')
const [override, setOverride] = React.useState(false)
if (!isMuted || override) {
return <>{children}</>
}
return (
<View style={[styles.container, pal.view, pal.border]}>
<FontAwesomeIcon
icon={['far', 'eye-slash']}
style={[styles.icon, pal.text]}
/>
<Text type="md" style={pal.textLight}>
Post from an account you muted.
</Text>
<TouchableOpacity
style={styles.showBtn}
onPress={() => setOverride(true)}>
<Text type="md" style={pal.link}>
Show post
</Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 14,
paddingHorizontal: 18,
borderTopWidth: 1,
},
icon: {
marginRight: 10,
},
showBtn: {
marginLeft: 'auto',
},
})

View File

@ -44,10 +44,12 @@ function DefaultAvatar({size}: {size: number}) {
export function UserAvatar({ export function UserAvatar({
size, size,
avatar, avatar,
hasWarning,
onSelectNewAvatar, onSelectNewAvatar,
}: { }: {
size: number size: number
avatar?: string | null avatar?: string | null
hasWarning?: boolean
onSelectNewAvatar?: (img: PickedMedia | null) => void onSelectNewAvatar?: (img: PickedMedia | null) => void
}) { }) {
const store = useStores() const store = useStores()
@ -105,6 +107,22 @@ export function UserAvatar({
}, },
}, },
] ]
const warning = React.useMemo(() => {
if (!hasWarning) {
return <></>
}
return (
<View style={[styles.warningIconContainer, pal.view]}>
<FontAwesomeIcon
icon="exclamation-circle"
style={styles.warningIcon}
size={Math.floor(size / 3)}
/>
</View>
)
}, [hasWarning, size, pal])
// onSelectNewAvatar is only passed as prop on the EditProfile component // onSelectNewAvatar is only passed as prop on the EditProfile component
return onSelectNewAvatar ? ( return onSelectNewAvatar ? (
<DropdownButton <DropdownButton
@ -137,14 +155,20 @@ export function UserAvatar({
</View> </View>
</DropdownButton> </DropdownButton>
) : avatar ? ( ) : avatar ? (
<View style={{width: size, height: size}}>
<HighPriorityImage <HighPriorityImage
testID="userAvatarImage" testID="userAvatarImage"
style={{width: size, height: size, borderRadius: Math.floor(size / 2)}} style={{width: size, height: size, borderRadius: Math.floor(size / 2)}}
resizeMode="stretch" resizeMode="stretch"
source={{uri: avatar}} source={{uri: avatar}}
/> />
{warning}
</View>
) : ( ) : (
<View style={{width: size, height: size}}>
<DefaultAvatar size={size} /> <DefaultAvatar size={size} />
{warning}
</View>
) )
} }
@ -165,4 +189,13 @@ const styles = StyleSheet.create({
height: 80, height: 80,
borderRadius: 40, borderRadius: 40,
}, },
warningIconContainer: {
position: 'absolute',
right: 0,
bottom: 0,
borderRadius: 100,
},
warningIcon: {
color: colors.red3,
},
}) })

View File

@ -0,0 +1,109 @@
import React from 'react'
import {
StyleProp,
StyleSheet,
TouchableOpacity,
View,
ViewStyle,
} from 'react-native'
import {ComAtprotoLabelDefs} from '@atproto/api'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {Text} from '../text/Text'
import {addStyle} from 'lib/styles'
export function ContentHider({
testID,
isMuted,
labels,
style,
containerStyle,
children,
}: React.PropsWithChildren<{
testID?: string
isMuted?: boolean
labels: ComAtprotoLabelDefs.Label[] | undefined
style?: StyleProp<ViewStyle>
containerStyle?: StyleProp<ViewStyle>
}>) {
const pal = usePalette('default')
const [override, setOverride] = React.useState(false)
const store = useStores()
const labelPref = store.preferences.getLabelPreference(labels)
if (!isMuted && labelPref.pref === 'show') {
return (
<View testID={testID} style={style}>
{children}
</View>
)
}
if (labelPref.pref === 'hide') {
return <></>
}
return (
<View style={[styles.container, pal.view, pal.border, containerStyle]}>
<View
style={[
styles.description,
pal.viewLight,
override && styles.descriptionOpen,
]}>
<Text type="md" style={pal.textLight}>
{isMuted ? (
<>Post from an account you muted.</>
) : (
<>Warning: {labelPref.desc.title}</>
)}
</Text>
<TouchableOpacity
style={styles.showBtn}
onPress={() => setOverride(v => !v)}>
<Text type="md" style={pal.link}>
{override ? 'Hide' : 'Show'}
</Text>
</TouchableOpacity>
</View>
{override && (
<View style={[styles.childrenContainer, pal.border]}>
<View testID={testID} style={addStyle(style, styles.child)}>
{children}
</View>
</View>
)}
</View>
)
}
const styles = StyleSheet.create({
container: {
marginBottom: 10,
borderWidth: 1,
borderRadius: 12,
},
description: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 14,
paddingLeft: 14,
paddingRight: 18,
borderRadius: 12,
},
descriptionOpen: {
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
},
icon: {
marginRight: 10,
},
showBtn: {
marginLeft: 'auto',
},
childrenContainer: {
paddingHorizontal: 12,
paddingTop: 8,
},
child: {},
})

View File

@ -0,0 +1,105 @@
import React from 'react'
import {
StyleProp,
StyleSheet,
TouchableOpacity,
View,
ViewStyle,
} from 'react-native'
import {ComAtprotoLabelDefs} from '@atproto/api'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {usePalette} from 'lib/hooks/usePalette'
import {Link} from '../Link'
import {Text} from '../text/Text'
import {addStyle} from 'lib/styles'
import {useStores} from 'state/index'
export function PostHider({
testID,
href,
isMuted,
labels,
style,
children,
}: React.PropsWithChildren<{
testID?: string
href: string
isMuted: boolean | undefined
labels: ComAtprotoLabelDefs.Label[] | undefined
style: StyleProp<ViewStyle>
}>) {
const store = useStores()
const pal = usePalette('default')
const [override, setOverride] = React.useState(false)
const bg = override ? pal.viewLight : pal.view
const labelPref = store.preferences.getLabelPreference(labels)
if (labelPref.pref === 'hide') {
return <></>
}
if (!isMuted) {
// NOTE: any further label enforcement should occur in ContentContainer
return (
<Link testID={testID} style={style} href={href} noFeedback>
{children}
</Link>
)
}
return (
<>
<View style={[styles.description, bg, pal.border]}>
<FontAwesomeIcon
icon={['far', 'eye-slash']}
style={[styles.icon, pal.text]}
/>
<Text type="md" style={pal.textLight}>
Post from an account you muted.
</Text>
<TouchableOpacity
style={styles.showBtn}
onPress={() => setOverride(v => !v)}>
<Text type="md" style={pal.link}>
{override ? 'Hide' : 'Show'} post
</Text>
</TouchableOpacity>
</View>
{override && (
<View style={[styles.childrenContainer, pal.border, bg]}>
<Link
testID={testID}
style={addStyle(style, styles.child)}
href={href}
noFeedback>
{children}
</Link>
</View>
)}
</>
)
}
const styles = StyleSheet.create({
description: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 14,
paddingHorizontal: 18,
borderTopWidth: 1,
},
icon: {
marginRight: 10,
},
showBtn: {
marginLeft: 'auto',
},
childrenContainer: {
paddingHorizontal: 6,
paddingBottom: 6,
},
child: {
borderWidth: 1,
borderRadius: 12,
},
})

View File

@ -0,0 +1,55 @@
import React from 'react'
import {StyleSheet, View} from 'react-native'
import {ComAtprotoLabelDefs} from '@atproto/api'
import {
FontAwesomeIcon,
FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome'
import {Text} from '../text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {getLabelValueGroup} from 'lib/labeling/helpers'
export function ProfileHeaderLabels({
labels,
}: {
labels: ComAtprotoLabelDefs.Label[] | undefined
}) {
const palErr = usePalette('error')
if (!labels?.length) {
return null
}
return (
<>
{labels.map((label, i) => {
const labelGroup = getLabelValueGroup(label?.val || '')
return (
<View
key={`${label.val}-${i}`}
style={[styles.container, palErr.border, palErr.view]}>
<FontAwesomeIcon
icon="circle-exclamation"
style={palErr.text as FontAwesomeIconStyle}
size={20}
/>
<Text style={palErr.text}>
This account has been flagged for{' '}
{labelGroup.title.toLocaleLowerCase()}.
</Text>
</View>
)
})}
</>
)
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
gap: 10,
borderWidth: 1,
borderRadius: 6,
paddingHorizontal: 10,
paddingVertical: 8,
},
})

View File

@ -42,6 +42,7 @@ export function QuoteEmbed({
authorAvatar={quote.author.avatar} authorAvatar={quote.author.avatar}
authorHandle={quote.author.handle} authorHandle={quote.author.handle}
authorDisplayName={quote.author.displayName} authorDisplayName={quote.author.displayName}
authorHasWarning={false}
postHref={itemHref} postHref={itemHref}
timestamp={quote.indexedAt} timestamp={quote.indexedAt}
/> />

View File

@ -34,6 +34,7 @@ import {faCompass} from '@fortawesome/free-regular-svg-icons/faCompass'
import {faEllipsis} from '@fortawesome/free-solid-svg-icons/faEllipsis' import {faEllipsis} from '@fortawesome/free-solid-svg-icons/faEllipsis'
import {faEnvelope} from '@fortawesome/free-solid-svg-icons/faEnvelope' import {faEnvelope} from '@fortawesome/free-solid-svg-icons/faEnvelope'
import {faExclamation} from '@fortawesome/free-solid-svg-icons/faExclamation' import {faExclamation} from '@fortawesome/free-solid-svg-icons/faExclamation'
import {faEye} from '@fortawesome/free-solid-svg-icons/faEye'
import {faEyeSlash as farEyeSlash} from '@fortawesome/free-regular-svg-icons/faEyeSlash' import {faEyeSlash as farEyeSlash} from '@fortawesome/free-regular-svg-icons/faEyeSlash'
import {faGear} from '@fortawesome/free-solid-svg-icons/faGear' import {faGear} from '@fortawesome/free-solid-svg-icons/faGear'
import {faGlobe} from '@fortawesome/free-solid-svg-icons/faGlobe' import {faGlobe} from '@fortawesome/free-solid-svg-icons/faGlobe'
@ -106,8 +107,8 @@ export function setup() {
faCompass, faCompass,
faEllipsis, faEllipsis,
faEnvelope, faEnvelope,
faEye,
faExclamation, faExclamation,
faQuoteLeft,
farEyeSlash, farEyeSlash,
faGear, faGear,
faGlobe, faGlobe,
@ -128,6 +129,7 @@ export function setup() {
faPenNib, faPenNib,
faPenToSquare, faPenToSquare,
faPlus, faPlus,
faQuoteLeft,
faReply, faReply,
faRetweet, faRetweet,
faRss, faRss,

View File

@ -194,7 +194,7 @@ const FeedPage = observer(
headerOffset={HEADER_OFFSET} headerOffset={HEADER_OFFSET}
/> />
{feed.hasNewLatest && !feed.isRefreshing && ( {feed.hasNewLatest && !feed.isRefreshing && (
<LoadLatestBtn onPress={onPressLoadLatest} /> <LoadLatestBtn onPress={onPressLoadLatest} label="posts" />
)} )}
<FAB <FAB
testID="composeFAB" testID="composeFAB"

View File

@ -1,8 +1,7 @@
import React, {useEffect} from 'react' import React from 'react'
import {FlatList, View} from 'react-native' import {FlatList, View} from 'react-native'
import {useFocusEffect} from '@react-navigation/native' import {useFocusEffect} from '@react-navigation/native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import useAppState from 'react-native-appstate-hook'
import { import {
NativeStackScreenProps, NativeStackScreenProps,
NotificationsTabNavigatorParams, NotificationsTabNavigatorParams,
@ -11,13 +10,12 @@ import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {ViewHeader} from '../com/util/ViewHeader' import {ViewHeader} from '../com/util/ViewHeader'
import {Feed} from '../com/notifications/Feed' import {Feed} from '../com/notifications/Feed'
import {InvitedUsers} from '../com/notifications/InvitedUsers' import {InvitedUsers} from '../com/notifications/InvitedUsers'
import {LoadLatestBtn} from 'view/com/util/LoadLatestBtn'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {useOnMainScroll} from 'lib/hooks/useOnMainScroll' import {useOnMainScroll} from 'lib/hooks/useOnMainScroll'
import {s} from 'lib/styles' import {s} from 'lib/styles'
import {useAnalytics} from 'lib/analytics' import {useAnalytics} from 'lib/analytics'
const NOTIFICATIONS_POLL_INTERVAL = 15e3
type Props = NativeStackScreenProps< type Props = NativeStackScreenProps<
NotificationsTabNavigatorParams, NotificationsTabNavigatorParams,
'Notifications' 'Notifications'
@ -28,46 +26,21 @@ export const NotificationsScreen = withAuthRequired(
const onMainScroll = useOnMainScroll(store) const onMainScroll = useOnMainScroll(store)
const scrollElRef = React.useRef<FlatList>(null) const scrollElRef = React.useRef<FlatList>(null)
const {screen} = useAnalytics() const {screen} = useAnalytics()
const {appState} = useAppState({
onForeground: () => doPoll(true),
})
// event handlers // event handlers
// = // =
const onPressTryAgain = () => { const onPressTryAgain = React.useCallback(() => {
store.me.notifications.refresh() store.me.notifications.refresh()
} }, [store])
const scrollToTop = React.useCallback(() => { const scrollToTop = React.useCallback(() => {
scrollElRef.current?.scrollToOffset({offset: 0}) scrollElRef.current?.scrollToOffset({offset: 0})
}, [scrollElRef]) }, [scrollElRef])
// periodic polling const onPressLoadLatest = React.useCallback(() => {
// = store.me.notifications.processQueue()
const doPoll = React.useCallback( scrollToTop()
async (isForegrounding = false) => { }, [store, scrollToTop])
if (isForegrounding) {
// app is foregrounding, refresh optimistically
store.log.debug('NotificationsScreen: Refreshing on app foreground')
await Promise.all([
store.me.notifications.loadUnreadCount(),
store.me.notifications.refresh(),
])
} else if (appState === 'active') {
// periodic poll, refresh if there are new notifs
store.log.debug('NotificationsScreen: Polling for new notifications')
const didChange = await store.me.notifications.loadUnreadCount()
if (didChange) {
store.log.debug('NotificationsScreen: Loading new notifications')
await store.me.notifications.loadLatest()
}
}
},
[appState, store],
)
useEffect(() => {
const pollInterval = setInterval(doPoll, NOTIFICATIONS_POLL_INTERVAL)
return () => clearInterval(pollInterval)
}, [doPoll])
// on-visible setup // on-visible setup
// = // =
@ -75,16 +48,16 @@ export const NotificationsScreen = withAuthRequired(
React.useCallback(() => { React.useCallback(() => {
store.shell.setMinimalShellMode(false) store.shell.setMinimalShellMode(false)
store.log.debug('NotificationsScreen: Updating feed') store.log.debug('NotificationsScreen: Updating feed')
const softResetSub = store.onScreenSoftReset(scrollToTop) const softResetSub = store.onScreenSoftReset(onPressLoadLatest)
store.me.notifications.loadUnreadCount() store.me.notifications.syncQueue()
store.me.notifications.loadLatest() store.me.notifications.update()
screen('Notifications') screen('Notifications')
return () => { return () => {
softResetSub.remove() softResetSub.remove()
store.me.notifications.markAllRead() store.me.notifications.markAllUnqueuedRead()
} }
}, [store, screen, scrollToTop]), }, [store, screen, onPressLoadLatest]),
) )
return ( return (
@ -97,6 +70,10 @@ export const NotificationsScreen = withAuthRequired(
onScroll={onMainScroll} onScroll={onMainScroll}
scrollElRef={scrollElRef} scrollElRef={scrollElRef}
/> />
{store.me.notifications.hasNewLatest &&
!store.me.notifications.isRefreshing && (
<LoadLatestBtn onPress={onPressLoadLatest} label="notifications" />
)}
</View> </View>
) )
}), }),

View File

@ -155,6 +155,7 @@ export const SearchScreen = withAuthRequired(
testID={`searchAutoCompleteResult-${item.handle}`} testID={`searchAutoCompleteResult-${item.handle}`}
handle={item.handle} handle={item.handle}
displayName={item.displayName} displayName={item.displayName}
labels={item.labels}
avatar={item.avatar} avatar={item.avatar}
/> />
))} ))}

View File

@ -124,6 +124,11 @@ export const SettingsScreen = withAuthRequired(
store.shell.openModal({name: 'invite-codes'}) store.shell.openModal({name: 'invite-codes'})
}, [track, store]) }, [track, store])
const onPressContentFiltering = React.useCallback(() => {
track('Settings:ContentfilteringButtonClicked')
store.shell.openModal({name: 'content-filtering-settings'})
}, [track, store])
const onPressSignout = React.useCallback(() => { const onPressSignout = React.useCallback(() => {
track('Settings:SignOutButtonClicked') track('Settings:SignOutButtonClicked')
store.session.logout() store.session.logout()
@ -248,6 +253,20 @@ export const SettingsScreen = withAuthRequired(
<Text type="xl-bold" style={[pal.text, styles.heading]}> <Text type="xl-bold" style={[pal.text, styles.heading]}>
Advanced Advanced
</Text> </Text>
<TouchableOpacity
testID="contentFilteringBtn"
style={[styles.linkCard, pal.view, isSwitching && styles.dimmed]}
onPress={isSwitching ? undefined : onPressContentFiltering}>
<View style={[styles.iconContainer, pal.btn]}>
<FontAwesomeIcon
icon="eye"
style={pal.text as FontAwesomeIconStyle}
/>
</View>
<Text type="lg" style={pal.text}>
Content moderation
</Text>
</TouchableOpacity>
<TouchableOpacity <TouchableOpacity
testID="changeHandleBtn" testID="changeHandleBtn"
style={[styles.linkCard, pal.view, isSwitching && styles.dimmed]} style={[styles.linkCard, pal.view, isSwitching && styles.dimmed]}

View File

@ -90,6 +90,7 @@ export const DesktopSearch = observer(function DesktopSearch() {
handle={item.handle} handle={item.handle}
displayName={item.displayName} displayName={item.displayName}
avatar={item.avatar} avatar={item.avatar}
labels={item.labels}
noBorder={i === 0} noBorder={i === 0}
/> />
))} ))}

View File

@ -30,10 +30,10 @@
tlds "^1.234.0" tlds "^1.234.0"
typed-emitter "^2.1.0" typed-emitter "^2.1.0"
"@atproto/api@0.2.5": "@atproto/api@0.2.6":
version "0.2.5" version "0.2.6"
resolved "https://registry.yarnpkg.com/@atproto/api/-/api-0.2.5.tgz#24375497351469a522497c7f92016d0b4233a172" resolved "https://registry.yarnpkg.com/@atproto/api/-/api-0.2.6.tgz#030d9d3385bb109cc028451ab26a5e24ee126b06"
integrity sha512-RJGhiwj6kOjrlVy7ES/SfJt3JyFwXdFZeBP4iw2ne/Ie0ZlanKhY0y9QHx5tI4rvEUP/wf0iKtaq2neczHi3bg== integrity sha512-vw5D0o0ByuWd89ob8vG8RPd0tDhPi4NTyqn0lCJQDhxcYXx4I96sZ3iCUf61m7g3VNumBAoC2ZRo9kdn/6tb5w==
dependencies: dependencies:
"@atproto/common-web" "*" "@atproto/common-web" "*"
"@atproto/uri" "*" "@atproto/uri" "*"
@ -122,10 +122,10 @@
resolved "https://registry.yarnpkg.com/@atproto/nsid/-/nsid-0.0.1.tgz#0cdc00cefe8f0b1385f352b9f57b3ad37fff09a4" resolved "https://registry.yarnpkg.com/@atproto/nsid/-/nsid-0.0.1.tgz#0cdc00cefe8f0b1385f352b9f57b3ad37fff09a4"
integrity sha512-t5M6/CzWBVYoBbIvfKDpqPj/+ZmyoK9ydZSStcTXosJ27XXwOPhz0VDUGKK2SM9G5Y7TPes8S5KTAU0UdVYFCw== integrity sha512-t5M6/CzWBVYoBbIvfKDpqPj/+ZmyoK9ydZSStcTXosJ27XXwOPhz0VDUGKK2SM9G5Y7TPes8S5KTAU0UdVYFCw==
"@atproto/pds@^0.1.3": "@atproto/pds@^0.1.4":
version "0.1.3" version "0.1.4"
resolved "https://registry.yarnpkg.com/@atproto/pds/-/pds-0.1.3.tgz#601c556cd1e10306c9b741d9361bc54d70bb2869" resolved "https://registry.yarnpkg.com/@atproto/pds/-/pds-0.1.4.tgz#43379912e127d6d4f79a514e785dab9b54fd7810"
integrity sha512-cVvmgXkzu7w1tDGGDK904sDzxF2AUqu0ij/1EU2rYmnZZAK+FTjKs8cqrJzRur9vm07A23JvBTuINtYzxHwSzA== integrity sha512-vrFYL+2nNm/0fJyUIgFK9h9FRuEf4rHjU/LJV7/nBO+HA3hP3U/mTgvVxuuHHvcRsRL5AVpAJR0xWFUoYsFmmg==
dependencies: dependencies:
"@atproto/api" "*" "@atproto/api" "*"
"@atproto/common" "*" "@atproto/common" "*"
@ -144,6 +144,7 @@
express "^4.17.2" express "^4.17.2"
express-async-errors "^3.1.1" express-async-errors "^3.1.1"
file-type "^16.5.4" file-type "^16.5.4"
form-data "^4.0.0"
handlebars "^4.7.7" handlebars "^4.7.7"
http-errors "^2.0.0" http-errors "^2.0.0"
http-terminator "^3.2.0" http-terminator "^3.2.0"