Compare commits

...

80 Commits

Author SHA1 Message Date
Eric Bailey 3e5b5f470d Reduce calls to getLogs 2024-11-15 11:35:34 -06:00
Eric Bailey db39f3e98a Reduce listConvos requests (#6378)
* Reduce page size for request

* Remove refetch interval entirely

* Add comment

* Optimistically mark as read

* Drop default active poll interval to 60s from 5min

* Only optimistically update unread count if success
2024-11-15 11:34:31 -06:00
dan 18aaa19b97 [Lightbox] Make the animation faster (#6382)
* [Lightbox] Make the animation faster

* Make it faster on Android too
2024-11-15 17:32:25 +00:00
Marc Rousavy 05312cce33 feat: Tweak shared element animation to make it much smoother (#6336) 2024-11-14 19:37:41 +00:00
Bartosz Kaszubowski 7d34f6bb5c NewChatDialog: remove extra padding on web (#6333) 2024-11-14 17:56:33 +00:00
Eric Bailey 5f7caf3010 Make ToggleButton full width everywhere (#6302)
* Fix 'Show badge' button label being cut off (#6215)

* Make em full width

---------

Co-authored-by: Khuddite <62555977+khuddite@users.noreply.github.com>
2024-11-13 21:55:19 +00:00
Paul Frazee 9640f08b8d Modify self labels for clarity 2024-11-13 21:54:24 +00:00
Paul Frazee ea0a1c3200 Test fixes 2024-11-13 21:54:24 +00:00
dan 4ca5267b98 [Lightbox] Small tweaks (#6301)
* Tweak lightbox springs

* Speed up dismiss speed

* Don't scroll to top while active lightbox

* Make Android a bit faster
2024-11-13 21:13:07 +00:00
dan 3bab7f7540 Patch RCTScrollView to fix centerContent (#6298) 2024-11-13 16:34:24 +00:00
Samuel Newman 017b7647b1 Add subtle web hover to treeview replies (#6142)
* add subtle web hover to treeview replies

* don't highlight indentation

* adjust position

* clean up some styles
2024-11-13 14:25:56 +00:00
Khuddite aa55798e55 Upgrade react-native-drawer-layout version to v4.0.1 (#6274) 2024-11-12 23:47:28 +00:00
Samuel Newman 6471e809aa Add backdated post indicator (#6156)
* add backdate indicator

* pill style

* add indexedAt

* update indicator - new copy, date in pill

* complete alf migration

* accidentally committed the missing indexedAt *again*!

* copy tweak
2024-11-12 21:02:41 +00:00
Samuel Newman f2916ce528 Slightly reduce rerenders in drawer (#6270)
* slightly reduce renders in drawer

* fix missing hook
2024-11-12 20:44:13 +00:00
Hailey 427f3a8bd7 Add email verification prompts throughout the app (#6174) 2024-11-12 11:18:53 -08:00
Samuel Newman dd8d14e133 dedupe date parsing (#6267) 2024-11-12 18:50:37 +00:00
Samuel Newman df3f71286d add subtle web hover to "View full thread" (#6256) 2024-11-12 17:49:49 +00:00
Samuel Newman b60629aff8 use hairline for feedlike (#6257) 2024-11-12 17:49:14 +00:00
Khuddite ae97032c41 Increase bottom padding for mobile login/signup footer (#6254) 2024-11-12 17:26:13 +00:00
dan b2e11d3171 Reduce Reanimated serialization traffic (#6219) 2024-11-12 17:19:52 +00:00
devin ivy d7841037f1 Embedr: fix build / node version (#6265)
* embedr: increase rate limits

* update embedr node version, build

* tidy
2024-11-12 12:14:47 -05:00
devin ivy af31ceb2b3 embedr: increase rate limits (#6255) 2024-11-12 10:37:33 -05:00
Khuddite 5ee809e421 Update error component of lists to take up the full height instead of its content height (#6236)
Co-authored-by: Samuel Newman <mozzius@protonmail.com>
2024-11-11 23:21:07 +00:00
Trivikram Kamat 7008f61ea4 Update Node.js to 20.x in Dockerfile (#6099)
* Update Node.js to 20.x in Dockerfile

* Update Node.js types and engines entry to 20.x

* Update Node.js version in .nvmrc

* Use node version from .nvmrc in linting job

* Use Type Assertion for clearTimeout
2024-11-11 18:58:22 +00:00
Minseo Lee 9e1a16686a deleted account (#6224) 2024-11-11 18:34:09 +00:00
JustSNguyen 2728de03d3 Fix unscrollable body when returning to desktop mode from mobile mode with navigation drawer open. (#6201)
* fix: only lock body when drawer is opened and not in desktop mode

* Reuse variable

---------

Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
2024-11-11 18:33:47 +00:00
Samuel Newman b85a7da26b fix error screen (#6235) 2024-11-11 18:13:05 +00:00
Khuddite 57464a8fe0 Increase copied animation lingering time for reduced motion (#6220)
* increase copied animation lingering time for reduced motion

* flip the condition

---------

Co-authored-by: dan <dan.abramov@gmail.com>
2024-11-11 10:40:47 +00:00
dan 9247407c70 Don't render unnecessary <Portal> instances (#6217) 2024-11-10 23:03:55 +00:00
Hazem Ali 9a10af7117 Fix Retain Cycles in SheetViewController (#6202)
* Fix retain cycle in SheetViewController.swift

* Fix retain cycles
2024-11-10 22:10:09 +00:00
dan b4412f3333 Fix render loop on Android (#6213) 2024-11-10 20:30:31 +00:00
Hailey 89c93313a3 android scroll performance fixes pt. 1 (#6196) 2024-11-09 16:24:51 -08:00
dan 3aeee1e4aa Fix web image layout (#6195) 2024-11-09 15:15:20 -08:00
dan 42abd97f61 [Lightbox] Always rely on Expo Image cache (#6189)
* Inline useImageAspectRatio

* Switch AutoSizedImage to read dimensions from Expo Image cache

* Include thumbnail dimensions in image data

* Use dims from Expo Image cache in lightbox

* Fix wiring so all thumbnails get dimensions

* Fix type

* Oops
2024-11-09 22:41:14 +00:00
dan 2d73c5a24c [Lightbox] Open animation (#6159)
* Measure all rects for embeds

* Measure avi rects too

* Animate lightbox in and out

* Account for safe area in the animation

* Tune spring times

* Remove null checks for measurements

* Remove superfluous view

* Block swipe while opening

* Interpolate width/height on native side for Android

* Make it fast by animating only affine transforms

* Fix tall image final state

The initial animation frame is still off on both platforms.

* Try to squeeze perf

* Avoid blank images during animation on iOS

* Fix bad rebase

* Fix a huge memory issue due to expo/expo#24894

* Fix last frame flash

* Fix thum dim calculation for tall images
2024-11-09 22:34:46 +00:00
Trivikram Kamat e73d5c6c20 Use ENV key=value in Dockerfile (#6100) 2024-11-09 13:24:48 -08:00
surfdude29 bf0a847ffe Tiny tweak to Thread Preferences string (#6177) 2024-11-08 23:28:23 -08:00
khuddite a6d009d06b set includeFontPadding false for fixed TextInput height on Android (#6170) 2024-11-09 00:10:04 +00:00
dan a908308810 Revert "Revert "Increase memory on iOS (#6141)" (#6165)" (#6176)
This reverts commit 7c45f7dcc7.
2024-11-09 00:08:00 +00:00
Samuel Newman 5da3f29498 [Settings] Ungate, and remove old settings (#6144)
* move export car dialog

* move disableemail2fadialog

* delete old settings screens

* fix type error

* Update Navigation.tsx

* Delete AccountDropdownBtn.tsx

* remove old change handle modal

* delete add app paswords

* forgot to actually delete the change handle modal
2024-11-08 22:42:18 +00:00
Hailey e8a03058bb options to checkbox (#6175) 2024-11-08 14:28:52 -08:00
Samuel Newman 7b5e8ae5ce [Settings] Improved account switcher (#6131)
* move out avatarstack to own file

* improved settings switch

* prefix with @

* fix types

* up chevron

* respect reduced motion setting

* respect reduced motion in other place
2024-11-08 19:04:18 +00:00
Samuel Newman e9d7c444ce fix 3 image grid in DMs (#6163) 2024-11-08 18:00:39 +00:00
dan ce8d62f8c9 Fix stuck lightbox (#6166)
* Add early exit guards once the gesture is over

* Work around the Reanimated bug

* Move derived reaction upwards to avoid duplicating it
2024-11-08 17:48:01 +00:00
dan 7c45f7dcc7 Revert "Increase memory on iOS (#6141)" (#6165)
This reverts commit 6570f56d8e.
2024-11-08 16:24:03 +00:00
gpp-0 6b1ffffce9 Fix non-home screen soft resetting when feed is selected from right nav (#6158) 2024-11-08 04:19:52 +00:00
Samuel Newman 468c4b8f5a Improve chat performance (#6157)
* fix worklet funcs on gestures

* don't access .value in render
2024-11-08 03:38:32 +00:00
dan 22dd4947f7 [Lightbox] Add border radius to avatars (#6136)
* Preserve shape in lightbox

* Rename shapes to semantic meanings

It looks like after all I do want to fork based on those.

* Round avatars on the web

* Oops
2024-11-08 02:52:03 +00:00
dan 5d0610d419 [Lightbox] New dismiss gesture (#6135)
* Make iOS scrollview bounded to the image

I've had to remove the dismiss handling because the scroll view no longer scrolls at rest.

* Fix double-tap not working right after a vertical swipe

It seems like for some reason the vertical swipe is still being handled by the scroll view, so double tap gets eaten while it's "coming back". But you don't really see it moving. Weird.

* Add an intermediate LightboxImage component

* Hoist useImageDimensions up

* Implement xplat dismiss gesture

This is now shared between platforms, letting us animate the backdrop and add a consistent "fly away" behavior.

* Optimize Android compositing perf

* Fix supertall images

For example, https://bsky.app/profile/schlagteslinks.bsky.social/post/3l7y4l6yur72e

* Fix oopsie
2024-11-08 02:49:32 +00:00
Samuel Newman 6570f56d8e Increase memory on iOS (#6141)
* increase memory on ios

* add extended-virtual-addressing
2024-11-07 13:21:05 +00:00
dan d666a2d7c3 [Lightbox] Set 2 as minimal allowed zoom level (#6132)
* [Lightbox] Set 2 as minimal allowed zoom level on iOS

* Fix both Android and iOS
2024-11-06 20:38:22 +00:00
Samuel Newman 27bbf8b67a dev options in new settings (#6128) 2024-11-06 17:59:22 +00:00
Samuel Newman 325bf1988a link up verify email dialog (#6042) 2024-11-06 17:55:10 +00:00
Hailey 324c5a44a5 fix prop names (#6130) 2024-11-06 17:47:51 +00:00
khuddite f95acdc836 Fix thin red circle around Like button on iOS (#6123)
* remove animation UI from DOM tree when not animated

* improve naming of vars

* more var changes

---------

Co-authored-by: Hailey <me@haileyok.com>
2024-11-06 12:36:31 +00:00
dan 206df2ab80 Remove SCREEN from lightbox layout (#6124)
* Assign an ID to lightbox and use it as a key

* Consolidate lightbox props into an object

* Remove unused prop

* Move SafeAreaView declaration

* Keep SafeAreaView always mounted

When exploring Android animation, I noticed its content jumps on the first frame. I think this should help prevent that.

* Pass safe area down for measurement

* Remove dependency on SCREEN in Android event handlers

* Remove dependency on SCREEN in iOS event handlers

* Remove dependency on SCREEN on iOS

* Remove dependency on SCREEN on Android

* Remove dependency on JS calc in controls

* Use flex for iOS layout
2024-11-06 00:21:35 +00:00
dan 6b826fb88d Lower feedfeedback seen threshold to 0.5s (#6127) 2024-11-05 22:27:48 +00:00
dan 84fb1b7f97 Update Reanimated (#6126)
* Update Reanimated

* Fix types

* Fix Reanimated value access warnings

* Fix types
2024-11-05 22:27:36 +00:00
Samuel Newman b0c5a37daa Improve accessibility for navigation on web (#6120)
* improve accessibility for bottom bar tabs

* improve a11y for left nav

* group main content into <main>

* use flex_1 rather than absoluteFill
2024-11-05 16:48:36 +00:00
Rohit Bansal 9772116343 Fixed issue 5845 (#6085) 2024-11-05 16:27:30 +00:00
Samuel Newman b0b00c9c7a use megabytes rather than mebibytes for video limit (#6117) 2024-11-05 16:00:30 +00:00
Bartosz Kaszubowski a78179aab3 StarterPack: fix "Follow All" processing layout (#6111) 2024-11-05 15:14:15 +00:00
Lars Kappert f8fb6cb9b3 Fix start value in youtube embed by removing "s" from url param (#6113) 2024-11-05 12:43:20 +00:00
Samuel Newman ab4e36115b return to using whitespace (#6109) 2024-11-04 21:47:35 +00:00
Samuel Newman 86840f2785 translate sort replies (#6110) 2024-11-04 21:47:21 +00:00
dan 26c48373e2 Refactor lightbox prop drilling (#6073)
* Refactor lightbox footer to render prop

* Unify lightbox types

* Unindent

* Refactor LightboxFooter props

* Move LightboxFooter into the implementation file
2024-11-04 21:31:21 +00:00
dan 174988bc5a Unify dimensions cache between lightbox and feed (#6047)
* Remove useless memo

* Use explicit values when useImageAspectRatio doesn't know

It's not very good that you can't distingiush when we haven't loaded vs when we're certain. This shifts the burden of dealing with missing values to the caller.

* Check cache early

* Handle src change

* Rewrite image-sizes.fetch to avoid mixing async styles

* Make image-sizes LRU

Code is copy paste from useImageDimensions.ts

* Rm unused fields

* Derive aspect on the fly

* Factor useImageDimensions out of useImageAspectRatio

* Move useImageDimensions into image-sizes

* Make lightbox use the same cache

* Wire up known dimensions to the lightbox

* Handle division by zero in the hook

* Use safe aspect for lightbox calculations
2024-11-04 21:28:27 +00:00
Cynthia ac9d910e1e fix(a11y): avoid plain divs as button or tabs (#6084)
Co-authored-by: Hailey <me@haileyok.com>
2024-11-03 09:18:27 -08:00
Yaël Guilloux c580f20b53 Improve focus-visible outlines in navigation (#6061)
* feat add focus_visible atom

* feat use focus_visible atom in Button.tsx style

* Tweak

---------

Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
2024-11-01 23:18:19 +00:00
dan 7111e38cd4 Revert "React compiler beta and reenable rule (#5898)" (#6071)
This reverts commit 1fc684aaef.
2024-11-01 22:17:05 +00:00
dan 3eb531b000 Composer UI fixes (#6065)
* Fix close button overlap

* Make footer actually sticky on web

* Special toast for thread

* Only stick to bottom for last post
2024-11-01 22:02:39 +00:00
dan 46004fb2d0 Fix duplicates in thread composer (#6068) 2024-11-01 21:55:37 +00:00
Samuel Newman d33ce1dea1 change language for autoplay setting (#6069) 2024-11-01 21:10:25 +00:00
dan ff01ffe35f Fix some images getting squished on Android due to EXIF tags (#6058) 2024-11-01 19:25:31 +00:00
Ben Harris 5c5fc3230b fix text clipping around external embed's domain (#6012) 2024-11-01 12:15:44 -07:00
dan 2398b84d17 Change post Follow button color on toggle (#6059) 2024-11-01 19:09:28 +00:00
Hailey fb4210b36c Add dids for discover debug (#6063)
* add dids

* keep is_internal
2024-11-01 19:09:13 +00:00
dan 8d5b551ed6 Hook debugTopics to override X-Bsky-Topics (#6060) 2024-11-01 18:28:54 +00:00
dan 125ac5049a [Statsig] Track threads (#6057)
* [Statsig] Send thread length

* Split events
2024-11-01 16:21:18 +00:00
dan 1c2186bc03 Fix character count with intent (#6056) 2024-11-01 16:21:10 +00:00
145 changed files with 3545 additions and 5531 deletions
+2 -1
View File
@@ -79,7 +79,8 @@ module.exports = {
},
],
'simple-import-sort/exports': 'error',
'react-compiler/react-compiler': 'warn',
// TODO: Reenable when we figure out why it gets stuck on CI.
// 'react-compiler/react-compiler': 'error',
'no-restricted-imports': [
'error',
{
@@ -3,8 +3,6 @@ on:
push:
branches:
- main
- bnewbold/embedr
- bnewbold/embedr-rebase
env:
REGISTRY: ${{ secrets.AWS_ECR_REGISTRY_USEAST2_PACKAGES_REGISTRY }}
+4
View File
@@ -16,6 +16,10 @@ jobs:
steps:
- name: Check out Git repository
uses: actions/checkout@v3
- name: Install node
uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- name: Yarn install
uses: Wandalen/wretry.action@master
with:
+1 -1
View File
@@ -1 +1 @@
18
20
+2 -2
View File
@@ -5,7 +5,7 @@ WORKDIR /usr/src/social-app
ENV DEBIAN_FRONTEND=noninteractive
# Node
ENV NODE_VERSION=18
ENV NODE_VERSION=20
ENV NVM_DIR=/usr/share/nvm
# Go
@@ -17,7 +17,7 @@ ENV GOEXPERIMENT="loopvar"
# Expo
ARG EXPO_PUBLIC_BUNDLE_IDENTIFIER
ENV EXPO_PUBLIC_BUNDLE_IDENTIFIER ${EXPO_PUBLIC_BUNDLE_IDENTIFIER:-dev}
ENV EXPO_PUBLIC_BUNDLE_IDENTIFIER=${EXPO_PUBLIC_BUNDLE_IDENTIFIER:-dev}
COPY . .
+1 -1
View File
@@ -5,7 +5,7 @@ WORKDIR /usr/src/social-app
ENV DEBIAN_FRONTEND=noninteractive
# Node
ENV NODE_VERSION=18
ENV NODE_VERSION=20
ENV NVM_DIR=/usr/share/nvm
# Go
+2 -2
View File
@@ -17,8 +17,8 @@ appId: xyz.blueskyweb.app
- inputText: "Post with an image"
- tapOn:
id: "openGalleryBtn"
- tapOn:
id: "labelsBtn"
- tapOn: "Content warnings"
- tapOn: "Content warnings"
- tapOn: "Porn"
- tapOn:
label: "Tap on confirm"
-1
View File
@@ -29,7 +29,6 @@ appId: xyz.blueskyweb.app
- pressKey: Enter
- tapOn:
id: "nextBtn"
- tapOn: "Not now"
- tapOn:
id: "handleInput"
- inputText: "e2e-test"
+4
View File
@@ -23,6 +23,7 @@ appId: xyz.blueskyweb.app
id: "editDescriptionInput"
- inputText: "They good"
- tapOn: "Save"
- tapOn: "Save"
- assertNotVisible:
id: "createOrEditListModal"
- tapOn: "About"
@@ -45,6 +46,7 @@ appId: xyz.blueskyweb.app
- eraseText
- inputText: "They bad"
- tapOn: "Save"
- tapOn: "Save"
- assertNotVisible:
id: "createOrEditListModal"
- assertVisible: Bad Ppl
@@ -60,6 +62,7 @@ appId: xyz.blueskyweb.app
id: "editDescriptionInput"
- eraseText
- tapOn: "Save"
- tapOn: "Save"
- assertNotVisible:
id: "createOrEditListModal"
- assertNotVisible:
@@ -87,6 +90,7 @@ appId: xyz.blueskyweb.app
id: "editDescriptionInput"
- inputText: "They good"
- tapOn: "Save"
- tapOn: "Save"
- assertNotVisible:
id: "createOrEditListModal"
- tapOn: "About"
-1
View File
@@ -23,5 +23,4 @@ appId: xyz.blueskyweb.app
id: "loginPasswordInput"
- inputText: "hunter2"
- pressKey: Enter
- tapOn: "Not now"
- assertVisible: "Following"
+1
View File
@@ -22,6 +22,7 @@ appId: xyz.blueskyweb.app
id: "editDescriptionInput"
- inputText: "Shhh"
- tapOn: "Save"
- tapOn: "Save"
# view modlist
- assertVisible: "Muted Users"
+1 -1
View File
@@ -13,7 +13,7 @@ appId: xyz.blueskyweb.app
- tapOn: "Select an avatar"
- waitForAnimationToEnd
- tapOn:
point: "16%,22%"
point: "50%,22%"
- waitForAnimationToEnd
- tapOn: "Choose"
- waitForAnimationToEnd
+12
View File
@@ -335,8 +335,10 @@ describe('shortenLinks', () => {
describe('parseEmbedPlayerFromUrl', () => {
const inputs = [
'https://youtu.be/videoId',
'https://youtu.be/videoId?t=1s',
'https://www.youtube.com/watch?v=videoId',
'https://www.youtube.com/watch?v=videoId&feature=share',
'https://www.youtube.com/watch?v=videoId&t=1s',
'https://youtube.com/watch?v=videoId',
'https://youtube.com/watch?v=videoId&feature=share',
'https://youtube.com/shorts/videoId',
@@ -441,6 +443,11 @@ describe('parseEmbedPlayerFromUrl', () => {
source: 'youtube',
playerUri: 'https://bsky.app/iframe/youtube.html?videoId=videoId&start=0',
},
{
type: 'youtube_video',
source: 'youtube',
playerUri: 'https://bsky.app/iframe/youtube.html?videoId=videoId&start=1',
},
{
type: 'youtube_video',
source: 'youtube',
@@ -451,6 +458,11 @@ describe('parseEmbedPlayerFromUrl', () => {
source: 'youtube',
playerUri: 'https://bsky.app/iframe/youtube.html?videoId=videoId&start=0',
},
{
type: 'youtube_video',
source: 'youtube',
playerUri: 'https://bsky.app/iframe/youtube.html?videoId=videoId&start=1',
},
{
type: 'youtube_video',
source: 'youtube',
+2
View File
@@ -99,6 +99,8 @@ module.exports = function (config) {
dark: DARK_SPLASH_CONFIG,
},
entitlements: {
'com.apple.developer.kernel.increased-memory-limit': true,
'com.apple.developer.kernel.extended-virtual-addressing': true,
'com.apple.security.application-groups': 'group.app.bsky',
},
privacyManifests: {
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><path fill="#000" fill-rule="evenodd" d="M15.439 3.148a1 1 0 0 1 .41.645l.568 3.22a7 7 0 1 1-6.174 10.97L4.32 19.027a1 1 0 0 1-1.159-.811L1.078 6.398a1 1 0 0 1 .81-1.158l12.803-2.258a1 1 0 0 1 .748.166ZM9.325 16.114A7 7 0 0 1 9 14c0-1.56.51-3 1.372-4.164l-6.456 1.139 1.041 5.909 4.368-.77ZM3.568 9.005l10.833-1.91-.347-1.97L3.22 7.036l.347 1.97ZM16 9a5 5 0 1 0 0 10 5 5 0 0 0 0-10Zm0 2a1 1 0 0 1 1 1v1.586l1.374 1.374a1 1 0 0 1-1.414 1.414l-1.667-1.667A1 1 0 0 1 15 14v-2a1 1 0 0 1 1-1Z" clip-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 589 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><path fill="#000" fill-rule="evenodd" d="M12 4a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5ZM7.5 6.5a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM12 14c-2.95 0-5.163 1.733-6.08 4.21a.47.47 0 0 0 .09.493.9.9 0 0 0 .687.297H11a1 1 0 1 1 0 2H6.697a2.9 2.9 0 0 1-2.219-1.011 2.46 2.46 0 0 1-.433-2.473C5.235 14.296 8.168 12 12 12c.787 0 1.54.097 2.252.282a1 1 0 1 1-.504 1.936A7 7 0 0 0 12 14Zm6 0a1 1 0 0 1 1 1v2h2a1 1 0 1 1 0 2h-2v2a1 1 0 1 1-2 0v-2h-2a1 1 0 1 1 0-2h2v-2a1 1 0 0 1 1-1Z" clip-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 569 B

+6 -1
View File
@@ -17,7 +17,12 @@ module.exports = function (api) {
],
plugins: [
'macros',
['babel-plugin-react-compiler', {target: '18'}],
[
'babel-plugin-react-compiler',
{
runtimeModule: 'react-compiler-runtime',
},
],
[
'module:react-native-dotenv',
{
+2 -2
View File
@@ -112,8 +112,8 @@ func serve(cctx *cli.Context) error {
Skipper: middleware.DefaultSkipper,
Store: middleware.NewRateLimiterMemoryStoreWithConfig(
middleware.RateLimiterMemoryStoreConfig{
Rate: 10, // requests per second
Burst: 30, // allow bursts
Rate: 20, // requests per second
Burst: 150, // allow bursts
ExpiresIn: 3 * time.Minute, // garbage collect entries older than 3 minutes
},
),
+21
View File
@@ -0,0 +1,21 @@
const React = require('react')
const $empty = Symbol.for('react.memo_cache_sentinel')
/**
* DANGER: this hook is NEVER meant to be called directly!
*
* Note that this is a temporary userspace implementation of this function
* from React 19. It is not as efficient and may invalidate more frequently
* than the official API. Please upgrade to React 19 as soon as you can.
**/
export function c(size) {
// eslint-disable-next-line react-hooks/rules-of-hooks
return React.useState(() => {
const $ = new Array(size)
for (let ii = 0; ii < size; ii++) {
$[ii] = $empty
}
// @ts-ignore
$[$empty] = true
return $
})[0]
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "react-compiler-runtime",
"version": "0.0.1",
"license": "MIT",
"main": "index.js",
"peerDependencies": {
"react": "^18.2.0"
}
}
@@ -64,11 +64,14 @@ class SheetViewController: UIViewController {
func updateDetents(contentHeight: CGFloat, preventExpansion: Bool) {
if let sheet = self.sheetPresentationController {
sheet.animateChanges {
self.setDetents(contentHeight: contentHeight, preventExpansion: preventExpansion)
if #available(iOS 16.0, *) {
sheet.invalidateDetents()
}
// Capture `self` weakly to prevent retain cycles.
// Also, capture `sheet` weakly to avoid potential strong references held by animateChanges.
sheet.animateChanges { [weak self, weak sheet] in
guard let weakSelf = self, let weakSheet = sheet else { return }
weakSelf.setDetents(contentHeight: contentHeight, preventExpansion: preventExpansion)
if #available(iOS 16.0, *) {
weakSheet.invalidateDetents()
}
}
}
}
+1 -24
View File
@@ -1,24 +1 @@
import React from 'react'
import {BottomSheetViewProps} from './BottomSheet.types'
import {BottomSheetNativeComponent} from './BottomSheetNativeComponent'
import {useBottomSheetPortal_INTERNAL} from './BottomSheetPortal'
export const BottomSheet = React.forwardRef<
BottomSheetNativeComponent,
BottomSheetViewProps
>(function BottomSheet(props, ref) {
const Portal = useBottomSheetPortal_INTERNAL()
if (__DEV__ && !Portal) {
throw new Error(
'BottomSheet: You need to wrap your component tree with a <BottomSheetPortalProvider> to use the bottom sheet.',
)
}
return (
<Portal>
<BottomSheetNativeComponent {...props} ref={ref} />
</Portal>
)
})
export {BottomSheetNativeComponent as BottomSheet} from './BottomSheetNativeComponent'
@@ -11,6 +11,7 @@ import {requireNativeModule, requireNativeViewManager} from 'expo-modules-core'
import {BottomSheetState, BottomSheetViewProps} from './BottomSheet.types'
import {BottomSheetPortalProvider} from './BottomSheetPortal'
import {Context as PortalContext} from './BottomSheetPortal'
const screenHeight = Dimensions.get('screen').height
@@ -34,6 +35,8 @@ export class BottomSheetNativeComponent extends React.Component<
> {
ref = React.createRef<any>()
static contextType = PortalContext
constructor(props: BottomSheetViewProps) {
super(props)
this.state = {
@@ -67,6 +70,17 @@ export class BottomSheetNativeComponent extends React.Component<
}
render() {
const Portal = this.context as React.ContextType<typeof PortalContext>
if (!Portal) {
throw new Error(
'BottomSheet: You need to wrap your component tree with a <BottomSheetPortalProvider> to use the bottom sheet.',
)
}
if (!this.state.open) {
return null
}
const {children, backgroundColor, ...rest} = this.props
const cornerRadius = rest.cornerRadius ?? 0
@@ -83,43 +97,41 @@ export class BottomSheetNativeComponent extends React.Component<
}
}
if (!this.state.open) {
return null
}
return (
<NativeView
{...rest}
onStateChange={this.onStateChange}
ref={this.ref}
style={{
position: 'absolute',
height: screenHeight,
width: '100%',
}}
containerBackgroundColor={backgroundColor}>
<View
style={[
{
flex: 1,
backgroundColor,
},
Platform.OS === 'android' && {
borderTopLeftRadius: cornerRadius,
borderTopRightRadius: cornerRadius,
},
extraStyles,
]}>
<Portal>
<NativeView
{...rest}
onStateChange={this.onStateChange}
ref={this.ref}
style={{
position: 'absolute',
height: screenHeight,
width: '100%',
}}
containerBackgroundColor={backgroundColor}>
<View
onLayout={e => {
const {height} = e.nativeEvent.layout
this.setState({viewHeight: height})
this.updateLayout()
}}>
<BottomSheetPortalProvider>{children}</BottomSheetPortalProvider>
style={[
{
flex: 1,
backgroundColor,
},
Platform.OS === 'android' && {
borderTopLeftRadius: cornerRadius,
borderTopRightRadius: cornerRadius,
},
extraStyles,
]}>
<View
onLayout={e => {
const {height} = e.nativeEvent.layout
this.setState({viewHeight: height})
this.updateLayout()
}}>
<BottomSheetPortalProvider>{children}</BottomSheetPortalProvider>
</View>
</View>
</View>
</NativeView>
</NativeView>
</Portal>
)
}
}
@@ -4,7 +4,7 @@ import {createPortalGroup_INTERNAL} from './lib/Portal'
type PortalContext = React.ElementType<{children: React.ReactNode}>
const Context = React.createContext({} as PortalContext)
export const Context = React.createContext({} as PortalContext)
export const useBottomSheetPortal_INTERNAL = () => React.useContext(Context)
+7 -7
View File
@@ -3,7 +3,7 @@
"version": "1.94.0",
"private": true,
"engines": {
"node": ">=18"
"node": ">=20"
},
"packageManager": "yarn@1.22.19",
"scripts": {
@@ -103,7 +103,7 @@
"@tiptap/suggestion": "^2.6.6",
"@types/invariant": "^2.2.37",
"@types/lodash.throttle": "^4.1.9",
"@types/node": "^18.16.2",
"@types/node": "^20.14.3",
"@zxing/text-encoding": "^0.9.0",
"array.prototype.findlast": "^1.2.3",
"await-lock": "^2.2.2",
@@ -166,14 +166,14 @@
"postinstall-postinstall": "^2.1.0",
"psl": "^1.9.0",
"react": "18.2.0",
"react-compiler-runtime": "^19.0.0-beta-6fc168f-20241025",
"react-compiler-runtime": "file:./lib/react-compiler-runtime",
"react-dom": "^18.2.0",
"react-image-crop": "^11.0.7",
"react-keyed-flatten-children": "^3.0.0",
"react-native": "0.74.1",
"react-native-compressor": "^1.8.24",
"react-native-date-picker": "^4.4.2",
"react-native-drawer-layout": "^4.0.0-alpha.3",
"react-native-drawer-layout": "^4.0.1",
"react-native-gesture-handler": "2.20.0",
"react-native-get-random-values": "~1.11.0",
"react-native-image-crop-picker": "0.41.2",
@@ -184,7 +184,7 @@
"react-native-picker-select": "^9.1.3",
"react-native-progress": "bluesky-social/react-native-progress",
"react-native-qrcode-styled": "^0.3.1",
"react-native-reanimated": "^3.11.0",
"react-native-reanimated": "^3.16.1",
"react-native-root-siblings": "^4.1.1",
"react-native-safe-area-context": "4.10.1",
"react-native-screens": "~3.31.1",
@@ -243,7 +243,7 @@
"babel-loader": "^9.1.2",
"babel-plugin-macros": "^3.1.0",
"babel-plugin-module-resolver": "^5.0.0",
"babel-plugin-react-compiler": "^19.0.0-beta-6fc168f-20241025",
"babel-plugin-react-compiler": "^0.0.0-experimental-592953e-20240517",
"babel-plugin-react-native-web": "^0.18.12",
"babel-preset-expo": "^10.0.0",
"eslint": "^8.19.0",
@@ -251,7 +251,7 @@
"eslint-plugin-ft-flow": "^2.0.3",
"eslint-plugin-lingui": "^0.2.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-compiler": "^19.0.0-beta-6fc168f-20241025",
"eslint-plugin-react-compiler": "^0.0.0-experimental-c8b3f72-20240517",
"eslint-plugin-react-native-a11y": "^3.3.0",
"eslint-plugin-simple-import-sort": "^12.0.0",
"html-webpack-plugin": "^5.5.0",
+18
View File
@@ -0,0 +1,18 @@
diff --git a/node_modules/expo-image-picker/android/src/main/java/expo/modules/imagepicker/exporters/RawImageExporter.kt b/node_modules/expo-image-picker/android/src/main/java/expo/modules/imagepicker/exporters/RawImageExporter.kt
index f339e5f..fa35e82 100644
--- a/node_modules/expo-image-picker/android/src/main/java/expo/modules/imagepicker/exporters/RawImageExporter.kt
+++ b/node_modules/expo-image-picker/android/src/main/java/expo/modules/imagepicker/exporters/RawImageExporter.kt
@@ -16,7 +16,12 @@ class RawImageExporter : ImageExporter {
copyFile(source, output, contentResolver)
val exifInterface = ExifInterface(output.absolutePath)
val imageRotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0)
- val isRotatedLandscape = (imageRotation == ExifInterface.ORIENTATION_ROTATE_90 || imageRotation == ExifInterface.ORIENTATION_ROTATE_270)
+ val isRotatedLandscape = (
+ imageRotation == ExifInterface.ORIENTATION_ROTATE_90 ||
+ imageRotation == ExifInterface.ORIENTATION_ROTATE_270 ||
+ imageRotation == ExifInterface.ORIENTATION_TRANSPOSE ||
+ imageRotation == ExifInterface.ORIENTATION_TRANSVERSE
+ )
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(output.absolutePath, options)
+125 -12
View File
@@ -9,7 +9,7 @@ index caa5540..c5d4e67 100644
- type != nil && [type length] > 0 ? type : @"application/octet-stream",
+ ![type isEqual:[NSNull null]] && [type length] > 0 ? type : @"application/octet-stream",
[data base64EncodedStringWithOptions:0]];
resolve(text);
diff --git a/node_modules/react-native/Libraries/Text/TextInput/RCTBaseTextInputView.mm b/node_modules/react-native/Libraries/Text/TextInput/RCTBaseTextInputView.mm
index b0d71dc..41b9a0e 100644
@@ -18,7 +18,7 @@ index b0d71dc..41b9a0e 100644
@@ -377,10 +377,6 @@ - (void)textInputDidBeginEditing
self.backedTextInputView.attributedText = [NSAttributedString new];
}
- if (_selectTextOnFocus) {
- [self.backedTextInputView selectAll:nil];
- }
@@ -35,7 +35,7 @@ index b0d71dc..41b9a0e 100644
+ [self.backedTextInputView selectAll:nil];
+ }
}
- (void)reactBlur
diff --git a/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControl.h b/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControl.h
index e9b330f..ec5f58c 100644
@@ -48,10 +48,10 @@ index e9b330f..ec5f58c 100644
+@property (nonatomic, copy) UIColor *customTintColor;
+
+- (void)forwarderBeginRefreshing;
@end
diff --git a/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControl.m b/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControl.m
index b09e653..288e60c 100644
index b09e653..d2b4e05 100644
--- a/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControl.m
+++ b/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControl.m
@@ -22,6 +22,7 @@ @implementation RCTRefreshControl {
@@ -60,12 +60,12 @@ index b09e653..288e60c 100644
CGFloat _progressViewOffset;
+ UIColor *_customTintColor;
}
- (instancetype)init
@@ -56,6 +57,12 @@ - (void)layoutSubviews
_isInitialRender = false;
}
+- (void)didMoveToSuperview
+{
+ [super didMoveToSuperview];
@@ -78,7 +78,7 @@ index b09e653..288e60c 100644
@@ -203,4 +210,58 @@ - (void)refreshControlValueChanged
}
}
+- (void)setCustomTintColor:(UIColor *)customTintColor
+{
+ _customTintColor = customTintColor;
@@ -139,26 +139,139 @@ index 40aaf9c..1c60164 100644
--- a/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControlManager.m
+++ b/node_modules/react-native/React/Views/RefreshControl/RCTRefreshControlManager.m
@@ -22,11 +22,12 @@ - (UIView *)view
RCT_EXPORT_VIEW_PROPERTY(onRefresh, RCTDirectEventBlock)
RCT_EXPORT_VIEW_PROPERTY(refreshing, BOOL)
-RCT_EXPORT_VIEW_PROPERTY(tintColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(title, NSString)
RCT_EXPORT_VIEW_PROPERTY(titleColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(progressViewOffset, CGFloat)
+RCT_REMAP_VIEW_PROPERTY(tintColor, customTintColor, UIColor)
+
RCT_EXPORT_METHOD(setNativeRefreshing : (nonnull NSNumber *)viewTag toRefreshing : (BOOL)refreshing)
{
[self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
diff --git a/node_modules/react-native/React/Views/ScrollView/RCTScrollView.m b/node_modules/react-native/React/Views/ScrollView/RCTScrollView.m
index 1aead51..39e6244 100644
--- a/node_modules/react-native/React/Views/ScrollView/RCTScrollView.m
+++ b/node_modules/react-native/React/Views/ScrollView/RCTScrollView.m
@@ -159,31 +159,6 @@ - (BOOL)touchesShouldCancelInContentView:(__unused UIView *)view
return !shouldDisableScrollInteraction;
}
-/*
- * Automatically centers the content such that if the content is smaller than the
- * ScrollView, we force it to be centered, but when you zoom or the content otherwise
- * becomes larger than the ScrollView, there is no padding around the content but it
- * can still fill the whole view.
- */
-- (void)setContentOffset:(CGPoint)contentOffset
-{
- UIView *contentView = [self contentView];
- if (contentView && _centerContent && !CGSizeEqualToSize(contentView.frame.size, CGSizeZero)) {
- CGSize subviewSize = contentView.frame.size;
- CGSize scrollViewSize = self.bounds.size;
- if (subviewSize.width <= scrollViewSize.width) {
- contentOffset.x = -(scrollViewSize.width - subviewSize.width) / 2.0;
- }
- if (subviewSize.height <= scrollViewSize.height) {
- contentOffset.y = -(scrollViewSize.height - subviewSize.height) / 2.0;
- }
- }
-
- super.contentOffset = CGPointMake(
- RCTSanitizeNaNValue(contentOffset.x, @"scrollView.contentOffset.x"),
- RCTSanitizeNaNValue(contentOffset.y, @"scrollView.contentOffset.y"));
-}
-
- (void)setFrame:(CGRect)frame
{
// Preserving and revalidating `contentOffset`.
@@ -427,6 +402,11 @@ - (void)setRemoveClippedSubviews:(__unused BOOL)removeClippedSubviews
// Does nothing
}
+- (void)setFrame:(CGRect)frame {
+ [super setFrame:frame];
+ [self centerContentIfNeeded];
+}
+
- (void)insertReactSubview:(UIView *)view atIndex:(NSInteger)atIndex
{
[super insertReactSubview:view atIndex:atIndex];
@@ -444,6 +424,8 @@ - (void)insertReactSubview:(UIView *)view atIndex:(NSInteger)atIndex
RCTApplyTransformationAccordingLayoutDirection(_contentView, self.reactLayoutDirection);
[_scrollView addSubview:view];
}
+
+ [self centerContentIfNeeded];
}
- (void)removeReactSubview:(UIView *)subview
@@ -652,9 +634,46 @@ -(void)delegateMethod : (UIScrollView *)scrollView \
}
RCT_SCROLL_EVENT_HANDLER(scrollViewWillBeginDecelerating, onMomentumScrollBegin)
-RCT_SCROLL_EVENT_HANDLER(scrollViewDidZoom, onScroll)
RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop)
+-(void)scrollViewDidZoom : (UIScrollView *)scrollView
+{
+ [self centerContentIfNeeded];
+
+ RCT_SEND_SCROLL_EVENT(onScroll, nil);
+ RCT_FORWARD_SCROLL_EVENT(scrollViewDidZoom : scrollView);
+}
+
+/*
+ * Automatically centers the content such that if the content is smaller than the
+ * ScrollView, we force it to be centered, but when you zoom or the content otherwise
+ * becomes larger than the ScrollView, there is no padding around the content but it
+ * can still fill the whole view.
+ *
+ * PATCHED: This deviates from the original React Native implementation to fix two issues:
+ *
+ * - The scroll view was swallowing any taps immediately after pinching
+ * - The scroll view was jittering when crossing the full screen threshold while pinching
+ *
+ * This implementation is based on https://petersteinberger.com/blog/2013/how-to-center-uiscrollview/.
+ */
+-(void)centerContentIfNeeded
+{
+ if (_scrollView.centerContent &&
+ !CGSizeEqualToSize(self.contentSize, CGSizeZero) &&
+ !CGSizeEqualToSize(self.bounds.size, CGSizeZero)
+ ) {
+ CGFloat top = 0, left = 0;
+ if (self.contentSize.width < self.bounds.size.width) {
+ left = (self.bounds.size.width - self.contentSize.width) * 0.5f;
+ }
+ if (self.contentSize.height < self.bounds.size.height) {
+ top = (self.bounds.size.height - self.contentSize.height) * 0.5f;
+ }
+ _scrollView.contentInset = UIEdgeInsetsMake(top, left, top, left);
+ }
+}
+
- (void)addScrollListener:(NSObject<UIScrollViewDelegate> *)scrollListener
{
[_scrollListeners addObject:scrollListener];
@@ -913,6 +932,7 @@ - (void)updateContentSizeIfNeeded
CGSize contentSize = self.contentSize;
if (!CGSizeEqualToSize(_scrollView.contentSize, contentSize)) {
_scrollView.contentSize = contentSize;
+ [self centerContentIfNeeded];
}
}
diff --git a/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java b/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java
index 5f5e1ab..aac00b6 100644
--- a/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java
+++ b/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java
@@ -99,8 +99,9 @@ public class JavaTimerManager {
}
// If the JS thread is busy for multiple frames we cancel any other pending runnable.
- if (mCurrentIdleCallbackRunnable != null) {
- mCurrentIdleCallbackRunnable.cancel();
@@ -166,5 +279,5 @@ index 5f5e1ab..aac00b6 100644
+ if (currentRunnable != null) {
+ currentRunnable.cancel();
}
mCurrentIdleCallbackRunnable = new IdleCallbackRunnable(frameTimeNanos);
@@ -1,209 +0,0 @@
diff --git a/node_modules/react-native-reanimated/src/createAnimatedComponent/commonTypes.ts b/node_modules/react-native-reanimated/src/createAnimatedComponent/commonTypes.ts
index 92ebe62..5f8207e 100644
--- a/node_modules/react-native-reanimated/src/createAnimatedComponent/commonTypes.ts
+++ b/node_modules/react-native-reanimated/src/createAnimatedComponent/commonTypes.ts
@@ -96,7 +96,8 @@ export interface AnimatedComponentRef extends Component {
export interface IAnimatedComponentInternal {
_styles: StyleProps[] | null;
_animatedProps?: Partial<AnimatedComponentProps<AnimatedProps>>;
- _viewTag: number;
+ _componentViewTag: number;
+ _eventViewTag: number;
_isFirstRender: boolean;
jestAnimatedStyle: { value: StyleProps };
_component: AnimatedComponentRef | HTMLElement | null;
diff --git a/node_modules/react-native-reanimated/src/createAnimatedComponent/createAnimatedComponent.tsx b/node_modules/react-native-reanimated/src/createAnimatedComponent/createAnimatedComponent.tsx
index 88b3fdf..2488ebc 100644
--- a/node_modules/react-native-reanimated/src/createAnimatedComponent/createAnimatedComponent.tsx
+++ b/node_modules/react-native-reanimated/src/createAnimatedComponent/createAnimatedComponent.tsx
@@ -122,7 +122,8 @@ export function createAnimatedComponent(
{
_styles: StyleProps[] | null = null;
_animatedProps?: Partial<AnimatedComponentProps<AnimatedProps>>;
- _viewTag = -1;
+ _componentViewTag = -1;
+ _eventViewTag = -1;
_isFirstRender = true;
jestAnimatedStyle: { value: StyleProps } = { value: {} };
_component: AnimatedComponentRef | HTMLElement | null = null;
@@ -143,7 +144,8 @@ export function createAnimatedComponent(
}
componentDidMount() {
- this._viewTag = this._getViewInfo().viewTag as number;
+ this._setComponentViewTag();
+ this._setEventViewTag();
this._attachNativeEvents();
this._jsPropsUpdater.addOnJSPropsChangeListener(this);
this._attachAnimatedStyles();
@@ -185,7 +187,10 @@ export function createAnimatedComponent(
if (this.props.sharedTransitionTag) {
this._configureSharedTransition(true);
}
- this._sharedElementTransition?.unregisterTransition(this._viewTag, true);
+ this._sharedElementTransition?.unregisterTransition(
+ this._componentViewTag,
+ true
+ );
const exiting = this.props.exiting;
if (
@@ -209,7 +214,7 @@ export function createAnimatedComponent(
: getReduceMotionFromConfig();
if (!reduceMotionInExiting) {
updateLayoutAnimations(
- this._viewTag,
+ this._componentViewTag,
LayoutAnimationType.EXITING,
maybeBuild(
exiting,
@@ -221,12 +226,22 @@ export function createAnimatedComponent(
}
}
- _getEventViewRef() {
- // Make sure to get the scrollable node for components that implement
- // `ScrollResponder.Mixin`.
- return (this._component as AnimatedComponentRef)?.getScrollableNode
- ? (this._component as AnimatedComponentRef).getScrollableNode?.()
- : this._component;
+ _setComponentViewTag() {
+ this._componentViewTag = this._getViewInfo().viewTag as number;
+ }
+
+ _setEventViewTag() {
+ // Setting the tag for registering events - since the event emitting view can be nested inside the main component
+ const componentAnimatedRef = this._component as AnimatedComponentRef;
+ if (componentAnimatedRef.getScrollableNode) {
+ const scrollableNode = componentAnimatedRef.getScrollableNode();
+ this._eventViewTag = findNodeHandle(scrollableNode) ?? -1;
+ } else {
+ this._eventViewTag =
+ findNodeHandle(
+ options?.setNativeProps ? this : componentAnimatedRef
+ ) ?? -1;
+ }
}
_attachNativeEvents() {
@@ -236,7 +251,7 @@ export function createAnimatedComponent(
has('workletEventHandler', prop) &&
prop.workletEventHandler instanceof WorkletEventHandler
) {
- prop.workletEventHandler.registerForEvents(this._viewTag, key);
+ prop.workletEventHandler.registerForEvents(this._eventViewTag, key);
}
}
}
@@ -248,7 +263,7 @@ export function createAnimatedComponent(
has('workletEventHandler', prop) &&
prop.workletEventHandler instanceof WorkletEventHandler
) {
- prop.workletEventHandler.unregisterFromEvents(this._viewTag);
+ prop.workletEventHandler.unregisterFromEvents(this._eventViewTag);
}
}
}
@@ -258,15 +273,17 @@ export function createAnimatedComponent(
for (const style of this._styles) {
style.viewsRef.remove(this);
}
- } else if (this._viewTag !== -1 && this._styles !== null) {
+ } else if (this._componentViewTag !== -1 && this._styles !== null) {
for (const style of this._styles) {
- style.viewDescriptors.remove(this._viewTag);
+ style.viewDescriptors.remove(this._componentViewTag);
}
if (this.props.animatedProps?.viewDescriptors) {
- this.props.animatedProps.viewDescriptors.remove(this._viewTag);
+ this.props.animatedProps.viewDescriptors.remove(
+ this._componentViewTag
+ );
}
if (isFabric()) {
- removeFromPropsRegistry(this._viewTag);
+ removeFromPropsRegistry(this._componentViewTag);
}
}
}
@@ -283,15 +300,19 @@ export function createAnimatedComponent(
const newProp = this.props[key];
if (!newProp) {
// Prop got deleted
- prevProp.workletEventHandler.unregisterFromEvents(this._viewTag);
+ prevProp.workletEventHandler.unregisterFromEvents(
+ this._eventViewTag
+ );
} else if (
has('workletEventHandler', newProp) &&
newProp.workletEventHandler instanceof WorkletEventHandler &&
newProp.workletEventHandler !== prevProp.workletEventHandler
) {
// Prop got changed
- prevProp.workletEventHandler.unregisterFromEvents(this._viewTag);
- newProp.workletEventHandler.registerForEvents(this._viewTag);
+ prevProp.workletEventHandler.unregisterFromEvents(
+ this._eventViewTag
+ );
+ newProp.workletEventHandler.registerForEvents(this._eventViewTag);
}
}
}
@@ -304,7 +325,7 @@ export function createAnimatedComponent(
!prevProps[key]
) {
// Prop got added
- newProp.workletEventHandler.registerForEvents(this._viewTag);
+ newProp.workletEventHandler.registerForEvents(this._eventViewTag);
}
}
}
@@ -381,7 +402,7 @@ export function createAnimatedComponent(
adaptViewConfig(viewConfig);
}
- this._viewTag = viewTag as number;
+ this._componentViewTag = viewTag as number;
// remove old styles
if (prevStyles) {
@@ -487,7 +508,11 @@ export function createAnimatedComponent(
AnimatedComponent.displayName
)
: undefined;
- updateLayoutAnimations(this._viewTag, LayoutAnimationType.LAYOUT, layout);
+ updateLayoutAnimations(
+ this._componentViewTag,
+ LayoutAnimationType.LAYOUT,
+ layout
+ );
}
_configureSharedTransition(isUnmounting = false) {
@@ -497,7 +522,7 @@ export function createAnimatedComponent(
const { sharedTransitionTag } = this.props;
if (!sharedTransitionTag) {
this._sharedElementTransition?.unregisterTransition(
- this._viewTag,
+ this._componentViewTag,
isUnmounting
);
this._sharedElementTransition = null;
@@ -508,7 +533,7 @@ export function createAnimatedComponent(
this._sharedElementTransition ??
new SharedTransition();
sharedElementTransition.registerTransition(
- this._viewTag,
+ this._componentViewTag,
sharedTransitionTag,
isUnmounting
);
@@ -527,7 +552,7 @@ export function createAnimatedComponent(
? (ref as HTMLElement)
: findNodeHandle(ref as Component);
- this._viewTag = tag as number;
+ this._componentViewTag = tag as number;
const { layout, entering, exiting, sharedTransitionTag } = this.props;
if (
+11 -11
View File
@@ -40,14 +40,11 @@ import {
shouldRequestEmailConfirmation,
snoozeEmailConfirmationPrompt,
} from '#/state/shell/reminders'
import {AccessibilitySettingsScreen} from '#/view/screens/AccessibilitySettings'
import {AppPasswords} from '#/view/screens/AppPasswords'
import {CommunityGuidelinesScreen} from '#/view/screens/CommunityGuidelines'
import {CopyrightPolicyScreen} from '#/view/screens/CopyrightPolicy'
import {DebugModScreen} from '#/view/screens/DebugMod'
import {FeedsScreen} from '#/view/screens/Feeds'
import {HomeScreen} from '#/view/screens/Home'
import {LanguageSettingsScreen} from '#/view/screens/LanguageSettings'
import {ListsScreen} from '#/view/screens/Lists'
import {LogScreen} from '#/view/screens/Log'
import {ModerationBlockedAccounts} from '#/view/screens/ModerationBlockedAccounts'
@@ -56,9 +53,6 @@ import {ModerationMutedAccounts} from '#/view/screens/ModerationMutedAccounts'
import {NotFoundScreen} from '#/view/screens/NotFound'
import {NotificationsScreen} from '#/view/screens/Notifications'
import {PostThreadScreen} from '#/view/screens/PostThread'
import {PreferencesExternalEmbeds} from '#/view/screens/PreferencesExternalEmbeds'
import {PreferencesFollowingFeed} from '#/view/screens/PreferencesFollowingFeed'
import {PreferencesThreads} from '#/view/screens/PreferencesThreads'
import {PrivacyPolicyScreen} from '#/view/screens/PrivacyPolicy'
import {ProfileScreen} from '#/view/screens/Profile'
import {ProfileFeedScreen} from '#/view/screens/ProfileFeed'
@@ -68,7 +62,6 @@ import {ProfileFollowsScreen} from '#/view/screens/ProfileFollows'
import {ProfileListScreen} from '#/view/screens/ProfileList'
import {SavedFeeds} from '#/view/screens/SavedFeeds'
import {SearchScreen} from '#/view/screens/Search'
import {SettingsScreen} from '#/view/screens/Settings'
import {Storybook} from '#/view/screens/Storybook'
import {SupportScreen} from '#/view/screens/Support'
import {TermsOfServiceScreen} from '#/view/screens/TermsOfService'
@@ -96,9 +89,16 @@ import {useTheme} from '#/alf'
import {router} from '#/routes'
import {Referrer} from '../modules/expo-bluesky-swiss-army'
import {AboutSettingsScreen} from './screens/Settings/AboutSettings'
import {AccessibilitySettingsScreen} from './screens/Settings/AccessibilitySettings'
import {AccountSettingsScreen} from './screens/Settings/AccountSettings'
import {AppPasswordsScreen} from './screens/Settings/AppPasswords'
import {ContentAndMediaSettingsScreen} from './screens/Settings/ContentAndMediaSettings'
import {ExternalMediaPreferencesScreen} from './screens/Settings/ExternalMediaPreferences'
import {FollowingFeedPreferencesScreen} from './screens/Settings/FollowingFeedPreferences'
import {LanguageSettingsScreen} from './screens/Settings/LanguageSettings'
import {PrivacyAndSecuritySettingsScreen} from './screens/Settings/PrivacyAndSecuritySettings'
import {SettingsScreen} from './screens/Settings/Settings'
import {ThreadPreferencesScreen} from './screens/Settings/ThreadPreferences'
const navigationRef = createNavigationContainerRef<AllNavigatorParams>()
@@ -285,7 +285,7 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
/>
<Stack.Screen
name="AppPasswords"
getComponent={() => AppPasswords}
getComponent={() => AppPasswordsScreen}
options={{title: title(msg`App Passwords`), requireAuth: true}}
/>
<Stack.Screen
@@ -295,7 +295,7 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
/>
<Stack.Screen
name="PreferencesFollowingFeed"
getComponent={() => PreferencesFollowingFeed}
getComponent={() => FollowingFeedPreferencesScreen}
options={{
title: title(msg`Following Feed Preferences`),
requireAuth: true,
@@ -303,12 +303,12 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
/>
<Stack.Screen
name="PreferencesThreads"
getComponent={() => PreferencesThreads}
getComponent={() => ThreadPreferencesScreen}
options={{title: title(msg`Threads Preferences`), requireAuth: true}}
/>
<Stack.Screen
name="PreferencesExternalEmbeds"
getComponent={() => PreferencesExternalEmbeds}
getComponent={() => ExternalMediaPreferencesScreen}
options={{
title: title(msg`External Media Preferences`),
requireAuth: true,
+1
View File
@@ -56,6 +56,7 @@ type Props = {
const AnimatedLogo = Animated.createAnimatedComponent(Logo)
export function Splash(props: React.PropsWithChildren<Props>) {
'use no memo'
const insets = useSafeAreaInsets()
const intro = useSharedValue(0)
const outroLogo = useSharedValue(0)
+4 -1
View File
@@ -1,4 +1,4 @@
import {Platform, StyleSheet, ViewStyle} from 'react-native'
import {Platform, StyleProp, StyleSheet, ViewStyle} from 'react-native'
import * as tokens from '#/alf/tokens'
import {native, web} from '#/alf/util/platform'
@@ -887,6 +887,9 @@ export const atoms = {
user_select_all: {
userSelect: 'all',
},
outline_inset_1: {
outlineOffset: '-1px',
} as StyleProp<ViewStyle>,
/*
* Text decoration
+25 -28
View File
@@ -103,35 +103,32 @@ export function ThemeProvider({
})
}, [])
return (
<Context.Provider
value={React.useMemo<Alf>(
() => ({
themes,
themeName: themeName,
theme: themes[themeName],
fonts: {
scale: fontScale,
scaleMultiplier: fontScaleMultiplier,
family: fontFamily,
setFontScale: setFontScaleAndPersist,
setFontFamily: setFontFamilyAndPersist,
},
flags: {},
}),
[
themeName,
themes,
fontScale,
setFontScaleAndPersist,
fontFamily,
setFontFamilyAndPersist,
fontScaleMultiplier,
],
)}>
{children}
</Context.Provider>
const value = React.useMemo<Alf>(
() => ({
themes,
themeName: themeName,
theme: themes[themeName],
fonts: {
scale: fontScale,
scaleMultiplier: fontScaleMultiplier,
family: fontFamily,
setFontScale: setFontScaleAndPersist,
setFontFamily: setFontFamilyAndPersist,
},
flags: {},
}),
[
themeName,
themes,
fontScale,
setFontScaleAndPersist,
fontFamily,
setFontFamilyAndPersist,
fontScaleMultiplier,
],
)
return <Context.Provider value={value}>{children}</Context.Provider>
}
export function useAlf() {
+76
View File
@@ -0,0 +1,76 @@
import React from 'react'
import {View} from 'react-native'
import {moderateProfile} from '@atproto/api'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useProfilesQuery} from '#/state/queries/profile'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, useTheme} from '#/alf'
export function AvatarStack({
profiles,
size = 26,
}: {
profiles: string[]
size?: number
}) {
const halfSize = size / 2
const {data, error} = useProfilesQuery({handles: profiles})
const t = useTheme()
const moderationOpts = useModerationOpts()
if (error) {
console.error(error)
return null
}
const isPending = !data || !moderationOpts
const items = isPending
? Array.from({length: profiles.length}).map((_, i) => ({
key: i,
profile: null,
moderation: null,
}))
: data.profiles.map(item => ({
key: item.did,
profile: item,
moderation: moderateProfile(item, moderationOpts),
}))
return (
<View
style={[
a.flex_row,
a.align_center,
a.relative,
{width: size + (items.length - 1) * halfSize},
]}>
{items.map((item, i) => (
<View
key={item.key}
style={[
t.atoms.bg_contrast_25,
a.relative,
{
width: size,
height: size,
left: i * -halfSize,
borderWidth: 1,
borderColor: t.atoms.bg.backgroundColor,
borderRadius: 999,
zIndex: 3 - i,
},
]}>
{item.profile && (
<UserAvatar
size={size - 2}
avatar={item.profile.avatar}
moderation={item.moderation.ui('avatar')}
/>
)}
</View>
))}
</View>
)
}
+1 -1
View File
@@ -15,7 +15,7 @@ import {
useKeyboardHandler,
} from 'react-native-keyboard-controller'
import {runOnJS} from 'react-native-reanimated'
import {ReanimatedScrollEvent} from 'react-native-reanimated/lib/typescript/reanimated2/hook/commonTypes'
import {ReanimatedScrollEvent} from 'react-native-reanimated/lib/typescript/hook/commonTypes'
import {useSafeAreaInsets} from 'react-native-safe-area-context'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
+1 -1
View File
@@ -32,7 +32,7 @@ export function Error({
return (
<CenteredView
style={[
a.flex_1,
a.h_full_vh,
a.align_center,
a.gap_5xl,
!gtMobile && a.justify_between,
+2 -1
View File
@@ -46,7 +46,7 @@ export function Root({
return <Context.Provider value={context}>{children}</Context.Provider>
}
export function Trigger({children, label}: TriggerProps) {
export function Trigger({children, label, role = 'button'}: TriggerProps) {
const {control} = React.useContext(Context)
const {state: focused, onIn: onFocus, onOut: onBlur} = useInteractionState()
const {
@@ -70,6 +70,7 @@ export function Trigger({children, label}: TriggerProps) {
onPressIn,
onPressOut,
accessibilityLabel: label,
accessibilityRole: role,
},
})
}
+2 -1
View File
@@ -111,7 +111,7 @@ const RadixTriggerPassThrough = React.forwardRef(
)
RadixTriggerPassThrough.displayName = 'RadixTriggerPassThrough'
export function Trigger({children, label}: TriggerProps) {
export function Trigger({children, label, role = 'button'}: TriggerProps) {
const {control} = React.useContext(Context)
const {
state: hovered,
@@ -155,6 +155,7 @@ export function Trigger({children, label}: TriggerProps) {
onMouseEnter,
onMouseLeave,
accessibilityLabel: label,
accessibilityRole: role,
},
})
}
+4
View File
@@ -1,6 +1,7 @@
import React from 'react'
import {
AccessibilityProps,
AccessibilityRole,
GestureResponderEvent,
PressableProps,
} from 'react-native'
@@ -36,6 +37,7 @@ export type RadixPassThroughTriggerProps = {
export type TriggerProps = {
children(props: TriggerChildProps): React.ReactNode
label: string
role?: AccessibilityRole
}
export type TriggerChildProps =
| {
@@ -63,6 +65,7 @@ export type TriggerChildProps =
onPressIn: () => void
onPressOut: () => void
accessibilityLabel: string
accessibilityRole: AccessibilityRole
}
}
| {
@@ -83,6 +86,7 @@ export type TriggerChildProps =
onMouseEnter: () => void
onMouseLeave: () => void
accessibilityLabel: string
accessibilityRole: AccessibilityRole
}
}
@@ -14,6 +14,7 @@ import {InfiniteData, UseInfiniteQueryResult} from '@tanstack/react-query'
import {useGenerateStarterPackMutation} from '#/lib/generate-starterpack'
import {useBottomBarOffset} from '#/lib/hooks/useBottomBarOffset'
import {useEmail} from '#/lib/hooks/useEmail'
import {useWebMediaQueries} from '#/lib/hooks/useWebMediaQueries'
import {NavigationProp} from '#/lib/routes/types'
import {parseStarterPackUri} from '#/lib/strings/starter-pack'
@@ -27,6 +28,7 @@ import {LinearGradientBackground} from '#/components/LinearGradientBackground'
import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt'
import {Default as StarterPackCard} from '#/components/StarterPack/StarterPackCard'
import {VerifyEmailDialog} from '../dialogs/VerifyEmailDialog'
import {PlusSmall_Stroke2_Corner0_Rounded as Plus} from '../icons/Plus'
interface SectionRef {
@@ -186,6 +188,9 @@ function Empty() {
const followersDialogControl = useDialogControl()
const errorDialogControl = useDialogControl()
const {needsEmailVerification} = useEmail()
const verifyEmailControl = useDialogControl()
const [isGenerating, setIsGenerating] = React.useState(false)
const {mutate: generateStarterPack} = useGenerateStarterPackMutation({
@@ -249,7 +254,13 @@ function Empty() {
color="primary"
size="small"
disabled={isGenerating}
onPress={confirmDialogControl.open}
onPress={() => {
if (needsEmailVerification) {
verifyEmailControl.open()
} else {
confirmDialogControl.open()
}
}}
style={{backgroundColor: 'transparent'}}>
<ButtonText style={{color: 'white'}}>
<Trans>Make one for me</Trans>
@@ -262,7 +273,13 @@ function Empty() {
color="primary"
size="small"
disabled={isGenerating}
onPress={() => navigation.navigate('StarterPackWizard')}
onPress={() => {
if (needsEmailVerification) {
verifyEmailControl.open()
} else {
navigation.navigate('StarterPackWizard')
}
}}
style={{
backgroundColor: 'white',
borderColor: 'white',
@@ -318,6 +335,12 @@ function Empty() {
onConfirm={generate}
confirmButtonCta={_(msg`Retry`)}
/>
<VerifyEmailDialog
reasonText={_(
msg`Before creating a starter pack, you must first verify your email.`,
)}
control={verifyEmailControl}
/>
</LinearGradientBackground>
)
}
+3 -1
View File
@@ -1,3 +1,5 @@
export function SubtleWebHover({}: {hover: boolean}) {
import {ViewStyleProp} from '#/alf'
export function SubtleWebHover({}: ViewStyleProp & {hover: boolean}) {
return null
}
+7 -5
View File
@@ -2,9 +2,12 @@ import React from 'react'
import {StyleSheet, View} from 'react-native'
import {isTouchDevice} from '#/lib/browser'
import {useTheme} from '#/alf'
import {useTheme, ViewStyleProp} from '#/alf'
export function SubtleWebHover({hover}: {hover: boolean}) {
export function SubtleWebHover({
style,
hover,
}: ViewStyleProp & {hover: boolean}) {
const t = useTheme()
if (isTouchDevice) {
return null
@@ -26,9 +29,8 @@ export function SubtleWebHover({hover}: {hover: boolean}) {
style={[
t.atoms.bg_contrast_25,
styles.container,
{
opacity: hover ? opacity : 0,
},
{opacity: hover ? opacity : 0},
style,
]}
/>
)
+41 -21
View File
@@ -18,8 +18,14 @@ import {Text} from '#/components/Typography'
export function VerifyEmailDialog({
control,
onCloseWithoutVerifying,
onCloseAfterVerifying,
reasonText,
}: {
control: Dialog.DialogControlProps
onCloseWithoutVerifying?: () => void
onCloseAfterVerifying?: () => void
reasonText?: string
}) {
const agent = useAgent()
@@ -30,18 +36,24 @@ export function VerifyEmailDialog({
control={control}
onClose={async () => {
if (!didVerify) {
onCloseWithoutVerifying?.()
return
}
try {
await agent.resumeSession(agent.session!)
onCloseAfterVerifying?.()
} catch (e: unknown) {
logger.error(String(e))
return
}
}}>
<Dialog.Handle />
<Inner control={control} setDidVerify={setDidVerify} />
<Inner
control={control}
setDidVerify={setDidVerify}
reasonText={reasonText}
/>
</Dialog.Outer>
)
}
@@ -49,9 +61,11 @@ export function VerifyEmailDialog({
export function Inner({
control,
setDidVerify,
reasonText,
}: {
control: Dialog.DialogControlProps
setDidVerify: (value: boolean) => void
reasonText?: string
}) {
const {_} = useLingui()
const {currentAccount} = useSession()
@@ -135,26 +149,32 @@ export function Inner({
<Text style={[a.text_md, a.leading_snug]}>
{currentStep === 'StepOne' ? (
<>
<Trans>
You'll receive an email at{' '}
<Text style={[a.text_md, a.leading_snug, a.font_bold]}>
{currentAccount?.email}
</Text>{' '}
to verify it's you.
</Trans>{' '}
<InlineLinkText
to="#"
label={_(msg`Change email address`)}
style={[a.text_md, a.leading_snug]}
onPress={e => {
e.preventDefault()
control.close(() => {
openModal({name: 'change-email'})
})
return false
}}>
<Trans>Need to change it?</Trans>
</InlineLinkText>
{!reasonText ? (
<>
<Trans>
You'll receive an email at{' '}
<Text style={[a.text_md, a.leading_snug, a.font_bold]}>
{currentAccount?.email}
</Text>{' '}
to verify it's you.
</Trans>{' '}
<InlineLinkText
to="#"
label={_(msg`Change email address`)}
style={[a.text_md, a.leading_snug]}
onPress={e => {
e.preventDefault()
control.close(() => {
openModal({name: 'change-email'})
})
return false
}}>
<Trans>Need to change it?</Trans>
</InlineLinkText>
</>
) : (
reasonText
)}
</>
) : (
uiStrings[currentStep].message
+2 -1
View File
@@ -53,9 +53,11 @@ export function ActionsWrapper({
.numberOfTaps(2)
.hitSlop(HITSLOP_10)
.onEnd(open)
.runOnJS(true)
const pressAndHoldGesture = Gesture.LongPress()
.onStart(() => {
'worklet'
scale.value = withTiming(1.05, {duration: 200}, finished => {
if (!finished) return
runOnJS(open)()
@@ -65,7 +67,6 @@ export function ActionsWrapper({
.onTouchesUp(shrink)
.onTouchesMove(shrink)
.cancelsTouchesInView(false)
.runOnJS(true)
const composedGestures = Gesture.Exclusive(
doubleTapGesture,
+41 -15
View File
@@ -3,14 +3,18 @@ import {View} from 'react-native'
import {AppBskyActorDefs} from '@atproto/api'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useNavigation} from '@react-navigation/native'
import {useEmail} from '#/lib/hooks/useEmail'
import {NavigationProp} from '#/lib/routes/types'
import {logEvent} from '#/lib/statsig/statsig'
import {useMaybeConvoForUser} from '#/state/queries/messages/get-convo-for-members'
import {atoms as a, useTheme} from '#/alf'
import {ButtonIcon} from '#/components/Button'
import {Button, ButtonIcon} from '#/components/Button'
import {canBeMessaged} from '#/components/dms/util'
import {Message_Stroke2_Corner0_Rounded as Message} from '#/components/icons/Message'
import {Link} from '#/components/Link'
import {useDialogControl} from '../Dialog'
import {VerifyEmailDialog} from '../dialogs/VerifyEmailDialog'
export function MessageProfileButton({
profile,
@@ -19,15 +23,29 @@ export function MessageProfileButton({
}) {
const {_} = useLingui()
const t = useTheme()
const navigation = useNavigation<NavigationProp>()
const {needsEmailVerification} = useEmail()
const verifyEmailControl = useDialogControl()
const {data: convo, isPending} = useMaybeConvoForUser(profile.did)
const onPress = React.useCallback(() => {
if (!convo?.id) {
return
}
if (needsEmailVerification) {
verifyEmailControl.open()
return
}
if (convo && !convo.lastMessage) {
logEvent('chat:create', {logContext: 'ProfileHeader'})
}
logEvent('chat:open', {logContext: 'ProfileHeader'})
}, [convo])
navigation.navigate('MessagesConversation', {conversation: convo.id})
}, [needsEmailVerification, verifyEmailControl, convo, navigation])
if (isPending) {
// show pending state based on declaration
@@ -53,18 +71,26 @@ export function MessageProfileButton({
if (convo) {
return (
<Link
testID="dmBtn"
size="small"
color="secondary"
variant="solid"
shape="round"
label={_(msg`Message ${profile.handle}`)}
to={`/messages/${convo.id}`}
style={[a.justify_center]}
onPress={onPress}>
<ButtonIcon icon={Message} size="md" />
</Link>
<>
<Button
accessibilityRole="button"
testID="dmBtn"
size="small"
color="secondary"
variant="solid"
shape="round"
label={_(msg`Message ${profile.handle}`)}
style={[a.justify_center]}
onPress={onPress}>
<ButtonIcon icon={Message} size="md" />
</Button>
<VerifyEmailDialog
reasonText={_(
msg`Before you may message another user, you must first verify your email.`,
)}
control={verifyEmailControl}
/>
</>
)
} else {
return null
+1 -1
View File
@@ -147,7 +147,7 @@ function HeaderReady({
const isDeletedAccount = profile?.handle === 'missing.invalid'
const displayName = isDeletedAccount
? 'Deleted Account'
? _(msg`Deleted Account`)
: sanitizeDisplayName(
profile.displayName || profile.handle,
moderation.ui('displayName'),
+19 -1
View File
@@ -2,6 +2,7 @@ import React, {useCallback} from 'react'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useEmail} from '#/lib/hooks/useEmail'
import {logEvent} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {useGetConvoForMembers} from '#/state/queries/messages/get-convo-for-members'
@@ -9,6 +10,8 @@ import {FAB} from '#/view/com/util/fab/FAB'
import * as Toast from '#/view/com/util/Toast'
import {useTheme} from '#/alf'
import * as Dialog from '#/components/Dialog'
import {useDialogControl} from '#/components/Dialog'
import {VerifyEmailDialog} from '#/components/dialogs/VerifyEmailDialog'
import {PlusLarge_Stroke2_Corner0_Rounded as Plus} from '#/components/icons/Plus'
import {SearchablePeopleList} from './SearchablePeopleList'
@@ -21,6 +24,8 @@ export function NewChat({
}) {
const t = useTheme()
const {_} = useLingui()
const {needsEmailVerification} = useEmail()
const verifyEmailControl = useDialogControl()
const {mutate: createChat} = useGetConvoForMembers({
onSuccess: data => {
@@ -48,7 +53,13 @@ export function NewChat({
<>
<FAB
testID="newChatFAB"
onPress={control.open}
onPress={() => {
if (needsEmailVerification) {
verifyEmailControl.open()
} else {
control.open()
}
}}
icon={<Plus size="lg" fill={t.palette.white} />}
accessibilityRole="button"
accessibilityLabel={_(msg`New chat`)}
@@ -62,6 +73,13 @@ export function NewChat({
onSelectChat={onCreateChat}
/>
</Dialog.Outer>
<VerifyEmailDialog
reasonText={_(
msg`Before you may message another user, you must first verify your email.`,
)}
control={verifyEmailControl}
/>
</>
)
}
@@ -278,7 +278,7 @@ export function SearchablePeopleList({
) : null}
</View>
<View style={[, web([a.pt_xs])]}>
<View style={web([a.pt_xs])}>
<SearchInput
inputRef={inputRef}
value={searchText}
@@ -313,6 +313,7 @@ export function SearchablePeopleList({
web([a.py_0, {height: '100vh', maxHeight: 600}, a.px_0]),
native({height: '100%'}),
]}
webInnerContentContainerStyle={a.py_0}
webInnerStyle={[a.py_0, {maxWidth: 500, minWidth: 200}]}
keyboardDismissMode="on-drag"
/>
+1 -1
View File
@@ -57,7 +57,7 @@ export const SearchInput = React.forwardRef<TextInput, SearchInputProps>(
<View
style={[
a.absolute,
a.z_10,
a.z_20,
a.my_auto,
a.inset_0,
a.justify_center,
+5
View File
@@ -0,0 +1,5 @@
import {createSinglePathSVG} from './TEMPLATE'
export const CalendarClock_Stroke2_Corner0_Rounded = createSinglePathSVG({
path: 'M15.439 3.148a1 1 0 0 1 .41.645l.568 3.22a7 7 0 1 1-6.174 10.97L4.32 19.027a1 1 0 0 1-1.159-.811L1.078 6.398a1 1 0 0 1 .81-1.158l12.803-2.258a1 1 0 0 1 .748.166ZM9.325 16.114A7 7 0 0 1 9 14c0-1.56.51-3 1.372-4.164l-6.456 1.139 1.041 5.909 4.368-.77ZM3.568 9.005l10.833-1.91-.347-1.97L3.22 7.036l.347 1.97ZM16 9a5 5 0 1 0 0 10 5 5 0 0 0 0-10Zm0 2a1 1 0 0 1 1 1v1.586l1.374 1.374a1 1 0 0 1-1.414 1.414l-1.667-1.667A1 1 0 0 1 15 14v-2a1 1 0 0 1 1-1Z',
})
+4
View File
@@ -24,6 +24,10 @@ export const PersonPlus_Filled_Stroke2_Corner0_Rounded = createSinglePathSVG({
path: 'M7.5 6.5a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM12 12c-4.758 0-8.083 3.521-8.496 7.906A1 1 0 0 0 4.5 21H15a3 3 0 1 1 0-6c0-.824.332-1.571.87-2.113C14.739 12.32 13.435 12 12 12Zm6 2a1 1 0 0 1 1 1v2h2a1 1 0 1 1 0 2h-2v2a1 1 0 1 1-2 0v-2h-2a1 1 0 1 1 0-2h2v-2a1 1 0 0 1 1-1Z',
})
export const PersonPlus_Stroke2_Corner2_Rounded = createSinglePathSVG({
path: 'M12 4a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5ZM7.5 6.5a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM12 14c-2.95 0-5.163 1.733-6.08 4.21a.47.47 0 0 0 .09.493.9.9 0 0 0 .687.297H11a1 1 0 1 1 0 2H6.697a2.9 2.9 0 0 1-2.219-1.011 2.46 2.46 0 0 1-.433-2.473C5.235 14.296 8.168 12 12 12c.787 0 1.54.097 2.252.282a1 1 0 1 1-.504 1.936A7 7 0 0 0 12 14Zm6 0a1 1 0 0 1 1 1v2h2a1 1 0 1 1 0 2h-2v2a1 1 0 1 1-2 0v-2h-2a1 1 0 1 1 0-2h2v-2a1 1 0 0 1 1-1Z',
})
export const PersonGroup_Stroke2_Corner2_Rounded = createSinglePathSVG({
path: 'M8 5a2 2 0 1 0 0 4 2 2 0 0 0 0-4ZM4 7a4 4 0 1 1 8 0 4 4 0 0 1-8 0Zm13-1a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3Zm-3.5 1.5a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0Zm7.301 9.7c-.836-2.6-2.88-3.503-4.575-3.111a1 1 0 0 1-.451-1.949c2.815-.651 5.81.966 6.93 4.448a2.49 2.49 0 0 1-.506 2.43A2.92 2.92 0 0 1 20 20h-2a1 1 0 1 1 0-2h2a.92.92 0 0 0 .69-.295.49.49 0 0 0 .112-.505ZM8 14c-1.865 0-3.878 1.274-4.681 4.151a.57.57 0 0 0 .132.55c.15.171.4.299.695.299h7.708a.93.93 0 0 0 .695-.299.57.57 0 0 0 .132-.55C11.878 15.274 9.865 14 8 14Zm0-2c2.87 0 5.594 1.98 6.607 5.613.53 1.9-1.09 3.387-2.753 3.387H4.146c-1.663 0-3.283-1.487-2.753-3.387C2.406 13.981 5.129 12 8 12Z',
})
@@ -22,7 +22,7 @@ export function Outer({children}: React.PropsWithChildren<{}>) {
<View
style={[
a.flex_row,
a.gap_md,
a.gap_sm,
a.px_lg,
a.py_lg,
a.justify_between,
@@ -74,10 +74,9 @@ export function Buttons({
hideLabel?: string
}) {
const {_} = useLingui()
const {gtPhone} = useBreakpoints()
return (
<View style={[{minHeight: 35}, gtPhone ? undefined : a.w_full]}>
<View style={[{minHeight: 35}, a.w_full]}>
<ToggleButton.Group
label={_(
msg`Configure content filtering setting for category: ${name}`,
@@ -259,7 +258,7 @@ export function LabelerLabelPreference({
</Content>
{showConfig && (
<View style={[gtPhone ? undefined : a.w_full]}>
<>
{cantConfigure ? (
<View
style={[
@@ -290,7 +289,7 @@ export function LabelerLabelPreference({
hideLabel={hideLabel}
/>
)}
</View>
</>
)}
</Outer>
)
+8 -1
View File
@@ -1,11 +1,18 @@
import {AtUri} from '@atproto/api'
import {BSKY_FEED_OWNER_DIDS} from '#/lib/constants'
import {isWeb} from '#/platform/detection'
import {UsePreferencesQueryResponse} from '#/state/queries/preferences'
let debugTopics = ''
if (isWeb && typeof window !== 'undefined') {
const params = new URLSearchParams(window.location.search)
debugTopics = params.get('debug_topics') ?? ''
}
export function createBskyTopicsHeader(userInterests?: string) {
return {
'X-Bsky-Topics': userInterests || '',
'X-Bsky-Topics': debugTopics || userInterests || '',
}
}
+8
View File
@@ -23,6 +23,14 @@ export const STARTER_PACK_MAX_SIZE = 150
// -prf
export const JOINED_THIS_WEEK = 650000 // estimate as of 10/28/24
export const DISCOVER_DEBUG_DIDS: Record<string, true> = {
'did:plc:oisofpd7lj26yvgiivf3lxsi': true, // hailey.at
'did:plc:fpruhuo22xkm5o7ttr2ktxdo': true, // danabra.mov
'did:plc:p2cp5gopk7mgjegy6wadk3ep': true, // samuel.bsky.team
'did:plc:ragtjsm2j2vknwkz3zp4oxrd': true, // pfrazee.com
'did:plc:vpkhqolt662uhesyj6nxm7ys': true, // why.bsky.team
}
const BASE_FEEDBACK_FORM_URL = `${HELP_DESK_URL}/requests/new`
export function FEEDBACK_FORM_URL({
email,
+3 -3
View File
@@ -91,15 +91,15 @@ export function CountWheel({
likeCount,
big,
isLiked,
isToggle,
hasBeenToggled,
}: {
likeCount: number
big?: boolean
isLiked: boolean
isToggle: boolean
hasBeenToggled: boolean
}) {
const t = useTheme()
const shouldAnimate = !useReducedMotion() && isToggle
const shouldAnimate = !useReducedMotion() && hasBeenToggled
const shouldRoll = decideShouldRoll(isLiked, likeCount)
// Incrementing the key will cause the `Animated.View` to re-render, with the newly selected entering/exiting
+3 -3
View File
@@ -39,15 +39,15 @@ export function CountWheel({
likeCount,
big,
isLiked,
isToggle,
hasBeenToggled,
}: {
likeCount: number
big?: boolean
isLiked: boolean
isToggle: boolean
hasBeenToggled: boolean
}) {
const t = useTheme()
const shouldAnimate = !useReducedMotion() && isToggle
const shouldAnimate = !useReducedMotion() && hasBeenToggled
const shouldRoll = decideShouldRoll(isLiked, likeCount)
const countView = React.useRef<HTMLDivElement>(null)
+6 -10
View File
@@ -71,15 +71,15 @@ const circle2Keyframe = new Keyframe({
export function AnimatedLikeIcon({
isLiked,
big,
isToggle,
hasBeenToggled,
}: {
isLiked: boolean
big?: boolean
isToggle: boolean
hasBeenToggled: boolean
}) {
const t = useTheme()
const size = big ? 22 : 18
const shouldAnimate = !useReducedMotion() && isToggle
const shouldAnimate = !useReducedMotion() && hasBeenToggled
return (
<View>
@@ -95,12 +95,10 @@ export function AnimatedLikeIcon({
width={size}
/>
)}
{isLiked ? (
{isLiked && shouldAnimate ? (
<>
<Animated.View
entering={
shouldAnimate ? circle1Keyframe.duration(300) : undefined
}
entering={circle1Keyframe.duration(300)}
style={{
position: 'absolute',
backgroundColor: s.likeColor.color,
@@ -114,9 +112,7 @@ export function AnimatedLikeIcon({
}}
/>
<Animated.View
entering={
shouldAnimate ? circle2Keyframe.duration(300) : undefined
}
entering={circle2Keyframe.duration(300)}
style={{
position: 'absolute',
backgroundColor: t.atoms.bg.backgroundColor,
+3 -3
View File
@@ -41,15 +41,15 @@ const circle2Keyframe = [
export function AnimatedLikeIcon({
isLiked,
big,
isToggle,
hasBeenToggled,
}: {
isLiked: boolean
big?: boolean
isToggle: boolean
hasBeenToggled: boolean
}) {
const t = useTheme()
const size = big ? 22 : 18
const shouldAnimate = !useReducedMotion() && isToggle
const shouldAnimate = !useReducedMotion() && hasBeenToggled
const prevIsLiked = React.useRef(isLiked)
const likeIconRef = React.useRef<HTMLDivElement>(null)
-14
View File
@@ -1,14 +0,0 @@
import React from 'react'
import {choose} from '#/lib/functions'
import {useTheme} from '#/lib/ThemeContext'
export function useCustomPalette<T>({light, dark}: {light: T; dark: T}) {
const theme = useTheme()
return React.useMemo(() => {
return choose<T, Record<string, T>>(theme.colorScheme, {
dark,
light,
})
}, [theme.colorScheme, dark, light])
}
+19
View File
@@ -0,0 +1,19 @@
import {useServiceConfigQuery} from '#/state/queries/email-verification-required'
import {useSession} from '#/state/session'
import {BSKY_SERVICE} from '../constants'
import {getHostnameFromUrl} from '../strings/url-helpers'
export function useEmail() {
const {currentAccount} = useSession()
const {data: serviceConfig} = useServiceConfigQuery()
const isSelfHost =
serviceConfig?.checkEmailConfirmed &&
currentAccount &&
getHostnameFromUrl(currentAccount.service) !==
getHostnameFromUrl(BSKY_SERVICE)
const needsEmailVerification = !isSelfHost && !currentAccount?.emailConfirmed
return {needsEmailVerification}
}
-35
View File
@@ -1,35 +0,0 @@
import {Image} from 'react-native'
import type {Dimensions} from '#/lib/media/types'
const sizes: Map<string, Dimensions> = new Map()
const activeRequests: Map<string, Promise<Dimensions>> = new Map()
export function get(uri: string): Dimensions | undefined {
return sizes.get(uri)
}
export async function fetch(uri: string): Promise<Dimensions> {
const Dimensions = sizes.get(uri)
if (Dimensions) {
return Dimensions
}
const prom =
activeRequests.get(uri) ||
new Promise<Dimensions>(resolve => {
Image.getSize(
uri,
(width: number, height: number) => resolve({width, height}),
(err: any) => {
console.error('Failed to fetch image dimensions for', uri, err)
resolve({width: 0, height: 0})
},
)
})
activeRequests.set(uri, prom)
const res = await prom
activeRequests.delete(uri)
sizes.set(uri, res)
return res
}
+1 -1
View File
@@ -3,7 +3,7 @@ import {ImagePickerAsset} from 'expo-image-picker'
import {VideoTooLargeError} from '#/lib/media/video/errors'
import {CompressedVideo} from './types'
const MAX_VIDEO_SIZE = 1024 * 1024 * 50 // 50mb
const MAX_VIDEO_SIZE = 1000 * 1000 * 50 // 50mb
// doesn't actually compress, converts to ArrayBuffer
export async function compressVideo(
+5
View File
@@ -122,11 +122,16 @@ export type LogEvents = {
'post:create': {
imageCount: number
isReply: boolean
isPartOfThread: boolean
hasLink: boolean
hasQuote: boolean
langs: string
logContext: 'Composer'
}
'thread:create': {
postCount: number
isReply: boolean
}
'post:like:sampled': {
doesLikerFollowPoster: boolean | undefined
doesPosterFollowLiker: boolean | undefined
+5 -2
View File
@@ -88,7 +88,9 @@ export function parseEmbedPlayerFromUrl(
// youtube
if (urlp.hostname === 'youtu.be') {
const videoId = urlp.pathname.split('/')[1]
const seek = encodeURIComponent(urlp.searchParams.get('t') ?? 0)
const t = urlp.searchParams.get('t') ?? '0'
const seek = encodeURIComponent(t.replace(/s$/, ''))
if (videoId) {
return {
type: 'youtube_video',
@@ -111,7 +113,8 @@ export function parseEmbedPlayerFromUrl(
isShorts || isLive
? shortOrLiveVideoId
: (urlp.searchParams.get('v') as string)
const seek = encodeURIComponent(urlp.searchParams.get('t') ?? 0)
const t = urlp.searchParams.get('t') ?? '0'
const seek = encodeURIComponent(t.replace(/s$/, ''))
if (videoId) {
return {
+25 -5
View File
@@ -4,10 +4,11 @@ import {useKeyboardController} from 'react-native-keyboard-controller'
import {AppBskyActorDefs, moderateProfile, ModerationOpts} from '@atproto/api'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
import {useFocusEffect, useNavigation} from '@react-navigation/native'
import {NativeStackScreenProps} from '@react-navigation/native-stack'
import {CommonNavigatorParams} from '#/lib/routes/types'
import {useEmail} from '#/lib/hooks/useEmail'
import {CommonNavigatorParams, NavigationProp} from '#/lib/routes/types'
import {isWeb} from '#/platform/detection'
import {useProfileShadow} from '#/state/cache/profile-shadow'
import {ConvoProvider, isConvoActive, useConvo} from '#/state/messages/convo'
@@ -19,6 +20,8 @@ import {useSetMinimalShellMode} from '#/state/shell'
import {CenteredView} from '#/view/com/util/Views'
import {MessagesList} from '#/screens/Messages/components/MessagesList'
import {atoms as a, useBreakpoints, useTheme, web} from '#/alf'
import {useDialogControl} from '#/components/Dialog'
import {VerifyEmailDialog} from '#/components/dialogs/VerifyEmailDialog'
import {MessagesListBlockedFooter} from '#/components/dms/MessagesListBlockedFooter'
import {MessagesListHeader} from '#/components/dms/MessagesListHeader'
import {Error} from '#/components/Error'
@@ -127,9 +130,7 @@ function Inner() {
setHasScrolled={setHasScrolled}
/>
) : (
<>
<View style={[a.align_center, a.gap_sm, a.flex_1]} />
</>
<View style={[a.align_center, a.gap_sm, a.flex_1]} />
)}
{!readyToShow && (
<View
@@ -163,8 +164,12 @@ function InnerReady({
hasScrolled: boolean
setHasScrolled: React.Dispatch<React.SetStateAction<boolean>>
}) {
const {_} = useLingui()
const convoState = useConvo()
const navigation = useNavigation<NavigationProp>()
const recipient = useProfileShadow(recipientUnshadowed)
const verifyEmailControl = useDialogControl()
const {needsEmailVerification} = useEmail()
const moderation = React.useMemo(() => {
return moderateProfile(recipient, moderationOpts)
@@ -181,6 +186,12 @@ function InnerReady({
}
}, [moderation])
React.useEffect(() => {
if (needsEmailVerification) {
verifyEmailControl.open()
}
}, [needsEmailVerification, verifyEmailControl])
return (
<>
<MessagesListHeader
@@ -203,6 +214,15 @@ function InnerReady({
}
/>
)}
<VerifyEmailDialog
reasonText={_(
msg`Before you may message another user, you must first verify your email.`,
)}
control={verifyEmailControl}
onCloseWithoutVerifying={() => {
navigation.navigate('Home')
}}
/>
</>
)
}
@@ -104,7 +104,7 @@ function ChatListItemReady({
const isDeletedAccount = profile.handle === 'missing.invalid'
const displayName = isDeletedAccount
? 'Deleted Account'
? _(msg`Deleted Account`)
: sanitizeDisplayName(
profile.displayName || profile.handle,
moderation.ui('displayName'),
@@ -18,6 +18,7 @@ import Graphemer from 'graphemer'
import {HITSLOP_10, MAX_DM_GRAPHEME_LENGTH} from '#/lib/constants'
import {useHaptics} from '#/lib/haptics'
import {useEmail} from '#/lib/hooks/useEmail'
import {isIOS} from '#/platform/detection'
import {
useMessageDraft,
@@ -61,10 +62,15 @@ export function MessageInput({
const [message, setMessage] = React.useState(getDraft)
const inputRef = useAnimatedRef<TextInput>()
const {needsEmailVerification} = useEmail()
useSaveMessageDraft(message)
useExtractEmbedFromFacets(message, setEmbed)
const onSubmit = React.useCallback(() => {
if (needsEmailVerification) {
return
}
if (!hasEmbed && message.trim() === '') {
return
}
@@ -84,6 +90,7 @@ export function MessageInput({
inputRef.current?.focus()
}, 100)
}, [
needsEmailVerification,
hasEmbed,
message,
clearDraft,
@@ -159,6 +166,7 @@ export function MessageInput({
ref={inputRef}
hitSlop={HITSLOP_10}
animatedProps={animatedProps}
editable={!needsEmailVerification}
/>
<Pressable
accessibilityRole="button"
@@ -171,7 +179,8 @@ export function MessageInput({
a.justify_center,
{height: 30, width: 30, backgroundColor: t.palette.primary_500},
]}
onPress={onSubmit}>
onPress={onSubmit}
disabled={needsEmailVerification}>
<PaperPlane fill={t.palette.white} style={[a.relative, {left: 1}]} />
</Pressable>
</View>
@@ -11,7 +11,7 @@ import {
useAnimatedStyle,
useSharedValue,
} from 'react-native-reanimated'
import {ReanimatedScrollEvent} from 'react-native-reanimated/lib/typescript/reanimated2/hook/commonTypes'
import {ReanimatedScrollEvent} from 'react-native-reanimated/lib/typescript/hook/commonTypes'
import {useSafeAreaInsets} from 'react-native-safe-area-context'
import {AppBskyEmbedRecord, AppBskyRichtextFacet, RichText} from '@atproto/api'
@@ -202,9 +202,9 @@ export function MessagesList({
convoState.items.length,
// these are stable
flatListRef,
isAtTop.value,
isAtBottom.value,
layoutHeight.value,
isAtTop,
isAtBottom,
layoutHeight,
],
)
@@ -212,7 +212,7 @@ export function MessagesList({
if (hasScrolled && prevContentHeight.current > layoutHeight.value) {
convoState.fetchMessageHistory()
}
}, [convoState, hasScrolled, layoutHeight.value])
}, [convoState, hasScrolled, layoutHeight])
const onScroll = React.useCallback(
(e: ReanimatedScrollEvent) => {
@@ -374,7 +374,7 @@ export function MessagesList({
},
[
flatListRef,
keyboardIsOpening.value,
keyboardIsOpening,
layoutScrollWithoutAnimation,
layoutHeight,
],
-131
View File
@@ -1,13 +1,11 @@
import React from 'react'
import {Linking, View} from 'react-native'
import {useSafeAreaFrame} from 'react-native-safe-area-context'
import {ComAtprotoLabelDefs} from '@atproto/api'
import {LABELS} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
import {IS_INTERNAL} from '#/lib/app-info'
import {getLabelingServiceTitle} from '#/lib/moderation'
import {CommonNavigatorParams, NativeStackScreenProps} from '#/lib/routes/types'
import {logger} from '#/logger'
@@ -18,11 +16,6 @@ import {
UsePreferencesQueryResponse,
usePreferencesSetAdultContentMutation,
} from '#/state/queries/preferences'
import {
useProfileQuery,
useProfileUpdateMutation,
} from '#/state/queries/profile'
import {useSession} from '#/state/session'
import {isNonConfigurableModerationAuthority} from '#/state/session/additional-moderation-authorities'
import {useSetMinimalShellMode} from '#/state/shell'
import {ViewHeader} from '#/view/com/util/ViewHeader'
@@ -469,131 +462,7 @@ export function ModerationScreenInner({
})}
</View>
)}
{!IS_INTERNAL && (
<>
<Text
style={[
a.text_md,
a.font_bold,
a.pt_2xl,
a.pb_md,
t.atoms.text_contrast_high,
]}>
<Trans>Logged-out visibility</Trans>
</Text>
<PwiOptOut />
</>
)}
<View style={{height: 200}} />
</ScrollView>
)
}
function PwiOptOut() {
const t = useTheme()
const {_} = useLingui()
const {currentAccount} = useSession()
const {data: profile} = useProfileQuery({did: currentAccount?.did})
const updateProfile = useProfileUpdateMutation()
const isOptedOut =
profile?.labels?.some(l => l.val === '!no-unauthenticated') || false
const canToggle = profile && !updateProfile.isPending
const onToggleOptOut = React.useCallback(() => {
if (!profile) {
return
}
let wasAdded = false
updateProfile.mutate({
profile,
updates: existing => {
// create labels attr if needed
existing.labels = ComAtprotoLabelDefs.isSelfLabels(existing.labels)
? existing.labels
: {
$type: 'com.atproto.label.defs#selfLabels',
values: [],
}
// toggle the label
const hasLabel = existing.labels.values.some(
l => l.val === '!no-unauthenticated',
)
if (hasLabel) {
wasAdded = false
existing.labels.values = existing.labels.values.filter(
l => l.val !== '!no-unauthenticated',
)
} else {
wasAdded = true
existing.labels.values.push({val: '!no-unauthenticated'})
}
// delete if no longer needed
if (existing.labels.values.length === 0) {
delete existing.labels
}
return existing
},
checkCommitted: res => {
const exists = !!res.data.labels?.some(
l => l.val === '!no-unauthenticated',
)
return exists === wasAdded
},
})
}, [updateProfile, profile])
return (
<View style={[a.pt_sm]}>
<View style={[a.flex_row, a.align_center, a.justify_between, a.gap_lg]}>
<Toggle.Item
disabled={!canToggle}
value={isOptedOut}
onChange={onToggleOptOut}
name="logged_out_visibility"
style={a.flex_1}
label={_(
msg`Discourage apps from showing my account to logged-out users`,
)}>
<Toggle.Switch />
<Toggle.LabelText style={[a.text_md, a.flex_1]}>
<Trans>
Discourage apps from showing my account to logged-out users
</Trans>
</Toggle.LabelText>
</Toggle.Item>
{updateProfile.isPending && <Loader />}
</View>
<View style={[a.pt_md, a.gap_md, {paddingLeft: 38}]}>
<Text style={[a.leading_snug, t.atoms.text_contrast_high]}>
<Trans>
Bluesky will not show your profile and posts to logged-out users.
Other apps may not honor this request. This does not make your
account private.
</Trans>
</Text>
<Text style={[a.font_bold, a.leading_snug, t.atoms.text_contrast_high]}>
<Trans>
Note: Bluesky is an open and public network. This setting only
limits the visibility of your content on the Bluesky app and
website, and other apps may not respect this setting. Your content
may still be shown to logged-out users by other apps and websites.
</Trans>
</Text>
<InlineLinkText
label={_(msg`Learn more about what is public on Bluesky.`)}
to="https://blueskyweb.zendesk.com/hc/en-us/articles/15835264007693-Data-Privacy">
<Trans>Learn more about what is public on Bluesky.</Trans>
</InlineLinkText>
</View>
</View>
)
}
+1 -1
View File
@@ -47,7 +47,7 @@ export function ProfileHeaderHandle({
a.rounded_xs,
{borderColor: t.palette.contrast_200},
]
: [a.text_md, a.leading_tight, t.atoms.text_contrast_medium],
: [a.text_md, a.leading_snug, t.atoms.text_contrast_medium],
web({wordBreak: 'break-all'}),
]}>
{invalidHandle ? _(msg`⚠Invalid Handle`) : `@${profile.handle}`}
+47 -13
View File
@@ -1,5 +1,12 @@
import React, {memo} from 'react'
import {StyleSheet, TouchableWithoutFeedback, View} from 'react-native'
import Animated, {
measure,
MeasuredDimensions,
runOnJS,
runOnUI,
useAnimatedRef,
} from 'react-native-reanimated'
import {AppBskyActorDefs, ModerationDecision} from '@atproto/api'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {msg} from '@lingui/macro'
@@ -42,6 +49,7 @@ let ProfileHeaderShell = ({
const {openLightbox} = useLightboxControls()
const navigation = useNavigation<NavigationProp>()
const {isDesktop} = useWebMediaQueries()
const aviRef = useAnimatedRef()
const onPressBack = React.useCallback(() => {
if (navigation.canGoBack()) {
@@ -51,16 +59,40 @@ let ProfileHeaderShell = ({
}
}, [navigation])
const _openLightbox = React.useCallback(
(uri: string, thumbRect: MeasuredDimensions | null) => {
openLightbox({
images: [
{
uri,
thumbUri: uri,
thumbRect,
dimensions: {
// It's fine if it's actually smaller but we know it's 1:1.
height: 1000,
width: 1000,
},
thumbDimensions: null,
type: 'circle-avi',
},
],
index: 0,
})
},
[openLightbox],
)
const onPressAvi = React.useCallback(() => {
const modui = moderation.ui('avatar')
if (profile.avatar && !(modui.blur && modui.noOverride)) {
openLightbox({
type: 'profile-image',
profile: profile,
thumbDims: null,
})
const avatar = profile.avatar
if (avatar && !(modui.blur && modui.noOverride)) {
runOnUI(() => {
'worklet'
const rect = measure(aviRef)
runOnJS(_openLightbox)(avatar, rect)
})()
}
}, [openLightbox, profile, moderation])
}, [profile, moderation, _openLightbox, aviRef])
const isMe = React.useMemo(
() => currentAccount?.did === profile.did,
@@ -138,12 +170,14 @@ let ProfileHeaderShell = ({
styles.avi,
profile.associated?.labeler && styles.aviLabeler,
]}>
<UserAvatar
type={profile.associated?.labeler ? 'labeler' : 'user'}
size={90}
avatar={profile.avatar}
moderation={moderation.ui('avatar')}
/>
<Animated.View ref={aviRef} collapsable={false}>
<UserAvatar
type={profile.associated?.labeler ? 'labeler' : 'user'}
size={90}
avatar={profile.avatar}
moderation={moderation.ui('avatar')}
/>
</Animated.View>
</View>
</TouchableWithoutFeedback>
</GrowableAvatar>
+36 -32
View File
@@ -6,15 +6,14 @@ import {NativeStackScreenProps} from '@react-navigation/native-stack'
import {CommonNavigatorParams} from '#/lib/routes/types'
import {useModalControls} from '#/state/modals'
import {useSession} from '#/state/session'
import {ExportCarDialog} from '#/view/screens/Settings/ExportCarDialog'
import * as SettingsList from '#/screens/Settings/components/SettingsList'
import {atoms as a, useTheme} from '#/alf'
import {useDialogControl} from '#/components/Dialog'
import {BirthDateSettingsDialog} from '#/components/dialogs/BirthDateSettings'
import {VerifyEmailDialog} from '#/components/dialogs/VerifyEmailDialog'
import {At_Stroke2_Corner2_Rounded as AtIcon} from '#/components/icons/At'
import {BirthdayCake_Stroke2_Corner2_Rounded as BirthdayCakeIcon} from '#/components/icons/BirthdayCake'
import {Car_Stroke2_Corner2_Rounded as CarIcon} from '#/components/icons/Car'
import {Check_Stroke2_Corner0_Rounded as CheckIcon} from '#/components/icons/Check'
import {Envelope_Stroke2_Corner2_Rounded as EnvelopeIcon} from '#/components/icons/Envelope'
import {Freeze_Stroke2_Corner2_Rounded as FreezeIcon} from '#/components/icons/Freeze'
import {Lock_Stroke2_Corner2_Rounded as LockIcon} from '#/components/icons/Lock'
@@ -24,6 +23,7 @@ import {Verified_Stroke2_Corner2_Rounded as VerifiedIcon} from '#/components/ico
import * as Layout from '#/components/Layout'
import {ChangeHandleDialog} from './components/ChangeHandleDialog'
import {DeactivateAccountDialog} from './components/DeactivateAccountDialog'
import {ExportCarDialog} from './components/ExportCarDialog'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'AccountSettings'>
export function AccountSettingsScreen({}: Props) {
@@ -31,6 +31,7 @@ export function AccountSettingsScreen({}: Props) {
const {_} = useLingui()
const {currentAccount} = useSession()
const {openModal} = useModalControls()
const verifyEmailControl = useDialogControl()
const birthdayControl = useDialogControl()
const changeHandleControl = useDialogControl()
const exportCarControl = useDialogControl()
@@ -43,25 +44,48 @@ export function AccountSettingsScreen({}: Props) {
<SettingsList.Container>
<SettingsList.Item>
<SettingsList.ItemIcon icon={EnvelopeIcon} />
<SettingsList.ItemText>
{/* Tricky flexbox situation here: we want the email to truncate, but by default it will make the "Email" text wrap instead.
For numberOfLines to work, we need flex: 1 on the BadgeText, but that means it goes to width: 50% because the
ItemText is also flex: 1. So we need to set flex: 0 on the ItemText to prevent it from growing, but if we did that everywhere
it wouldn't push the BadgeText/Chevron/whatever to the right.
TODO: find a general solution for this. workaround in this case is to set the ItemText to flex: 1 and BadgeText to flex: 0 -sfn */}
<SettingsList.ItemText style={[a.flex_0]}>
<Trans>Email</Trans>
</SettingsList.ItemText>
{currentAccount && (
<>
<SettingsList.BadgeText>
<SettingsList.BadgeText style={[a.flex_1]}>
{currentAccount.email || <Trans>(no email)</Trans>}
</SettingsList.BadgeText>
{currentAccount.emailConfirmed ? (
<CheckIcon color={t.palette.positive_500} size="sm" />
) : (
<SettingsList.BadgeButton
label={_(msg`Verify`)}
onPress={() => {}}
/>
{currentAccount.emailConfirmed && (
<VerifiedIcon fill={t.palette.primary_500} size="md" />
)}
</>
)}
</SettingsList.Item>
{currentAccount && !currentAccount.emailConfirmed && (
<SettingsList.PressableItem
label={_(msg`Verify your email`)}
onPress={() => verifyEmailControl.open()}
style={[
a.my_xs,
a.mx_lg,
a.rounded_md,
{backgroundColor: t.palette.primary_50},
]}
hoverStyle={[{backgroundColor: t.palette.primary_100}]}
contentContainerStyle={[a.rounded_md, a.px_lg]}>
<SettingsList.ItemIcon
icon={VerifiedIcon}
color={t.palette.primary_500}
/>
<SettingsList.ItemText
style={[{color: t.palette.primary_500}, a.font_bold]}>
<Trans>Verify your email</Trans>
</SettingsList.ItemText>
<SettingsList.Chevron color={t.palette.primary_500} />
</SettingsList.PressableItem>
)}
<SettingsList.PressableItem
label={_(msg`Change email`)}
onPress={() => openModal({name: 'change-email'})}>
@@ -71,27 +95,6 @@ export function AccountSettingsScreen({}: Props) {
</SettingsList.ItemText>
<SettingsList.Chevron />
</SettingsList.PressableItem>
<SettingsList.LinkItem
to="/settings/privacy-and-security"
label={_(msg`Protect your account`)}
style={[
a.my_xs,
a.mx_lg,
a.rounded_md,
{backgroundColor: t.palette.primary_50},
]}
chevronColor={t.palette.primary_500}
hoverStyle={[{backgroundColor: t.palette.primary_100}]}
contentContainerStyle={[a.rounded_md, a.px_lg]}>
<SettingsList.ItemIcon
icon={VerifiedIcon}
color={t.palette.primary_500}
/>
<SettingsList.ItemText
style={[{color: t.palette.primary_500}, a.font_bold]}>
<Trans>Protect your account</Trans>
</SettingsList.ItemText>
</SettingsList.LinkItem>
<SettingsList.Divider />
<SettingsList.Item>
<SettingsList.ItemIcon icon={BirthdayCakeIcon} />
@@ -155,6 +158,7 @@ export function AccountSettingsScreen({}: Props) {
</SettingsList.Container>
</Layout.Content>
<VerifyEmailDialog control={verifyEmailControl} />
<BirthDateSettingsDialog control={birthdayControl} />
<ChangeHandleDialog control={changeHandleControl} />
<ExportCarDialog control={exportCarControl} />
@@ -86,13 +86,13 @@ export function ContentAndMediaSettingsScreen({}: Props) {
)}
<Toggle.Item
name="disable_autoplay"
label={_(msg`Disable autoplay for videos and GIFs`)}
value={autoplayDisabledPref}
onChange={value => setAutoplayDisabledPref(value)}>
label={_(msg`Autoplay videos and GIFs`)}
value={!autoplayDisabledPref}
onChange={value => setAutoplayDisabledPref(!value)}>
<SettingsList.Item>
<SettingsList.ItemIcon icon={PlayIcon} />
<SettingsList.ItemText>
<Trans>Disable autoplay for videos and GIFs</Trans>
<Trans>Autoplay videos and GIFs</Trans>
</SettingsList.ItemText>
<Toggle.Platform />
</SettingsList.Item>
+274 -94
View File
@@ -1,56 +1,75 @@
import React from 'react'
import {View} from 'react-native'
import React, {useState} from 'react'
import {LayoutAnimation, Pressable, View} from 'react-native'
import {Linking} from 'react-native'
import {useReducedMotion} from 'react-native-reanimated'
import {AppBskyActorDefs, moderateProfile} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useNavigation} from '@react-navigation/native'
import {NativeStackScreenProps} from '@react-navigation/native-stack'
import {IS_INTERNAL} from '#/lib/app-info'
import {HELP_DESK_URL} from '#/lib/constants'
import {CommonNavigatorParams} from '#/lib/routes/types'
import {useAccountSwitcher} from '#/lib/hooks/useAccountSwitcher'
import {CommonNavigatorParams, NavigationProp} from '#/lib/routes/types'
import {sanitizeHandle} from '#/lib/strings/handles'
import {useProfileShadow} from '#/state/cache/profile-shadow'
import {clearStorage} from '#/state/persisted'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useDeleteActorDeclaration} from '#/state/queries/messages/actor-declaration'
import {useProfileQuery, useProfilesQuery} from '#/state/queries/profile'
import {useSession, useSessionApi} from '#/state/session'
import {SessionAccount, useSession, useSessionApi} from '#/state/session'
import {useOnboardingDispatch} from '#/state/shell'
import {useLoggedOutViewControls} from '#/state/shell/logged-out'
import {useCloseAllActiveElements} from '#/state/util'
import * as Toast from '#/view/com/util/Toast'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {ProfileHeaderDisplayName} from '#/screens/Profile/Header/DisplayName'
import {ProfileHeaderHandle} from '#/screens/Profile/Header/Handle'
import * as SettingsList from '#/screens/Settings/components/SettingsList'
import {atoms as a, useTheme} from '#/alf'
import {atoms as a, tokens, useTheme} from '#/alf'
import {AvatarStack} from '#/components/AvatarStack'
import {useDialogControl} from '#/components/Dialog'
import {SwitchAccountDialog} from '#/components/dialogs/SwitchAccount'
import {Accessibility_Stroke2_Corner2_Rounded as AccessibilityIcon} from '#/components/icons/Accessibility'
import {BubbleInfo_Stroke2_Corner2_Rounded as BubbleInfoIcon} from '#/components/icons/BubbleInfo'
import {ChevronTop_Stroke2_Corner0_Rounded as ChevronUpIcon} from '#/components/icons/Chevron'
import {CircleQuestion_Stroke2_Corner2_Rounded as CircleQuestionIcon} from '#/components/icons/CircleQuestion'
import {CodeBrackets_Stroke2_Corner2_Rounded as CodeBracketsIcon} from '#/components/icons/CodeBrackets'
import {DotGrid_Stroke2_Corner0_Rounded as DotsHorizontal} from '#/components/icons/DotGrid'
import {Earth_Stroke2_Corner2_Rounded as EarthIcon} from '#/components/icons/Globe'
import {Lock_Stroke2_Corner2_Rounded as LockIcon} from '#/components/icons/Lock'
import {PaintRoller_Stroke2_Corner2_Rounded as PaintRollerIcon} from '#/components/icons/PaintRoller'
import {
Person_Stroke2_Corner2_Rounded as PersonIcon,
PersonGroup_Stroke2_Corner2_Rounded as PersonGroupIcon,
PersonPlus_Stroke2_Corner2_Rounded as PersonPlusIcon,
PersonX_Stroke2_Corner0_Rounded as PersonXIcon,
} from '#/components/icons/Person'
import {RaisingHand4Finger_Stroke2_Corner2_Rounded as HandIcon} from '#/components/icons/RaisingHand'
import {Window_Stroke2_Corner2_Rounded as WindowIcon} from '#/components/icons/Window'
import * as Layout from '#/components/Layout'
import {Loader} from '#/components/Loader'
import * as Menu from '#/components/Menu'
import * as Prompt from '#/components/Prompt'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'Settings'>
export function SettingsScreen({}: Props) {
const {_} = useLingui()
const reducedMotion = useReducedMotion()
const {logoutEveryAccount} = useSessionApi()
const {accounts, currentAccount} = useSession()
const switchAccountControl = useDialogControl()
const signOutPromptControl = Prompt.usePromptControl()
const {data: profile} = useProfileQuery({did: currentAccount?.did})
const {setShowLoggedOut} = useLoggedOutViewControls()
const closeEverything = useCloseAllActiveElements()
const onAddAnotherAccount = () => {
setShowLoggedOut(true)
closeEverything()
}
const {data: otherProfiles} = useProfilesQuery({
handles: accounts
.filter(acc => acc.did !== currentAccount?.did)
.map(acc => acc.handle),
})
const {pendingDid, onPressSwitchAccount} = useAccountSwitcher()
const [showAccounts, setShowAccounts] = useState(false)
const [showDevOptions, setShowDevOptions] = useState(false)
return (
<Layout.Screen>
@@ -69,34 +88,59 @@ export function SettingsScreen({}: Props) {
]}>
{profile && <ProfilePreview profile={profile} />}
</View>
<SettingsList.PressableItem
label={
accounts.length > 1
? _(msg`Switch account`)
: _(msg`Add another account`)
}
onPress={() =>
accounts.length > 1
? switchAccountControl.open()
: onAddAnotherAccount()
}>
<SettingsList.ItemIcon icon={PersonGroupIcon} />
<SettingsList.ItemText>
{accounts.length > 1 ? (
<Trans>Switch account</Trans>
) : (
<Trans>Add another account</Trans>
{accounts.length > 1 ? (
<>
<SettingsList.PressableItem
label={_(msg`Switch account`)}
accessibilityHint={_(
msg`Show other accounts you can switch to`,
)}
onPress={() => {
if (!reducedMotion) {
LayoutAnimation.configureNext(
LayoutAnimation.Presets.easeInEaseOut,
)
}
setShowAccounts(s => !s)
}}>
<SettingsList.ItemIcon icon={PersonGroupIcon} />
<SettingsList.ItemText>
<Trans>Switch account</Trans>
</SettingsList.ItemText>
{showAccounts ? (
<SettingsList.ItemIcon icon={ChevronUpIcon} size="md" />
) : (
<AvatarStack
profiles={accounts
.map(acc => acc.did)
.filter(did => did !== currentAccount?.did)
.slice(0, 5)}
/>
)}
</SettingsList.PressableItem>
{showAccounts && (
<>
<SettingsList.Divider />
{accounts
.filter(acc => acc.did !== currentAccount?.did)
.map(account => (
<AccountRow
key={account.did}
account={account}
profile={otherProfiles?.profiles?.find(
p => p.did === account.did,
)}
pendingDid={pendingDid}
onPressSwitchAccount={onPressSwitchAccount}
/>
))}
<AddAccountRow />
</>
)}
</SettingsList.ItemText>
{accounts.length > 1 && (
<AvatarStack
profiles={accounts
.map(acc => acc.did)
.filter(did => did !== currentAccount?.did)
.slice(0, 5)}
/>
)}
</SettingsList.PressableItem>
</>
) : (
<AddAccountRow />
)}
<SettingsList.Divider />
<SettingsList.LinkItem to="/settings/account" label={_(msg`Account`)}>
<SettingsList.ItemIcon icon={PersonIcon} />
@@ -175,6 +219,27 @@ export function SettingsScreen({}: Props) {
<Trans>Sign out</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
{IS_INTERNAL && (
<>
<SettingsList.Divider />
<SettingsList.PressableItem
onPress={() => {
if (!reducedMotion) {
LayoutAnimation.configureNext(
LayoutAnimation.Presets.easeInEaseOut,
)
}
setShowDevOptions(d => !d)
}}
label={_(msg`Developer options`)}>
<SettingsList.ItemIcon icon={CodeBracketsIcon} />
<SettingsList.ItemText>
<Trans>Developer options</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
{showDevOptions && <DevOptions />}
</>
)}
</SettingsList.Container>
</Layout.Content>
@@ -218,66 +283,181 @@ function ProfilePreview({
)
}
const AVI_SIZE = 26
const HALF_AVI_SIZE = AVI_SIZE / 2
function DevOptions() {
const {_} = useLingui()
const onboardingDispatch = useOnboardingDispatch()
const navigation = useNavigation<NavigationProp>()
const {mutate: deleteChatDeclarationRecord} = useDeleteActorDeclaration()
function AvatarStack({profiles}: {profiles: string[]}) {
const {data, error} = useProfilesQuery({handles: profiles})
const t = useTheme()
const moderationOpts = useModerationOpts()
if (error) {
console.error(error)
return null
const resetOnboarding = async () => {
navigation.navigate('Home')
onboardingDispatch({type: 'start'})
Toast.show(_(msg`Onboarding reset`))
}
const isPending = !data || !moderationOpts
const items = isPending
? Array.from({length: profiles.length}).map((_, i) => ({
key: i,
profile: null,
moderation: null,
}))
: data.profiles.map(item => ({
key: item.did,
profile: item,
moderation: moderateProfile(item, moderationOpts),
}))
const clearAllStorage = async () => {
await clearStorage()
Toast.show(_(msg`Storage cleared, you need to restart the app now.`))
}
return (
<View
style={[
a.flex_row,
a.align_center,
a.relative,
{width: AVI_SIZE + (items.length - 1) * HALF_AVI_SIZE},
]}>
{items.map((item, i) => (
<View
key={item.key}
style={[
t.atoms.bg_contrast_25,
a.relative,
{
width: AVI_SIZE,
height: AVI_SIZE,
left: i * -HALF_AVI_SIZE,
borderWidth: 1,
borderColor: t.atoms.bg.backgroundColor,
borderRadius: 999,
zIndex: 3 - i,
},
]}>
{item.profile && (
<UserAvatar
size={AVI_SIZE - 2}
avatar={item.profile.avatar}
moderation={item.moderation.ui('avatar')}
/>
)}
</View>
))}
<>
<SettingsList.PressableItem
onPress={() => navigation.navigate('Log')}
label={_(msg`Open system log`)}>
<SettingsList.ItemText>
<Trans>System log</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
<SettingsList.PressableItem
onPress={() => navigation.navigate('Debug')}
label={_(msg`Open storybook page`)}>
<SettingsList.ItemText>
<Trans>Storybook</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
<SettingsList.PressableItem
onPress={() => navigation.navigate('DebugMod')}
label={_(msg`Open moderation debug page`)}>
<SettingsList.ItemText>
<Trans>Debug Moderation</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
<SettingsList.PressableItem
onPress={() => deleteChatDeclarationRecord()}
label={_(msg`Open storybook page`)}>
<SettingsList.ItemText>
<Trans>Delete chat declaration record</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
<SettingsList.PressableItem
onPress={() => resetOnboarding()}
label={_(msg`Reset onboarding state`)}>
<SettingsList.ItemText>
<Trans>Reset onboarding state</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
<SettingsList.PressableItem
onPress={() => clearAllStorage()}
label={_(msg`Clear all storage data`)}>
<SettingsList.ItemText>
<Trans>Clear all storage data (restart after this)</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
</>
)
}
function AddAccountRow() {
const {_} = useLingui()
const {setShowLoggedOut} = useLoggedOutViewControls()
const closeEverything = useCloseAllActiveElements()
const onAddAnotherAccount = () => {
setShowLoggedOut(true)
closeEverything()
}
return (
<SettingsList.PressableItem
onPress={onAddAnotherAccount}
label={_(msg`Add another account`)}>
<SettingsList.ItemIcon icon={PersonPlusIcon} />
<SettingsList.ItemText>
<Trans>Add another account</Trans>
</SettingsList.ItemText>
</SettingsList.PressableItem>
)
}
function AccountRow({
profile,
account,
pendingDid,
onPressSwitchAccount,
}: {
profile?: AppBskyActorDefs.ProfileViewDetailed
account: SessionAccount
pendingDid: string | null
onPressSwitchAccount: (
account: SessionAccount,
logContext: 'Settings',
) => void
}) {
const {_} = useLingui()
const t = useTheme()
const moderationOpts = useModerationOpts()
const removePromptControl = Prompt.usePromptControl()
const {removeAccount} = useSessionApi()
const onSwitchAccount = () => {
if (pendingDid) return
onPressSwitchAccount(account, 'Settings')
}
return (
<View style={[a.relative]}>
<SettingsList.PressableItem
onPress={onSwitchAccount}
label={_(msg`Switch account`)}>
{moderationOpts && profile ? (
<UserAvatar
size={28}
avatar={profile.avatar}
moderation={moderateProfile(profile, moderationOpts).ui('avatar')}
/>
) : (
<View style={[{width: 28}]} />
)}
<SettingsList.ItemText>
<Trans>{sanitizeHandle(account.handle, '@')}</Trans>
</SettingsList.ItemText>
{pendingDid === account.did && <SettingsList.ItemIcon icon={Loader} />}
</SettingsList.PressableItem>
{!pendingDid && (
<Menu.Root>
<Menu.Trigger label={_(msg`Account options`)}>
{({props, state}) => (
<Pressable
{...props}
style={[
a.absolute,
{top: 10, right: tokens.space.lg},
a.p_xs,
a.rounded_full,
(state.hovered || state.pressed) && t.atoms.bg_contrast_25,
]}>
<DotsHorizontal size="md" style={t.atoms.text} />
</Pressable>
)}
</Menu.Trigger>
<Menu.Outer showCancel>
<Menu.Item
label={_(msg`Remove account`)}
onPress={() => removePromptControl.open()}>
<Menu.ItemText>
<Trans>Remove account</Trans>
</Menu.ItemText>
<Menu.ItemIcon icon={PersonXIcon} />
</Menu.Item>
</Menu.Outer>
</Menu.Root>
)}
<Prompt.Basic
control={removePromptControl}
title={_(msg`Remove from quick access?`)}
description={_(
msg`This will remove @${account.handle} from the quick access list.`,
)}
onConfirm={() => {
removeAccount(account)
Toast.show(_(msg`Account removed from quick access`))
}}
confirmButtonCta={_(msg`Remove`)}
confirmButtonColor="negative"
/>
</View>
)
}
+4 -2
View File
@@ -44,7 +44,9 @@ export function ThreadPreferencesScreen({}: Props) {
<SettingsList.Container>
<SettingsList.Group>
<SettingsList.ItemIcon icon={BubblesIcon} />
<SettingsList.ItemText>Sort replies</SettingsList.ItemText>
<SettingsList.ItemText>
<Trans>Sort replies</Trans>
</SettingsList.ItemText>
<View style={[a.w_full, a.gap_md]}>
<Text style={[a.flex_1, t.atoms.text_contrast_medium]}>
<Trans>Sort replies to the same post by:</Trans>
@@ -109,7 +111,7 @@ export function ThreadPreferencesScreen({}: Props) {
style={[a.w_full, a.gap_md]}>
<Toggle.LabelText style={[a.flex_1]}>
<Trans>
Show replies by people you follow before all other replies.
Show replies by people you follow before all other replies
</Trans>
</Toggle.LabelText>
<Toggle.Platform />
+11 -3
View File
@@ -1,6 +1,10 @@
import React, {useCallback, useEffect, useState} from 'react'
import {GestureResponderEvent, View} from 'react-native'
import Animated, {FadeOutUp, ZoomIn} from 'react-native-reanimated'
import Animated, {
FadeOutUp,
useReducedMotion,
ZoomIn,
} from 'react-native-reanimated'
import * as Clipboard from 'expo-clipboard'
import {Trans} from '@lingui/macro'
@@ -16,13 +20,17 @@ export function CopyButton({
}: ButtonProps & {value: string}) {
const [hasBeenCopied, setHasBeenCopied] = useState(false)
const t = useTheme()
const isReducedMotionEnabled = useReducedMotion()
useEffect(() => {
if (hasBeenCopied) {
const timeout = setTimeout(() => setHasBeenCopied(false), 100)
const timeout = setTimeout(
() => setHasBeenCopied(false),
isReducedMotionEnabled ? 2000 : 100,
)
return () => clearTimeout(timeout)
}
}, [hasBeenCopied])
}, [hasBeenCopied, isReducedMotionEnabled])
const onPress = useCallback(
(evt: GestureResponderEvent) => {
@@ -4,9 +4,9 @@ import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
import {useAgent, useSession} from '#/state/session'
import {DisableEmail2FADialog} from '#/view/screens/Settings/DisableEmail2FADialog'
import {useDialogControl} from '#/components/Dialog'
import * as Prompt from '#/components/Prompt'
import {DisableEmail2FADialog} from './DisableEmail2FADialog'
import * as SettingsList from './SettingsList'
export function Email2FAToggle() {
@@ -264,7 +264,13 @@ export function Chevron({color: colorProp}: {color?: string}) {
return <ItemIcon icon={ChevronRightIcon} size="md" color={color} />
}
export function BadgeText({children}: {children: React.ReactNode}) {
export function BadgeText({
children,
style,
}: {
children: React.ReactNode
style?: StyleProp<ViewStyle>
}) {
const t = useTheme()
return (
<Text
@@ -273,6 +279,7 @@ export function BadgeText({children}: {children: React.ReactNode}) {
a.text_md,
a.text_right,
a.leading_snug,
style,
]}
numberOfLines={1}>
{children}
@@ -429,11 +429,12 @@ function Header({
color="primary"
size="small"
disabled={isProcessing}
onPress={onFollowAll}>
onPress={onFollowAll}
style={[a.flex_row, a.gap_xs, a.align_center]}>
<ButtonText>
<Trans>Follow all</Trans>
{isProcessing && <Loader size="xs" />}
</ButtonText>
{isProcessing && <Loader size="xs" />}
</Button>
)}
<OverflowMenu
+1 -1
View File
@@ -72,7 +72,7 @@ export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) {
const sendToFeed = React.useMemo(
() =>
throttle(sendToFeedNoDelay, 15e3, {
throttle(sendToFeedNoDelay, 10e3, {
leading: false,
trailing: true,
}),
+11 -24
View File
@@ -1,30 +1,15 @@
import React from 'react'
import type {MeasuredDimensions} from 'react-native-reanimated'
import {AppBskyActorDefs} from '@atproto/api'
import {nanoid} from 'nanoid/non-secure'
import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
import {ImageSource} from '#/view/com/lightbox/ImageViewing/@types'
type ProfileImageLightbox = {
type: 'profile-image'
profile: AppBskyActorDefs.ProfileViewDetailed
thumbDims: null
}
type ImagesLightboxItem = {
uri: string
thumbUri: string
alt?: string
}
type ImagesLightbox = {
type: 'images'
images: ImagesLightboxItem[]
thumbDims: MeasuredDimensions | null
export type Lightbox = {
id: string
images: ImageSource[]
index: number
}
type Lightbox = ProfileImageLightbox | ImagesLightbox
const LightboxContext = React.createContext<{
activeLightbox: Lightbox | null
}>({
@@ -32,7 +17,7 @@ const LightboxContext = React.createContext<{
})
const LightboxControlContext = React.createContext<{
openLightbox: (lightbox: Lightbox) => void
openLightbox: (lightbox: Omit<Lightbox, 'id'>) => void
closeLightbox: () => boolean
}>({
openLightbox: () => {},
@@ -44,9 +29,11 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
null,
)
const openLightbox = useNonReactiveCallback((lightbox: Lightbox) => {
setActiveLightbox(lightbox)
})
const openLightbox = useNonReactiveCallback(
(lightbox: Omit<Lightbox, 'id'>) => {
setActiveLightbox({...lightbox, id: nanoid()})
},
)
const closeLightbox = useNonReactiveCallback(() => {
let wasActive = !!activeLightbox
+2 -2
View File
@@ -1,5 +1,5 @@
export const ACTIVE_POLL_INTERVAL = 3e3
export const MESSAGE_SCREEN_POLL_INTERVAL = 10e3
export const ACTIVE_POLL_INTERVAL = 4e3
export const MESSAGE_SCREEN_POLL_INTERVAL = 30e3
export const BACKGROUND_POLL_INTERVAL = 60e3
export const INACTIVE_TIMEOUT = 60e3 * 5
+1 -1
View File
@@ -1,2 +1,2 @@
export const DEFAULT_POLL_INTERVAL = 60e3 * 5
export const DEFAULT_POLL_INTERVAL = 60e3
export const BACKGROUND_POLL_INTERVAL = 60e3 * 5
-11
View File
@@ -48,11 +48,6 @@ export interface DeleteAccountModal {
name: 'delete-account'
}
export interface ChangeHandleModal {
name: 'change-handle'
onChanged: () => void
}
export interface WaitlistModal {
name: 'waitlist'
}
@@ -61,10 +56,6 @@ export interface InviteCodesModal {
name: 'invite-codes'
}
export interface AddAppPasswordModal {
name: 'add-app-password'
}
export interface ContentLanguagesSettingsModal {
name: 'content-languages-settings'
}
@@ -101,8 +92,6 @@ export interface InAppBrowserConsentModal {
export type Modal =
// Account
| AddAppPasswordModal
| ChangeHandleModal
| DeleteAccountModal
| VerifyEmailModal
| ChangeEmailModal
@@ -0,0 +1,25 @@
import {useQuery} from '@tanstack/react-query'
interface ServiceConfig {
checkEmailConfirmed: boolean
}
export function useServiceConfigQuery() {
return useQuery({
queryKey: ['service-config'],
queryFn: async () => {
const res = await fetch(
'https://api.bsky.app/xrpc/app.bsky.unspecced.getConfig',
)
if (!res.ok) {
return {
checkEmailConfirmed: false,
}
}
const json = await res.json()
return json as ServiceConfig
},
staleTime: 5 * 60 * 1000,
})
}
+36 -3
View File
@@ -5,7 +5,11 @@ import {STALE} from '#/state/queries'
import {DM_SERVICE_HEADERS} from '#/state/queries/messages/const'
import {useOnMarkAsRead} from '#/state/queries/messages/list-converations'
import {useAgent} from '#/state/session'
import {RQKEY as LIST_CONVOS_KEY} from './list-converations'
import {
ConvoListQueryData,
getConvoFromQueryData,
RQKEY as LIST_CONVOS_KEY,
} from './list-converations'
const RQKEY_ROOT = 'convo'
export const RQKEY = (convoId: string) => [RQKEY_ROOT, convoId]
@@ -57,8 +61,37 @@ export function useMarkAsReadMutation() {
if (!convoId) throw new Error('No convoId provided')
optimisticUpdate(convoId)
},
onSettled() {
queryClient.invalidateQueries({queryKey: LIST_CONVOS_KEY})
onSuccess(_, {convoId}) {
if (!convoId) return
queryClient.setQueryData(LIST_CONVOS_KEY, (old: ConvoListQueryData) => {
if (!old) return old
const existingConvo = getConvoFromQueryData(convoId, old)
if (existingConvo) {
return {
...old,
pages: old.pages.map(page => {
return {
...page,
convos: page.convos.map(convo => {
if (convo.id === convoId) {
return {
...convo,
unreadCount: 0,
}
}
return convo
}),
}
}),
}
} else {
// If we somehow marked a convo as read that doesn't exist in the
// list, then we don't need to do anything.
}
})
},
})
}
@@ -39,7 +39,7 @@ export function useListConvosQuery({
queryKey: RQKEY,
queryFn: async ({pageParam}) => {
const {data} = await agent.api.chat.bsky.convo.listConvos(
{cursor: pageParam},
{cursor: pageParam, limit: 20},
{headers: DM_SERVICE_HEADERS},
)
@@ -47,9 +47,6 @@ export function useListConvosQuery({
},
initialPageParam: undefined as RQPageParam,
getNextPageParam: lastPage => lastPage.cursor,
// refetch every 60 seconds since we can't get *all* info from the logs
// i.e. reading chats on another device won't update the unread count
refetchInterval: 60_000,
})
}
@@ -180,6 +177,11 @@ export function ListConvosProviderInner({
}),
}
} else {
/**
* We received a message from an conversation old enough that
* it doesn't exist in the query cache, meaning we need to
* refetch and bump the old convo to the top.
*/
debouncedRefetch()
}
})
@@ -245,12 +247,12 @@ export function useUnreadMessageCount() {
return useMemo(() => {
return {
count,
numUnread: count > 0 ? (count > 30 ? '30+' : String(count)) : undefined,
numUnread: count > 0 ? (count > 10 ? '10+' : String(count)) : undefined,
}
}, [count])
}
type ConvoListQueryData = {
export type ConvoListQueryData = {
pageParams: Array<string | undefined>
pages: Array<ChatBskyConvoListConvos.OutputSchema>
}
@@ -301,7 +303,7 @@ function optimisticDelete(chatId: string, old: ConvoListQueryData) {
}
}
function getConvoFromQueryData(chatId: string, old: ConvoListQueryData) {
export function getConvoFromQueryData(chatId: string, old: ConvoListQueryData) {
for (const page of old.pages) {
for (const convo of page.convos) {
if (convo.id === chatId) {
+8
View File
@@ -18,12 +18,20 @@ const stateContext = React.createContext<StateContext>({
addListener() {},
removeListener() {},
modify() {},
get() {
return 0
},
set() {},
},
footerMode: {
value: 0,
addListener() {},
removeListener() {},
modify() {},
get() {
return 0
},
set() {},
},
})
const setContext = React.createContext<SetContext>((_: boolean) => {})
+8
View File
@@ -12,12 +12,20 @@ const stateContext = React.createContext<StateContext>({
addListener() {},
removeListener() {},
modify() {},
get() {
return 0
},
set() {},
},
footerHeight: {
value: 0,
addListener() {},
removeListener() {},
modify() {},
get() {
return 0
},
set() {},
},
})
+49 -5
View File
@@ -58,6 +58,7 @@ import {EmbeddingDisabledError} from '#/lib/api/resolve'
import {until} from '#/lib/async/until'
import {MAX_GRAPHEME_LENGTH} from '#/lib/constants'
import {useAnimatedScrollHandler} from '#/lib/hooks/useAnimatedScrollHandler_FIXED'
import {useEmail} from '#/lib/hooks/useEmail'
import {useIsKeyboardVisible} from '#/lib/hooks/useIsKeyboardVisible'
import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
import {usePalette} from '#/lib/hooks/usePalette'
@@ -110,6 +111,8 @@ import * as Toast from '#/view/com/util/Toast'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, native, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import {useDialogControl} from '#/components/Dialog'
import {VerifyEmailDialog} from '#/components/dialogs/VerifyEmailDialog'
import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfo} from '#/components/icons/CircleInfo'
import {EmojiArc_Stroke2_Corner0_Rounded as EmojiSmile} from '#/components/icons/Emoji'
import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
@@ -297,6 +300,15 @@ export const ComposePost = ({
}
}, [onPressCancel, closeAllDialogs, closeAllModals])
const {needsEmailVerification} = useEmail()
const emailVerificationControl = useDialogControl()
useEffect(() => {
if (needsEmailVerification) {
emailVerificationControl.open()
}
}, [needsEmailVerification, emailVerificationControl])
const missingAltError = useMemo(() => {
if (!requireAltTextEnabled) {
return
@@ -405,6 +417,7 @@ export const ComposePost = ({
? post.embed.media.images.length
: 0,
isReply: index > 0 || !!replyTo,
isPartOfThread: thread.posts.length > 1,
hasLink: !!post.embed.link,
hasQuote: !!post.embed.quote,
langs: langPrefs.postLanguage,
@@ -413,6 +426,12 @@ export const ComposePost = ({
index++
}
}
if (thread.posts.length > 1) {
logEvent('thread:create', {
postCount: thread.posts.length,
isReply: !!replyTo,
})
}
}
if (postUri && !replyTo) {
emitPostCreated()
@@ -436,7 +455,9 @@ export const ComposePost = ({
}
onClose()
Toast.show(
replyTo
thread.posts.length > 1
? _(msg`Your posts have been published`)
: replyTo
? _(msg`Your reply has been published`)
: _(msg`Your post has been published`),
)
@@ -516,6 +537,7 @@ export const ComposePost = ({
}
}, [composerState])
const isLastThreadedPost = thread.posts.length > 1 && nextPost === undefined
const {
scrollHandler,
onScrollViewContentSizeChange,
@@ -524,7 +546,7 @@ export const ComposePost = ({
bottomBarAnimatedStyle,
} = useScrollTracker({
scrollViewRef,
stickyBottom: true,
stickyBottom: isLastThreadedPost,
})
const keyboardVerticalOffset = useKeyboardVerticalOffset()
@@ -557,9 +579,18 @@ export const ComposePost = ({
</>
)
const isFooterSticky = !isNative && thread.posts.length > 1
const isWebFooterSticky = !isNative && thread.posts.length > 1
return (
<BottomSheetPortalProvider>
<VerifyEmailDialog
control={emailVerificationControl}
onCloseWithoutVerifying={() => {
onClose()
}}
reasonText={_(
msg`Before creating a post, you must first verify your email.`,
)}
/>
<KeyboardAvoidingView
testID="composePostView"
behavior={isIOS ? 'padding' : 'height'}
@@ -608,6 +639,7 @@ export const ComposePost = ({
dispatch={composerDispatch}
textInput={post.id === activePost.id ? textInput : null}
isFirstPost={index === 0}
isPartOfThread={thread.posts.length > 1}
isReply={index > 0 || !!replyTo}
isActive={post.id === activePost.id}
canRemovePost={thread.posts.length > 1}
@@ -617,11 +649,13 @@ export const ComposePost = ({
onPublish={onComposerPostPublish}
onError={setError}
/>
{isFooterSticky && post.id === activePost.id && footer}
{isWebFooterSticky && post.id === activePost.id && (
<View style={styles.stickyFooterWeb}>{footer}</View>
)}
</React.Fragment>
))}
</Animated.ScrollView>
{!isFooterSticky && footer}
{!isWebFooterSticky && footer}
</View>
<Prompt.Basic
@@ -644,6 +678,7 @@ let ComposerPost = React.memo(function ComposerPost({
isActive,
isReply,
isFirstPost,
isPartOfThread,
canRemovePost,
canRemoveQuote,
onClearVideo,
@@ -657,6 +692,7 @@ let ComposerPost = React.memo(function ComposerPost({
isActive: boolean
isReply: boolean
isFirstPost: boolean
isPartOfThread: boolean
canRemovePost: boolean
canRemoveQuote: boolean
onClearVideo: (postId: string) => void
@@ -736,6 +772,9 @@ let ComposerPost = React.memo(function ComposerPost({
placeholder={selectTextInputPlaceholder}
autoFocus
webForceMinHeight={forceMinHeight}
// To avoid overlap with the close button:
hasRightPadding={isPartOfThread}
isActive={isActive}
setRichText={rt => {
dispatchPost({type: 'update_richtext', richtext: rt})
}}
@@ -1387,6 +1426,11 @@ const styles = StyleSheet.create({
paddingVertical: 6,
marginLeft: 12,
},
stickyFooterWeb: {
// @ts-ignore web-only
position: 'sticky',
bottom: 0,
},
errorLine: {
flexDirection: 'row',
alignItems: 'center',
+23 -21
View File
@@ -144,36 +144,40 @@ function DialogInner({
}}>
<View style={[a.gap_sm]}>
<Toggle.Item name="sexual" label={_(msg`Suggestive`)}>
<Toggle.Radio />
<Toggle.Checkbox />
<Toggle.LabelText>
<Trans>Suggestive</Trans>
</Toggle.LabelText>
</Toggle.Item>
<Toggle.Item name="nudity" label={_(msg`Nudity`)}>
<Toggle.Radio />
<Toggle.Checkbox />
<Toggle.LabelText>
<Trans>Nudity</Trans>
</Toggle.LabelText>
</Toggle.Item>
<Toggle.Item name="porn" label={_(msg`Porn`)}>
<Toggle.Radio />
<Toggle.Checkbox />
<Toggle.LabelText>
<Trans>Porn</Trans>
<Trans>Adult</Trans>
</Toggle.LabelText>
</Toggle.Item>
</View>
</Toggle.Group>
<Text style={[a.mt_sm, t.atoms.text_contrast_medium]}>
{labels.includes('sexual') ? (
<Trans>Pictures meant for adults.</Trans>
) : labels.includes('nudity') ? (
<Trans>Artistic or non-erotic nudity.</Trans>
) : labels.includes('porn') ? (
<Trans>Sexual activity or erotic nudity.</Trans>
) : (
<Trans>Does not contain adult content.</Trans>
)}
</Text>
{labels.includes('sexual') ||
labels.includes('nudity') ||
labels.includes('porn') ? (
<Text style={[a.mt_sm, t.atoms.text_contrast_medium]}>
{labels.includes('sexual') ? (
<Trans>Pictures meant for adults.</Trans>
) : labels.includes('nudity') ? (
<Trans>Artistic or non-erotic nudity.</Trans>
) : labels.includes('porn') ? (
<Trans>Sexual activity or erotic nudity.</Trans>
) : (
''
)}
</Text>
) : null}
</View>
</View>
<View>
@@ -203,16 +207,14 @@ function DialogInner({
</Toggle.LabelText>
</Toggle.Item>
</Toggle.Group>
<Text style={[a.mt_sm, t.atoms.text_contrast_medium]}>
{labels.includes('graphic-media') ? (
{labels.includes('graphic-media') ? (
<Text style={[a.mt_sm, t.atoms.text_contrast_medium]}>
<Trans>
Media that may be disturbing or inappropriate for some
audiences.
</Trans>
) : (
<Trans>Does not contain graphic or disturbing content.</Trans>
)}
</Text>
</Text>
) : null}
</View>
</View>
</View>
+6 -2
View File
@@ -224,7 +224,7 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft {
return {
...state,
richtext: action.richtext,
shortenedGraphemeLength: shortenLinks(action.richtext).graphemeLength,
shortenedGraphemeLength: getShortenedLength(action.richtext),
}
}
case 'update_labels': {
@@ -516,7 +516,7 @@ export function createComposerState({
{
id: nanoid(),
richtext: initRichText,
shortenedGraphemeLength: 0,
shortenedGraphemeLength: getShortenedLength(initRichText),
labels: [],
embed: {
quote,
@@ -530,3 +530,7 @@ export function createComposerState({
},
}
}
function getShortenedLength(rt: RichText) {
return shortenLinks(rt).graphemeLength
}
@@ -44,6 +44,8 @@ interface TextInputProps extends ComponentProps<typeof RNTextInput> {
richtext: RichText
placeholder: string
webForceMinHeight: boolean
hasRightPadding: boolean
isActive: boolean
setRichText: (v: RichText) => void
onPhotoPasted: (uri: string) => void
onPressPublish: (richtext: RichText) => void
@@ -60,6 +62,7 @@ export const TextInput = forwardRef(function TextInputImpl(
{
richtext,
placeholder,
hasRightPadding,
setRichText,
onPhotoPasted,
onNewLink,
@@ -231,7 +234,7 @@ export const TextInput = forwardRef(function TextInputImpl(
}, [t, richtext, inputTextStyle])
return (
<View style={[a.flex_1, a.pl_md]}>
<View style={[a.flex_1, a.pl_md, hasRightPadding && a.pr_4xl]}>
<PasteInput
testID="composerTextInput"
ref={textInput}
@@ -249,7 +252,11 @@ export const TextInput = forwardRef(function TextInputImpl(
style={[
inputTextStyle,
a.w_full,
{textAlignVertical: 'top', minHeight: 60},
{
textAlignVertical: 'top',
minHeight: 60,
includeFontPadding: false,
},
]}
{...props}>
{textDecorated}
@@ -42,6 +42,8 @@ interface TextInputProps {
placeholder: string
suggestedLinks: Set<string>
webForceMinHeight: boolean
hasRightPadding: boolean
isActive: boolean
setRichText: (v: RichText | ((v: RichText) => RichText)) => void
onPhotoPasted: (uri: string) => void
onPressPublish: (richtext: RichText) => void
@@ -55,6 +57,8 @@ export const TextInput = React.forwardRef(function TextInputImpl(
richtext,
placeholder,
webForceMinHeight,
hasRightPadding,
isActive,
setRichText,
onPhotoPasted,
onPressPublish,
@@ -94,19 +98,30 @@ export const TextInput = React.forwardRef(function TextInputImpl(
)
React.useEffect(() => {
if (!isActive) {
return
}
textInputWebEmitter.addListener('publish', onPressPublish)
return () => {
textInputWebEmitter.removeListener('publish', onPressPublish)
}
}, [onPressPublish])
}, [onPressPublish, isActive])
React.useEffect(() => {
if (!isActive) {
return
}
textInputWebEmitter.addListener('media-pasted', onPhotoPasted)
return () => {
textInputWebEmitter.removeListener('media-pasted', onPhotoPasted)
}
}, [onPhotoPasted])
}, [isActive, onPhotoPasted])
React.useEffect(() => {
if (!isActive) {
return
}
const handleDrop = (event: DragEvent) => {
const transfer = event.dataTransfer
if (transfer) {
@@ -144,7 +159,7 @@ export const TextInput = React.forwardRef(function TextInputImpl(
document.body.removeEventListener('dragover', handleDragEnter)
document.body.removeEventListener('dragleave', handleDragLeave)
}
}, [setIsDropping])
}, [setIsDropping, isActive])
const pastSuggestedUris = useRef(new Set<string>())
const prevDetectedUris = useRef(new Map<string, LinkFacetMatch>())
@@ -242,11 +257,14 @@ export const TextInput = React.forwardRef(function TextInputImpl(
[editor],
)
React.useEffect(() => {
if (!isActive) {
return
}
textInputWebEmitter.addListener('emoji-inserted', onEmojiInserted)
return () => {
textInputWebEmitter.removeListener('emoji-inserted', onEmojiInserted)
}
}, [onEmojiInserted])
}, [onEmojiInserted, isActive])
React.useImperativeHandle(ref, () => ({
focus: () => {
@@ -291,7 +309,7 @@ export const TextInput = React.forwardRef(function TextInputImpl(
return (
<>
<View style={styles.container}>
<View style={[styles.container, hasRightPadding && styles.rightPadding]}>
{/* @ts-ignore inputStyle is fine */}
<EditorContent editor={editor} style={inputStyle} />
</View>
@@ -357,6 +375,9 @@ const styles = StyleSheet.create({
marginLeft: 8,
marginBottom: 10,
},
rightPadding: {
paddingRight: 32,
},
dropContainer: {
backgroundColor: '#0007',
pointerEvents: 'none',
+4 -1
View File
@@ -162,7 +162,10 @@ export function FeedSourceCardLoaded({
style={[
pal.border,
{
borderTopWidth: showMinimalPlaceholder || hideTopBorder ? 0 : 1,
borderTopWidth:
showMinimalPlaceholder || hideTopBorder
? 0
: StyleSheet.hairlineWidth,
flexDirection: 'row',
alignItems: 'center',
flex: 1,
@@ -6,6 +6,9 @@
*
*/
import {TransformsStyle} from 'react-native'
import {MeasuredDimensions} from 'react-native-reanimated'
export type Dimensions = {
width: number
height: number
@@ -16,4 +19,17 @@ export type Position = {
y: number
}
export type ImageSource = {uri: string; thumbUri: string; alt?: string}
export type ImageSource = {
uri: string
dimensions: Dimensions | null
thumbUri: string
thumbDimensions: Dimensions | null
thumbRect: MeasuredDimensions | null
alt?: string
type: 'image' | 'circle-avi' | 'rect-avi'
}
export type Transform = Exclude<
TransformsStyle['transform'],
string | undefined
>
@@ -1,19 +1,26 @@
import React, {useState} from 'react'
import {ActivityIndicator, Dimensions, StyleSheet} from 'react-native'
import {Gesture, GestureDetector} from 'react-native-gesture-handler'
import {ActivityIndicator, StyleSheet} from 'react-native'
import {
Gesture,
GestureDetector,
PanGesture,
} from 'react-native-gesture-handler'
import Animated, {
runOnJS,
SharedValue,
useAnimatedReaction,
useAnimatedRef,
useAnimatedStyle,
useSharedValue,
withDecay,
withSpring,
} from 'react-native-reanimated'
import {Image} from 'expo-image'
import type {Dimensions as ImageDimensions, ImageSource} from '../../@types'
import useImageDimensions from '../../hooks/useImageDimensions'
import type {
Dimensions as ImageDimensions,
ImageSource,
Transform,
} from '../../@types'
import {
applyRounding,
createTransform,
@@ -24,14 +31,7 @@ import {
TransformMatrix,
} from '../../transforms'
const windowDim = Dimensions.get('window')
const screenDim = Dimensions.get('screen')
const statusBarHeight = windowDim.height - screenDim.height
const SCREEN = {
width: windowDim.width,
height: windowDim.height + statusBarHeight,
}
const MIN_DOUBLE_TAP_SCALE = 2
const MIN_SCREEN_ZOOM = 2
const MAX_ORIGINAL_IMAGE_ZOOM = 2
const initialTransform = createTransform()
@@ -41,24 +41,46 @@ type Props = {
onRequestClose: () => void
onTap: () => void
onZoom: (isZoomed: boolean) => void
onLoad: (dims: ImageDimensions) => void
isScrollViewBeingDragged: boolean
showControls: boolean
measureSafeArea: () => {
x: number
y: number
width: number
height: number
}
imageAspect: number | undefined
imageDimensions: ImageDimensions | undefined
dismissSwipePan: PanGesture
transforms: Readonly<
SharedValue<{
scaleAndMoveTransform: Transform
cropFrameTransform: Transform
cropContentTransform: Transform
isResting: boolean
isHidden: boolean
}>
>
}
const ImageItem = ({
imageSrc,
onTap,
onZoom,
onRequestClose,
onLoad,
isScrollViewBeingDragged,
measureSafeArea,
imageAspect,
imageDimensions,
dismissSwipePan,
transforms,
}: Props) => {
const [isScaled, setIsScaled] = useState(false)
const imageDimensions = useImageDimensions(imageSrc)
const committedTransform = useSharedValue(initialTransform)
const panTranslation = useSharedValue({x: 0, y: 0})
const pinchOrigin = useSharedValue({x: 0, y: 0})
const pinchScale = useSharedValue(1)
const pinchTranslation = useSharedValue({x: 0, y: 0})
const dismissSwipeTranslateY = useSharedValue(0)
const containerRef = useAnimatedRef()
// Keep track of when we're entering or leaving scaled rendering.
@@ -89,51 +111,32 @@ const ImageItem = ({
onZoom(nextIsScaled)
}
const animatedStyle = useAnimatedStyle(() => {
// Apply the active adjustments on top of the committed transform before the gestures.
// This is matrix multiplication, so operations are applied in the reverse order.
let t = createTransform()
prependPan(t, panTranslation.value)
prependPinch(t, pinchScale.value, pinchOrigin.value, pinchTranslation.value)
prependTransform(t, committedTransform.value)
const [translateX, translateY, scale] = readTransform(t)
const dismissDistance = dismissSwipeTranslateY.value
const dismissProgress = Math.min(
Math.abs(dismissDistance) / (SCREEN.height / 2),
1,
)
return {
opacity: 1 - dismissProgress,
transform: [
{translateX},
{translateY: translateY + dismissDistance},
{scale},
],
}
})
// On Android, stock apps prevent going "out of bounds" on pan or pinch. You should "bump" into edges.
// If the user tried to pan too hard, this function will provide the negative panning to stay in bounds.
function getExtraTranslationToStayInBounds(
candidateTransform: TransformMatrix,
screenSize: {width: number; height: number},
) {
'worklet'
if (!imageDimensions) {
if (!imageAspect) {
return [0, 0]
}
const [nextTranslateX, nextTranslateY, nextScale] =
readTransform(candidateTransform)
const scaledDimensions = getScaledDimensions(imageDimensions, nextScale)
const scaledDimensions = getScaledDimensions(
imageAspect,
nextScale,
screenSize,
)
const clampedTranslateX = clampTranslation(
nextTranslateX,
scaledDimensions.width,
SCREEN.width,
screenSize.width,
)
const clampedTranslateY = clampTranslation(
nextTranslateY,
scaledDimensions.height,
SCREEN.height,
screenSize.height,
)
const dx = clampedTranslateX - nextTranslateX
const dy = clampedTranslateY - nextTranslateY
@@ -143,21 +146,25 @@ const ImageItem = ({
const pinch = Gesture.Pinch()
.onStart(e => {
'worklet'
const screenSize = measureSafeArea()
pinchOrigin.value = {
x: e.focalX - SCREEN.width / 2,
y: e.focalY - SCREEN.height / 2,
x: e.focalX - screenSize.width / 2,
y: e.focalY - screenSize.height / 2,
}
})
.onChange(e => {
'worklet'
const screenSize = measureSafeArea()
if (!imageDimensions) {
return
}
// Don't let the picture zoom in so close that it gets blurry.
// Also, like in stock Android apps, don't let the user zoom out further than 1:1.
const [, , committedScale] = readTransform(committedTransform.value)
const maxCommittedScale =
(imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM
const maxCommittedScale = Math.max(
MIN_SCREEN_ZOOM,
(imageDimensions.width / screenSize.width) * MAX_ORIGINAL_IMAGE_ZOOM,
)
const minPinchScale = 1 / committedScale
const maxPinchScale = maxCommittedScale / committedScale
const nextPinchScale = Math.min(
@@ -172,7 +179,7 @@ const ImageItem = ({
prependPan(t, panTranslation.value)
prependPinch(t, nextPinchScale, pinchOrigin.value, pinchTranslation.value)
prependTransform(t, committedTransform.value)
const [dx, dy] = getExtraTranslationToStayInBounds(t)
const [dx, dy] = getExtraTranslationToStayInBounds(t, screenSize)
if (dx !== 0 || dy !== 0) {
pinchTranslation.value = {
x: pinchTranslation.value.x + dx,
@@ -206,9 +213,11 @@ const ImageItem = ({
.minPointers(isScaled ? 1 : 2)
.onChange(e => {
'worklet'
const screenSize = measureSafeArea()
if (!imageDimensions) {
return
}
const nextPanTranslation = {x: e.translationX, y: e.translationY}
let t = createTransform()
prependPan(t, nextPanTranslation)
@@ -221,7 +230,7 @@ const ImageItem = ({
prependTransform(t, committedTransform.value)
// Prevent panning from going out of bounds.
const [dx, dy] = getExtraTranslationToStayInBounds(t)
const [dx, dy] = getExtraTranslationToStayInBounds(t, screenSize)
nextPanTranslation.x += dx
nextPanTranslation.y += dy
panTranslation.value = nextPanTranslation
@@ -248,7 +257,8 @@ const ImageItem = ({
.numberOfTaps(2)
.onEnd(e => {
'worklet'
if (!imageDimensions) {
const screenSize = measureSafeArea()
if (!imageDimensions || !imageAspect) {
return
}
const [, , committedScale] = readTransform(committedTransform.value)
@@ -260,56 +270,38 @@ const ImageItem = ({
}
// Try to zoom in so that we get rid of the black bars (whatever the orientation was).
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = SCREEN.width / SCREEN.height
const screenAspect = screenSize.width / screenSize.height
const candidateScale = Math.max(
imageAspect / screenAspect,
screenAspect / imageAspect,
MIN_DOUBLE_TAP_SCALE,
MIN_SCREEN_ZOOM,
)
// But don't zoom in so close that the picture gets blurry.
const maxScale =
(imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM
const maxScale = Math.max(
MIN_SCREEN_ZOOM,
(imageDimensions.width / screenSize.width) * MAX_ORIGINAL_IMAGE_ZOOM,
)
const scale = Math.min(candidateScale, maxScale)
// Calculate where we would be if the user pinched into the double tapped point.
// We won't use this transform directly because it may go out of bounds.
const candidateTransform = createTransform()
const origin = {
x: e.absoluteX - SCREEN.width / 2,
y: e.absoluteY - SCREEN.height / 2,
x: e.absoluteX - screenSize.width / 2,
y: e.absoluteY - screenSize.height / 2,
}
prependPinch(candidateTransform, scale, origin, {x: 0, y: 0})
// Now we know how much we went out of bounds, so we can shoot correctly.
const [dx, dy] = getExtraTranslationToStayInBounds(candidateTransform)
const [dx, dy] = getExtraTranslationToStayInBounds(
candidateTransform,
screenSize,
)
const finalTransform = createTransform()
prependPinch(finalTransform, scale, origin, {x: dx, y: dy})
committedTransform.value = withClampedSpring(finalTransform)
})
const dismissSwipePan = Gesture.Pan()
.enabled(!isScaled)
.activeOffsetY([-10, 10])
.failOffsetX([-10, 10])
.maxPointers(1)
.onUpdate(e => {
'worklet'
dismissSwipeTranslateY.value = e.translationY
})
.onEnd(e => {
'worklet'
if (Math.abs(e.velocityY) > 1000) {
dismissSwipeTranslateY.value = withDecay({velocity: e.velocityY})
runOnJS(onRequestClose)()
} else {
dismissSwipeTranslateY.value = withSpring(0, {
stiffness: 700,
damping: 50,
})
}
})
const composedGesture = isScrollViewBeingDragged
? // If the parent is not at rest, provide a no-op gesture.
Gesture.Manual()
@@ -320,38 +312,116 @@ const ImageItem = ({
singleTap,
)
const containerStyle = useAnimatedStyle(() => {
const {scaleAndMoveTransform, isHidden} = transforms.value
// Apply the active adjustments on top of the committed transform before the gestures.
// This is matrix multiplication, so operations are applied in the reverse order.
let t = createTransform()
prependPan(t, panTranslation.value)
prependPinch(t, pinchScale.value, pinchOrigin.value, pinchTranslation.value)
prependTransform(t, committedTransform.value)
const [translateX, translateY, scale] = readTransform(t)
const manipulationTransform = [
{translateX},
{translateY: translateY},
{scale},
]
const screenSize = measureSafeArea()
return {
opacity: isHidden ? 0 : 1,
transform: scaleAndMoveTransform.concat(manipulationTransform),
width: screenSize.width,
maxHeight: screenSize.height,
alignSelf: 'center',
aspectRatio: imageAspect ?? 1 /* force onLoad */,
}
})
const imageCropStyle = useAnimatedStyle(() => {
const {cropFrameTransform} = transforms.value
return {
flex: 1,
overflow: 'hidden',
transform: cropFrameTransform,
}
})
const imageStyle = useAnimatedStyle(() => {
const {cropContentTransform} = transforms.value
return {
flex: 1,
transform: cropContentTransform,
opacity: imageAspect === undefined ? 0 : 1,
}
})
const [showLoader, setShowLoader] = useState(false)
const [hasLoaded, setHasLoaded] = useState(false)
useAnimatedReaction(
() => {
return transforms.value.isResting && !hasLoaded
},
(show, prevShow) => {
if (show && !prevShow) {
runOnJS(setShowLoader)(false)
} else if (!prevShow && show) {
runOnJS(setShowLoader)(true)
}
},
)
const type = imageSrc.type
const borderRadius =
type === 'circle-avi' ? 1e5 : type === 'rect-avi' ? 20 : 0
return (
<Animated.View
ref={containerRef}
// Necessary to make opacity work for both children together.
renderToHardwareTextureAndroid
style={[styles.container, animatedStyle]}>
<ActivityIndicator size="small" color="#FFF" style={styles.loading} />
<GestureDetector gesture={composedGesture}>
<Image
contentFit="contain"
source={{uri: imageSrc.uri}}
placeholderContentFit="contain"
placeholder={{uri: imageSrc.thumbUri}}
style={styles.image}
accessibilityLabel={imageSrc.alt}
accessibilityHint=""
accessibilityIgnoresInvertColors
cachePolicy="memory"
/>
</GestureDetector>
</Animated.View>
<GestureDetector gesture={composedGesture}>
<Animated.View
ref={containerRef}
style={[styles.container]}
renderToHardwareTextureAndroid>
<Animated.View style={containerStyle}>
{showLoader && (
<ActivityIndicator
size="small"
color="#FFF"
style={styles.loading}
/>
)}
<Animated.View style={imageCropStyle}>
<Animated.View style={imageStyle}>
<Image
contentFit="cover"
source={{uri: imageSrc.uri}}
placeholderContentFit="cover"
placeholder={{uri: imageSrc.thumbUri}}
accessibilityLabel={imageSrc.alt}
onLoad={
hasLoaded
? undefined
: e => {
setHasLoaded(true)
onLoad({width: e.source.width, height: e.source.height})
}
}
style={{flex: 1, borderRadius}}
accessibilityHint=""
accessibilityIgnoresInvertColors
cachePolicy="memory"
/>
</Animated.View>
</Animated.View>
</Animated.View>
</Animated.View>
</GestureDetector>
)
}
const styles = StyleSheet.create({
container: {
width: SCREEN.width,
height: SCREEN.height,
height: '100%',
overflow: 'hidden',
},
image: {
flex: 1,
justifyContent: 'center',
},
loading: {
position: 'absolute',
@@ -359,26 +429,27 @@ const styles = StyleSheet.create({
right: 0,
top: 0,
bottom: 0,
justifyContent: 'center',
},
})
function getScaledDimensions(
imageDimensions: ImageDimensions,
imageAspect: number,
scale: number,
screenSize: {width: number; height: number},
): ImageDimensions {
'worklet'
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = SCREEN.width / SCREEN.height
const screenAspect = screenSize.width / screenSize.height
const isLandscape = imageAspect > screenAspect
if (isLandscape) {
return {
width: scale * SCREEN.width,
height: (scale * SCREEN.width) / imageAspect,
width: scale * screenSize.width,
height: (scale * screenSize.width) / imageAspect,
}
} else {
return {
width: scale * SCREEN.height * imageAspect,
height: scale * SCREEN.height,
width: scale * screenSize.height * imageAspect,
height: scale * screenSize.height,
}
}
}
@@ -7,79 +7,90 @@
*/
import React, {useState} from 'react'
import {ActivityIndicator, Dimensions, StyleSheet} from 'react-native'
import {Gesture, GestureDetector} from 'react-native-gesture-handler'
import {ActivityIndicator, StyleSheet} from 'react-native'
import {
Gesture,
GestureDetector,
PanGesture,
} from 'react-native-gesture-handler'
import Animated, {
interpolate,
runOnJS,
SharedValue,
useAnimatedReaction,
useAnimatedRef,
useAnimatedStyle,
useSharedValue,
} from 'react-native-reanimated'
import {useSafeAreaFrame} from 'react-native-safe-area-context'
import {Image} from 'expo-image'
import {useAnimatedScrollHandler} from '#/lib/hooks/useAnimatedScrollHandler_FIXED'
import {Dimensions as ImageDimensions, ImageSource} from '../../@types'
import useImageDimensions from '../../hooks/useImageDimensions'
import {
Dimensions as ImageDimensions,
ImageSource,
Transform,
} from '../../@types'
const SWIPE_CLOSE_OFFSET = 75
const SWIPE_CLOSE_VELOCITY = 1
const SCREEN = Dimensions.get('screen')
const MAX_ORIGINAL_IMAGE_ZOOM = 2
const MIN_DOUBLE_TAP_SCALE = 2
const MIN_SCREEN_ZOOM = 2
type Props = {
imageSrc: ImageSource
onRequestClose: () => void
onTap: () => void
onZoom: (scaled: boolean) => void
onLoad: (dims: ImageDimensions) => void
isScrollViewBeingDragged: boolean
showControls: boolean
measureSafeArea: () => {
x: number
y: number
width: number
height: number
}
imageAspect: number | undefined
imageDimensions: ImageDimensions | undefined
dismissSwipePan: PanGesture
transforms: Readonly<
SharedValue<{
scaleAndMoveTransform: Transform
cropFrameTransform: Transform
cropContentTransform: Transform
isResting: boolean
isHidden: boolean
}>
>
}
const ImageItem = ({
imageSrc,
onTap,
onZoom,
onRequestClose,
onLoad,
showControls,
measureSafeArea,
imageAspect,
imageDimensions,
dismissSwipePan,
transforms,
}: Props) => {
const scrollViewRef = useAnimatedRef<Animated.ScrollView>()
const translationY = useSharedValue(0)
const [scaled, setScaled] = useState(false)
const imageDimensions = useImageDimensions(imageSrc)
const maxZoomScale = imageDimensions
? (imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM
: 1
const animatedStyle = useAnimatedStyle(() => {
return {
opacity: interpolate(
translationY.value,
[-SWIPE_CLOSE_OFFSET, 0, SWIPE_CLOSE_OFFSET],
[0.5, 1, 0.5],
),
}
})
const screenSizeDelayedForJSThreadOnly = useSafeAreaFrame()
const maxZoomScale = Math.max(
MIN_SCREEN_ZOOM,
imageDimensions
? (imageDimensions.width / screenSizeDelayedForJSThreadOnly.width) *
MAX_ORIGINAL_IMAGE_ZOOM
: 1,
)
const scrollHandler = useAnimatedScrollHandler({
onScroll(e) {
const nextIsScaled = e.zoomScale > 1
translationY.value = nextIsScaled ? 0 : e.contentOffset.y
if (scaled !== nextIsScaled) {
runOnJS(handleZoom)(nextIsScaled)
}
},
onEndDrag(e) {
const velocityY = e.velocity?.y ?? 0
const nextIsScaled = e.zoomScale > 1
if (scaled !== nextIsScaled) {
runOnJS(handleZoom)(nextIsScaled)
}
if (!nextIsScaled && Math.abs(velocityY) > SWIPE_CLOSE_VELOCITY) {
runOnJS(onRequestClose)()
}
},
})
function handleZoom(nextIsScaled: boolean) {
@@ -87,24 +98,13 @@ const ImageItem = ({
setScaled(nextIsScaled)
}
function handleDoubleTap(absoluteX: number, absoluteY: number) {
function zoomTo(nextZoomRect: {
x: number
y: number
width: number
height: number
}) {
const scrollResponderRef = scrollViewRef?.current?.getScrollResponder()
let nextZoomRect = {
x: 0,
y: 0,
width: SCREEN.width,
height: SCREEN.height,
}
const willZoom = !scaled
if (willZoom) {
nextZoomRect = getZoomRectAfterDoubleTap(
imageDimensions,
absoluteX,
absoluteY,
)
}
// @ts-ignore
scrollResponderRef?.scrollResponderZoomTo({
...nextZoomRect, // This rect is in screen coordinates
@@ -121,36 +121,123 @@ const ImageItem = ({
.numberOfTaps(2)
.onEnd(e => {
'worklet'
const screenSize = measureSafeArea()
const {absoluteX, absoluteY} = e
runOnJS(handleDoubleTap)(absoluteX, absoluteY)
let nextZoomRect = {
x: 0,
y: 0,
width: screenSize.width,
height: screenSize.height,
}
const willZoom = !scaled
if (willZoom) {
nextZoomRect = getZoomRectAfterDoubleTap(
imageAspect,
absoluteX,
absoluteY,
screenSize,
)
}
runOnJS(zoomTo)(nextZoomRect)
})
const composedGesture = Gesture.Exclusive(doubleTap, singleTap)
const composedGesture = Gesture.Exclusive(
dismissSwipePan,
doubleTap,
singleTap,
)
const containerStyle = useAnimatedStyle(() => {
const {scaleAndMoveTransform, isHidden} = transforms.value
return {
flex: 1,
transform: scaleAndMoveTransform,
opacity: isHidden ? 0 : 1,
}
})
const imageCropStyle = useAnimatedStyle(() => {
const screenSize = measureSafeArea()
const {cropFrameTransform} = transforms.value
return {
overflow: 'hidden',
transform: cropFrameTransform,
width: screenSize.width,
maxHeight: screenSize.height,
alignSelf: 'center',
aspectRatio: imageAspect ?? 1 /* force onLoad */,
opacity: imageAspect === undefined ? 0 : 1,
}
})
const imageStyle = useAnimatedStyle(() => {
const {cropContentTransform} = transforms.value
return {
transform: cropContentTransform,
width: '100%',
aspectRatio: imageAspect ?? 1 /* force onLoad */,
opacity: imageAspect === undefined ? 0 : 1,
}
})
const [showLoader, setShowLoader] = useState(false)
const [hasLoaded, setHasLoaded] = useState(false)
useAnimatedReaction(
() => {
return transforms.value.isResting && !hasLoaded
},
(show, prevShow) => {
if (show && !prevShow) {
runOnJS(setShowLoader)(false)
} else if (!prevShow && show) {
runOnJS(setShowLoader)(true)
}
},
)
const type = imageSrc.type
const borderRadius =
type === 'circle-avi' ? 1e5 : type === 'rect-avi' ? 20 : 0
return (
<GestureDetector gesture={composedGesture}>
<Animated.ScrollView
// @ts-ignore Something's up with the types here
ref={scrollViewRef}
style={styles.listItem}
pinchGestureEnabled
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
maximumZoomScale={maxZoomScale}
onScroll={scrollHandler}>
<Animated.View style={[styles.imageScrollContainer, animatedStyle]}>
onScroll={scrollHandler}
style={containerStyle}
bounces={scaled}
bouncesZoom={true}
centerContent>
{showLoader && (
<ActivityIndicator size="small" color="#FFF" style={styles.loading} />
<Image
contentFit="contain"
source={{uri: imageSrc.uri}}
placeholderContentFit="contain"
placeholder={{uri: imageSrc.thumbUri}}
style={styles.image}
accessibilityLabel={imageSrc.alt}
accessibilityHint=""
enableLiveTextInteraction={showControls && !scaled}
accessibilityIgnoresInvertColors
/>
)}
<Animated.View style={imageCropStyle}>
<Animated.View style={imageStyle}>
<Image
contentFit="contain"
source={{uri: imageSrc.uri}}
placeholderContentFit="contain"
placeholder={{uri: imageSrc.thumbUri}}
style={{flex: 1, borderRadius}}
accessibilityLabel={imageSrc.alt}
accessibilityHint=""
enableLiveTextInteraction={showControls && !scaled}
accessibilityIgnoresInvertColors
onLoad={
hasLoaded
? undefined
: e => {
setHasLoaded(true)
onLoad({width: e.source.width, height: e.source.height})
}
}
/>
</Animated.View>
</Animated.View>
</Animated.ScrollView>
</GestureDetector>
@@ -158,17 +245,6 @@ const ImageItem = ({
}
const styles = StyleSheet.create({
imageScrollContainer: {
height: SCREEN.height,
},
listItem: {
width: SCREEN.width,
height: SCREEN.height,
},
image: {
width: SCREEN.width,
height: SCREEN.height,
},
loading: {
position: 'absolute',
top: 0,
@@ -176,60 +252,64 @@ const styles = StyleSheet.create({
right: 0,
bottom: 0,
},
image: {
flex: 1,
},
})
const getZoomRectAfterDoubleTap = (
imageDimensions: ImageDimensions | null,
imageAspect: number | undefined,
touchX: number,
touchY: number,
screenSize: {width: number; height: number},
): {
x: number
y: number
width: number
height: number
} => {
if (!imageDimensions) {
'worklet'
if (!imageAspect) {
return {
x: 0,
y: 0,
width: SCREEN.width,
height: SCREEN.height,
width: screenSize.width,
height: screenSize.height,
}
}
// First, let's figure out how much we want to zoom in.
// We want to try to zoom in at least close enough to get rid of black bars.
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = SCREEN.width / SCREEN.height
const screenAspect = screenSize.width / screenSize.height
const zoom = Math.max(
imageAspect / screenAspect,
screenAspect / imageAspect,
MIN_DOUBLE_TAP_SCALE,
MIN_SCREEN_ZOOM,
)
// Unlike in the Android version, we don't constrain the *max* zoom level here.
// Instead, this is done in the ScrollView props so that it constraints pinch too.
// Next, we'll be calculating the rectangle to "zoom into" in screen coordinates.
// We already know the zoom level, so this gives us the rectangle size.
let rectWidth = SCREEN.width / zoom
let rectHeight = SCREEN.height / zoom
let rectWidth = screenSize.width / zoom
let rectHeight = screenSize.height / zoom
// Before we settle on the zoomed rect, figure out the safe area it has to be inside.
// We don't want to introduce new black bars or make existing black bars unbalanced.
let minX = 0
let minY = 0
let maxX = SCREEN.width - rectWidth
let maxY = SCREEN.height - rectHeight
let maxX = screenSize.width - rectWidth
let maxY = screenSize.height - rectHeight
if (imageAspect >= screenAspect) {
// The image has horizontal black bars. Exclude them from the safe area.
const renderedHeight = SCREEN.width / imageAspect
const horizontalBarHeight = (SCREEN.height - renderedHeight) / 2
const renderedHeight = screenSize.width / imageAspect
const horizontalBarHeight = (screenSize.height - renderedHeight) / 2
minY += horizontalBarHeight
maxY -= horizontalBarHeight
} else {
// The image has vertical black bars. Exclude them from the safe area.
const renderedWidth = SCREEN.height * imageAspect
const verticalBarWidth = (SCREEN.width - renderedWidth) / 2
const renderedWidth = screenSize.height * imageAspect
const verticalBarWidth = (screenSize.width - renderedWidth) / 2
minX += verticalBarWidth
maxX -= verticalBarWidth
}
@@ -244,7 +324,7 @@ const getZoomRectAfterDoubleTap = (
rectX = Math.max(rectX, minX)
} else {
// Keep the rect centered on the screen so that black bars are balanced.
rectX = SCREEN.width / 2 - rectWidth / 2
rectX = screenSize.width / 2 - rectWidth / 2
}
let rectY
if (maxY >= minY) {
@@ -255,7 +335,7 @@ const getZoomRectAfterDoubleTap = (
rectY = Math.max(rectY, minY)
} else {
// Keep the rect centered on the screen so that black bars are balanced.
rectY = SCREEN.height / 2 - rectHeight / 2
rectY = screenSize.height / 2 - rectHeight / 2
}
return {
@@ -2,16 +2,42 @@
import React from 'react'
import {View} from 'react-native'
import {PanGesture} from 'react-native-gesture-handler'
import {SharedValue} from 'react-native-reanimated'
import {ImageSource} from '../../@types'
import {Dimensions} from '#/lib/media/types'
import {
Dimensions as ImageDimensions,
ImageSource,
Transform,
} from '../../@types'
type Props = {
imageSrc: ImageSource
onRequestClose: () => void
onTap: () => void
onZoom: (scaled: boolean) => void
onLoad: (dims: Dimensions) => void
isScrollViewBeingDragged: boolean
showControls: boolean
measureSafeArea: () => {
x: number
y: number
width: number
height: number
}
imageAspect: number | undefined
imageDimensions: ImageDimensions | undefined
dismissSwipePan: PanGesture
transforms: Readonly<
SharedValue<{
scaleAndMoveTransform: Transform
cropFrameTransform: Transform
cropContentTransform: Transform
isResting: boolean
isHidden: boolean
}>
>
}
const ImageItem = (_props: Props) => {

Some files were not shown because too many files have changed in this diff Show More