Compare commits
159 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d76716f3ef | |||
| 80ada4d20a | |||
| 00e1e56a7d | |||
| 818c6ae879 | |||
| 07fe058577 | |||
| a924df4dcd | |||
| 47771b9066 | |||
| 6335be14e1 | |||
| 748212e000 | |||
| 20a46c8cff | |||
| de38595a7a | |||
| 7d158f82fb | |||
| 8e541d753a | |||
| 7229cda5a5 | |||
| df55c5fdeb | |||
| 2571432875 | |||
| 3107bb07c9 | |||
| 78e459d06f | |||
| e6bda92b20 | |||
| 7f3324d4a4 | |||
| 570b78c32e | |||
| 41fd6eb95b | |||
| 2ad0d059ac | |||
| 511d5d999b | |||
| 712cd3fde5 | |||
| accb25ccf2 | |||
| 826b841e10 | |||
| 3c8036587e | |||
| a915a57b10 | |||
| fab9f839d0 | |||
| e7f973852f | |||
| 5f553c29df | |||
| ed5a97d0fa | |||
| 37d94ca0e3 | |||
| 48f5cebc80 | |||
| bdb2bfdd83 | |||
| 74e0b73db5 | |||
| d07ea64434 | |||
| 160055e4f9 | |||
| 81c525f2b2 | |||
| f1b69a332a | |||
| 4f171be9bf | |||
| 6e2eaa746d | |||
| 8e2cfa52de | |||
| f1cfea5786 | |||
| 094a58490f | |||
| 17c58d40ff | |||
| 37cafb080b | |||
| a46059ca46 | |||
| 971c402788 | |||
| a687d3f028 | |||
| 9562a80908 | |||
| e47c3dbe0e | |||
| a01497fed4 | |||
| 0ab19b45a2 | |||
| 07afcab6b2 | |||
| 2698a6b50b | |||
| bb22ebd588 | |||
| 9dec9d7276 | |||
| 9a13fe50cc | |||
| f80bd30ef4 | |||
| edc9ac272c | |||
| b05cf9f3c1 | |||
| f8c46c08ca | |||
| 826cbbd4bf | |||
| 9fa90bb8d9 | |||
| 23ad3ad98b | |||
| 5839d2a30c | |||
| 85b2b390df | |||
| 1755c2e538 | |||
| dcbceb5d9f | |||
| 21af10bc3d | |||
| 9375532698 | |||
| abe61b7517 | |||
| 28f8999252 | |||
| 76a3c66f54 | |||
| 47b0d36b73 | |||
| 46b63accb8 | |||
| 143fc80951 | |||
| ee82e78d5c | |||
| cb193a827d | |||
| b7599e5bea | |||
| b164f151cc | |||
| ee5d7a63ce | |||
| c06611fb71 | |||
| 5c78b2266f | |||
| fcd22d4ccb | |||
| c3e97fee1d | |||
| a03f57c8c3 | |||
| 3e1b2346ee | |||
| b83fa95793 | |||
| 005fc7cc38 | |||
| c07d27645f | |||
| 1140b05b83 | |||
| 4c7b9652db | |||
| dc53ef1ec1 | |||
| 6e30c339da | |||
| 630637874d | |||
| 3fbac466ac | |||
| a59d235e8b | |||
| 3ca4bd805a | |||
| 34759798eb | |||
| 8ceabe2a11 | |||
| ed391c346d | |||
| 4b3ec54add | |||
| 9239efac9c | |||
| 620e002841 | |||
| 6fe2b52f68 | |||
| ca357ecbcf | |||
| 9fb2c29c67 | |||
| 6f7032d42b | |||
| b778017000 | |||
| bb9d340d42 | |||
| 0b2c85b967 | |||
| bdabfa9d38 | |||
| cf1b0b1881 | |||
| 60886b76c8 | |||
| 17a183514a | |||
| f580d4daf0 | |||
| d4714baf13 | |||
| a741a201b9 | |||
| 26bbe07068 | |||
| 5fd2d36273 | |||
| cd43adf698 | |||
| 1dc017367e | |||
| 6758755316 | |||
| 828e53d533 | |||
| 0079030244 | |||
| 08355e5166 | |||
| 4a59227459 | |||
| 3007c1dc8a | |||
| 486fb72798 | |||
| e9a11114d3 | |||
| 20b699a008 | |||
| 1bcbc0cf2a | |||
| f2d164ec23 | |||
| 4b59a21cac | |||
| 43c8fb6f03 | |||
| 7ccbd14d5f | |||
| 4272d291a9 | |||
| edf3114e47 | |||
| ec819f06ce | |||
| 95f8bd8ddb | |||
| 08333002cc | |||
| 3de1d556a9 | |||
| 8da10a5edc | |||
| 47d2d3cbf2 | |||
| 4c4ba553bd | |||
| f18b9b32b0 | |||
| 71b59021b9 | |||
| 3a21c02b8a | |||
| c5b6f88e9a | |||
| 019aae5f01 | |||
| 7c51a3931a | |||
| d1c14940fb | |||
| 0dfc039a47 | |||
| c858b58307 | |||
| 9c8a1b8a31 | |||
| bc64c86b12 |
@@ -1,3 +1,6 @@
|
||||
# Copy this to `.env` and `.env.test` files
|
||||
|
||||
SENTRY_AUTH_TOKEN=
|
||||
EXPO_PUBLIC_ENV=development
|
||||
EXPO_PUBLIC_LOG_LEVEL=debug
|
||||
EXPO_PUBLIC_LOG_DEBUG=
|
||||
|
||||
+3
-1
@@ -7,7 +7,7 @@ module.exports = {
|
||||
'prettier',
|
||||
],
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['@typescript-eslint', 'detox', 'react'],
|
||||
plugins: ['@typescript-eslint', 'detox', 'react', 'lingui'],
|
||||
rules: {
|
||||
'react/no-unescaped-entities': 0,
|
||||
'react-native/no-inline-styles': 0,
|
||||
@@ -25,6 +25,8 @@ module.exports = {
|
||||
'bskyweb',
|
||||
'*.html',
|
||||
'bskyweb',
|
||||
'src/locale/locales/_build/',
|
||||
'src/locale/locales/**/*.js',
|
||||
],
|
||||
settings: {
|
||||
componentWrapperFunctions: ['observer'],
|
||||
|
||||
@@ -17,9 +17,15 @@ jobs:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Yarn install
|
||||
run: yarn --frozen-lockfile
|
||||
uses: Wandalen/wretry.action@master
|
||||
with:
|
||||
command: yarn --frozen-lockfile
|
||||
attempt_limit: 3
|
||||
attempt_delay: 2000
|
||||
- name: Lint check
|
||||
run: yarn lint
|
||||
- name: Check & compile i18n
|
||||
run: yarn intl:build
|
||||
- name: Type check
|
||||
run: yarn typecheck
|
||||
testing:
|
||||
@@ -27,13 +33,19 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install node 18
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Yarn install
|
||||
run: yarn --frozen-lockfile
|
||||
uses: Wandalen/wretry.action@master
|
||||
with:
|
||||
command: yarn --frozen-lockfile
|
||||
attempt_limit: 3
|
||||
attempt_delay: 2000
|
||||
- name: Check & compile i18n
|
||||
run: yarn intl:build
|
||||
- name: Run tests
|
||||
run: |
|
||||
yarn test --forceExit
|
||||
NODE_ENV=test EXPO_PUBLIC_ENV=test yarn test --forceExit
|
||||
|
||||
+5
-1
@@ -102,4 +102,8 @@ ios/
|
||||
google-services.json
|
||||
|
||||
# Performance results (Flashlight)
|
||||
.perf/
|
||||
.perf/
|
||||
|
||||
# i18n
|
||||
src/locale/locales/_build/
|
||||
src/locale/locales/**/*.js
|
||||
|
||||
@@ -31,6 +31,7 @@ RUN \. "$NVM_DIR/nvm.sh" && \
|
||||
nvm use $NODE_VERSION && \
|
||||
npm install --global yarn && \
|
||||
yarn && \
|
||||
yarn intl:compile && \
|
||||
yarn build-web
|
||||
|
||||
# DEBUG
|
||||
|
||||
@@ -14,7 +14,7 @@ build-web: ## Compile web bundle, copy to bskyweb directory
|
||||
|
||||
.PHONY: test
|
||||
test: ## Run all tests
|
||||
yarn test
|
||||
NODE_ENV=test EXPO_PUBLIC_ENV=test yarn test
|
||||
|
||||
.PHONY: lint
|
||||
lint: ## Run style checks and verify syntax
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer, sleep} from '../util'
|
||||
|
||||
describe('Composer', () => {
|
||||
@@ -45,6 +47,8 @@ describe('Composer', () => {
|
||||
})
|
||||
|
||||
it('Reply text only', async () => {
|
||||
await element(by.id('e2eRefreshHome')).tap()
|
||||
|
||||
const post = by.id('feedItem-by-alice.test')
|
||||
await element(by.id('replyBtn').withAncestor(post)).atIndex(0).tap()
|
||||
await element(by.id('composerTextInput')).typeText('Reply text only')
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, createServer} from '../util'
|
||||
|
||||
describe('Create account', () => {
|
||||
@@ -10,6 +12,8 @@ describe('Create account', () => {
|
||||
})
|
||||
|
||||
it('I can create a new account', async () => {
|
||||
await element(by.id('e2eOpenLoggedOutView')).tap()
|
||||
|
||||
await element(by.id('createAccountButton')).tap()
|
||||
await device.takeScreenshot('1- opened create account screen')
|
||||
await element(by.id('otherServerBtn')).tap()
|
||||
@@ -17,14 +21,20 @@ describe('Create account', () => {
|
||||
await element(by.id('customServerInput')).clearText()
|
||||
await element(by.id('customServerInput')).typeText(service)
|
||||
await device.takeScreenshot('3- input test server URL')
|
||||
|
||||
await element(by.id('nextBtn')).tap()
|
||||
|
||||
await element(by.id('emailInput')).typeText('example@test.com')
|
||||
await element(by.id('passwordInput')).typeText('hunter2')
|
||||
await device.takeScreenshot('4- entered account details')
|
||||
|
||||
await element(by.id('nextBtn')).tap()
|
||||
|
||||
await element(by.id('handleInput')).typeText('e2e-test')
|
||||
await device.takeScreenshot('4- entered handle')
|
||||
|
||||
await element(by.id('nextBtn')).tap()
|
||||
|
||||
await expect(element(by.id('welcomeOnboarding'))).toBeVisible()
|
||||
await element(by.id('continueBtn')).tap()
|
||||
await expect(element(by.id('recommendedFeedsOnboarding'))).toBeVisible()
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, loginAsBob, createServer, sleep} from '../util'
|
||||
|
||||
describe('Curate lists', () => {
|
||||
@@ -11,7 +13,6 @@ describe('Curate lists', () => {
|
||||
})
|
||||
|
||||
it('Login and create a curatelists', async () => {
|
||||
await expect(element(by.id('signInButton'))).toBeVisible()
|
||||
await loginAsAlice()
|
||||
await element(by.id('e2eGotoLists')).tap()
|
||||
await element(by.id('newUserListBtn')).tap()
|
||||
@@ -27,7 +28,7 @@ describe('Curate lists', () => {
|
||||
|
||||
it('Edit display name and description via the edit curatelist modal', async () => {
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('editNameInput')).clearText()
|
||||
await element(by.id('editNameInput')).typeText('Bad Ppl')
|
||||
@@ -45,7 +46,7 @@ describe('Curate lists', () => {
|
||||
|
||||
it('Remove description via the edit curatelist modal', async () => {
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('editDescriptionInput')).clearText()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
@@ -60,7 +61,7 @@ describe('Curate lists', () => {
|
||||
it('Set avi via the edit curatelist modal', async () => {
|
||||
await expect(element(by.id('userAvatarFallback'))).toExist()
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('changeAvatarBtn')).tap()
|
||||
await element(by.text('Library')).tap()
|
||||
@@ -77,7 +78,7 @@ describe('Curate lists', () => {
|
||||
it('Remove avi via the edit curatelist modal', async () => {
|
||||
await expect(element(by.id('userAvatarImage'))).toExist()
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('changeAvatarBtn')).tap()
|
||||
await element(by.text('Remove')).tap()
|
||||
@@ -98,6 +99,7 @@ describe('Curate lists', () => {
|
||||
})
|
||||
|
||||
it('Create a new curatelist', async () => {
|
||||
await element(by.id('e2eGotoLists')).tap()
|
||||
await element(by.id('newUserListBtn')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('editNameInput')).typeText('Good Ppl')
|
||||
@@ -128,6 +130,7 @@ describe('Curate lists', () => {
|
||||
})
|
||||
|
||||
it('Pins the list', async () => {
|
||||
await expect(element(by.id('pinBtn'))).toBeVisible()
|
||||
await element(by.id('pinBtn')).tap()
|
||||
await element(by.id('e2eGotoHome')).tap()
|
||||
await element(by.id('homeScreenFeedTabs-Good Ppl')).tap()
|
||||
@@ -152,15 +155,15 @@ describe('Curate lists', () => {
|
||||
await expect(element(by.id('user-bob.test'))).toBeVisible()
|
||||
await element(by.id('user-bob.test-editBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).toBeVisible()
|
||||
await element(by.id('toggleBtn-Good Ppl')).tap()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
await element(by.id('user-bob.test-addBtn')).tap()
|
||||
await element(by.id('doneBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).not.toBeVisible()
|
||||
})
|
||||
|
||||
it('Shows the curatelist on my profile', async () => {
|
||||
await element(by.id('bottomBarProfileBtn')).tap()
|
||||
await element(by.id('selector')).swipe('left')
|
||||
await element(by.id('selector-4')).tap()
|
||||
await element(by.id('profilePager-selector')).swipe('left')
|
||||
await element(by.id('profilePager-selector-5')).tap()
|
||||
await element(by.id('list-Good Ppl')).tap()
|
||||
})
|
||||
|
||||
@@ -173,15 +176,15 @@ describe('Curate lists', () => {
|
||||
await element(by.id('profileHeaderDropdownBtn')).tap()
|
||||
await element(by.text('Add to Lists')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).toBeVisible()
|
||||
await element(by.id('toggleBtn-Good Ppl')).tap()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
await element(by.id('user-bob.test-addBtn')).tap()
|
||||
await element(by.id('doneBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).not.toBeVisible()
|
||||
|
||||
await element(by.id('profileHeaderDropdownBtn')).tap()
|
||||
await element(by.text('Add to Lists')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).toBeVisible()
|
||||
await element(by.id('toggleBtn-Good Ppl')).tap()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
await element(by.id('user-bob.test-addBtn')).tap()
|
||||
await element(by.id('doneBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).not.toBeVisible()
|
||||
})
|
||||
|
||||
@@ -192,8 +195,8 @@ describe('Curate lists', () => {
|
||||
await element(by.id('bottomBarSearchBtn')).tap()
|
||||
await element(by.id('searchTextInput')).typeText('alice')
|
||||
await element(by.id('searchAutoCompleteResult-alice.test')).tap()
|
||||
await element(by.id('selector')).swipe('left')
|
||||
await element(by.id('selector-3')).tap()
|
||||
await element(by.id('profilePager-selector')).swipe('left')
|
||||
await element(by.id('profilePager-selector-3')).tap()
|
||||
await element(by.id('list-Good Ppl')).tap()
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Report List')).tap()
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer} from '../util'
|
||||
|
||||
describe('Home screen', () => {
|
||||
beforeAll(async () => {
|
||||
await createServer('?users&follows&posts')
|
||||
await createServer('?users&follows&posts&feeds')
|
||||
await openApp({permissions: {notifications: 'YES'}})
|
||||
})
|
||||
|
||||
@@ -13,6 +15,23 @@ describe('Home screen', () => {
|
||||
await element(by.id('homeScreenFeedTabs-Following')).tap()
|
||||
})
|
||||
|
||||
it('Can go to feeds page using feeds button in tab bar', async () => {
|
||||
await element(by.id('homeScreenFeedTabs-Feeds ✨')).tap()
|
||||
await expect(element(by.text('Discover new feeds'))).toBeVisible()
|
||||
})
|
||||
|
||||
it('Feeds button disappears after pinning a feed', async () => {
|
||||
await element(by.id('bottomBarProfileBtn')).tap()
|
||||
await element(by.id('profilePager-selector')).swipe('left')
|
||||
await element(by.id('profilePager-selector-4')).tap()
|
||||
await element(by.id('feed-alice-favs')).tap()
|
||||
await element(by.id('pinBtn')).tap()
|
||||
await element(by.id('bottomBarHomeBtn')).tap()
|
||||
await expect(
|
||||
element(by.id('homeScreenFeedTabs-Feeds ✨')),
|
||||
).not.toBeVisible()
|
||||
})
|
||||
|
||||
it('Can like posts', async () => {
|
||||
const carlaPosts = by.id('feedItem-by-carla.test')
|
||||
await expect(
|
||||
@@ -65,14 +84,14 @@ describe('Home screen', () => {
|
||||
|
||||
it('Can swipe between feeds', async () => {
|
||||
await element(by.id('homeScreen')).swipe('left', 'fast', 0.75)
|
||||
await expect(element(by.id('whatshotFeedPage'))).toBeVisible()
|
||||
await expect(element(by.id('customFeedPage'))).toBeVisible()
|
||||
await element(by.id('homeScreen')).swipe('right', 'fast', 0.75)
|
||||
await expect(element(by.id('followingFeedPage'))).toBeVisible()
|
||||
})
|
||||
|
||||
it('Can tap between feeds', async () => {
|
||||
await element(by.id("homeScreenFeedTabs-What's hot")).tap()
|
||||
await expect(element(by.id('whatshotFeedPage'))).toBeVisible()
|
||||
await element(by.id('homeScreenFeedTabs-alice-favs')).tap()
|
||||
await expect(element(by.id('customFeedPage'))).toBeVisible()
|
||||
await element(by.id('homeScreenFeedTabs-Following')).tap()
|
||||
await expect(element(by.id('followingFeedPage'))).toBeVisible()
|
||||
})
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
* with the side drawer.
|
||||
*/
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer} from '../util'
|
||||
|
||||
describe('invite-codes', () => {
|
||||
@@ -16,7 +18,6 @@ describe('invite-codes', () => {
|
||||
})
|
||||
|
||||
it('I can fetch invite codes', async () => {
|
||||
await expect(element(by.id('signInButton'))).toBeVisible()
|
||||
await loginAsAlice()
|
||||
await element(by.id('e2eOpenInviteCodesModal')).tap()
|
||||
await expect(element(by.id('inviteCodesModal'))).toBeVisible()
|
||||
@@ -27,6 +28,7 @@ describe('invite-codes', () => {
|
||||
})
|
||||
|
||||
it('I can create a new account with the invite code', async () => {
|
||||
await element(by.id('e2eOpenLoggedOutView')).tap()
|
||||
await element(by.id('createAccountButton')).tap()
|
||||
await device.takeScreenshot('1- opened create account screen')
|
||||
await element(by.id('otherServerBtn')).tap()
|
||||
@@ -51,19 +53,4 @@ describe('invite-codes', () => {
|
||||
await element(by.id('continueBtn')).tap()
|
||||
await expect(element(by.id('homeScreen'))).toBeVisible()
|
||||
})
|
||||
|
||||
it('I get a notification for the new user', async () => {
|
||||
await element(by.id('e2eSignOut')).tap()
|
||||
await loginAsAlice()
|
||||
await waitFor(element(by.id('homeScreen')))
|
||||
.toBeVisible()
|
||||
.withTimeout(5000)
|
||||
await element(by.id('bottomBarNotificationsBtn')).tap()
|
||||
await expect(element(by.id('invitedUser'))).toBeVisible()
|
||||
})
|
||||
|
||||
it('I can dismiss the new user notification', async () => {
|
||||
await element(by.id('dismissBtn')).tap()
|
||||
await expect(element(by.id('invitedUser'))).not.toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, login, createServer} from '../util'
|
||||
|
||||
describe('Login', () => {
|
||||
@@ -10,6 +12,8 @@ describe('Login', () => {
|
||||
})
|
||||
|
||||
it('As Alice, I can login', async () => {
|
||||
await element(by.id('e2eOpenLoggedOutView')).tap()
|
||||
|
||||
await expect(element(by.id('signInButton'))).toBeVisible()
|
||||
await login(service, 'alice', 'hunter2', {
|
||||
takeScreenshots: true,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer} from '../util'
|
||||
|
||||
describe('Mergefeed', () => {
|
||||
@@ -9,8 +11,12 @@ describe('Mergefeed', () => {
|
||||
})
|
||||
|
||||
it('Login', async () => {
|
||||
await element(by.id('e2eOpenLoggedOutView')).tap()
|
||||
await loginAsAlice()
|
||||
await element(by.id('e2eToggleMergefeed')).tap()
|
||||
await element(by.id('bottomBarFeedsBtn')).tap()
|
||||
await element(by.id('feed-alice-favs-toggleSave')).tap()
|
||||
await element(by.id('e2eGotoHome')).tap()
|
||||
})
|
||||
|
||||
it('Sees the expected mix of posts with default filters', async () => {
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, loginAsBob, createServer, sleep} from '../util'
|
||||
|
||||
describe('Mod lists', () => {
|
||||
@@ -11,7 +13,6 @@ describe('Mod lists', () => {
|
||||
})
|
||||
|
||||
it('Login and view my modlists', async () => {
|
||||
await expect(element(by.id('signInButton'))).toBeVisible()
|
||||
await loginAsAlice()
|
||||
await element(by.id('e2eGotoModeration')).tap()
|
||||
await element(by.id('moderationlistsBtn')).tap()
|
||||
@@ -31,7 +32,7 @@ describe('Mod lists', () => {
|
||||
|
||||
it('Edit display name and description via the edit modlist modal', async () => {
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('editNameInput')).clearText()
|
||||
await element(by.id('editNameInput')).typeText('Bad Ppl')
|
||||
@@ -49,7 +50,7 @@ describe('Mod lists', () => {
|
||||
|
||||
it('Remove description via the edit modlist modal', async () => {
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('editDescriptionInput')).clearText()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
@@ -64,7 +65,7 @@ describe('Mod lists', () => {
|
||||
it('Set avi via the edit modlist modal', async () => {
|
||||
await expect(element(by.id('userAvatarFallback'))).toExist()
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('changeAvatarBtn')).tap()
|
||||
await element(by.text('Library')).tap()
|
||||
@@ -81,7 +82,7 @@ describe('Mod lists', () => {
|
||||
it('Remove avi via the edit modlist modal', async () => {
|
||||
await expect(element(by.id('userAvatarImage'))).toExist()
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Edit List Details')).tap()
|
||||
await element(by.text('Edit list details')).tap()
|
||||
await expect(element(by.id('createOrEditListModal'))).toBeVisible()
|
||||
await element(by.id('changeAvatarBtn')).tap()
|
||||
await element(by.text('Remove')).tap()
|
||||
@@ -131,15 +132,15 @@ describe('Mod lists', () => {
|
||||
await expect(element(by.id('user-warn-posts.test'))).toBeVisible()
|
||||
await element(by.id('user-warn-posts.test-editBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).toBeVisible()
|
||||
await element(by.id('toggleBtn-Bad Ppl')).tap()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
await element(by.id('user-warn-posts.test-addBtn')).tap()
|
||||
await element(by.id('doneBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).not.toBeVisible()
|
||||
})
|
||||
|
||||
it('Shows the modlist on my profile', async () => {
|
||||
await element(by.id('bottomBarProfileBtn')).tap()
|
||||
await element(by.id('selector')).swipe('left')
|
||||
await element(by.id('selector-4')).tap()
|
||||
await element(by.id('profilePager-selector')).swipe('left')
|
||||
await element(by.id('profilePager-selector-5')).tap()
|
||||
await element(by.id('list-Bad Ppl')).tap()
|
||||
})
|
||||
|
||||
@@ -152,15 +153,15 @@ describe('Mod lists', () => {
|
||||
await element(by.id('profileHeaderDropdownBtn')).tap()
|
||||
await element(by.text('Add to Lists')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).toBeVisible()
|
||||
await element(by.id('toggleBtn-Bad Ppl')).tap()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
await element(by.id('user-bob.test-addBtn')).tap()
|
||||
await element(by.id('doneBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).not.toBeVisible()
|
||||
|
||||
await element(by.id('profileHeaderDropdownBtn')).tap()
|
||||
await element(by.text('Add to Lists')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).toBeVisible()
|
||||
await element(by.id('toggleBtn-Bad Ppl')).tap()
|
||||
await element(by.id('saveBtn')).tap()
|
||||
await element(by.id('user-bob.test-addBtn')).tap()
|
||||
await element(by.id('doneBtn')).tap()
|
||||
await expect(element(by.id('userAddRemoveListsModal'))).not.toBeVisible()
|
||||
})
|
||||
|
||||
@@ -171,8 +172,8 @@ describe('Mod lists', () => {
|
||||
await element(by.id('bottomBarSearchBtn')).tap()
|
||||
await element(by.id('searchTextInput')).typeText('alice')
|
||||
await element(by.id('searchAutoCompleteResult-alice.test')).tap()
|
||||
await element(by.id('selector')).swipe('left')
|
||||
await element(by.id('selector-3')).tap()
|
||||
await element(by.id('profilePager-selector')).swipe('left')
|
||||
await element(by.id('profilePager-selector-3')).tap()
|
||||
await element(by.id('list-Bad Ppl')).tap()
|
||||
await element(by.id('headerDropdownBtn')).tap()
|
||||
await element(by.text('Report List')).tap()
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer, sleep} from '../util'
|
||||
|
||||
describe('Profile screen', () => {
|
||||
@@ -11,17 +13,16 @@ describe('Profile screen', () => {
|
||||
})
|
||||
|
||||
it('Login and navigate to my profile', async () => {
|
||||
await expect(element(by.id('signInButton'))).toBeVisible()
|
||||
await loginAsAlice()
|
||||
await element(by.id('bottomBarProfileBtn')).tap()
|
||||
})
|
||||
|
||||
it('Can see feeds', async () => {
|
||||
await element(by.id('selector')).swipe('left')
|
||||
await element(by.id('selector-4')).tap()
|
||||
await element(by.id('profilePager-selector')).swipe('left')
|
||||
await element(by.id('profilePager-selector-4')).tap()
|
||||
await expect(element(by.id('feed-alice-favs'))).toBeVisible()
|
||||
await element(by.id('selector')).swipe('right')
|
||||
await element(by.id('selector-0')).tap()
|
||||
await element(by.id('profilePager-selector')).swipe('right')
|
||||
await element(by.id('profilePager-selector-0')).tap()
|
||||
})
|
||||
|
||||
it('Open and close edit profile modal', async () => {
|
||||
@@ -135,6 +136,14 @@ describe('Profile screen', () => {
|
||||
})
|
||||
|
||||
it('Can like posts', async () => {
|
||||
await element(by.id('postsFeed-flatlist')).swipe(
|
||||
'down',
|
||||
'slow',
|
||||
1,
|
||||
0.5,
|
||||
0.5,
|
||||
)
|
||||
|
||||
const posts = by.id('feedItem-by-bob.test')
|
||||
await expect(
|
||||
element(by.id('likeCount').withAncestor(posts)).atIndex(0),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer} from '../util'
|
||||
|
||||
describe('Search screen', () => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer, sleep} from '../util'
|
||||
|
||||
describe('Self-labeling', () => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, loginAsBob, createServer} from '../util'
|
||||
|
||||
describe('Thread muting', () => {
|
||||
@@ -48,7 +50,7 @@ describe('Thread muting', () => {
|
||||
await loginAsBob()
|
||||
|
||||
await element(by.id('bottomBarProfileBtn')).tap()
|
||||
await element(by.id('selector-1')).tap()
|
||||
await element(by.id('profilePager-selector-1')).tap()
|
||||
const bobPosts = by.id('feedItem-by-bob.test')
|
||||
await element(by.id('replyBtn').withAncestor(bobPosts)).atIndex(0).tap()
|
||||
await element(by.id('composerTextInput')).typeText('Reply 2')
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* eslint-env detox/detox */
|
||||
|
||||
import {describe, beforeAll, it} from '@jest/globals'
|
||||
import {expect} from 'detox'
|
||||
import {openApp, loginAsAlice, createServer} from '../util'
|
||||
|
||||
describe('Thread screen', () => {
|
||||
@@ -31,15 +33,15 @@ describe('Thread screen', () => {
|
||||
it('Can like the root post', async () => {
|
||||
const post = by.id('postThreadItem-by-bob.test')
|
||||
await expect(
|
||||
element(by.id('likeCount').withAncestor(post)).atIndex(0),
|
||||
element(by.id('likeCount-expanded').withAncestor(post)).atIndex(0),
|
||||
).not.toExist()
|
||||
await element(by.id('likeBtn').withAncestor(post)).atIndex(0).tap()
|
||||
await expect(
|
||||
element(by.id('likeCount').withAncestor(post)).atIndex(0),
|
||||
element(by.id('likeCount-expanded').withAncestor(post)).atIndex(0),
|
||||
).toHaveText('1 like')
|
||||
await element(by.id('likeBtn').withAncestor(post)).atIndex(0).tap()
|
||||
await expect(
|
||||
element(by.id('likeCount').withAncestor(post)).atIndex(0),
|
||||
element(by.id('likeCount-expanded').withAncestor(post)).atIndex(0),
|
||||
).not.toExist()
|
||||
})
|
||||
|
||||
@@ -61,21 +63,21 @@ describe('Thread screen', () => {
|
||||
it('Can repost the root post', async () => {
|
||||
const post = by.id('postThreadItem-by-bob.test')
|
||||
await expect(
|
||||
element(by.id('repostCount').withAncestor(post)).atIndex(0),
|
||||
element(by.id('repostCount-expanded').withAncestor(post)).atIndex(0),
|
||||
).not.toExist()
|
||||
await element(by.id('repostBtn').withAncestor(post)).atIndex(0).tap()
|
||||
await expect(element(by.id('repostModal'))).toBeVisible()
|
||||
await element(by.id('repostBtn').withAncestor(by.id('repostModal'))).tap()
|
||||
await expect(element(by.id('repostModal'))).not.toBeVisible()
|
||||
await expect(
|
||||
element(by.id('repostCount').withAncestor(post)).atIndex(0),
|
||||
element(by.id('repostCount-expanded').withAncestor(post)).atIndex(0),
|
||||
).toHaveText('1 repost')
|
||||
await element(by.id('repostBtn').withAncestor(post)).atIndex(0).tap()
|
||||
await expect(element(by.id('repostModal'))).toBeVisible()
|
||||
await element(by.id('repostBtn').withAncestor(by.id('repostModal'))).tap()
|
||||
await expect(element(by.id('repostModal'))).not.toBeVisible()
|
||||
await expect(
|
||||
element(by.id('repostCount').withAncestor(post)).atIndex(0),
|
||||
element(by.id('repostCount-expanded').withAncestor(post)).atIndex(0),
|
||||
).not.toExist()
|
||||
})
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import {it, describe, expect} from '@jest/globals'
|
||||
|
||||
import {
|
||||
linkRequiresWarning,
|
||||
isPossiblyAUrl,
|
||||
@@ -6,6 +8,7 @@ import {
|
||||
|
||||
describe('linkRequiresWarning', () => {
|
||||
type Case = [string, string, boolean]
|
||||
|
||||
const cases: Case[] = [
|
||||
['http://example.com', 'http://example.com', false],
|
||||
['http://example.com', 'example.com', false],
|
||||
@@ -64,6 +67,10 @@ describe('linkRequiresWarning', () => {
|
||||
['http://bsky.app/', 'https://google.com', true],
|
||||
['https://bsky.app/', 'https://google.com', true],
|
||||
|
||||
// case insensitive
|
||||
['https://Example.com', 'example.com', false],
|
||||
['https://example.com', 'Example.com', false],
|
||||
|
||||
// bad uri inputs, default to true
|
||||
['', '', true],
|
||||
['example.com', 'example.com', true],
|
||||
|
||||
+39
-5
@@ -1,12 +1,41 @@
|
||||
const pkg = require('./package.json')
|
||||
|
||||
module.exports = function () {
|
||||
const hasSentryToken = !!process.env.SENTRY_AUTH_TOKEN
|
||||
/**
|
||||
* App version number. Should be incremented as part of a release cycle.
|
||||
*/
|
||||
const VERSION = pkg.version
|
||||
|
||||
/**
|
||||
* iOS build number. Must be incremented for each TestFlight version.
|
||||
*/
|
||||
const IOS_BUILD_NUMBER = '10'
|
||||
|
||||
/**
|
||||
* Android build number. Must be incremented for each release.
|
||||
*/
|
||||
const ANDROID_VERSION_CODE = 46
|
||||
|
||||
/**
|
||||
* Uses built-in Expo env vars
|
||||
*
|
||||
* @see https://docs.expo.dev/build-reference/variables/#built-in-environment-variables
|
||||
*/
|
||||
const PLATFORM = process.env.EAS_BUILD_PLATFORM
|
||||
|
||||
/**
|
||||
* Additional granularity for the `dist` field
|
||||
*/
|
||||
const DIST_BUILD_NUMBER =
|
||||
PLATFORM === 'android' ? ANDROID_VERSION_CODE : IOS_BUILD_NUMBER
|
||||
|
||||
return {
|
||||
expo: {
|
||||
version: VERSION,
|
||||
name: 'Bluesky',
|
||||
slug: 'bluesky',
|
||||
scheme: 'bluesky',
|
||||
owner: 'blueskysocial',
|
||||
version: '1.56.0',
|
||||
runtimeVersion: {
|
||||
policy: 'appVersion',
|
||||
},
|
||||
@@ -19,7 +48,7 @@ module.exports = function () {
|
||||
backgroundColor: '#ffffff',
|
||||
},
|
||||
ios: {
|
||||
buildNumber: '3',
|
||||
buildNumber: IOS_BUILD_NUMBER,
|
||||
supportsTablet: false,
|
||||
bundleIdentifier: 'xyz.blueskyweb.app',
|
||||
config: {
|
||||
@@ -43,7 +72,7 @@ module.exports = function () {
|
||||
backgroundColor: '#ffffff',
|
||||
},
|
||||
android: {
|
||||
versionCode: 46,
|
||||
versionCode: ANDROID_VERSION_CODE,
|
||||
adaptiveIcon: {
|
||||
foregroundImage: './assets/adaptive-icon.png',
|
||||
backgroundColor: '#ffffff',
|
||||
@@ -74,7 +103,7 @@ module.exports = function () {
|
||||
},
|
||||
plugins: [
|
||||
'expo-localization',
|
||||
hasSentryToken && 'sentry-expo',
|
||||
Boolean(process.env.SENTRY_AUTH_TOKEN) && 'sentry-expo',
|
||||
[
|
||||
'expo-build-properties',
|
||||
{
|
||||
@@ -100,11 +129,16 @@ module.exports = function () {
|
||||
},
|
||||
hooks: {
|
||||
postPublish: [
|
||||
/*
|
||||
* @see https://docs.expo.dev/guides/using-sentry/#app-configuration
|
||||
*/
|
||||
{
|
||||
file: 'sentry-expo/upload-sourcemaps',
|
||||
config: {
|
||||
organization: 'blueskyweb',
|
||||
project: 'react-native',
|
||||
release: VERSION,
|
||||
dist: `${PLATFORM}.${VERSION}.${DIST_BUILD_NUMBER}`,
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
+4
-1
@@ -1,5 +1,8 @@
|
||||
# Testing instructions
|
||||
|
||||
Make sure you've copied `.env.example` to `.env.test` and provided any required
|
||||
values.
|
||||
|
||||
### Using Maestro E2E tests
|
||||
1. Install Maestro by following [these instructions](https://maestro.mobile.dev/getting-started/installing-maestro). This will help us run the E2E tests.
|
||||
2. You can write Maestro tests in `__e2e__/maestro` directory by creating a new `.yaml` file or by modifying an existing one.
|
||||
@@ -11,4 +14,4 @@
|
||||
2. Install Flashlight by following [these instructions](https://docs.flashlight.dev/)
|
||||
3. The simplest way to get started is by running `yarn perf:measure` which will run a live preview of the performance test results. You can [see a demo here](https://github.com/bamlab/flashlight/assets/4534323/4038a342-f145-4c3b-8cde-17949bf52612)
|
||||
4. The `yarn perf:test:measure` will run the `scroll.yaml` test located in `__e2e__/maestro/scroll.yaml` and give the results in `.perf/results.json` which can be viewed by running `yarn:perf:results`
|
||||
5. You can also run your own tests by running `yarn perf:test <path_to_test>` where `<path_to_test>` is the path to your test file. For example, `yarn perf:test __e2e__/maestro/scroll.yaml` will run the `scroll.yaml` test located in `__e2e__/maestro/scroll.yaml`.
|
||||
5. You can also run your own tests by running `yarn perf:test <path_to_test>` where `<path_to_test>` is the path to your test file. For example, `yarn perf:test __e2e__/maestro/scroll.yaml` will run the `scroll.yaml` test located in `__e2e__/maestro/scroll.yaml`.
|
||||
|
||||
@@ -4,42 +4,33 @@
|
||||
"promptToConfigurePushNotifications": false
|
||||
},
|
||||
"build": {
|
||||
"base": {
|
||||
"node": "18.18.2"
|
||||
},
|
||||
"development": {
|
||||
"extends": "base",
|
||||
"developmentClient": true,
|
||||
"distribution": "internal",
|
||||
"channel": "development",
|
||||
"ios": {
|
||||
"simulator": true,
|
||||
"resourceClass": "m-large"
|
||||
},
|
||||
"channel": "development"
|
||||
},
|
||||
"development-device": {
|
||||
"developmentClient": true,
|
||||
"distribution": "internal",
|
||||
"ios": {
|
||||
"resourceClass": "m-large"
|
||||
},
|
||||
"channel": "development"
|
||||
"resourceClass": "large"
|
||||
}
|
||||
},
|
||||
"preview": {
|
||||
"extends": "base",
|
||||
"distribution": "internal",
|
||||
"channel": "preview",
|
||||
"ios": {
|
||||
"resourceClass": "m-large"
|
||||
},
|
||||
"channel": "preview"
|
||||
"resourceClass": "large"
|
||||
}
|
||||
},
|
||||
"production": {
|
||||
"extends": "base",
|
||||
"ios": {
|
||||
"resourceClass": "m-large"
|
||||
"resourceClass": "large"
|
||||
},
|
||||
"channel": "production"
|
||||
},
|
||||
"dev-android-apk": {
|
||||
"developmentClient": true,
|
||||
"android": {
|
||||
"buildType": "apk",
|
||||
"gradleCommand": ":app:assembleRelease"
|
||||
}
|
||||
}
|
||||
},
|
||||
"submit": {
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import 'react-native-gesture-handler' // must be first
|
||||
|
||||
import {LogBox} from 'react-native'
|
||||
LogBox.ignoreLogs(['Require cycle:']) // suppress require-cycle warnings, it's fine
|
||||
|
||||
import 'platform/polyfills'
|
||||
import '#/platform/polyfills'
|
||||
import {IS_TEST} from '#/env'
|
||||
import {registerRootComponent} from 'expo'
|
||||
import {doPolyfill} from '#/lib/api/api-polyfill'
|
||||
|
||||
import App from './src/App'
|
||||
import App from '#/App'
|
||||
|
||||
doPolyfill()
|
||||
|
||||
if (IS_TEST) {
|
||||
LogBox.ignoreAllLogs() // suppress all logs in tests
|
||||
} else {
|
||||
LogBox.ignoreLogs(['Require cycle:']) // suppress require-cycle warnings, it's fine
|
||||
}
|
||||
|
||||
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
|
||||
// It also ensures that whether you load the app in Expo Go or in a native build,
|
||||
|
||||
+5
-2
@@ -1,4 +1,7 @@
|
||||
import 'platform/polyfills'
|
||||
import '#/platform/polyfills'
|
||||
import {registerRootComponent} from 'expo'
|
||||
import App from './src/App'
|
||||
import {doPolyfill} from '#/lib/api/api-polyfill'
|
||||
import App from '#/App'
|
||||
|
||||
doPolyfill()
|
||||
registerRootComponent(App)
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import {configure} from '@testing-library/react-native'
|
||||
import 'react-native-gesture-handler/jestSetup'
|
||||
|
||||
// IMPORTANT: this is what's used in the native runtime
|
||||
import 'react-native-url-polyfill/auto'
|
||||
|
||||
configure({asyncUtilTimeout: 20000})
|
||||
|
||||
jest.mock('@react-native-async-storage/async-storage', () =>
|
||||
|
||||
+6
-2
@@ -59,17 +59,21 @@ export async function createServer(
|
||||
): Promise<TestPDS> {
|
||||
const port = await getPort()
|
||||
const port2 = await getPort(port + 1)
|
||||
const port3 = await getPort(port2 + 1)
|
||||
const pdsUrl = `http://localhost:${port}`
|
||||
const id = ids.next()
|
||||
|
||||
const testNet = await TestNetwork.create({
|
||||
pds: {
|
||||
port,
|
||||
publicUrl: pdsUrl,
|
||||
inviteRequired,
|
||||
hostname: 'localhost',
|
||||
dbPostgresSchema: `pds_${id}`,
|
||||
inviteRequired,
|
||||
},
|
||||
bsky: {
|
||||
dbPostgresSchema: `bsky_${id}`,
|
||||
port: port3,
|
||||
publicUrl: 'http://localhost:2584',
|
||||
},
|
||||
plc: {port: port2},
|
||||
})
|
||||
|
||||
+11
-7
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "bsky.app",
|
||||
"version": "1.56.0",
|
||||
"version": "1.57.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"prepare": "is-ci || husky install",
|
||||
@@ -10,6 +10,7 @@
|
||||
"ios": "expo run:ios",
|
||||
"web": "expo start --web",
|
||||
"build-web": "expo export:web && node ./scripts/post-web-build.js && cp --verbose ./web-build/static/js/*.* ./bskyweb/static/js/",
|
||||
"build-all": "yarn intl:build && eas build --platform all",
|
||||
"start": "expo start --dev-client",
|
||||
"start:prod": "expo start --dev-client --no-dev --minify",
|
||||
"clean-cache": "rm -rf node_modules/.cache/babel-loader/*",
|
||||
@@ -20,15 +21,16 @@
|
||||
"lint": "eslint ./src --ext .js,.jsx,.ts,.tsx",
|
||||
"typecheck": "tsc --project ./tsconfig.check.json",
|
||||
"e2e:mock-server": "./jest/dev-infra/with-test-redis-and-db.sh ts-node __e2e__/mock-server.ts",
|
||||
"e2e:metro": "RN_SRC_EXT=e2e.ts,e2e.tsx expo run:ios",
|
||||
"e2e:build": "detox build -c ios.sim.debug",
|
||||
"e2e:run": "detox test --configuration ios.sim.debug --take-screenshots all",
|
||||
"e2e:metro": "NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:ios",
|
||||
"e2e:build": "NODE_ENV=test detox build -c ios.sim.debug",
|
||||
"e2e:run": "NODE_ENV=test detox test --configuration ios.sim.debug --take-screenshots all",
|
||||
"perf:test": "NODE_ENV=test maestro test",
|
||||
"perf:test:run": "NODE_ENV=test maestro test __e2e__/maestro/scroll.yaml",
|
||||
"perf:test:measure": "NODE_ENV=test flashlight test --bundleId xyz.blueskyweb.app --testCommand 'yarn perf:test' --duration 150000 --resultsFilePath .perf/results.json",
|
||||
"perf:test:results": "NODE_ENV=test flashlight report .perf/results.json",
|
||||
"perf:measure": "NODE_ENV=test flashlight measure",
|
||||
"build:apk": "eas build -p android --profile dev-android-apk",
|
||||
"intl:build": "yarn intl:check && yarn intl:compile",
|
||||
"intl:check": "yarn intl:extract && git diff-index -G'(^[^\\*# /])|(^#\\w)|(^\\s+[^\\*#/])' HEAD || (echo '\n⚠️ i18n detected un-extracted translations\n' && exit 1)",
|
||||
"intl:extract": "lingui extract",
|
||||
"intl:compile": "lingui compile"
|
||||
},
|
||||
@@ -108,6 +110,7 @@
|
||||
"fast-text-encoding": "^1.0.6",
|
||||
"history": "^5.3.0",
|
||||
"js-sha256": "^0.9.0",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"lande": "^1.0.10",
|
||||
"lodash.chunk": "^4.2.0",
|
||||
"lodash.debounce": "^4.0.8",
|
||||
@@ -145,7 +148,7 @@
|
||||
"react-native-pager-view": "6.1.4",
|
||||
"react-native-picker-select": "^8.1.0",
|
||||
"react-native-progress": "bluesky-social/react-native-progress",
|
||||
"react-native-reanimated": "^3.4.2",
|
||||
"react-native-reanimated": "^3.6.0",
|
||||
"react-native-root-siblings": "^4.1.1",
|
||||
"react-native-safe-area-context": "4.6.3",
|
||||
"react-native-screens": "~3.22.0",
|
||||
@@ -166,7 +169,7 @@
|
||||
"zod": "^3.20.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@atproto/dev-env": "^0.2.5",
|
||||
"@atproto/dev-env": "^0.2.16",
|
||||
"@babel/core": "^7.23.2",
|
||||
"@babel/preset-env": "^7.20.0",
|
||||
"@babel/runtime": "^7.20.0",
|
||||
@@ -204,6 +207,7 @@
|
||||
"eslint": "^8.19.0",
|
||||
"eslint-plugin-detox": "^1.0.0",
|
||||
"eslint-plugin-ft-flow": "^2.0.3",
|
||||
"eslint-plugin-lingui": "^0.2.0",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react-native-a11y": "^3.3.0",
|
||||
"html-webpack-plugin": "^5.5.0",
|
||||
|
||||
+16
-21
@@ -6,19 +6,16 @@ import {RootSiblingParent} from 'react-native-root-siblings'
|
||||
import * as SplashScreen from 'expo-splash-screen'
|
||||
import {GestureHandlerRootView} from 'react-native-gesture-handler'
|
||||
import {QueryClientProvider} from '@tanstack/react-query'
|
||||
import {enableFreeze} from 'react-native-screens'
|
||||
|
||||
import 'view/icons'
|
||||
|
||||
import {init as initPersistedState} from '#/state/persisted'
|
||||
import {init as initReminders} from '#/state/shell/reminders'
|
||||
import {listenSessionDropped} from './state/events'
|
||||
import {useColorMode} from 'state/shell'
|
||||
import {ThemeProvider} from 'lib/ThemeContext'
|
||||
import {s} from 'lib/styles'
|
||||
import {Shell} from 'view/shell'
|
||||
import * as notifications from 'lib/notifications/notifications'
|
||||
import * as analytics from 'lib/analytics/analytics'
|
||||
import * as Toast from 'view/com/util/Toast'
|
||||
import {queryClient} from 'lib/react-query'
|
||||
import {TestCtrls} from 'view/com/testing/TestCtrls'
|
||||
@@ -28,6 +25,8 @@ import {Provider as LightboxStateProvider} from 'state/lightbox'
|
||||
import {Provider as MutedThreadsProvider} from 'state/muted-threads'
|
||||
import {Provider as InvitesStateProvider} from 'state/invites'
|
||||
import {Provider as PrefsStateProvider} from 'state/preferences'
|
||||
import {Provider as LoggedOutViewProvider} from 'state/shell/logged-out'
|
||||
import I18nProvider from './locale/i18nProvider'
|
||||
import {
|
||||
Provider as SessionProvider,
|
||||
useSession,
|
||||
@@ -35,24 +34,16 @@ import {
|
||||
} from 'state/session'
|
||||
import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread'
|
||||
import * as persisted from '#/state/persisted'
|
||||
import {i18n} from '@lingui/core'
|
||||
import {I18nProvider} from '@lingui/react'
|
||||
import {messages} from './locale/locales/en/messages'
|
||||
i18n.load('en', messages)
|
||||
i18n.activate('en')
|
||||
|
||||
enableFreeze(true)
|
||||
SplashScreen.preventAutoHideAsync()
|
||||
|
||||
function InnerApp() {
|
||||
const colorMode = useColorMode()
|
||||
const {isInitialLoad} = useSession()
|
||||
const {isInitialLoad, currentAccount} = useSession()
|
||||
const {resumeSession} = useSessionApi()
|
||||
|
||||
// init
|
||||
useEffect(() => {
|
||||
initReminders()
|
||||
analytics.init()
|
||||
notifications.init(queryClient)
|
||||
listenSessionDropped(() => {
|
||||
Toast.show('Sorry! Your session expired. Please log in again.')
|
||||
@@ -73,10 +64,12 @@ function InnerApp() {
|
||||
*/
|
||||
|
||||
return (
|
||||
<UnreadNotifsProvider>
|
||||
<ThemeProvider theme={colorMode}>
|
||||
<analytics.Provider>
|
||||
<I18nProvider i18n={i18n}>
|
||||
<React.Fragment
|
||||
// Resets the entire tree below when it changes:
|
||||
key={currentAccount?.did}>
|
||||
<LoggedOutViewProvider>
|
||||
<UnreadNotifsProvider>
|
||||
<ThemeProvider theme={colorMode}>
|
||||
{/* All components should be within this provider */}
|
||||
<RootSiblingParent>
|
||||
<GestureHandlerRootView style={s.h100pct}>
|
||||
@@ -84,10 +77,10 @@ function InnerApp() {
|
||||
<Shell />
|
||||
</GestureHandlerRootView>
|
||||
</RootSiblingParent>
|
||||
</I18nProvider>
|
||||
</analytics.Provider>
|
||||
</ThemeProvider>
|
||||
</UnreadNotifsProvider>
|
||||
</ThemeProvider>
|
||||
</UnreadNotifsProvider>
|
||||
</LoggedOutViewProvider>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -115,7 +108,9 @@ function App() {
|
||||
<InvitesStateProvider>
|
||||
<ModalStateProvider>
|
||||
<LightboxStateProvider>
|
||||
<InnerApp />
|
||||
<I18nProvider>
|
||||
<InnerApp />
|
||||
</I18nProvider>
|
||||
</LightboxStateProvider>
|
||||
</ModalStateProvider>
|
||||
</InvitesStateProvider>
|
||||
|
||||
+17
-23
@@ -4,27 +4,23 @@ import React, {useState, useEffect} from 'react'
|
||||
import {QueryClientProvider} from '@tanstack/react-query'
|
||||
import {SafeAreaProvider} from 'react-native-safe-area-context'
|
||||
import {RootSiblingParent} from 'react-native-root-siblings'
|
||||
import {enableFreeze} from 'react-native-screens'
|
||||
|
||||
import 'view/icons'
|
||||
|
||||
import {init as initPersistedState} from '#/state/persisted'
|
||||
import {init as initReminders} from '#/state/shell/reminders'
|
||||
import {useColorMode} from 'state/shell'
|
||||
import * as analytics from 'lib/analytics/analytics'
|
||||
import {Shell} from 'view/shell/index'
|
||||
import {ToastContainer} from 'view/com/util/Toast.web'
|
||||
import {ThemeProvider} from 'lib/ThemeContext'
|
||||
import {queryClient} from 'lib/react-query'
|
||||
import {i18n} from '@lingui/core'
|
||||
import {I18nProvider} from '@lingui/react'
|
||||
import {defaultLocale, dynamicActivate} from './locale/i18n'
|
||||
import {Provider as ShellStateProvider} from 'state/shell'
|
||||
import {Provider as ModalStateProvider} from 'state/modals'
|
||||
import {Provider as LightboxStateProvider} from 'state/lightbox'
|
||||
import {Provider as MutedThreadsProvider} from 'state/muted-threads'
|
||||
import {Provider as InvitesStateProvider} from 'state/invites'
|
||||
import {Provider as PrefsStateProvider} from 'state/preferences'
|
||||
import {Provider as LoggedOutViewProvider} from 'state/shell/logged-out'
|
||||
import I18nProvider from './locale/i18nProvider'
|
||||
import {
|
||||
Provider as SessionProvider,
|
||||
useSession,
|
||||
@@ -33,19 +29,13 @@ import {
|
||||
import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread'
|
||||
import * as persisted from '#/state/persisted'
|
||||
|
||||
enableFreeze(true)
|
||||
|
||||
function InnerApp() {
|
||||
const {isInitialLoad} = useSession()
|
||||
const {isInitialLoad, currentAccount} = useSession()
|
||||
const {resumeSession} = useSessionApi()
|
||||
const colorMode = useColorMode()
|
||||
|
||||
// init
|
||||
useEffect(() => {
|
||||
initReminders()
|
||||
analytics.init()
|
||||
dynamicActivate(defaultLocale) // async import of locale data
|
||||
|
||||
const account = persisted.get('session').currentAccount
|
||||
resumeSession(account)
|
||||
}, [resumeSession])
|
||||
@@ -61,21 +51,23 @@ function InnerApp() {
|
||||
*/
|
||||
|
||||
return (
|
||||
<UnreadNotifsProvider>
|
||||
<ThemeProvider theme={colorMode}>
|
||||
<analytics.Provider>
|
||||
<I18nProvider i18n={i18n}>
|
||||
<React.Fragment
|
||||
// Resets the entire tree below when it changes:
|
||||
key={currentAccount?.did}>
|
||||
<LoggedOutViewProvider>
|
||||
<UnreadNotifsProvider>
|
||||
<ThemeProvider theme={colorMode}>
|
||||
{/* All components should be within this provider */}
|
||||
<RootSiblingParent>
|
||||
<SafeAreaProvider>
|
||||
<Shell />
|
||||
</SafeAreaProvider>
|
||||
</RootSiblingParent>
|
||||
</I18nProvider>
|
||||
<ToastContainer />
|
||||
</analytics.Provider>
|
||||
</ThemeProvider>
|
||||
</UnreadNotifsProvider>
|
||||
<ToastContainer />
|
||||
</ThemeProvider>
|
||||
</UnreadNotifsProvider>
|
||||
</LoggedOutViewProvider>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -103,7 +95,9 @@ function App() {
|
||||
<InvitesStateProvider>
|
||||
<ModalStateProvider>
|
||||
<LightboxStateProvider>
|
||||
<InnerApp />
|
||||
<I18nProvider>
|
||||
<InnerApp />
|
||||
</I18nProvider>
|
||||
</LightboxStateProvider>
|
||||
</ModalStateProvider>
|
||||
</InvitesStateProvider>
|
||||
|
||||
+57
-30
@@ -9,7 +9,6 @@ import {
|
||||
DefaultTheme,
|
||||
DarkTheme,
|
||||
} from '@react-navigation/native'
|
||||
import {createNativeStackNavigator} from '@react-navigation/native-stack'
|
||||
import {
|
||||
BottomTabBarProps,
|
||||
createBottomTabNavigator,
|
||||
@@ -36,6 +35,13 @@ import {bskyTitle} from 'lib/strings/headings'
|
||||
import {JSX} from 'react/jsx-runtime'
|
||||
import {timeout} from 'lib/async/timeout'
|
||||
import {useUnreadNotifications} from './state/queries/notifications/unread'
|
||||
import {useSession} from './state/session'
|
||||
import {useModalControls} from './state/modals'
|
||||
import {
|
||||
shouldRequestEmailConfirmation,
|
||||
setEmailConfirmationRequested,
|
||||
} from './state/shell/reminders'
|
||||
import {init as initAnalytics} from './lib/analytics/analytics'
|
||||
|
||||
import {HomeScreen} from './view/screens/Home'
|
||||
import {SearchScreen} from './view/screens/Search'
|
||||
@@ -69,16 +75,18 @@ import {ModerationBlockedAccounts} from 'view/screens/ModerationBlockedAccounts'
|
||||
import {SavedFeeds} from 'view/screens/SavedFeeds'
|
||||
import {PreferencesHomeFeed} from 'view/screens/PreferencesHomeFeed'
|
||||
import {PreferencesThreads} from 'view/screens/PreferencesThreads'
|
||||
import {createNativeStackNavigatorWithAuth} from './view/shell/createNativeStackNavigatorWithAuth'
|
||||
|
||||
const navigationRef = createNavigationContainerRef<AllNavigatorParams>()
|
||||
|
||||
const HomeTab = createNativeStackNavigator<HomeTabNavigatorParams>()
|
||||
const SearchTab = createNativeStackNavigator<SearchTabNavigatorParams>()
|
||||
const FeedsTab = createNativeStackNavigator<FeedsTabNavigatorParams>()
|
||||
const HomeTab = createNativeStackNavigatorWithAuth<HomeTabNavigatorParams>()
|
||||
const SearchTab = createNativeStackNavigatorWithAuth<SearchTabNavigatorParams>()
|
||||
const FeedsTab = createNativeStackNavigatorWithAuth<FeedsTabNavigatorParams>()
|
||||
const NotificationsTab =
|
||||
createNativeStackNavigator<NotificationsTabNavigatorParams>()
|
||||
const MyProfileTab = createNativeStackNavigator<MyProfileTabNavigatorParams>()
|
||||
const Flat = createNativeStackNavigator<FlatNavigatorParams>()
|
||||
createNativeStackNavigatorWithAuth<NotificationsTabNavigatorParams>()
|
||||
const MyProfileTab =
|
||||
createNativeStackNavigatorWithAuth<MyProfileTabNavigatorParams>()
|
||||
const Flat = createNativeStackNavigatorWithAuth<FlatNavigatorParams>()
|
||||
const Tab = createBottomTabNavigator<BottomTabNavigatorParams>()
|
||||
|
||||
/**
|
||||
@@ -97,37 +105,37 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
|
||||
<Stack.Screen
|
||||
name="Lists"
|
||||
component={ListsScreen}
|
||||
options={{title: title('Lists')}}
|
||||
options={{title: title('Lists'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Moderation"
|
||||
getComponent={() => ModerationScreen}
|
||||
options={{title: title('Moderation')}}
|
||||
options={{title: title('Moderation'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="ModerationModlists"
|
||||
getComponent={() => ModerationModlistsScreen}
|
||||
options={{title: title('Moderation Lists')}}
|
||||
options={{title: title('Moderation Lists'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="ModerationMutedAccounts"
|
||||
getComponent={() => ModerationMutedAccounts}
|
||||
options={{title: title('Muted Accounts')}}
|
||||
options={{title: title('Muted Accounts'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="ModerationBlockedAccounts"
|
||||
getComponent={() => ModerationBlockedAccounts}
|
||||
options={{title: title('Blocked Accounts')}}
|
||||
options={{title: title('Blocked Accounts'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Settings"
|
||||
getComponent={() => SettingsScreen}
|
||||
options={{title: title('Settings')}}
|
||||
options={{title: title('Settings'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="LanguageSettings"
|
||||
getComponent={() => LanguageSettingsScreen}
|
||||
options={{title: title('Language Settings')}}
|
||||
options={{title: title('Language Settings'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Profile"
|
||||
@@ -154,7 +162,7 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
|
||||
<Stack.Screen
|
||||
name="ProfileList"
|
||||
getComponent={() => ProfileListScreen}
|
||||
options={{title: title('List')}}
|
||||
options={{title: title('List'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="PostThread"
|
||||
@@ -184,12 +192,12 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
|
||||
<Stack.Screen
|
||||
name="Debug"
|
||||
getComponent={() => DebugScreen}
|
||||
options={{title: title('Debug')}}
|
||||
options={{title: title('Debug'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Log"
|
||||
getComponent={() => LogScreen}
|
||||
options={{title: title('Log')}}
|
||||
options={{title: title('Log'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Support"
|
||||
@@ -219,22 +227,22 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
|
||||
<Stack.Screen
|
||||
name="AppPasswords"
|
||||
getComponent={() => AppPasswords}
|
||||
options={{title: title('App Passwords')}}
|
||||
options={{title: title('App Passwords'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="SavedFeeds"
|
||||
getComponent={() => SavedFeeds}
|
||||
options={{title: title('Edit My Feeds')}}
|
||||
options={{title: title('Edit My Feeds'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="PreferencesHomeFeed"
|
||||
getComponent={() => PreferencesHomeFeed}
|
||||
options={{title: title('Home Feed Preferences')}}
|
||||
options={{title: title('Home Feed Preferences'), requireAuth: true}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="PreferencesThreads"
|
||||
getComponent={() => PreferencesThreads}
|
||||
options={{title: title('Threads Preferences')}}
|
||||
options={{title: title('Threads Preferences'), requireAuth: true}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
@@ -339,6 +347,7 @@ function NotificationsTabNavigator() {
|
||||
<NotificationsTab.Screen
|
||||
name="Notifications"
|
||||
getComponent={() => NotificationsScreen}
|
||||
options={{requireAuth: true}}
|
||||
/>
|
||||
{commonScreens(NotificationsTab as typeof HomeTab)}
|
||||
</NotificationsTab.Navigator>
|
||||
@@ -357,8 +366,8 @@ function MyProfileTabNavigator() {
|
||||
contentStyle,
|
||||
}}>
|
||||
<MyProfileTab.Screen
|
||||
name="MyProfile"
|
||||
// @ts-ignore // TODO: fix this broken type in ProfileScreen
|
||||
name="MyProfile"
|
||||
getComponent={() => ProfileScreen}
|
||||
initialParams={{
|
||||
name: 'me',
|
||||
@@ -405,7 +414,7 @@ const FlatNavigator = () => {
|
||||
<Flat.Screen
|
||||
name="Notifications"
|
||||
getComponent={() => NotificationsScreen}
|
||||
options={{title: title('Notifications')}}
|
||||
options={{title: title('Notifications'), requireAuth: true}}
|
||||
/>
|
||||
{commonScreens(Flat as typeof HomeTab, numUnread)}
|
||||
</Flat.Navigator>
|
||||
@@ -462,6 +471,18 @@ const LINKING = {
|
||||
|
||||
function RoutesContainer({children}: React.PropsWithChildren<{}>) {
|
||||
const theme = useColorSchemeStyle(DefaultTheme, DarkTheme)
|
||||
const {currentAccount} = useSession()
|
||||
const {openModal} = useModalControls()
|
||||
|
||||
function onReady() {
|
||||
initAnalytics(currentAccount)
|
||||
|
||||
if (currentAccount && shouldRequestEmailConfirmation(currentAccount)) {
|
||||
openModal({name: 'verify-email', showReminder: true})
|
||||
setEmailConfirmationRequested()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<NavigationContainer
|
||||
ref={navigationRef}
|
||||
@@ -469,12 +490,8 @@ function RoutesContainer({children}: React.PropsWithChildren<{}>) {
|
||||
theme={theme}
|
||||
onReady={() => {
|
||||
SplashScreen.hideAsync()
|
||||
const initMs = Math.round(
|
||||
// @ts-ignore Emitted by Metro in the bundle prelude
|
||||
performance.now() - global.__BUNDLE_START_TIME__,
|
||||
)
|
||||
console.log(`Time to first paint: ${initMs} ms`)
|
||||
logModuleInitTrace()
|
||||
logModuleInitTime()
|
||||
onReady()
|
||||
}}>
|
||||
{children}
|
||||
</NavigationContainer>
|
||||
@@ -583,7 +600,17 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
})
|
||||
|
||||
function logModuleInitTrace() {
|
||||
let didInit = false
|
||||
function logModuleInitTime() {
|
||||
if (didInit) {
|
||||
return
|
||||
}
|
||||
didInit = true
|
||||
const initMs = Math.round(
|
||||
// @ts-ignore Emitted by Metro in the bundle prelude
|
||||
performance.now() - global.__BUNDLE_START_TIME__,
|
||||
)
|
||||
console.log(`Time to first paint: ${initMs} ms`)
|
||||
if (__DEV__) {
|
||||
// This log is noisy, so keep false committed
|
||||
const shouldLog = false
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
export const IS_TEST = process.env.NODE_ENV === 'test'
|
||||
export const IS_TEST = process.env.EXPO_PUBLIC_ENV === 'test'
|
||||
export const IS_DEV = __DEV__
|
||||
export const IS_PROD = !IS_DEV
|
||||
export const LOG_DEBUG = process.env.EXPO_PUBLIC_LOG_DEBUG || ''
|
||||
|
||||
@@ -1,85 +1,90 @@
|
||||
import React from 'react'
|
||||
import {AppState, AppStateStatus} from 'react-native'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
import {
|
||||
createClient,
|
||||
AnalyticsProvider,
|
||||
useAnalytics as useAnalyticsOrig,
|
||||
ClientMethods,
|
||||
} from '@segment/analytics-react-native'
|
||||
import {z} from 'zod'
|
||||
import {useSession} from '#/state/session'
|
||||
import {createClient, SegmentClient} from '@segment/analytics-react-native'
|
||||
import {useSession, SessionAccount} from '#/state/session'
|
||||
import {sha256} from 'js-sha256'
|
||||
import {ScreenEvent, TrackEvent} from './types'
|
||||
import {TrackEvent, AnalyticsMethods} from './types'
|
||||
import {logger} from '#/logger'
|
||||
import {listenSessionLoaded} from '#/state/events'
|
||||
|
||||
export const appInfo = z.object({
|
||||
build: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
namespace: z.string().optional(),
|
||||
version: z.string().optional(),
|
||||
})
|
||||
export type AppInfo = z.infer<typeof appInfo>
|
||||
type AppInfo = {
|
||||
build?: string | undefined
|
||||
name?: string | undefined
|
||||
namespace?: string | undefined
|
||||
version?: string | undefined
|
||||
}
|
||||
|
||||
const segmentClient = createClient({
|
||||
writeKey: '8I6DsgfiSLuoONyaunGoiQM7A6y2ybdI',
|
||||
trackAppLifecycleEvents: false,
|
||||
proxy: 'https://api.events.bsky.app/v1',
|
||||
})
|
||||
// Delay creating until first actual use.
|
||||
let segmentClient: SegmentClient | null = null
|
||||
function getClient(): SegmentClient {
|
||||
if (!segmentClient) {
|
||||
segmentClient = createClient({
|
||||
writeKey: '8I6DsgfiSLuoONyaunGoiQM7A6y2ybdI',
|
||||
trackAppLifecycleEvents: false,
|
||||
proxy: 'https://api.events.bsky.app/v1',
|
||||
})
|
||||
}
|
||||
return segmentClient
|
||||
}
|
||||
|
||||
export const track = segmentClient?.track?.bind?.(segmentClient) as TrackEvent
|
||||
export const track: TrackEvent = async (...args) => {
|
||||
await getClient().track(...args)
|
||||
}
|
||||
|
||||
export function useAnalytics() {
|
||||
export function useAnalytics(): AnalyticsMethods {
|
||||
const {hasSession} = useSession()
|
||||
const methods: ClientMethods = useAnalyticsOrig()
|
||||
return React.useMemo(() => {
|
||||
if (hasSession) {
|
||||
return {
|
||||
screen: methods.screen as ScreenEvent, // ScreenEvents defines all the possible screen names
|
||||
track: methods.track as TrackEvent, // TrackEvents defines all the possible track events and their properties
|
||||
identify: methods.identify,
|
||||
flush: methods.flush,
|
||||
group: methods.group,
|
||||
alias: methods.alias,
|
||||
reset: methods.reset,
|
||||
async screen(...args) {
|
||||
await getClient().screen(...args)
|
||||
},
|
||||
async track(...args) {
|
||||
await getClient().track(...args)
|
||||
},
|
||||
}
|
||||
}
|
||||
// dont send analytics pings for anonymous users
|
||||
return {
|
||||
screen: () => Promise<void>,
|
||||
track: () => Promise<void>,
|
||||
identify: () => Promise<void>,
|
||||
flush: () => Promise<void>,
|
||||
group: () => Promise<void>,
|
||||
alias: () => Promise<void>,
|
||||
reset: () => Promise<void>,
|
||||
screen: async () => {},
|
||||
track: async () => {},
|
||||
}
|
||||
}, [hasSession, methods])
|
||||
}, [hasSession])
|
||||
}
|
||||
|
||||
export function init() {
|
||||
listenSessionLoaded(account => {
|
||||
export function init(account: SessionAccount | undefined) {
|
||||
setupListenersOnce()
|
||||
|
||||
if (account) {
|
||||
const client = getClient()
|
||||
if (account.did) {
|
||||
const did_hashed = sha256(account.did)
|
||||
segmentClient.identify(did_hashed, {did_hashed})
|
||||
client.identify(did_hashed, {did_hashed})
|
||||
logger.debug('Ping w/hash')
|
||||
} else {
|
||||
logger.debug('Ping w/o hash')
|
||||
segmentClient.identify()
|
||||
client.identify()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let didSetupListeners = false
|
||||
function setupListenersOnce() {
|
||||
if (didSetupListeners) {
|
||||
return
|
||||
}
|
||||
didSetupListeners = true
|
||||
// NOTE
|
||||
// this is a copy of segment's own lifecycle event tracking
|
||||
// we handle it manually to ensure that it never fires while the app is backgrounded
|
||||
// -prf
|
||||
segmentClient.isReady.onChange(async () => {
|
||||
const client = getClient()
|
||||
client.isReady.onChange(async () => {
|
||||
if (AppState.currentState !== 'active') {
|
||||
logger.debug('Prevented a metrics ping while the app was backgrounded')
|
||||
return
|
||||
}
|
||||
const context = segmentClient.context.get()
|
||||
const context = client.context.get()
|
||||
if (typeof context?.app === 'undefined') {
|
||||
logger.debug('Aborted metrics ping due to unavailable context')
|
||||
return
|
||||
@@ -91,19 +96,19 @@ export function init() {
|
||||
logger.debug('Recording app info', {new: newAppInfo, old: oldAppInfo})
|
||||
|
||||
if (typeof oldAppInfo === 'undefined') {
|
||||
segmentClient.track('Application Installed', {
|
||||
client.track('Application Installed', {
|
||||
version: newAppInfo.version,
|
||||
build: newAppInfo.build,
|
||||
})
|
||||
} else if (newAppInfo.version !== oldAppInfo.version) {
|
||||
segmentClient.track('Application Updated', {
|
||||
client.track('Application Updated', {
|
||||
version: newAppInfo.version,
|
||||
build: newAppInfo.build,
|
||||
previous_version: oldAppInfo.version,
|
||||
previous_build: oldAppInfo.build,
|
||||
})
|
||||
}
|
||||
segmentClient.track('Application Opened', {
|
||||
client.track('Application Opened', {
|
||||
from_background: false,
|
||||
version: newAppInfo.version,
|
||||
build: newAppInfo.build,
|
||||
@@ -113,25 +118,19 @@ export function init() {
|
||||
let lastState: AppStateStatus = AppState.currentState
|
||||
AppState.addEventListener('change', (state: AppStateStatus) => {
|
||||
if (state === 'active' && lastState !== 'active') {
|
||||
const context = segmentClient.context.get()
|
||||
segmentClient.track('Application Opened', {
|
||||
const context = client.context.get()
|
||||
client.track('Application Opened', {
|
||||
from_background: true,
|
||||
version: context?.app?.version,
|
||||
build: context?.app?.build,
|
||||
})
|
||||
} else if (state !== 'active' && lastState === 'active') {
|
||||
segmentClient.track('Application Backgrounded')
|
||||
client.track('Application Backgrounded')
|
||||
}
|
||||
lastState = state
|
||||
})
|
||||
}
|
||||
|
||||
export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
return (
|
||||
<AnalyticsProvider client={segmentClient}>{children}</AnalyticsProvider>
|
||||
)
|
||||
}
|
||||
|
||||
async function writeAppInfo(value: AppInfo) {
|
||||
await AsyncStorage.setItem('BSKY_APP_INFO', JSON.stringify(value))
|
||||
}
|
||||
|
||||
@@ -1,66 +1,68 @@
|
||||
import React from 'react'
|
||||
import {
|
||||
createClient,
|
||||
AnalyticsProvider,
|
||||
useAnalytics as useAnalyticsOrig,
|
||||
} from '@segment/analytics-react'
|
||||
import {createClient} from '@segment/analytics-react'
|
||||
import {sha256} from 'js-sha256'
|
||||
import {TrackEvent, AnalyticsMethods} from './types'
|
||||
|
||||
import {useSession} from '#/state/session'
|
||||
import {useSession, SessionAccount} from '#/state/session'
|
||||
import {logger} from '#/logger'
|
||||
import {listenSessionLoaded} from '#/state/events'
|
||||
|
||||
const segmentClient = createClient(
|
||||
{
|
||||
writeKey: '8I6DsgfiSLuoONyaunGoiQM7A6y2ybdI',
|
||||
},
|
||||
{
|
||||
integrations: {
|
||||
'Segment.io': {
|
||||
apiHost: 'api.events.bsky.app/v1',
|
||||
type SegmentClient = ReturnType<typeof createClient>
|
||||
|
||||
// Delay creating until first actual use.
|
||||
let segmentClient: SegmentClient | null = null
|
||||
function getClient(): SegmentClient {
|
||||
if (!segmentClient) {
|
||||
segmentClient = createClient(
|
||||
{
|
||||
writeKey: '8I6DsgfiSLuoONyaunGoiQM7A6y2ybdI',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
export const track = segmentClient?.track?.bind?.(segmentClient)
|
||||
{
|
||||
integrations: {
|
||||
'Segment.io': {
|
||||
apiHost: 'api.events.bsky.app/v1',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
return segmentClient
|
||||
}
|
||||
|
||||
export function useAnalytics() {
|
||||
export const track: TrackEvent = async (...args) => {
|
||||
await getClient().track(...args)
|
||||
}
|
||||
|
||||
export function useAnalytics(): AnalyticsMethods {
|
||||
const {hasSession} = useSession()
|
||||
const methods = useAnalyticsOrig()
|
||||
return React.useMemo(() => {
|
||||
if (hasSession) {
|
||||
return methods
|
||||
return {
|
||||
async screen(...args) {
|
||||
await getClient().screen(...args)
|
||||
},
|
||||
async track(...args) {
|
||||
await getClient().track(...args)
|
||||
},
|
||||
}
|
||||
}
|
||||
// dont send analytics pings for anonymous users
|
||||
return {
|
||||
screen: () => {},
|
||||
track: () => {},
|
||||
identify: () => {},
|
||||
flush: () => {},
|
||||
group: () => {},
|
||||
alias: () => {},
|
||||
reset: () => {},
|
||||
screen: async () => {},
|
||||
track: async () => {},
|
||||
}
|
||||
}, [hasSession, methods])
|
||||
}, [hasSession])
|
||||
}
|
||||
|
||||
export function init() {
|
||||
listenSessionLoaded(account => {
|
||||
export function init(account: SessionAccount | undefined) {
|
||||
if (account) {
|
||||
const client = getClient()
|
||||
if (account.did) {
|
||||
if (account.did) {
|
||||
const did_hashed = sha256(account.did)
|
||||
segmentClient.identify(did_hashed, {did_hashed})
|
||||
logger.debug('Ping w/hash')
|
||||
} else {
|
||||
logger.debug('Ping w/o hash')
|
||||
segmentClient.identify()
|
||||
}
|
||||
const did_hashed = sha256(account.did)
|
||||
client.identify(did_hashed, {did_hashed})
|
||||
logger.debug('Ping w/hash')
|
||||
} else {
|
||||
logger.debug('Ping w/o hash')
|
||||
client.identify()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
return (
|
||||
<AnalyticsProvider client={segmentClient}>{children}</AnalyticsProvider>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ export type ScreenEvent = (
|
||||
name: keyof ScreenPropertiesMap,
|
||||
properties?: ScreenPropertiesMap[keyof ScreenPropertiesMap],
|
||||
) => Promise<void>
|
||||
|
||||
interface TrackPropertiesMap {
|
||||
// LOGIN / SIGN UP events
|
||||
'Sign In': {resumedSession: boolean} // CAN BE SERVER
|
||||
@@ -41,12 +42,6 @@ interface TrackPropertiesMap {
|
||||
'Post:ThreadMute': {} // CAN BE SERVER
|
||||
'Post:ThreadUnmute': {} // CAN BE SERVER
|
||||
'Post:Reply': {} // CAN BE SERVER
|
||||
// FEED ITEM events
|
||||
'FeedItem:PostReply': {} // CAN BE SERVER
|
||||
'FeedItem:PostRepost': {} // CAN BE SERVER
|
||||
'FeedItem:PostLike': {} // CAN BE SERVER
|
||||
'FeedItem:PostDelete': {} // CAN BE SERVER
|
||||
'FeedItem:ThreadMute': {} // CAN BE SERVER
|
||||
// PROFILE events
|
||||
'Profile:Follow': {
|
||||
username: string
|
||||
@@ -79,7 +74,6 @@ interface TrackPropertiesMap {
|
||||
'Settings:AddAccountButtonClicked': {}
|
||||
'Settings:ChangeHandleButtonClicked': {}
|
||||
'Settings:InvitecodesButtonClicked': {}
|
||||
'Settings:ContentfilteringButtonClicked': {}
|
||||
'Settings:SignOutButtonClicked': {}
|
||||
'Settings:ContentlanguagesButtonClicked': {}
|
||||
// MENU events
|
||||
@@ -104,6 +98,8 @@ interface TrackPropertiesMap {
|
||||
'Lists:Unmute': {} // CAN BE SERVER
|
||||
'Lists:Block': {} // CAN BE SERVER
|
||||
'Lists:Unblock': {} // CAN BE SERVER
|
||||
'Lists:Delete': {} // CAN BE SERVER
|
||||
'Lists:Share': {} // CAN BE SERVER
|
||||
// CUSTOM FEED events
|
||||
'CustomFeed:Save': {}
|
||||
'CustomFeed:Unsave': {}
|
||||
@@ -134,6 +130,7 @@ interface TrackPropertiesMap {
|
||||
'Onboarding:Skipped': {}
|
||||
'Onboarding:Reset': {}
|
||||
'Onboarding:SuggestedFollowFollowed': {}
|
||||
'Onboarding:CustomFeedAdded': {}
|
||||
}
|
||||
|
||||
interface ScreenPropertiesMap {
|
||||
@@ -154,3 +151,8 @@ interface ScreenPropertiesMap {
|
||||
MutedAccounts: {}
|
||||
SavedFeeds: {}
|
||||
}
|
||||
|
||||
export type AnalyticsMethods = {
|
||||
screen: ScreenEvent
|
||||
track: TrackEvent
|
||||
}
|
||||
|
||||
+19
-15
@@ -16,13 +16,7 @@ export type FeedTunerFn = (
|
||||
export class FeedViewPostsSlice {
|
||||
isFlattenedReply = false
|
||||
|
||||
constructor(public items: FeedViewPost[] = []) {}
|
||||
|
||||
get _reactKey() {
|
||||
return `slice-${this.items[0].post.uri}-${
|
||||
this.items[0].reason?.indexedAt || this.items[0].post.indexedAt
|
||||
}`
|
||||
}
|
||||
constructor(public items: FeedViewPost[], public _reactKey: string) {}
|
||||
|
||||
get uri() {
|
||||
if (this.isFlattenedReply) {
|
||||
@@ -117,28 +111,34 @@ export class FeedViewPostsSlice {
|
||||
}
|
||||
|
||||
export class NoopFeedTuner {
|
||||
reset() {}
|
||||
private keyCounter = 0
|
||||
|
||||
reset() {
|
||||
this.keyCounter = 0
|
||||
}
|
||||
tune(
|
||||
feed: FeedViewPost[],
|
||||
_tunerFns: FeedTunerFn[] = [],
|
||||
_opts?: {dryRun: boolean; maintainOrder: boolean},
|
||||
): FeedViewPostsSlice[] {
|
||||
return feed.map(item => new FeedViewPostsSlice([item]))
|
||||
return feed.map(
|
||||
item => new FeedViewPostsSlice([item], `slice-${this.keyCounter++}`),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export class FeedTuner {
|
||||
private keyCounter = 0
|
||||
seenUris: Set<string> = new Set()
|
||||
|
||||
constructor() {}
|
||||
constructor(public tunerFns: FeedTunerFn[]) {}
|
||||
|
||||
reset() {
|
||||
this.keyCounter = 0
|
||||
this.seenUris.clear()
|
||||
}
|
||||
|
||||
tune(
|
||||
feed: FeedViewPost[],
|
||||
tunerFns: FeedTunerFn[] = [],
|
||||
{dryRun, maintainOrder}: {dryRun: boolean; maintainOrder: boolean} = {
|
||||
dryRun: false,
|
||||
maintainOrder: false,
|
||||
@@ -147,7 +147,9 @@ export class FeedTuner {
|
||||
let slices: FeedViewPostsSlice[] = []
|
||||
|
||||
if (maintainOrder) {
|
||||
slices = feed.map(item => new FeedViewPostsSlice([item]))
|
||||
slices = feed.map(
|
||||
item => new FeedViewPostsSlice([item], `slice-${this.keyCounter++}`),
|
||||
)
|
||||
} else {
|
||||
// arrange the posts into thread slices
|
||||
for (let i = feed.length - 1; i >= 0; i--) {
|
||||
@@ -163,12 +165,14 @@ export class FeedTuner {
|
||||
continue
|
||||
}
|
||||
}
|
||||
slices.unshift(new FeedViewPostsSlice([item]))
|
||||
slices.unshift(
|
||||
new FeedViewPostsSlice([item], `slice-${this.keyCounter++}`),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// run the custom tuners
|
||||
for (const tunerFn of tunerFns) {
|
||||
for (const tunerFn of this.tunerFns) {
|
||||
slices = tunerFn(this, slices.slice())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import {
|
||||
AppBskyFeedDefs,
|
||||
AppBskyFeedGetAuthorFeed as GetAuthorFeed,
|
||||
BskyAgent,
|
||||
} from '@atproto/api'
|
||||
import {FeedAPI, FeedAPIResponse} from './types'
|
||||
import {getAgent} from '#/state/session'
|
||||
|
||||
export class AuthorFeedAPI implements FeedAPI {
|
||||
constructor(
|
||||
public agent: BskyAgent,
|
||||
public params: GetAuthorFeed.QueryParams,
|
||||
) {}
|
||||
constructor(public params: GetAuthorFeed.QueryParams) {}
|
||||
|
||||
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
|
||||
const res = await this.agent.getAuthorFeed({
|
||||
const res = await getAgent().getAuthorFeed({
|
||||
...this.params,
|
||||
limit: 1,
|
||||
})
|
||||
@@ -26,7 +23,7 @@ export class AuthorFeedAPI implements FeedAPI {
|
||||
cursor: string | undefined
|
||||
limit: number
|
||||
}): Promise<FeedAPIResponse> {
|
||||
const res = await this.agent.getAuthorFeed({
|
||||
const res = await getAgent().getAuthorFeed({
|
||||
...this.params,
|
||||
cursor,
|
||||
limit,
|
||||
@@ -63,13 +60,13 @@ function isAuthorReplyChain(
|
||||
posts: AppBskyFeedDefs.FeedViewPost[],
|
||||
): boolean {
|
||||
// current post is by a different user (shouldn't happen)
|
||||
if (post.post.author.handle !== actor) return false
|
||||
if (post.post.author.did !== actor) return false
|
||||
|
||||
const replyParent = post.reply?.parent
|
||||
|
||||
if (AppBskyFeedDefs.isPostView(replyParent)) {
|
||||
// reply parent is by a different user
|
||||
if (replyParent.author.handle !== actor) return false
|
||||
if (replyParent.author.did !== actor) return false
|
||||
|
||||
// A top-level post that matches the parent of the current post.
|
||||
const parentPost = posts.find(p => p.post.uri === replyParent.uri)
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import {
|
||||
AppBskyFeedDefs,
|
||||
AppBskyFeedGetFeed as GetCustomFeed,
|
||||
BskyAgent,
|
||||
} from '@atproto/api'
|
||||
import {FeedAPI, FeedAPIResponse} from './types'
|
||||
import {getAgent} from '#/state/session'
|
||||
|
||||
export class CustomFeedAPI implements FeedAPI {
|
||||
constructor(
|
||||
public agent: BskyAgent,
|
||||
public params: GetCustomFeed.QueryParams,
|
||||
) {}
|
||||
constructor(public params: GetCustomFeed.QueryParams) {}
|
||||
|
||||
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
|
||||
const res = await this.agent.app.bsky.feed.getFeed({
|
||||
const res = await getAgent().app.bsky.feed.getFeed({
|
||||
...this.params,
|
||||
limit: 1,
|
||||
})
|
||||
@@ -26,7 +23,7 @@ export class CustomFeedAPI implements FeedAPI {
|
||||
cursor: string | undefined
|
||||
limit: number
|
||||
}): Promise<FeedAPIResponse> {
|
||||
const res = await this.agent.app.bsky.feed.getFeed({
|
||||
const res = await getAgent().app.bsky.feed.getFeed({
|
||||
...this.params,
|
||||
cursor,
|
||||
limit,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import {AppBskyFeedDefs, BskyAgent} from '@atproto/api'
|
||||
import {AppBskyFeedDefs} from '@atproto/api'
|
||||
import {FeedAPI, FeedAPIResponse} from './types'
|
||||
import {getAgent} from '#/state/session'
|
||||
|
||||
export class FollowingFeedAPI implements FeedAPI {
|
||||
constructor(public agent: BskyAgent) {}
|
||||
constructor() {}
|
||||
|
||||
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
|
||||
const res = await this.agent.getTimeline({
|
||||
const res = await getAgent().getTimeline({
|
||||
limit: 1,
|
||||
})
|
||||
return res.data.feed[0]
|
||||
@@ -18,7 +19,7 @@ export class FollowingFeedAPI implements FeedAPI {
|
||||
cursor: string | undefined
|
||||
limit: number
|
||||
}): Promise<FeedAPIResponse> {
|
||||
const res = await this.agent.getTimeline({
|
||||
const res = await getAgent().getTimeline({
|
||||
cursor,
|
||||
limit,
|
||||
})
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import {
|
||||
AppBskyFeedDefs,
|
||||
AppBskyFeedGetActorLikes as GetActorLikes,
|
||||
BskyAgent,
|
||||
} from '@atproto/api'
|
||||
import {FeedAPI, FeedAPIResponse} from './types'
|
||||
import {getAgent} from '#/state/session'
|
||||
|
||||
export class LikesFeedAPI implements FeedAPI {
|
||||
constructor(
|
||||
public agent: BskyAgent,
|
||||
public params: GetActorLikes.QueryParams,
|
||||
) {}
|
||||
constructor(public params: GetActorLikes.QueryParams) {}
|
||||
|
||||
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
|
||||
const res = await this.agent.getActorLikes({
|
||||
const res = await getAgent().getActorLikes({
|
||||
...this.params,
|
||||
limit: 1,
|
||||
})
|
||||
@@ -26,7 +23,7 @@ export class LikesFeedAPI implements FeedAPI {
|
||||
cursor: string | undefined
|
||||
limit: number
|
||||
}): Promise<FeedAPIResponse> {
|
||||
const res = await this.agent.getActorLikes({
|
||||
const res = await getAgent().getActorLikes({
|
||||
...this.params,
|
||||
cursor,
|
||||
limit,
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import {
|
||||
AppBskyFeedDefs,
|
||||
AppBskyFeedGetListFeed as GetListFeed,
|
||||
BskyAgent,
|
||||
} from '@atproto/api'
|
||||
import {FeedAPI, FeedAPIResponse} from './types'
|
||||
import {getAgent} from '#/state/session'
|
||||
|
||||
export class ListFeedAPI implements FeedAPI {
|
||||
constructor(
|
||||
public agent: BskyAgent,
|
||||
public params: GetListFeed.QueryParams,
|
||||
) {}
|
||||
constructor(public params: GetListFeed.QueryParams) {}
|
||||
|
||||
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
|
||||
const res = await this.agent.app.bsky.feed.getListFeed({
|
||||
const res = await getAgent().app.bsky.feed.getListFeed({
|
||||
...this.params,
|
||||
limit: 1,
|
||||
})
|
||||
@@ -26,7 +23,7 @@ export class ListFeedAPI implements FeedAPI {
|
||||
cursor: string | undefined
|
||||
limit: number
|
||||
}): Promise<FeedAPIResponse> {
|
||||
const res = await this.agent.app.bsky.feed.getListFeed({
|
||||
const res = await getAgent().app.bsky.feed.getListFeed({
|
||||
...this.params,
|
||||
cursor,
|
||||
limit,
|
||||
|
||||
+16
-24
@@ -1,4 +1,4 @@
|
||||
import {AppBskyFeedDefs, AppBskyFeedGetTimeline, BskyAgent} from '@atproto/api'
|
||||
import {AppBskyFeedDefs, AppBskyFeedGetTimeline} from '@atproto/api'
|
||||
import shuffle from 'lodash.shuffle'
|
||||
import {timeout} from 'lib/async/timeout'
|
||||
import {bundleAsync} from 'lib/async/bundle'
|
||||
@@ -7,6 +7,7 @@ import {FeedTuner} from '../feed-manip'
|
||||
import {FeedAPI, FeedAPIResponse, ReasonFeedSource} from './types'
|
||||
import {FeedParams} from '#/state/queries/post-feed'
|
||||
import {FeedTunerFn} from '../feed-manip'
|
||||
import {getAgent} from '#/state/session'
|
||||
|
||||
const REQUEST_WAIT_MS = 500 // 500ms
|
||||
const POST_AGE_CUTOFF = 60e3 * 60 * 24 // 24hours
|
||||
@@ -18,16 +19,12 @@ export class MergeFeedAPI implements FeedAPI {
|
||||
itemCursor = 0
|
||||
sampleCursor = 0
|
||||
|
||||
constructor(
|
||||
public agent: BskyAgent,
|
||||
public params: FeedParams,
|
||||
public feedTuners: FeedTunerFn[],
|
||||
) {
|
||||
this.following = new MergeFeedSource_Following(this.agent, this.feedTuners)
|
||||
constructor(public params: FeedParams, public feedTuners: FeedTunerFn[]) {
|
||||
this.following = new MergeFeedSource_Following(this.feedTuners)
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.following = new MergeFeedSource_Following(this.agent, this.feedTuners)
|
||||
this.following = new MergeFeedSource_Following(this.feedTuners)
|
||||
this.customFeeds = [] // just empty the array, they will be captured in _fetchNext()
|
||||
this.feedCursor = 0
|
||||
this.itemCursor = 0
|
||||
@@ -35,8 +32,7 @@ export class MergeFeedAPI implements FeedAPI {
|
||||
if (this.params.mergeFeedEnabled && this.params.mergeFeedSources) {
|
||||
this.customFeeds = shuffle(
|
||||
this.params.mergeFeedSources.map(
|
||||
feedUri =>
|
||||
new MergeFeedSource_Custom(this.agent, feedUri, this.feedTuners),
|
||||
feedUri => new MergeFeedSource_Custom(feedUri, this.feedTuners),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
@@ -45,7 +41,7 @@ export class MergeFeedAPI implements FeedAPI {
|
||||
}
|
||||
|
||||
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
|
||||
const res = await this.agent.getTimeline({
|
||||
const res = await getAgent().getTimeline({
|
||||
limit: 1,
|
||||
})
|
||||
return res.data.feed[0]
|
||||
@@ -137,7 +133,7 @@ class MergeFeedSource {
|
||||
queue: AppBskyFeedDefs.FeedViewPost[] = []
|
||||
hasMore = true
|
||||
|
||||
constructor(public agent: BskyAgent, public feedTuners: FeedTunerFn[]) {}
|
||||
constructor(public feedTuners: FeedTunerFn[]) {}
|
||||
|
||||
get numReady() {
|
||||
return this.queue.length
|
||||
@@ -184,7 +180,7 @@ class MergeFeedSource {
|
||||
}
|
||||
|
||||
class MergeFeedSource_Following extends MergeFeedSource {
|
||||
tuner = new FeedTuner()
|
||||
tuner = new FeedTuner(this.feedTuners)
|
||||
|
||||
reset() {
|
||||
super.reset()
|
||||
@@ -199,9 +195,9 @@ class MergeFeedSource_Following extends MergeFeedSource {
|
||||
cursor: string | undefined,
|
||||
limit: number,
|
||||
): Promise<AppBskyFeedGetTimeline.Response> {
|
||||
const res = await this.agent.getTimeline({cursor, limit})
|
||||
const res = await getAgent().getTimeline({cursor, limit})
|
||||
// run the tuner pre-emptively to ensure better mixing
|
||||
const slices = this.tuner.tune(res.data.feed, this.feedTuners, {
|
||||
const slices = this.tuner.tune(res.data.feed, {
|
||||
dryRun: false,
|
||||
maintainOrder: true,
|
||||
})
|
||||
@@ -213,20 +209,16 @@ class MergeFeedSource_Following extends MergeFeedSource {
|
||||
class MergeFeedSource_Custom extends MergeFeedSource {
|
||||
minDate: Date
|
||||
|
||||
constructor(
|
||||
public agent: BskyAgent,
|
||||
public feedUri: string,
|
||||
public feedTuners: FeedTunerFn[],
|
||||
) {
|
||||
super(agent, feedTuners)
|
||||
constructor(public feedUri: string, public feedTuners: FeedTunerFn[]) {
|
||||
super(feedTuners)
|
||||
this.sourceInfo = {
|
||||
$type: 'reasonFeedSource',
|
||||
displayName: feedUri.split('/').pop() || '',
|
||||
uri: feedUriToHref(feedUri),
|
||||
}
|
||||
this.minDate = new Date(Date.now() - POST_AGE_CUTOFF)
|
||||
this.agent.app.bsky.feed
|
||||
.getFeedGenerator({
|
||||
getAgent()
|
||||
.app.bsky.feed.getFeedGenerator({
|
||||
feed: feedUri,
|
||||
})
|
||||
.then(
|
||||
@@ -244,7 +236,7 @@ class MergeFeedSource_Custom extends MergeFeedSource {
|
||||
limit: number,
|
||||
): Promise<AppBskyFeedGetTimeline.Response> {
|
||||
try {
|
||||
const res = await this.agent.app.bsky.feed.getFeed({
|
||||
const res = await getAgent().app.bsky.feed.getFeed({
|
||||
cursor,
|
||||
limit,
|
||||
feed: this.feedUri,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export {unstable_batchedUpdates as batchedUpdates} from 'react-native'
|
||||
@@ -0,0 +1,2 @@
|
||||
// @ts-ignore
|
||||
export {unstable_batchedUpdates as batchedUpdates} from 'react-dom'
|
||||
@@ -1 +1,2 @@
|
||||
export const LOGIN_INCLUDE_DEV_SERVERS = true
|
||||
export const PWI_ENABLED = false
|
||||
|
||||
@@ -116,8 +116,8 @@ export async function DEFAULT_FEEDS(
|
||||
} else {
|
||||
// production
|
||||
return {
|
||||
pinned: [PROD_DEFAULT_FEED('whats-hot')],
|
||||
saved: [PROD_DEFAULT_FEED('whats-hot')],
|
||||
pinned: [],
|
||||
saved: [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,54 @@
|
||||
import {useCallback} from 'react'
|
||||
import {useNavigation} from '@react-navigation/native'
|
||||
|
||||
import {isWeb} from '#/platform/detection'
|
||||
import {NavigationProp} from '#/lib/routes/types'
|
||||
import {useAnalytics} from '#/lib/analytics/analytics'
|
||||
import {useSessionApi, SessionAccount} from '#/state/session'
|
||||
import * as Toast from '#/view/com/util/Toast'
|
||||
import {useCloseAllActiveElements} from '#/state/util'
|
||||
import {useLoggedOutViewControls} from '#/state/shell/logged-out'
|
||||
|
||||
export function useAccountSwitcher() {
|
||||
const {track} = useAnalytics()
|
||||
const {selectAccount, clearCurrentAccount} = useSessionApi()
|
||||
const closeAllActiveElements = useCloseAllActiveElements()
|
||||
const navigation = useNavigation<NavigationProp>()
|
||||
const {setShowLoggedOut} = useLoggedOutViewControls()
|
||||
|
||||
const onPressSwitchAccount = useCallback(
|
||||
async (acct: SessionAccount) => {
|
||||
async (account: SessionAccount) => {
|
||||
track('Settings:SwitchAccountButtonClicked')
|
||||
|
||||
try {
|
||||
await selectAccount(acct)
|
||||
closeAllActiveElements()
|
||||
Toast.show(`Signed in as ${acct.handle}`)
|
||||
if (account.accessJwt) {
|
||||
closeAllActiveElements()
|
||||
navigation.navigate(isWeb ? 'Home' : 'HomeTab')
|
||||
await selectAccount(account)
|
||||
setTimeout(() => {
|
||||
Toast.show(`Signed in as @${account.handle}`)
|
||||
}, 100)
|
||||
} else {
|
||||
closeAllActiveElements()
|
||||
setShowLoggedOut(true)
|
||||
Toast.show(
|
||||
`Please sign in as @${account.handle}`,
|
||||
'circle-exclamation',
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
Toast.show('Sorry! We need you to enter your password.')
|
||||
clearCurrentAccount() // back user out to login
|
||||
}
|
||||
},
|
||||
[track, clearCurrentAccount, selectAccount, closeAllActiveElements],
|
||||
[
|
||||
track,
|
||||
clearCurrentAccount,
|
||||
selectAccount,
|
||||
closeAllActiveElements,
|
||||
navigation,
|
||||
setShowLoggedOut,
|
||||
],
|
||||
)
|
||||
|
||||
return {onPressSwitchAccount}
|
||||
|
||||
@@ -11,31 +11,31 @@ export const useAnimatedScrollHandler: typeof useAnimatedScrollHandler_BUGGY = (
|
||||
})
|
||||
return useAnimatedScrollHandler_BUGGY(
|
||||
{
|
||||
onBeginDrag(e) {
|
||||
onBeginDrag(e, ctx) {
|
||||
if (typeof ref.current !== 'function' && ref.current.onBeginDrag) {
|
||||
ref.current.onBeginDrag(e)
|
||||
ref.current.onBeginDrag(e, ctx)
|
||||
}
|
||||
},
|
||||
onEndDrag(e) {
|
||||
onEndDrag(e, ctx) {
|
||||
if (typeof ref.current !== 'function' && ref.current.onEndDrag) {
|
||||
ref.current.onEndDrag(e)
|
||||
ref.current.onEndDrag(e, ctx)
|
||||
}
|
||||
},
|
||||
onMomentumBegin(e) {
|
||||
onMomentumBegin(e, ctx) {
|
||||
if (typeof ref.current !== 'function' && ref.current.onMomentumBegin) {
|
||||
ref.current.onMomentumBegin(e)
|
||||
ref.current.onMomentumBegin(e, ctx)
|
||||
}
|
||||
},
|
||||
onMomentumEnd(e) {
|
||||
onMomentumEnd(e, ctx) {
|
||||
if (typeof ref.current !== 'function' && ref.current.onMomentumEnd) {
|
||||
ref.current.onMomentumEnd(e)
|
||||
ref.current.onMomentumEnd(e, ctx)
|
||||
}
|
||||
},
|
||||
onScroll(e) {
|
||||
onScroll(e, ctx) {
|
||||
if (typeof ref.current === 'function') {
|
||||
ref.current(e)
|
||||
ref.current(e, ctx)
|
||||
} else if (ref.current.onScroll) {
|
||||
ref.current.onScroll(e)
|
||||
ref.current.onScroll(e, ctx)
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@ import {useCallback, useEffect} from 'react'
|
||||
import {AppState} from 'react-native'
|
||||
import {logger} from '#/logger'
|
||||
import {useModalControls} from '#/state/modals'
|
||||
import {t} from '@lingui/macro'
|
||||
|
||||
export function useOTAUpdate() {
|
||||
const {openModal} = useModalControls()
|
||||
@@ -11,9 +12,8 @@ export function useOTAUpdate() {
|
||||
const showUpdatePopup = useCallback(() => {
|
||||
openModal({
|
||||
name: 'confirm',
|
||||
title: 'Update Available',
|
||||
message:
|
||||
'A new version of the app is available. Please update to continue using the app.',
|
||||
title: t`Update Available`,
|
||||
message: t`A new version of the app is available. Please update to continue using the app.`,
|
||||
onPressConfirm: async () => {
|
||||
Updates.reloadAsync().catch(err => {
|
||||
throw err
|
||||
|
||||
@@ -3,8 +3,8 @@ import {isNative} from 'platform/detection'
|
||||
|
||||
export function useWebMediaQueries() {
|
||||
const isDesktop = useMediaQuery({minWidth: 1300})
|
||||
const isTablet = useMediaQuery({minWidth: 800, maxWidth: 1300})
|
||||
const isMobile = useMediaQuery({maxWidth: 800})
|
||||
const isTablet = useMediaQuery({minWidth: 800, maxWidth: 1300 - 1})
|
||||
const isMobile = useMediaQuery({maxWidth: 800 - 1})
|
||||
const isTabletOrMobile = isMobile || isTablet
|
||||
const isTabletOrDesktop = isDesktop || isTablet
|
||||
if (isNative) {
|
||||
|
||||
+20
-1
@@ -1,4 +1,4 @@
|
||||
import {ModerationCause, ProfileModeration} from '@atproto/api'
|
||||
import {ModerationCause, ProfileModeration, PostModeration} from '@atproto/api'
|
||||
|
||||
export interface ModerationCauseDescription {
|
||||
name: string
|
||||
@@ -92,6 +92,25 @@ export function getProfileModerationCauses(
|
||||
}) as ModerationCause[]
|
||||
}
|
||||
|
||||
export function isPostMediaBlurred(
|
||||
decisions: PostModeration['decisions'],
|
||||
): boolean {
|
||||
return decisions.post.blurMedia
|
||||
}
|
||||
|
||||
export function isQuoteBlurred(
|
||||
decisions: PostModeration['decisions'],
|
||||
): boolean {
|
||||
return (
|
||||
decisions.quote?.blur ||
|
||||
decisions.quote?.blurMedia ||
|
||||
decisions.quote?.filter ||
|
||||
decisions.quotedAccount?.blur ||
|
||||
decisions.quotedAccount?.filter ||
|
||||
false
|
||||
)
|
||||
}
|
||||
|
||||
export function isCauseALabelOnUri(
|
||||
cause: ModerationCause | undefined,
|
||||
uri: string,
|
||||
|
||||
@@ -5,75 +5,81 @@ import {devicePlatform, isIOS} from 'platform/detection'
|
||||
import {track} from 'lib/analytics/analytics'
|
||||
import {logger} from '#/logger'
|
||||
import {RQKEY as RQKEY_NOTIFS} from '#/state/queries/notifications/feed'
|
||||
import {listenSessionLoaded} from '#/state/events'
|
||||
import {truncateAndInvalidate} from '#/state/queries/util'
|
||||
import {SessionAccount, getAgent} from '#/state/session'
|
||||
|
||||
const SERVICE_DID = (serviceUrl?: string) =>
|
||||
serviceUrl?.includes('staging')
|
||||
? 'did:web:api.staging.bsky.dev'
|
||||
: 'did:web:api.bsky.app'
|
||||
|
||||
export function init(queryClient: QueryClient) {
|
||||
listenSessionLoaded(async (account, agent) => {
|
||||
// request notifications permission once the user has logged in
|
||||
const perms = await Notifications.getPermissionsAsync()
|
||||
if (!perms.granted) {
|
||||
await Notifications.requestPermissionsAsync()
|
||||
}
|
||||
export async function requestPermissionsAndRegisterToken(
|
||||
account: SessionAccount,
|
||||
) {
|
||||
// request notifications permission once the user has logged in
|
||||
const perms = await Notifications.getPermissionsAsync()
|
||||
if (!perms.granted) {
|
||||
await Notifications.requestPermissionsAsync()
|
||||
}
|
||||
|
||||
// register the push token with the server
|
||||
const token = await getPushToken()
|
||||
if (token) {
|
||||
try {
|
||||
await agent.api.app.bsky.notification.registerPush({
|
||||
serviceDid: SERVICE_DID(account.service),
|
||||
platform: devicePlatform,
|
||||
token: token.data,
|
||||
appId: 'xyz.blueskyweb.app',
|
||||
})
|
||||
logger.debug(
|
||||
'Notifications: Sent push token (init)',
|
||||
{
|
||||
tokenType: token.type,
|
||||
token: token.data,
|
||||
},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error('Notifications: Failed to set push token', {error})
|
||||
}
|
||||
}
|
||||
// register the push token with the server
|
||||
const token = await Notifications.getDevicePushTokenAsync()
|
||||
try {
|
||||
await getAgent().api.app.bsky.notification.registerPush({
|
||||
serviceDid: SERVICE_DID(account.service),
|
||||
platform: devicePlatform,
|
||||
token: token.data,
|
||||
appId: 'xyz.blueskyweb.app',
|
||||
})
|
||||
logger.debug(
|
||||
'Notifications: Sent push token (init)',
|
||||
{
|
||||
tokenType: token.type,
|
||||
token: token.data,
|
||||
},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error('Notifications: Failed to set push token', {error})
|
||||
}
|
||||
}
|
||||
|
||||
// listens for new changes to the push token
|
||||
// In rare situations, a push token may be changed by the push notification service while the app is running. When a token is rolled, the old one becomes invalid and sending notifications to it will fail. A push token listener will let you handle this situation gracefully by registering the new token with your backend right away.
|
||||
Notifications.addPushTokenListener(async ({data: t, type}) => {
|
||||
export function registerTokenChangeHandler(
|
||||
account: SessionAccount,
|
||||
): () => void {
|
||||
// listens for new changes to the push token
|
||||
// In rare situations, a push token may be changed by the push notification service while the app is running. When a token is rolled, the old one becomes invalid and sending notifications to it will fail. A push token listener will let you handle this situation gracefully by registering the new token with your backend right away.
|
||||
const sub = Notifications.addPushTokenListener(async newToken => {
|
||||
logger.debug(
|
||||
'Notifications: Push token changed',
|
||||
{tokenType: newToken.data, token: newToken.type},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
try {
|
||||
await getAgent().api.app.bsky.notification.registerPush({
|
||||
serviceDid: SERVICE_DID(account.service),
|
||||
platform: devicePlatform,
|
||||
token: newToken.data,
|
||||
appId: 'xyz.blueskyweb.app',
|
||||
})
|
||||
logger.debug(
|
||||
'Notifications: Push token changed',
|
||||
{t, tokenType: type},
|
||||
'Notifications: Sent push token (event)',
|
||||
{
|
||||
tokenType: newToken.type,
|
||||
token: newToken.data,
|
||||
},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
if (t) {
|
||||
try {
|
||||
await agent.api.app.bsky.notification.registerPush({
|
||||
serviceDid: SERVICE_DID(account.service),
|
||||
platform: devicePlatform,
|
||||
token: t,
|
||||
appId: 'xyz.blueskyweb.app',
|
||||
})
|
||||
logger.debug(
|
||||
'Notifications: Sent push token (event)',
|
||||
{
|
||||
tokenType: type,
|
||||
token: t,
|
||||
},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error('Notifications: Failed to set push token', {error})
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Notifications: Failed to set push token', {error})
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
sub.remove()
|
||||
}
|
||||
}
|
||||
|
||||
export function init(queryClient: QueryClient) {
|
||||
// handle notifications that are received, both in the foreground or background
|
||||
Notifications.addNotificationReceivedListener(event => {
|
||||
logger.debug(
|
||||
@@ -83,7 +89,7 @@ export function init(queryClient: QueryClient) {
|
||||
)
|
||||
if (event.request.trigger.type === 'push') {
|
||||
// refresh notifications in the background
|
||||
queryClient.invalidateQueries({queryKey: RQKEY_NOTIFS()})
|
||||
truncateAndInvalidate(queryClient, RQKEY_NOTIFS())
|
||||
// handle payload-based deeplinks
|
||||
let payload
|
||||
if (isIOS) {
|
||||
@@ -103,35 +109,23 @@ export function init(queryClient: QueryClient) {
|
||||
})
|
||||
|
||||
// handle notifications that are tapped on
|
||||
const sub = Notifications.addNotificationResponseReceivedListener(
|
||||
response => {
|
||||
Notifications.addNotificationResponseReceivedListener(response => {
|
||||
logger.debug(
|
||||
'Notifications: response received',
|
||||
{
|
||||
actionIdentifier: response.actionIdentifier,
|
||||
},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
if (response.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER) {
|
||||
logger.debug(
|
||||
'Notifications: response received',
|
||||
{
|
||||
actionIdentifier: response.actionIdentifier,
|
||||
},
|
||||
'User pressed a notification, opening notifications tab',
|
||||
{},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
if (
|
||||
response.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER
|
||||
) {
|
||||
logger.debug(
|
||||
'User pressed a notification, opening notifications tab',
|
||||
{},
|
||||
logger.DebugContext.notifications,
|
||||
)
|
||||
track('Notificatons:OpenApp')
|
||||
queryClient.invalidateQueries({queryKey: RQKEY_NOTIFS()})
|
||||
resetToTab('NotificationsTab') // open notifications tab
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
return () => {
|
||||
sub.remove()
|
||||
}
|
||||
}
|
||||
|
||||
export function getPushToken() {
|
||||
return Notifications.getDevicePushTokenAsync()
|
||||
track('Notificatons:OpenApp')
|
||||
truncateAndInvalidate(queryClient, RQKEY_NOTIFS())
|
||||
resetToTab('NotificationsTab') // open notifications tab
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,6 +8,15 @@ export const queryClient = new QueryClient({
|
||||
// so we NEVER want to enable this
|
||||
// -prf
|
||||
refetchOnWindowFocus: false,
|
||||
// Structural sharing between responses makes it impossible to rely on
|
||||
// "first seen" timestamps on objects to determine if they're fresh.
|
||||
// Disable this optimization so that we can rely on "first seen" timestamps.
|
||||
structuralSharing: false,
|
||||
// We don't want to retry queries by default, because in most cases we
|
||||
// want to fail early and show a response to the user. There are
|
||||
// exceptions, and those can be made on a per-query basis. For others, we
|
||||
// should give users controls to retry.
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import {NavigationProp} from '@react-navigation/native'
|
||||
import {State, RouteParams} from './types'
|
||||
|
||||
export function getRootNavigation<T extends {}>(
|
||||
nav: NavigationProp<T>,
|
||||
): NavigationProp<T> {
|
||||
while (nav.getParent()) {
|
||||
nav = nav.getParent()
|
||||
}
|
||||
return nav
|
||||
}
|
||||
|
||||
export function getCurrentRoute(state: State) {
|
||||
let node = state.routes[state.index || 0]
|
||||
while (node.state?.routes && typeof node.state?.index === 'number') {
|
||||
|
||||
+41
-2
@@ -1,8 +1,47 @@
|
||||
/**
|
||||
* Importing these separately from `platform/detection` and `lib/app-info` to
|
||||
* avoid future conflicts and/or circular deps
|
||||
*/
|
||||
|
||||
import {Platform} from 'react-native'
|
||||
import app from 'react-native-version-number'
|
||||
import * as info from 'expo-updates'
|
||||
import {init} from 'sentry-expo'
|
||||
|
||||
/**
|
||||
* Matches the build profile `channel` props in `eas.json`
|
||||
*/
|
||||
const buildChannel = (info.channel || 'development') as
|
||||
| 'development'
|
||||
| 'preview'
|
||||
| 'production'
|
||||
|
||||
/**
|
||||
* Examples:
|
||||
* - `dev`
|
||||
* - `1.57.0`
|
||||
*/
|
||||
const release = app.appVersion ?? 'dev'
|
||||
|
||||
/**
|
||||
* Examples:
|
||||
* - `web.dev`
|
||||
* - `ios.dev`
|
||||
* - `android.dev`
|
||||
* - `web.1.57.0`
|
||||
* - `ios.1.57.0.3`
|
||||
* - `android.1.57.0.46`
|
||||
*/
|
||||
const dist = `${Platform.OS}.${release}${
|
||||
app.buildVersion ? `.${app.buildVersion}` : ''
|
||||
}`
|
||||
|
||||
init({
|
||||
autoSessionTracking: false,
|
||||
dsn: 'https://05bc3789bf994b81bd7ce20c86ccd3ae@o4505071687041024.ingest.sentry.io/4505071690514432',
|
||||
enableInExpoDevelopment: false, // if true, Sentry will try to send events/errors in development mode.
|
||||
debug: false, // If `true`, Sentry will try to print out useful debugging information if something goes wrong with sending the event. Set it to `false` in production
|
||||
environment: __DEV__ ? 'development' : 'production', // Set the environment
|
||||
enableInExpoDevelopment: false, // enable this to test in dev
|
||||
environment: buildChannel,
|
||||
dist,
|
||||
release,
|
||||
})
|
||||
|
||||
@@ -168,8 +168,15 @@ export function getYoutubeVideoId(link: string): string | undefined {
|
||||
return videoId
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the label in the post text matches the host of the link facet.
|
||||
*
|
||||
* Hosts are case-insensitive, so should be lowercase for comparison.
|
||||
* @see https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2
|
||||
*/
|
||||
export function linkRequiresWarning(uri: string, label: string) {
|
||||
const labelDomain = labelToDomain(label)
|
||||
|
||||
let urip
|
||||
try {
|
||||
urip = new URL(uri)
|
||||
@@ -177,7 +184,9 @@ export function linkRequiresWarning(uri: string, label: string) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (urip.hostname === 'bsky.app') {
|
||||
const host = urip.hostname.toLowerCase()
|
||||
|
||||
if (host === 'bsky.app') {
|
||||
// if this is a link to internal content,
|
||||
// warn if it represents itself as a URL to another app
|
||||
if (
|
||||
@@ -194,20 +203,26 @@ export function linkRequiresWarning(uri: string, label: string) {
|
||||
if (!labelDomain) {
|
||||
return true
|
||||
}
|
||||
return labelDomain !== urip.hostname
|
||||
return labelDomain !== host
|
||||
}
|
||||
}
|
||||
|
||||
function labelToDomain(label: string): string | undefined {
|
||||
/**
|
||||
* Returns a lowercase domain hostname if the label is a valid URL.
|
||||
*
|
||||
* Hosts are case-insensitive, so should be lowercase for comparison.
|
||||
* @see https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2
|
||||
*/
|
||||
export function labelToDomain(label: string): string | undefined {
|
||||
// any spaces just immediately consider the label a non-url
|
||||
if (/\s/.test(label)) {
|
||||
return undefined
|
||||
}
|
||||
try {
|
||||
return new URL(label).hostname
|
||||
return new URL(label).hostname.toLowerCase()
|
||||
} catch {}
|
||||
try {
|
||||
return new URL('https://' + label).hostname
|
||||
return new URL('https://' + label).hostname.toLowerCase()
|
||||
} catch {}
|
||||
return undefined
|
||||
}
|
||||
|
||||
+17
-3
@@ -1,5 +1,10 @@
|
||||
import {useEffect} from 'react'
|
||||
import {i18n} from '@lingui/core'
|
||||
|
||||
import {useLanguagePrefs} from '#/state/preferences'
|
||||
import {messages as messagesEn} from '#/locale/locales/en/messages'
|
||||
import {messages as messagesHi} from '#/locale/locales/hi/messages'
|
||||
|
||||
export const locales = {
|
||||
en: 'English',
|
||||
cs: 'Česky',
|
||||
@@ -14,7 +19,16 @@ export const defaultLocale = 'en'
|
||||
* @param locale any locale string
|
||||
*/
|
||||
export async function dynamicActivate(locale: string) {
|
||||
const {messages} = await import(`./locales/${locale}/messages`)
|
||||
i18n.load(locale, messages)
|
||||
i18n.activate(locale)
|
||||
if (locale === 'hi') {
|
||||
i18n.loadAndActivate({locale, messages: messagesHi})
|
||||
} else {
|
||||
i18n.loadAndActivate({locale, messages: messagesEn})
|
||||
}
|
||||
}
|
||||
|
||||
export async function useLocaleLanguage() {
|
||||
const {appLanguage} = useLanguagePrefs()
|
||||
useEffect(() => {
|
||||
dynamicActivate(appLanguage)
|
||||
}, [appLanguage])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import {useEffect} from 'react'
|
||||
import {i18n} from '@lingui/core'
|
||||
|
||||
import {useLanguagePrefs} from '#/state/preferences'
|
||||
|
||||
export const locales = {
|
||||
en: 'English',
|
||||
cs: 'Česky',
|
||||
fr: 'Français',
|
||||
hi: 'हिंदी',
|
||||
es: 'Español',
|
||||
}
|
||||
export const defaultLocale = 'en'
|
||||
|
||||
/**
|
||||
* We do a dynamic import of just the catalog that we need
|
||||
* @param locale any locale string
|
||||
*/
|
||||
export async function dynamicActivate(locale: string) {
|
||||
let mod: any
|
||||
|
||||
if (locale === 'hi') {
|
||||
mod = await import(`./locales/hi/messages`)
|
||||
} else {
|
||||
mod = await import(`./locales/en/messages`)
|
||||
}
|
||||
|
||||
i18n.load(locale, mod.messages)
|
||||
i18n.activate(locale)
|
||||
}
|
||||
|
||||
export async function useLocaleLanguage() {
|
||||
const {appLanguage} = useLanguagePrefs()
|
||||
useEffect(() => {
|
||||
dynamicActivate(appLanguage)
|
||||
}, [appLanguage])
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import React from 'react'
|
||||
import {I18nProvider as DefaultI18nProvider} from '@lingui/react'
|
||||
import {i18n} from '@lingui/core'
|
||||
import {useLocaleLanguage} from './i18n'
|
||||
|
||||
export default function I18nProvider({children}: {children: React.ReactNode}) {
|
||||
useLocaleLanguage()
|
||||
return <DefaultI18nProvider i18n={i18n}>{children}</DefaultI18nProvider>
|
||||
}
|
||||
@@ -4,6 +4,16 @@ interface Language {
|
||||
name: string
|
||||
}
|
||||
|
||||
interface AppLanguage {
|
||||
code2: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export const APP_LANGUAGES: AppLanguage[] = [
|
||||
{code2: 'en', name: 'English'},
|
||||
{code2: 'hi', name: 'हिंदी'},
|
||||
]
|
||||
|
||||
export const LANGUAGES: Language[] = [
|
||||
{code3: 'aar', code2: 'aa', name: 'Afar'},
|
||||
{code3: 'abk', code2: 'ab', name: 'Abkhazian'},
|
||||
|
||||
File diff suppressed because one or more lines are too long
+1197
-406
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+1197
-406
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+1197
-406
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+1197
-406
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+1564
-781
File diff suppressed because it is too large
Load Diff
@@ -179,6 +179,7 @@ describe('general functionality', () => {
|
||||
level: 'debug', // Sentry bug, log becomes debug
|
||||
timestamp: sentryTimestamp,
|
||||
})
|
||||
jest.runAllTimers()
|
||||
expect(Sentry.captureMessage).toHaveBeenCalledWith(message, {
|
||||
level: 'log',
|
||||
tags: undefined,
|
||||
@@ -193,6 +194,7 @@ describe('general functionality', () => {
|
||||
level: 'warning',
|
||||
timestamp: sentryTimestamp,
|
||||
})
|
||||
jest.runAllTimers()
|
||||
expect(Sentry.captureMessage).toHaveBeenCalledWith(message, {
|
||||
level: 'warning',
|
||||
tags: undefined,
|
||||
@@ -222,6 +224,26 @@ describe('general functionality', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('sentryTransport serializes errors', () => {
|
||||
const message = 'message'
|
||||
const timestamp = Date.now()
|
||||
const sentryTimestamp = timestamp / 1000
|
||||
|
||||
sentryTransport(
|
||||
LogLevel.Debug,
|
||||
message,
|
||||
{error: new Error('foo')},
|
||||
timestamp,
|
||||
)
|
||||
expect(Sentry.addBreadcrumb).toHaveBeenCalledWith({
|
||||
message,
|
||||
data: {error: 'Error: foo'},
|
||||
type: 'default',
|
||||
level: LogLevel.Debug,
|
||||
timestamp: sentryTimestamp,
|
||||
})
|
||||
})
|
||||
|
||||
test('add/remove transport', () => {
|
||||
const timestamp = Date.now()
|
||||
const logger = new Logger({enabled: true})
|
||||
|
||||
+56
-14
@@ -90,6 +90,16 @@ const enabledLogLevels: {
|
||||
[LogLevel.Error]: [LogLevel.Error],
|
||||
}
|
||||
|
||||
export function prepareMetadata(metadata: Metadata): Metadata {
|
||||
return Object.keys(metadata).reduce((acc, key) => {
|
||||
let value = metadata[key]
|
||||
if (value instanceof Error) {
|
||||
value = value.toString()
|
||||
}
|
||||
return {...acc, [key]: value}
|
||||
}, {})
|
||||
}
|
||||
|
||||
/**
|
||||
* Used in dev mode to nicely log to the console
|
||||
*/
|
||||
@@ -100,7 +110,7 @@ export const consoleTransport: Transport = (
|
||||
timestamp,
|
||||
) => {
|
||||
const extra = Object.keys(metadata).length
|
||||
? ' ' + JSON.stringify(metadata, null, ' ')
|
||||
? ' ' + JSON.stringify(prepareMetadata(metadata), null, ' ')
|
||||
: ''
|
||||
const log = {
|
||||
[LogLevel.Debug]: console.debug,
|
||||
@@ -110,7 +120,14 @@ export const consoleTransport: Transport = (
|
||||
[LogLevel.Error]: console.error,
|
||||
}[level]
|
||||
|
||||
log(`${format(timestamp, 'HH:mm:ss')} ${message.toString()}${extra}`)
|
||||
if (message instanceof Error) {
|
||||
console.info(
|
||||
`${format(timestamp, 'HH:mm:ss')} ${message.toString()}${extra}`,
|
||||
)
|
||||
log(message)
|
||||
} else {
|
||||
log(`${format(timestamp, 'HH:mm:ss')} ${message.toString()}${extra}`)
|
||||
}
|
||||
}
|
||||
|
||||
export const sentryTransport: Transport = (
|
||||
@@ -119,6 +136,8 @@ export const sentryTransport: Transport = (
|
||||
{type, tags, ...metadata},
|
||||
timestamp,
|
||||
) => {
|
||||
const meta = prepareMetadata(metadata)
|
||||
|
||||
/**
|
||||
* If a string, report a breadcrumb
|
||||
*/
|
||||
@@ -135,7 +154,7 @@ export const sentryTransport: Transport = (
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message,
|
||||
data: metadata,
|
||||
data: meta,
|
||||
type: type || 'default',
|
||||
level: severity,
|
||||
timestamp: timestamp / 1000, // Sentry expects seconds
|
||||
@@ -151,11 +170,11 @@ export const sentryTransport: Transport = (
|
||||
[LogLevel.Warn]: 'warning',
|
||||
[LogLevel.Error]: 'error',
|
||||
}[level] || 'log') as Sentry.Breadcrumb['level']
|
||||
|
||||
Sentry.captureMessage(message, {
|
||||
// Defer non-critical messages so they're sent in a batch
|
||||
queueMessageForSentry(message, {
|
||||
level: messageLevel,
|
||||
tags,
|
||||
extra: metadata,
|
||||
extra: meta,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
@@ -164,11 +183,37 @@ export const sentryTransport: Transport = (
|
||||
*/
|
||||
Sentry.captureException(message, {
|
||||
tags,
|
||||
extra: metadata,
|
||||
extra: meta,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const queuedMessages: [string, Parameters<typeof Sentry.captureMessage>[1]][] =
|
||||
[]
|
||||
let sentrySendTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
function queueMessageForSentry(
|
||||
message: string,
|
||||
captureContext: Parameters<typeof Sentry.captureMessage>[1],
|
||||
) {
|
||||
queuedMessages.push([message, captureContext])
|
||||
if (!sentrySendTimeout) {
|
||||
// Throttle sending messages with a leading delay
|
||||
// so that we can get Sentry out of the critical path.
|
||||
sentrySendTimeout = setTimeout(() => {
|
||||
sentrySendTimeout = null
|
||||
sendQueuedMessages()
|
||||
}, 7000)
|
||||
}
|
||||
}
|
||||
function sendQueuedMessages() {
|
||||
while (queuedMessages.length > 0) {
|
||||
const record = queuedMessages.shift()
|
||||
if (record) {
|
||||
Sentry.captureMessage(record[0], record[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main class. Defaults are provided in the constructor so that subclasses are
|
||||
* technically possible, if we need to go that route in the future.
|
||||
@@ -275,16 +320,13 @@ export class Logger {
|
||||
*/
|
||||
export const logger = new Logger()
|
||||
|
||||
/**
|
||||
* Report to console in dev, Sentry in prod, nothing in test.
|
||||
*/
|
||||
if (env.IS_DEV && !env.IS_TEST) {
|
||||
logger.addTransport(consoleTransport)
|
||||
|
||||
/**
|
||||
* Uncomment this to test Sentry in dev
|
||||
/*
|
||||
* Comment this out to disable Sentry transport in dev
|
||||
*/
|
||||
// logger.addTransport(sentryTransport);
|
||||
} else if (env.IS_PROD) {
|
||||
// logger.addTransport(sentryTransport)
|
||||
} else if (env.IS_PROD) {
|
||||
logger.addTransport(sentryTransport)
|
||||
}
|
||||
|
||||
Vendored
+61
-61
@@ -1,11 +1,14 @@
|
||||
import {useEffect, useState, useCallback, useRef} from 'react'
|
||||
import {useEffect, useState, useMemo} from 'react'
|
||||
import EventEmitter from 'eventemitter3'
|
||||
import {AppBskyFeedDefs} from '@atproto/api'
|
||||
import {Shadow} from './types'
|
||||
import {batchedUpdates} from '#/lib/batchedUpdates'
|
||||
import {Shadow, castAsShadow} from './types'
|
||||
import {findAllPostsInQueryData as findAllPostsInNotifsQueryData} from '../queries/notifications/feed'
|
||||
import {findAllPostsInQueryData as findAllPostsInFeedQueryData} from '../queries/post-feed'
|
||||
import {findAllPostsInQueryData as findAllPostsInThreadQueryData} from '../queries/post-thread'
|
||||
import {queryClient} from 'lib/react-query'
|
||||
export type {Shadow} from './types'
|
||||
|
||||
const emitter = new EventEmitter()
|
||||
|
||||
export interface PostShadow {
|
||||
likeUri: string | undefined
|
||||
likeCount: number | undefined
|
||||
@@ -16,86 +19,83 @@ export interface PostShadow {
|
||||
|
||||
export const POST_TOMBSTONE = Symbol('PostTombstone')
|
||||
|
||||
interface CacheEntry {
|
||||
ts: number
|
||||
value: PostShadow
|
||||
}
|
||||
const emitter = new EventEmitter()
|
||||
const shadows: WeakMap<
|
||||
AppBskyFeedDefs.PostView,
|
||||
Partial<PostShadow>
|
||||
> = new WeakMap()
|
||||
|
||||
export function usePostShadow(
|
||||
post: AppBskyFeedDefs.PostView,
|
||||
ifAfterTS: number,
|
||||
): Shadow<AppBskyFeedDefs.PostView> | typeof POST_TOMBSTONE {
|
||||
const [state, setState] = useState<CacheEntry>({
|
||||
ts: Date.now(),
|
||||
value: fromPost(post),
|
||||
})
|
||||
const firstRun = useRef(true)
|
||||
const [shadow, setShadow] = useState(() => shadows.get(post))
|
||||
const [prevPost, setPrevPost] = useState(post)
|
||||
if (post !== prevPost) {
|
||||
setPrevPost(post)
|
||||
setShadow(shadows.get(post))
|
||||
}
|
||||
|
||||
const onUpdate = useCallback(
|
||||
(value: Partial<PostShadow>) => {
|
||||
setState(s => ({ts: Date.now(), value: {...s.value, ...value}}))
|
||||
},
|
||||
[setState],
|
||||
)
|
||||
|
||||
// react to shadow updates
|
||||
useEffect(() => {
|
||||
function onUpdate() {
|
||||
setShadow(shadows.get(post))
|
||||
}
|
||||
emitter.addListener(post.uri, onUpdate)
|
||||
return () => {
|
||||
emitter.removeListener(post.uri, onUpdate)
|
||||
}
|
||||
}, [post.uri, onUpdate])
|
||||
}, [post, setShadow])
|
||||
|
||||
// react to post updates
|
||||
useEffect(() => {
|
||||
// dont fire on first run to avoid needless re-renders
|
||||
if (!firstRun.current) {
|
||||
setState({ts: Date.now(), value: fromPost(post)})
|
||||
return useMemo(() => {
|
||||
if (shadow) {
|
||||
return mergeShadow(post, shadow)
|
||||
} else {
|
||||
return castAsShadow(post)
|
||||
}
|
||||
firstRun.current = false
|
||||
}, [post])
|
||||
|
||||
return state.ts > ifAfterTS
|
||||
? mergeShadow(post, state.value)
|
||||
: {...post, isShadowed: true}
|
||||
}
|
||||
|
||||
export function updatePostShadow(uri: string, value: Partial<PostShadow>) {
|
||||
emitter.emit(uri, value)
|
||||
}
|
||||
|
||||
export function isPostShadowed(
|
||||
v: AppBskyFeedDefs.PostView | Shadow<AppBskyFeedDefs.PostView>,
|
||||
): v is Shadow<AppBskyFeedDefs.PostView> {
|
||||
return 'isShadowed' in v && !!v.isShadowed
|
||||
}
|
||||
|
||||
function fromPost(post: AppBskyFeedDefs.PostView): PostShadow {
|
||||
return {
|
||||
likeUri: post.viewer?.like,
|
||||
likeCount: post.likeCount,
|
||||
repostUri: post.viewer?.repost,
|
||||
repostCount: post.repostCount,
|
||||
isDeleted: false,
|
||||
}
|
||||
}, [post, shadow])
|
||||
}
|
||||
|
||||
function mergeShadow(
|
||||
post: AppBskyFeedDefs.PostView,
|
||||
shadow: PostShadow,
|
||||
shadow: Partial<PostShadow>,
|
||||
): Shadow<AppBskyFeedDefs.PostView> | typeof POST_TOMBSTONE {
|
||||
if (shadow.isDeleted) {
|
||||
return POST_TOMBSTONE
|
||||
}
|
||||
return {
|
||||
return castAsShadow({
|
||||
...post,
|
||||
likeCount: shadow.likeCount,
|
||||
repostCount: shadow.repostCount,
|
||||
likeCount: 'likeCount' in shadow ? shadow.likeCount : post.likeCount,
|
||||
repostCount:
|
||||
'repostCount' in shadow ? shadow.repostCount : post.repostCount,
|
||||
viewer: {
|
||||
...(post.viewer || {}),
|
||||
like: shadow.likeUri,
|
||||
repost: shadow.repostUri,
|
||||
like: 'likeUri' in shadow ? shadow.likeUri : post.viewer?.like,
|
||||
repost: 'repostUri' in shadow ? shadow.repostUri : post.viewer?.repost,
|
||||
},
|
||||
isShadowed: true,
|
||||
})
|
||||
}
|
||||
|
||||
export function updatePostShadow(uri: string, value: Partial<PostShadow>) {
|
||||
const cachedPosts = findPostsInCache(uri)
|
||||
for (let post of cachedPosts) {
|
||||
shadows.set(post, {...shadows.get(post), ...value})
|
||||
}
|
||||
batchedUpdates(() => {
|
||||
emitter.emit(uri)
|
||||
})
|
||||
}
|
||||
|
||||
function* findPostsInCache(
|
||||
uri: string,
|
||||
): Generator<AppBskyFeedDefs.PostView, void> {
|
||||
for (let post of findAllPostsInFeedQueryData(queryClient, uri)) {
|
||||
yield post
|
||||
}
|
||||
for (let post of findAllPostsInNotifsQueryData(queryClient, uri)) {
|
||||
yield post
|
||||
}
|
||||
for (let node of findAllPostsInThreadQueryData(queryClient, uri)) {
|
||||
if (node.type === 'post') {
|
||||
yield node.post
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+61
-59
@@ -1,99 +1,101 @@
|
||||
import {useEffect, useState, useCallback, useRef} from 'react'
|
||||
import {useEffect, useState, useMemo} from 'react'
|
||||
import EventEmitter from 'eventemitter3'
|
||||
import {AppBskyActorDefs} from '@atproto/api'
|
||||
import {Shadow} from './types'
|
||||
import {batchedUpdates} from '#/lib/batchedUpdates'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInListMembersQueryData} from '../queries/list-members'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInMyBlockedAccountsQueryData} from '../queries/my-blocked-accounts'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInMyMutedAccountsQueryData} from '../queries/my-muted-accounts'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInPostLikedByQueryData} from '../queries/post-liked-by'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInPostRepostedByQueryData} from '../queries/post-reposted-by'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInProfileQueryData} from '../queries/profile'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInProfileFollowersQueryData} from '../queries/profile-followers'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInProfileFollowsQueryData} from '../queries/profile-follows'
|
||||
import {findAllProfilesInQueryData as findAllProfilesInSuggestedFollowsQueryData} from '../queries/suggested-follows'
|
||||
import {Shadow, castAsShadow} from './types'
|
||||
import {queryClient} from 'lib/react-query'
|
||||
export type {Shadow} from './types'
|
||||
|
||||
const emitter = new EventEmitter()
|
||||
|
||||
export interface ProfileShadow {
|
||||
followingUri: string | undefined
|
||||
muted: boolean | undefined
|
||||
blockingUri: string | undefined
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
ts: number
|
||||
value: ProfileShadow
|
||||
}
|
||||
|
||||
type ProfileView =
|
||||
| AppBskyActorDefs.ProfileView
|
||||
| AppBskyActorDefs.ProfileViewBasic
|
||||
| AppBskyActorDefs.ProfileViewDetailed
|
||||
|
||||
export function useProfileShadow(
|
||||
profile: ProfileView,
|
||||
ifAfterTS: number,
|
||||
): Shadow<ProfileView> {
|
||||
const [state, setState] = useState<CacheEntry>({
|
||||
ts: Date.now(),
|
||||
value: fromProfile(profile),
|
||||
})
|
||||
const firstRun = useRef(true)
|
||||
const shadows: WeakMap<ProfileView, Partial<ProfileShadow>> = new WeakMap()
|
||||
const emitter = new EventEmitter()
|
||||
|
||||
const onUpdate = useCallback(
|
||||
(value: Partial<ProfileShadow>) => {
|
||||
setState(s => ({ts: Date.now(), value: {...s.value, ...value}}))
|
||||
},
|
||||
[setState],
|
||||
)
|
||||
export function useProfileShadow(profile: ProfileView): Shadow<ProfileView> {
|
||||
const [shadow, setShadow] = useState(() => shadows.get(profile))
|
||||
const [prevPost, setPrevPost] = useState(profile)
|
||||
if (profile !== prevPost) {
|
||||
setPrevPost(profile)
|
||||
setShadow(shadows.get(profile))
|
||||
}
|
||||
|
||||
// react to shadow updates
|
||||
useEffect(() => {
|
||||
function onUpdate() {
|
||||
setShadow(shadows.get(profile))
|
||||
}
|
||||
emitter.addListener(profile.did, onUpdate)
|
||||
return () => {
|
||||
emitter.removeListener(profile.did, onUpdate)
|
||||
}
|
||||
}, [profile.did, onUpdate])
|
||||
|
||||
// react to profile updates
|
||||
useEffect(() => {
|
||||
// dont fire on first run to avoid needless re-renders
|
||||
if (!firstRun.current) {
|
||||
setState({ts: Date.now(), value: fromProfile(profile)})
|
||||
}
|
||||
firstRun.current = false
|
||||
}, [profile])
|
||||
|
||||
return state.ts > ifAfterTS
|
||||
? mergeShadow(profile, state.value)
|
||||
: {...profile, isShadowed: true}
|
||||
return useMemo(() => {
|
||||
if (shadow) {
|
||||
return mergeShadow(profile, shadow)
|
||||
} else {
|
||||
return castAsShadow(profile)
|
||||
}
|
||||
}, [profile, shadow])
|
||||
}
|
||||
|
||||
export function updateProfileShadow(
|
||||
uri: string,
|
||||
did: string,
|
||||
value: Partial<ProfileShadow>,
|
||||
) {
|
||||
emitter.emit(uri, value)
|
||||
}
|
||||
|
||||
export function isProfileShadowed<T extends ProfileView>(
|
||||
v: T | Shadow<T>,
|
||||
): v is Shadow<T> {
|
||||
return 'isShadowed' in v && !!v.isShadowed
|
||||
}
|
||||
|
||||
function fromProfile(profile: ProfileView): ProfileShadow {
|
||||
return {
|
||||
followingUri: profile.viewer?.following,
|
||||
muted: profile.viewer?.muted,
|
||||
blockingUri: profile.viewer?.blocking,
|
||||
const cachedProfiles = findProfilesInCache(did)
|
||||
for (let post of cachedProfiles) {
|
||||
shadows.set(post, {...shadows.get(post), ...value})
|
||||
}
|
||||
batchedUpdates(() => {
|
||||
emitter.emit(did, value)
|
||||
})
|
||||
}
|
||||
|
||||
function mergeShadow(
|
||||
profile: ProfileView,
|
||||
shadow: ProfileShadow,
|
||||
shadow: Partial<ProfileShadow>,
|
||||
): Shadow<ProfileView> {
|
||||
return {
|
||||
return castAsShadow({
|
||||
...profile,
|
||||
viewer: {
|
||||
...(profile.viewer || {}),
|
||||
following: shadow.followingUri,
|
||||
muted: shadow.muted,
|
||||
blocking: shadow.blockingUri,
|
||||
following:
|
||||
'followingUri' in shadow
|
||||
? shadow.followingUri
|
||||
: profile.viewer?.following,
|
||||
muted: 'muted' in shadow ? shadow.muted : profile.viewer?.muted,
|
||||
blocking:
|
||||
'blockingUri' in shadow ? shadow.blockingUri : profile.viewer?.blocking,
|
||||
},
|
||||
isShadowed: true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function* findProfilesInCache(did: string): Generator<ProfileView, void> {
|
||||
yield* findAllProfilesInListMembersQueryData(queryClient, did)
|
||||
yield* findAllProfilesInMyBlockedAccountsQueryData(queryClient, did)
|
||||
yield* findAllProfilesInMyMutedAccountsQueryData(queryClient, did)
|
||||
yield* findAllProfilesInPostLikedByQueryData(queryClient, did)
|
||||
yield* findAllProfilesInPostRepostedByQueryData(queryClient, did)
|
||||
yield* findAllProfilesInProfileQueryData(queryClient, did)
|
||||
yield* findAllProfilesInProfileFollowersQueryData(queryClient, did)
|
||||
yield* findAllProfilesInProfileFollowsQueryData(queryClient, did)
|
||||
yield* findAllProfilesInSuggestedFollowsQueryData(queryClient, did)
|
||||
}
|
||||
|
||||
Vendored
+7
-1
@@ -1 +1,7 @@
|
||||
export type Shadow<T> = T & {isShadowed: true}
|
||||
// This isn't a real property, but it prevents T being compatible with Shadow<T>.
|
||||
declare const shadowTag: unique symbol
|
||||
export type Shadow<T> = T & {[shadowTag]: true}
|
||||
|
||||
export function castAsShadow<T>(value: T): Shadow<T> {
|
||||
return value as any as Shadow<T>
|
||||
}
|
||||
|
||||
+8
-15
@@ -1,6 +1,4 @@
|
||||
import EventEmitter from 'eventemitter3'
|
||||
import {BskyAgent} from '@atproto/api'
|
||||
import {SessionAccount} from './session'
|
||||
|
||||
type UnlistenFn = () => void
|
||||
|
||||
@@ -16,19 +14,6 @@ export function listenSoftReset(fn: () => void): UnlistenFn {
|
||||
return () => emitter.off('soft-reset', fn)
|
||||
}
|
||||
|
||||
export function emitSessionLoaded(
|
||||
sessionAccount: SessionAccount,
|
||||
agent: BskyAgent,
|
||||
) {
|
||||
emitter.emit('session-loaded', sessionAccount, agent)
|
||||
}
|
||||
export function listenSessionLoaded(
|
||||
fn: (sessionAccount: SessionAccount, agent: BskyAgent) => void,
|
||||
): UnlistenFn {
|
||||
emitter.on('session-loaded', fn)
|
||||
return () => emitter.off('session-loaded', fn)
|
||||
}
|
||||
|
||||
export function emitSessionDropped() {
|
||||
emitter.emit('session-dropped')
|
||||
}
|
||||
@@ -36,3 +21,11 @@ export function listenSessionDropped(fn: () => void): UnlistenFn {
|
||||
emitter.on('session-dropped', fn)
|
||||
return () => emitter.off('session-dropped', fn)
|
||||
}
|
||||
|
||||
export function emitPostCreated() {
|
||||
emitter.emit('post-created')
|
||||
}
|
||||
export function listenPostCreated(fn: () => void): UnlistenFn {
|
||||
emitter.on('post-created', fn)
|
||||
return () => emitter.off('post-created', fn)
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ export interface CreateOrEditListModal {
|
||||
export interface UserAddRemoveListsModal {
|
||||
name: 'user-add-remove-lists'
|
||||
subject: string
|
||||
handle: string
|
||||
displayName: string
|
||||
onAdd?: (listUri: string) => void
|
||||
onRemove?: (listUri: string) => void
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React from 'react'
|
||||
import * as persisted from '#/state/persisted'
|
||||
import {track} from '#/lib/analytics/analytics'
|
||||
|
||||
type StateContext = persisted.Schema['mutedThreads']
|
||||
type ToggleContext = (uri: string) => boolean
|
||||
@@ -19,9 +20,11 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
if (arr.includes(uri)) {
|
||||
arr = arr.filter(v => v !== uri)
|
||||
muted = false
|
||||
track('Post:ThreadUnmute')
|
||||
} else {
|
||||
arr = arr.concat([uri])
|
||||
muted = true
|
||||
track('Post:ThreadMute')
|
||||
}
|
||||
persisted.write('mutedThreads', arr)
|
||||
return arr
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import type {LegacySchema} from '#/state/persisted/legacy'
|
||||
|
||||
export const ALICE_DID = 'did:plc:ALICE_DID'
|
||||
export const BOB_DID = 'did:plc:BOB_DID'
|
||||
|
||||
export const LEGACY_DATA_DUMP: LegacySchema = {
|
||||
session: {
|
||||
data: {
|
||||
service: 'https://bsky.social/',
|
||||
did: ALICE_DID,
|
||||
},
|
||||
accounts: [
|
||||
{
|
||||
service: 'https://bsky.social',
|
||||
did: ALICE_DID,
|
||||
refreshJwt: 'refreshJwt',
|
||||
accessJwt: 'accessJwt',
|
||||
handle: 'alice.test',
|
||||
email: 'alice@bsky.test',
|
||||
displayName: 'Alice',
|
||||
aviUrl: 'avi',
|
||||
emailConfirmed: true,
|
||||
},
|
||||
{
|
||||
service: 'https://bsky.social',
|
||||
did: BOB_DID,
|
||||
refreshJwt: 'refreshJwt',
|
||||
accessJwt: 'accessJwt',
|
||||
handle: 'bob.test',
|
||||
email: 'bob@bsky.test',
|
||||
displayName: 'Bob',
|
||||
aviUrl: 'avi',
|
||||
emailConfirmed: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
me: {
|
||||
did: ALICE_DID,
|
||||
handle: 'alice.test',
|
||||
displayName: 'Alice',
|
||||
description: '',
|
||||
avatar: 'avi',
|
||||
},
|
||||
onboarding: {step: 'Home'},
|
||||
shell: {colorMode: 'system'},
|
||||
preferences: {
|
||||
primaryLanguage: 'en',
|
||||
contentLanguages: ['en'],
|
||||
postLanguage: 'en',
|
||||
postLanguageHistory: ['en', 'en', 'ja', 'pt', 'de', 'en'],
|
||||
contentLabels: {
|
||||
nsfw: 'warn',
|
||||
nudity: 'warn',
|
||||
suggestive: 'warn',
|
||||
gore: 'warn',
|
||||
hate: 'hide',
|
||||
spam: 'hide',
|
||||
impersonation: 'warn',
|
||||
},
|
||||
savedFeeds: ['feed_a', 'feed_b', 'feed_c'],
|
||||
pinnedFeeds: ['feed_a', 'feed_b'],
|
||||
requireAltTextEnabled: false,
|
||||
},
|
||||
invitedUsers: {seenDids: [], copiedInvites: []},
|
||||
mutedThreads: {uris: []},
|
||||
reminders: {},
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import {jest, expect, test, afterEach} from '@jest/globals'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
|
||||
import {defaults} from '#/state/persisted/schema'
|
||||
import {migrate} from '#/state/persisted/legacy'
|
||||
import * as store from '#/state/persisted/store'
|
||||
import * as persisted from '#/state/persisted'
|
||||
|
||||
const write = jest.mocked(store.write)
|
||||
const read = jest.mocked(store.read)
|
||||
|
||||
jest.mock('#/logger')
|
||||
jest.mock('#/state/persisted/legacy', () => ({
|
||||
migrate: jest.fn(),
|
||||
}))
|
||||
jest.mock('#/state/persisted/store', () => ({
|
||||
write: jest.fn(),
|
||||
read: jest.fn(),
|
||||
}))
|
||||
|
||||
afterEach(() => {
|
||||
jest.useFakeTimers()
|
||||
jest.clearAllMocks()
|
||||
AsyncStorage.clear()
|
||||
})
|
||||
|
||||
test('init: fresh install, no migration', async () => {
|
||||
await persisted.init()
|
||||
|
||||
expect(migrate).toHaveBeenCalledTimes(1)
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
expect(write).toHaveBeenCalledWith(defaults)
|
||||
|
||||
// default value
|
||||
expect(persisted.get('colorMode')).toBe('system')
|
||||
})
|
||||
|
||||
test('init: fresh install, migration ran', async () => {
|
||||
read.mockResolvedValueOnce(defaults)
|
||||
|
||||
await persisted.init()
|
||||
|
||||
expect(migrate).toHaveBeenCalledTimes(1)
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
|
||||
// default value
|
||||
expect(persisted.get('colorMode')).toBe('system')
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import {jest, expect, test, afterEach} from '@jest/globals'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
|
||||
import {defaults, schema} from '#/state/persisted/schema'
|
||||
import {transform, migrate} from '#/state/persisted/legacy'
|
||||
import * as store from '#/state/persisted/store'
|
||||
import {logger} from '#/logger'
|
||||
import * as fixtures from '#/state/persisted/__tests__/fixtures'
|
||||
|
||||
const write = jest.mocked(store.write)
|
||||
const read = jest.mocked(store.read)
|
||||
|
||||
jest.mock('#/logger')
|
||||
jest.mock('#/state/persisted/store', () => ({
|
||||
write: jest.fn(),
|
||||
read: jest.fn(),
|
||||
}))
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks()
|
||||
AsyncStorage.clear()
|
||||
})
|
||||
|
||||
test('migrate: fresh install', async () => {
|
||||
await migrate()
|
||||
|
||||
expect(AsyncStorage.getItem).toHaveBeenCalledWith('root')
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
expect(logger.log).toHaveBeenCalledWith(
|
||||
'persisted state: no migration needed',
|
||||
)
|
||||
})
|
||||
|
||||
test('migrate: fresh install, existing new storage', async () => {
|
||||
read.mockResolvedValueOnce(defaults)
|
||||
|
||||
await migrate()
|
||||
|
||||
expect(AsyncStorage.getItem).toHaveBeenCalledWith('root')
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
expect(logger.log).toHaveBeenCalledWith(
|
||||
'persisted state: no migration needed',
|
||||
)
|
||||
})
|
||||
|
||||
test('migrate: fresh install, AsyncStorage error', async () => {
|
||||
const prevGetItem = AsyncStorage.getItem
|
||||
|
||||
const error = new Error('test error')
|
||||
|
||||
AsyncStorage.getItem = jest.fn(() => {
|
||||
throw error
|
||||
})
|
||||
|
||||
await migrate()
|
||||
|
||||
expect(AsyncStorage.getItem).toHaveBeenCalledWith('root')
|
||||
expect(logger.error).toHaveBeenCalledWith(error, {
|
||||
message: 'persisted state: error migrating legacy storage',
|
||||
})
|
||||
|
||||
AsyncStorage.getItem = prevGetItem
|
||||
})
|
||||
|
||||
test('migrate: has legacy data', async () => {
|
||||
await AsyncStorage.setItem('root', JSON.stringify(fixtures.LEGACY_DATA_DUMP))
|
||||
|
||||
await migrate()
|
||||
|
||||
expect(write).toHaveBeenCalledWith(transform(fixtures.LEGACY_DATA_DUMP))
|
||||
expect(logger.log).toHaveBeenCalledWith(
|
||||
'persisted state: migrated legacy storage',
|
||||
)
|
||||
})
|
||||
|
||||
test('migrate: has legacy data, fails validation', async () => {
|
||||
const legacy = fixtures.LEGACY_DATA_DUMP
|
||||
// @ts-ignore
|
||||
legacy.shell.colorMode = 'invalid'
|
||||
await AsyncStorage.setItem('root', JSON.stringify(legacy))
|
||||
|
||||
await migrate()
|
||||
|
||||
const transformed = transform(legacy)
|
||||
const validate = schema.safeParse(transformed)
|
||||
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
'persisted state: legacy data failed validation',
|
||||
// @ts-ignore
|
||||
{error: validate.error},
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import {expect, test} from '@jest/globals'
|
||||
|
||||
import {transform} from '#/state/persisted/legacy'
|
||||
import {defaults, schema} from '#/state/persisted/schema'
|
||||
import * as fixtures from '#/state/persisted/__tests__/fixtures'
|
||||
|
||||
test('defaults', () => {
|
||||
expect(() => schema.parse(defaults)).not.toThrow()
|
||||
})
|
||||
|
||||
test('transform', () => {
|
||||
const data = transform({})
|
||||
expect(() => schema.parse(data)).not.toThrow()
|
||||
})
|
||||
|
||||
test('transform: legacy fixture', () => {
|
||||
const data = transform(fixtures.LEGACY_DATA_DUMP)
|
||||
expect(() => schema.parse(data)).not.toThrow()
|
||||
expect(data.session.currentAccount?.did).toEqual(fixtures.ALICE_DID)
|
||||
expect(data.session.accounts.length).toEqual(2)
|
||||
})
|
||||
@@ -19,20 +19,24 @@ const _emitter = new EventEmitter()
|
||||
* the Provider.
|
||||
*/
|
||||
export async function init() {
|
||||
logger.debug('persisted state: initializing')
|
||||
logger.info('persisted state: initializing')
|
||||
|
||||
broadcast.onmessage = onBroadcastMessage
|
||||
|
||||
try {
|
||||
await migrate() // migrate old store
|
||||
const stored = await store.read() // check for new store
|
||||
if (!stored) await store.write(defaults) // opt: init new store
|
||||
if (!stored) {
|
||||
logger.info('persisted state: initializing default storage')
|
||||
await store.write(defaults) // opt: init new store
|
||||
}
|
||||
_state = stored || defaults // return new store
|
||||
logger.log('persisted state: initialized')
|
||||
} catch (e) {
|
||||
logger.error('persisted state: failed to load root state from storage', {
|
||||
error: e,
|
||||
})
|
||||
// AsyncStorage failured, but we can still continue in memory
|
||||
// AsyncStorage failure, but we can still continue in memory
|
||||
return defaults
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
|
||||
import {logger} from '#/logger'
|
||||
import {defaults, Schema} from '#/state/persisted/schema'
|
||||
import {defaults, Schema, schema} from '#/state/persisted/schema'
|
||||
import {write, read} from '#/state/persisted/store'
|
||||
|
||||
/**
|
||||
* The shape of the serialized data from our legacy Mobx store.
|
||||
*/
|
||||
type LegacySchema = {
|
||||
export type LegacySchema = {
|
||||
shell: {
|
||||
colorMode: 'system' | 'light' | 'dark'
|
||||
}
|
||||
@@ -15,7 +15,7 @@ type LegacySchema = {
|
||||
data: {
|
||||
service: string
|
||||
did: `did:plc:${string}`
|
||||
}
|
||||
} | null
|
||||
accounts: {
|
||||
service: string
|
||||
did: `did:plc:${string}`
|
||||
@@ -61,12 +61,11 @@ type LegacySchema = {
|
||||
copiedInvites: string[]
|
||||
}
|
||||
mutedThreads: {uris: string[]}
|
||||
reminders: {lastEmailConfirm: string}
|
||||
reminders: {lastEmailConfirm?: string}
|
||||
}
|
||||
|
||||
const DEPRECATED_ROOT_STATE_STORAGE_KEY = 'root'
|
||||
|
||||
// TODO remove, assume that partial data may be here during our refactor
|
||||
export function transform(legacy: Partial<LegacySchema>): Schema {
|
||||
return {
|
||||
colorMode: legacy.shell?.colorMode || defaults.colorMode,
|
||||
@@ -94,6 +93,8 @@ export function transform(legacy: Partial<LegacySchema>): Schema {
|
||||
postLanguageHistory:
|
||||
legacy.preferences?.postLanguageHistory ||
|
||||
defaults.languagePrefs.postLanguageHistory,
|
||||
appLanguage:
|
||||
legacy.preferences?.postLanguage || defaults.languagePrefs.appLanguage,
|
||||
},
|
||||
requireAltTextEnabled:
|
||||
legacy.preferences?.requireAltTextEnabled ||
|
||||
@@ -114,24 +115,74 @@ export function transform(legacy: Partial<LegacySchema>): Schema {
|
||||
* local storage AND old storage exists.
|
||||
*/
|
||||
export async function migrate() {
|
||||
logger.debug('persisted state: migrate')
|
||||
logger.info('persisted state: check need to migrate')
|
||||
|
||||
try {
|
||||
const rawLegacyData = await AsyncStorage.getItem(
|
||||
DEPRECATED_ROOT_STATE_STORAGE_KEY,
|
||||
)
|
||||
const alreadyMigrated = Boolean(await read())
|
||||
const newData = await read()
|
||||
const alreadyMigrated = Boolean(newData)
|
||||
|
||||
/* TODO BEGIN DEBUG — remove this eventually */
|
||||
try {
|
||||
if (rawLegacyData) {
|
||||
const legacy = JSON.parse(rawLegacyData) as Partial<LegacySchema>
|
||||
logger.info(`persisted state: debug legacy data`, {
|
||||
hasExistingLoggedInAccount: Boolean(legacy?.session?.data),
|
||||
numberOfExistingAccounts: legacy?.session?.accounts?.length,
|
||||
foundExistingCurrentAccount: Boolean(
|
||||
legacy.session?.accounts?.find(
|
||||
a => a.did === legacy.session?.data?.did,
|
||||
),
|
||||
),
|
||||
})
|
||||
logger.info(`persisted state: debug new data`, {
|
||||
hasNewData: Boolean(newData),
|
||||
hasExistingLoggedInAccount: Boolean(newData?.session?.currentAccount),
|
||||
numberOfExistingAccounts: newData?.session?.accounts?.length,
|
||||
existingAccountMatchesLegacy: Boolean(
|
||||
newData?.session?.currentAccount?.did ===
|
||||
legacy?.session?.data?.did,
|
||||
),
|
||||
})
|
||||
}
|
||||
} catch (e: any) {
|
||||
logger.error(e, {message: `persisted state: legacy debugging failed`})
|
||||
}
|
||||
/* TODO END DEBUG */
|
||||
|
||||
if (!alreadyMigrated && rawLegacyData) {
|
||||
logger.debug('persisted state: migrating legacy storage')
|
||||
logger.info('persisted state: migrating legacy storage')
|
||||
|
||||
const legacyData = JSON.parse(rawLegacyData)
|
||||
const newData = transform(legacyData)
|
||||
await write(newData)
|
||||
logger.debug('persisted state: migrated legacy storage')
|
||||
const validate = schema.safeParse(newData)
|
||||
|
||||
if (validate.success) {
|
||||
await write(newData)
|
||||
logger.log('persisted state: migrated legacy storage')
|
||||
} else {
|
||||
logger.error('persisted state: legacy data failed validation', {
|
||||
error: validate.error,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
logger.log('persisted state: no migration needed')
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('persisted state: error migrating legacy storage', {
|
||||
error: String(e),
|
||||
} catch (e: any) {
|
||||
logger.error(e, {
|
||||
message: 'persisted state: error migrating legacy storage',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearLegacyStorage() {
|
||||
try {
|
||||
await AsyncStorage.removeItem(DEPRECATED_ROOT_STATE_STORAGE_KEY)
|
||||
} catch (e: any) {
|
||||
logger.error(`persisted legacy store: failed to clear`, {
|
||||
error: e.toString(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,14 @@ import {z} from 'zod'
|
||||
import {deviceLocales} from '#/platform/detection'
|
||||
|
||||
// only data needed for rendering account page
|
||||
// TODO agent.resumeSession requires the following fields
|
||||
const accountSchema = z.object({
|
||||
service: z.string(),
|
||||
did: z.string(),
|
||||
handle: z.string(),
|
||||
email: z.string(),
|
||||
emailConfirmed: z.boolean(),
|
||||
email: z.string().optional(),
|
||||
emailConfirmed: z.boolean().optional(),
|
||||
refreshJwt: z.string().optional(), // optional because it can expire
|
||||
accessJwt: z.string().optional(), // optional because it can expire
|
||||
// displayName: z.string().optional(),
|
||||
// aviUrl: z.string().optional(),
|
||||
})
|
||||
export type PersistedAccount = z.infer<typeof accountSchema>
|
||||
|
||||
@@ -30,6 +27,7 @@ export const schema = z.object({
|
||||
contentLanguages: z.array(z.string()), // should move to server
|
||||
postLanguage: z.string(), // should move to server
|
||||
postLanguageHistory: z.array(z.string()),
|
||||
appLanguage: z.string(),
|
||||
}),
|
||||
requireAltTextEnabled: z.boolean(), // should move to server
|
||||
mutedThreads: z.array(z.string()), // should move to server
|
||||
@@ -58,6 +56,7 @@ export const defaults: Schema = {
|
||||
postLanguageHistory: (deviceLocales || [])
|
||||
.concat(['en', 'ja', 'pt', 'de'])
|
||||
.slice(0, 6),
|
||||
appLanguage: deviceLocales[0] || 'en',
|
||||
},
|
||||
requireAltTextEnabled: false,
|
||||
mutedThreads: [],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
|
||||
import {Schema, schema} from '#/state/persisted/schema'
|
||||
import {logger} from '#/logger'
|
||||
|
||||
const BSKY_STORAGE = 'BSKY_STORAGE'
|
||||
|
||||
@@ -16,3 +17,11 @@ export async function read(): Promise<Schema | undefined> {
|
||||
return objData
|
||||
}
|
||||
}
|
||||
|
||||
export async function clear() {
|
||||
try {
|
||||
await AsyncStorage.removeItem(BSKY_STORAGE)
|
||||
} catch (e: any) {
|
||||
logger.error(`persisted store: failed to clear`, {error: e.toString()})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,13 @@ import {useMemo} from 'react'
|
||||
import {FeedTuner} from '#/lib/api/feed-manip'
|
||||
import {FeedDescriptor} from '../queries/post-feed'
|
||||
import {useLanguagePrefs} from './languages'
|
||||
import {usePreferencesQuery} from '../queries/preferences'
|
||||
import {useSession} from '../session'
|
||||
|
||||
export function useFeedTuners(feedDesc: FeedDescriptor) {
|
||||
const langPrefs = useLanguagePrefs()
|
||||
const {data: preferences} = usePreferencesQuery()
|
||||
const {currentAccount} = useSession()
|
||||
|
||||
return useMemo(() => {
|
||||
if (feedDesc.startsWith('feedgen')) {
|
||||
@@ -19,30 +23,30 @@ export function useFeedTuners(feedDesc: FeedDescriptor) {
|
||||
if (feedDesc === 'home' || feedDesc === 'following') {
|
||||
const feedTuners = []
|
||||
|
||||
if (false /*TODOthis.homeFeed.hideReposts*/) {
|
||||
if (preferences?.feedViewPrefs.hideReposts) {
|
||||
feedTuners.push(FeedTuner.removeReposts)
|
||||
} else {
|
||||
feedTuners.push(FeedTuner.dedupReposts)
|
||||
}
|
||||
|
||||
if (true /*TODOthis.homeFeed.hideReplies*/) {
|
||||
if (preferences?.feedViewPrefs.hideReplies) {
|
||||
feedTuners.push(FeedTuner.removeReplies)
|
||||
} /* TODO else {
|
||||
} else {
|
||||
feedTuners.push(
|
||||
FeedTuner.thresholdRepliesOnly({
|
||||
userDid: this.rootStore.session.data?.did || '',
|
||||
minLikes: this.homeFeed.hideRepliesByLikeCount,
|
||||
followedOnly: !!this.homeFeed.hideRepliesByUnfollowed,
|
||||
userDid: currentAccount?.did || '',
|
||||
minLikes: preferences?.feedViewPrefs.hideRepliesByLikeCount || 0,
|
||||
followedOnly: !!preferences?.feedViewPrefs.hideRepliesByUnfollowed,
|
||||
}),
|
||||
)
|
||||
}*/
|
||||
}
|
||||
|
||||
if (false /*TODOthis.homeFeed.hideQuotePosts*/) {
|
||||
if (preferences?.feedViewPrefs.hideQuotePosts) {
|
||||
feedTuners.push(FeedTuner.removeQuotePosts)
|
||||
}
|
||||
|
||||
return feedTuners
|
||||
}
|
||||
return []
|
||||
}, [feedDesc, langPrefs])
|
||||
}, [feedDesc, currentAccount, preferences, langPrefs])
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ type ApiContext = {
|
||||
toggleContentLanguage: (code2: string) => void
|
||||
togglePostLanguage: (code2: string) => void
|
||||
savePostLanguageToHistory: () => void
|
||||
setAppLanguage: (code2: string) => void
|
||||
}
|
||||
|
||||
const stateContext = React.createContext<StateContext>(
|
||||
@@ -22,6 +23,7 @@ const apiContext = React.createContext<ApiContext>({
|
||||
toggleContentLanguage: (_: string) => {},
|
||||
togglePostLanguage: (_: string) => {},
|
||||
savePostLanguageToHistory: () => {},
|
||||
setAppLanguage: (_: string) => {},
|
||||
})
|
||||
|
||||
export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
@@ -104,6 +106,9 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
.slice(0, 6),
|
||||
}))
|
||||
},
|
||||
setAppLanguage(code2: string) {
|
||||
setStateWrapped(s => ({...s, appLanguage: code2}))
|
||||
},
|
||||
}),
|
||||
[state, setStateWrapped],
|
||||
)
|
||||
|
||||
@@ -8,7 +8,8 @@ export const RQKEY = () => ['app-passwords']
|
||||
|
||||
export function useAppPasswordsQuery() {
|
||||
return useQuery({
|
||||
staleTime: STALE.MINUTES.ONE,
|
||||
staleTime: STALE.MINUTES.FIVE,
|
||||
refetchInterval: STALE.MINUTES.ONE,
|
||||
queryKey: RQKEY(),
|
||||
queryFn: async () => {
|
||||
const res = await getAgent().com.atproto.server.listAppPasswords({})
|
||||
|
||||
+55
-10
@@ -160,6 +160,51 @@ export function useFeedSourceInfoQuery({uri}: {uri: string}) {
|
||||
})
|
||||
}
|
||||
|
||||
export const isFeedPublicQueryKey = ({uri}: {uri: string}) => [
|
||||
'isFeedPublic',
|
||||
uri,
|
||||
]
|
||||
|
||||
export function useIsFeedPublicQuery({uri}: {uri: string}) {
|
||||
return useQuery({
|
||||
queryKey: isFeedPublicQueryKey({uri}),
|
||||
queryFn: async ({queryKey}) => {
|
||||
const [, uri] = queryKey
|
||||
try {
|
||||
const res = await getAgent().app.bsky.feed.getFeed({
|
||||
feed: uri,
|
||||
limit: 1,
|
||||
})
|
||||
return {
|
||||
isPublic: Boolean(res.data.feed),
|
||||
error: undefined,
|
||||
}
|
||||
} catch (e: any) {
|
||||
/**
|
||||
* This should be an `XRPCError`, but I can't safely import from
|
||||
* `@atproto/xrpc` due to a depdency on node's `crypto` module.
|
||||
*
|
||||
* @see https://github.com/bluesky-social/atproto/blob/c17971a2d8e424cc7f10c071d97c07c08aa319cf/packages/xrpc/src/client.ts#L126
|
||||
*/
|
||||
if (e?.status === 401) {
|
||||
return {
|
||||
isPublic: false,
|
||||
error: e,
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Non-401 response means something else went wrong on the server
|
||||
*/
|
||||
return {
|
||||
isPublic: true,
|
||||
error: e,
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useGetPopularFeedsQueryKey = ['getPopularFeeds']
|
||||
|
||||
export function useGetPopularFeedsQuery() {
|
||||
@@ -214,13 +259,19 @@ const FOLLOWING_FEED_STUB: FeedSourceInfo = {
|
||||
likeUri: '',
|
||||
}
|
||||
|
||||
export function usePinnedFeedsInfos(): FeedSourceInfo[] {
|
||||
export function usePinnedFeedsInfos(): {
|
||||
feeds: FeedSourceInfo[]
|
||||
hasPinnedCustom: boolean
|
||||
} {
|
||||
const queryClient = useQueryClient()
|
||||
const [tabs, setTabs] = React.useState<FeedSourceInfo[]>([
|
||||
FOLLOWING_FEED_STUB,
|
||||
])
|
||||
const {data: preferences} = usePreferencesQuery()
|
||||
const pinnedFeedsKey = JSON.stringify(preferences?.feeds?.pinned)
|
||||
|
||||
const hasPinnedCustom = React.useMemo<boolean>(() => {
|
||||
return tabs.some(tab => tab !== FOLLOWING_FEED_STUB)
|
||||
}, [tabs])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!preferences?.feeds?.pinned) return
|
||||
@@ -267,13 +318,7 @@ export function usePinnedFeedsInfos(): FeedSourceInfo[] {
|
||||
}
|
||||
|
||||
fetchFeedInfo()
|
||||
}, [
|
||||
queryClient,
|
||||
setTabs,
|
||||
preferences?.feeds?.pinned,
|
||||
// ensure we react to re-ordering
|
||||
pinnedFeedsKey,
|
||||
])
|
||||
}, [queryClient, setTabs, preferences?.feeds?.pinned])
|
||||
|
||||
return tabs
|
||||
return {feeds: tabs, hasPinnedCustom}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import {BskyAgent} from '@atproto/api'
|
||||
|
||||
export const PUBLIC_BSKY_AGENT = new BskyAgent({
|
||||
service: 'https://api.bsky.app',
|
||||
service: 'https://public.api.bsky.app',
|
||||
})
|
||||
|
||||
export const STALE = {
|
||||
SECONDS: {
|
||||
FIFTEEN: 1e3 * 15,
|
||||
THIRTY: 1e3 * 30,
|
||||
},
|
||||
MINUTES: {
|
||||
ONE: 1e3 * 60,
|
||||
FIVE: 1e3 * 60 * 5,
|
||||
|
||||
@@ -3,6 +3,7 @@ import {useQuery} from '@tanstack/react-query'
|
||||
|
||||
import {getAgent} from '#/state/session'
|
||||
import {STALE} from '#/state/queries'
|
||||
import {cleanError} from '#/lib/strings/errors'
|
||||
|
||||
function isInviteAvailable(invite: ComAtprotoServerDefs.InviteCode): boolean {
|
||||
return invite.available - invite.uses.length > 0 && !invite.disabled
|
||||
@@ -14,10 +15,28 @@ export type InviteCodesQueryResponse = Exclude<
|
||||
>
|
||||
export function useInviteCodesQuery() {
|
||||
return useQuery({
|
||||
staleTime: STALE.HOURS.ONE,
|
||||
staleTime: STALE.MINUTES.FIVE,
|
||||
refetchInterval: STALE.MINUTES.FIVE,
|
||||
queryKey: ['inviteCodes'],
|
||||
queryFn: async () => {
|
||||
const res = await getAgent().com.atproto.server.getAccountInviteCodes({})
|
||||
const res = await getAgent()
|
||||
.com.atproto.server.getAccountInviteCodes({})
|
||||
.catch(e => {
|
||||
if (cleanError(e) === 'Bad token scope') {
|
||||
return null
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
})
|
||||
|
||||
if (res === null) {
|
||||
return {
|
||||
disabled: true,
|
||||
all: [],
|
||||
available: [],
|
||||
used: [],
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.data?.codes) {
|
||||
throw new Error(`useInviteCodesQuery: no codes returned`)
|
||||
@@ -27,6 +46,7 @@ export function useInviteCodesQuery() {
|
||||
const used = res.data.codes.filter(code => !isInviteAvailable(code))
|
||||
|
||||
return {
|
||||
disabled: false,
|
||||
all: [...available, ...used],
|
||||
available,
|
||||
used,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import {AppBskyGraphGetList} from '@atproto/api'
|
||||
import {useInfiniteQuery, InfiniteData, QueryKey} from '@tanstack/react-query'
|
||||
import {AppBskyActorDefs, AppBskyGraphGetList} from '@atproto/api'
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
InfiniteData,
|
||||
QueryClient,
|
||||
QueryKey,
|
||||
} from '@tanstack/react-query'
|
||||
|
||||
import {getAgent} from '#/state/session'
|
||||
import {STALE} from '#/state/queries'
|
||||
@@ -31,3 +36,34 @@ export function useListMembersQuery(uri: string) {
|
||||
getNextPageParam: lastPage => lastPage.cursor,
|
||||
})
|
||||
}
|
||||
|
||||
export function* findAllProfilesInQueryData(
|
||||
queryClient: QueryClient,
|
||||
did: string,
|
||||
): Generator<AppBskyActorDefs.ProfileView, void> {
|
||||
const queryDatas = queryClient.getQueriesData<
|
||||
InfiniteData<AppBskyGraphGetList.OutputSchema>
|
||||
>({
|
||||
queryKey: ['list-members'],
|
||||
})
|
||||
for (const [_queryKey, queryData] of queryDatas) {
|
||||
if (!queryData) {
|
||||
continue
|
||||
}
|
||||
for (const [_queryKey, queryData] of queryDatas) {
|
||||
if (!queryData?.pages) {
|
||||
continue
|
||||
}
|
||||
for (const page of queryData?.pages) {
|
||||
if (page.list.creator.did === did) {
|
||||
yield page.list.creator
|
||||
}
|
||||
for (const item of page.items) {
|
||||
if (item.subject.did === did) {
|
||||
yield item.subject
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-27
@@ -3,7 +3,6 @@ import {
|
||||
AppBskyGraphGetList,
|
||||
AppBskyGraphList,
|
||||
AppBskyGraphDefs,
|
||||
BskyAgent,
|
||||
} from '@atproto/api'
|
||||
import {Image as RNImage} from 'react-native-image-crop-picker'
|
||||
import {useQuery, useMutation, useQueryClient} from '@tanstack/react-query'
|
||||
@@ -75,13 +74,9 @@ export function useListCreateMutation() {
|
||||
)
|
||||
|
||||
// wait for the appview to update
|
||||
await whenAppViewReady(
|
||||
getAgent(),
|
||||
res.uri,
|
||||
(v: AppBskyGraphGetList.Response) => {
|
||||
return typeof v?.data?.list.uri === 'string'
|
||||
},
|
||||
)
|
||||
await whenAppViewReady(res.uri, (v: AppBskyGraphGetList.Response) => {
|
||||
return typeof v?.data?.list.uri === 'string'
|
||||
})
|
||||
return res
|
||||
},
|
||||
onSuccess() {
|
||||
@@ -142,16 +137,12 @@ export function useListMetadataMutation() {
|
||||
).data
|
||||
|
||||
// wait for the appview to update
|
||||
await whenAppViewReady(
|
||||
getAgent(),
|
||||
res.uri,
|
||||
(v: AppBskyGraphGetList.Response) => {
|
||||
const list = v.data.list
|
||||
return (
|
||||
list.name === record.name && list.description === record.description
|
||||
)
|
||||
},
|
||||
)
|
||||
await whenAppViewReady(res.uri, (v: AppBskyGraphGetList.Response) => {
|
||||
const list = v.data.list
|
||||
return (
|
||||
list.name === record.name && list.description === record.description
|
||||
)
|
||||
})
|
||||
return res
|
||||
},
|
||||
onSuccess(data, variables) {
|
||||
@@ -216,13 +207,9 @@ export function useListDeleteMutation() {
|
||||
}
|
||||
|
||||
// wait for the appview to update
|
||||
await whenAppViewReady(
|
||||
getAgent(),
|
||||
uri,
|
||||
(v: AppBskyGraphGetList.Response) => {
|
||||
return !v?.success
|
||||
},
|
||||
)
|
||||
await whenAppViewReady(uri, (v: AppBskyGraphGetList.Response) => {
|
||||
return !v?.success
|
||||
})
|
||||
},
|
||||
onSuccess() {
|
||||
invalidateMyLists(queryClient)
|
||||
@@ -271,7 +258,6 @@ export function useListBlockMutation() {
|
||||
}
|
||||
|
||||
async function whenAppViewReady(
|
||||
agent: BskyAgent,
|
||||
uri: string,
|
||||
fn: (res: AppBskyGraphGetList.Response) => boolean,
|
||||
) {
|
||||
@@ -280,7 +266,7 @@ async function whenAppViewReady(
|
||||
1e3, // 1s delay between tries
|
||||
fn,
|
||||
() =>
|
||||
agent.app.bsky.graph.getList({
|
||||
getAgent().app.bsky.graph.getList({
|
||||
list: uri,
|
||||
limit: 1,
|
||||
}),
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import {AppBskyGraphGetBlocks} from '@atproto/api'
|
||||
import {useInfiniteQuery, InfiniteData, QueryKey} from '@tanstack/react-query'
|
||||
import {AppBskyActorDefs, AppBskyGraphGetBlocks} from '@atproto/api'
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
InfiniteData,
|
||||
QueryClient,
|
||||
QueryKey,
|
||||
} from '@tanstack/react-query'
|
||||
|
||||
import {getAgent} from '#/state/session'
|
||||
import {STALE} from '#/state/queries'
|
||||
|
||||
export const RQKEY = () => ['my-blocked-accounts']
|
||||
type RQPageParam = string | undefined
|
||||
@@ -15,7 +19,6 @@ export function useMyBlockedAccountsQuery() {
|
||||
QueryKey,
|
||||
RQPageParam
|
||||
>({
|
||||
staleTime: STALE.MINUTES.ONE,
|
||||
queryKey: RQKEY(),
|
||||
async queryFn({pageParam}: {pageParam: RQPageParam}) {
|
||||
const res = await getAgent().app.bsky.graph.getBlocks({
|
||||
@@ -28,3 +31,26 @@ export function useMyBlockedAccountsQuery() {
|
||||
getNextPageParam: lastPage => lastPage.cursor,
|
||||
})
|
||||
}
|
||||
|
||||
export function* findAllProfilesInQueryData(
|
||||
queryClient: QueryClient,
|
||||
did: string,
|
||||
): Generator<AppBskyActorDefs.ProfileView, void> {
|
||||
const queryDatas = queryClient.getQueriesData<
|
||||
InfiniteData<AppBskyGraphGetBlocks.OutputSchema>
|
||||
>({
|
||||
queryKey: ['my-blocked-accounts'],
|
||||
})
|
||||
for (const [_queryKey, queryData] of queryDatas) {
|
||||
if (!queryData?.pages) {
|
||||
continue
|
||||
}
|
||||
for (const page of queryData?.pages) {
|
||||
for (const block of page.blocks) {
|
||||
if (block.did === did) {
|
||||
yield block
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import {AppBskyGraphGetMutes} from '@atproto/api'
|
||||
import {useInfiniteQuery, InfiniteData, QueryKey} from '@tanstack/react-query'
|
||||
import {AppBskyActorDefs, AppBskyGraphGetMutes} from '@atproto/api'
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
InfiniteData,
|
||||
QueryClient,
|
||||
QueryKey,
|
||||
} from '@tanstack/react-query'
|
||||
|
||||
import {getAgent} from '#/state/session'
|
||||
import {STALE} from '#/state/queries'
|
||||
|
||||
export const RQKEY = () => ['my-muted-accounts']
|
||||
type RQPageParam = string | undefined
|
||||
@@ -15,7 +19,6 @@ export function useMyMutedAccountsQuery() {
|
||||
QueryKey,
|
||||
RQPageParam
|
||||
>({
|
||||
staleTime: STALE.MINUTES.ONE,
|
||||
queryKey: RQKEY(),
|
||||
async queryFn({pageParam}: {pageParam: RQPageParam}) {
|
||||
const res = await getAgent().app.bsky.graph.getMutes({
|
||||
@@ -28,3 +31,26 @@ export function useMyMutedAccountsQuery() {
|
||||
getNextPageParam: lastPage => lastPage.cursor,
|
||||
})
|
||||
}
|
||||
|
||||
export function* findAllProfilesInQueryData(
|
||||
queryClient: QueryClient,
|
||||
did: string,
|
||||
): Generator<AppBskyActorDefs.ProfileView, void> {
|
||||
const queryDatas = queryClient.getQueriesData<
|
||||
InfiniteData<AppBskyGraphGetMutes.OutputSchema>
|
||||
>({
|
||||
queryKey: ['my-muted-accounts'],
|
||||
})
|
||||
for (const [_queryKey, queryData] of queryDatas) {
|
||||
if (!queryData?.pages) {
|
||||
continue
|
||||
}
|
||||
for (const page of queryData?.pages) {
|
||||
for (const mute of page.mutes) {
|
||||
if (mute.did === did) {
|
||||
yield mute
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,55 +1,52 @@
|
||||
import {
|
||||
AppBskyFeedDefs,
|
||||
AppBskyFeedPost,
|
||||
AppBskyFeedRepost,
|
||||
AppBskyFeedLike,
|
||||
AppBskyNotificationListNotifications,
|
||||
BskyAgent,
|
||||
} from '@atproto/api'
|
||||
import chunk from 'lodash.chunk'
|
||||
import {useInfiniteQuery, InfiniteData, QueryKey} from '@tanstack/react-query'
|
||||
import {getAgent} from '../../session'
|
||||
import {useModerationOpts} from '../preferences'
|
||||
import {shouldFilterNotif} from './util'
|
||||
import {useMutedThreads} from '#/state/muted-threads'
|
||||
/**
|
||||
* NOTE
|
||||
* The ./unread.ts API:
|
||||
*
|
||||
* - Provides a `checkUnread()` function to sync with the server,
|
||||
* - Periodically calls `checkUnread()`, and
|
||||
* - Caches the first page of notifications.
|
||||
*
|
||||
* IMPORTANT: This query uses ./unread.ts's cache as its first page,
|
||||
* IMPORTANT: which means the cache-freshness of this query is driven by the unread API.
|
||||
*
|
||||
* Follow these rules:
|
||||
*
|
||||
* 1. Call `checkUnread()` if you want to fetch latest in the background.
|
||||
* 2. Call `checkUnread({invalidate: true})` if you want latest to sync into this query's results immediately.
|
||||
* 3. Don't call this query's `refetch()` if you're trying to sync latest; call `checkUnread()` instead.
|
||||
*/
|
||||
|
||||
import {AppBskyFeedDefs} from '@atproto/api'
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
InfiniteData,
|
||||
QueryKey,
|
||||
useQueryClient,
|
||||
QueryClient,
|
||||
} from '@tanstack/react-query'
|
||||
import {useModerationOpts} from '../preferences'
|
||||
import {useUnreadNotificationsApi} from './unread'
|
||||
import {fetchPage} from './util'
|
||||
import {FeedPage} from './types'
|
||||
import {useMutedThreads} from '#/state/muted-threads'
|
||||
import {STALE} from '..'
|
||||
import {embedViewRecordToPostView, getEmbeddedPost} from '../util'
|
||||
|
||||
export type {NotificationType, FeedNotification, FeedPage} from './types'
|
||||
|
||||
const GROUPABLE_REASONS = ['like', 'repost', 'follow']
|
||||
const PAGE_SIZE = 30
|
||||
const MS_1HR = 1e3 * 60 * 60
|
||||
const MS_2DAY = MS_1HR * 48
|
||||
|
||||
type RQPageParam = string | undefined
|
||||
type NotificationType =
|
||||
| 'post-like'
|
||||
| 'feedgen-like'
|
||||
| 'repost'
|
||||
| 'mention'
|
||||
| 'reply'
|
||||
| 'quote'
|
||||
| 'follow'
|
||||
| 'unknown'
|
||||
|
||||
export function RQKEY() {
|
||||
return ['notification-feed']
|
||||
}
|
||||
|
||||
export interface FeedNotification {
|
||||
_reactKey: string
|
||||
type: NotificationType
|
||||
notification: AppBskyNotificationListNotifications.Notification
|
||||
additional?: AppBskyNotificationListNotifications.Notification[]
|
||||
subjectUri?: string
|
||||
subject?: AppBskyFeedDefs.PostView
|
||||
}
|
||||
|
||||
export interface FeedPage {
|
||||
cursor: string | undefined
|
||||
items: FeedNotification[]
|
||||
}
|
||||
|
||||
export function useNotificationFeedQuery(opts?: {enabled?: boolean}) {
|
||||
const queryClient = useQueryClient()
|
||||
const moderationOpts = useModerationOpts()
|
||||
const threadMutes = useMutedThreads()
|
||||
const unreads = useUnreadNotificationsApi()
|
||||
const enabled = opts?.enabled !== false
|
||||
|
||||
return useInfiniteQuery<
|
||||
@@ -59,39 +56,30 @@ export function useNotificationFeedQuery(opts?: {enabled?: boolean}) {
|
||||
QueryKey,
|
||||
RQPageParam
|
||||
>({
|
||||
staleTime: STALE.INFINITY,
|
||||
queryKey: RQKEY(),
|
||||
async queryFn({pageParam}: {pageParam: RQPageParam}) {
|
||||
const res = await getAgent().listNotifications({
|
||||
limit: PAGE_SIZE,
|
||||
cursor: pageParam,
|
||||
})
|
||||
|
||||
// filter out notifs by mod rules
|
||||
const notifs = res.data.notifications.filter(
|
||||
notif => !shouldFilterNotif(notif, moderationOpts),
|
||||
)
|
||||
|
||||
// group notifications which are essentially similar (follows, likes on a post)
|
||||
let notifsGrouped = groupNotifications(notifs)
|
||||
|
||||
// we fetch subjects of notifications (usually posts) now instead of lazily
|
||||
// in the UI to avoid relayouts
|
||||
const subjects = await fetchSubjects(getAgent(), notifsGrouped)
|
||||
for (const notif of notifsGrouped) {
|
||||
if (notif.subjectUri) {
|
||||
notif.subject = subjects.get(notif.subjectUri)
|
||||
}
|
||||
let page
|
||||
if (!pageParam) {
|
||||
// for the first page, we check the cached page held by the unread-checker first
|
||||
page = unreads.getCachedUnreadPage()
|
||||
}
|
||||
if (!page) {
|
||||
page = await fetchPage({
|
||||
limit: PAGE_SIZE,
|
||||
cursor: pageParam,
|
||||
queryClient,
|
||||
moderationOpts,
|
||||
threadMutes,
|
||||
})
|
||||
}
|
||||
|
||||
// apply thread muting
|
||||
notifsGrouped = notifsGrouped.filter(
|
||||
notif => !isThreadMuted(notif, threadMutes),
|
||||
)
|
||||
|
||||
return {
|
||||
cursor: res.data.cursor,
|
||||
items: notifsGrouped,
|
||||
// if the first page has an unread, mark all read
|
||||
if (!pageParam && page.items[0] && !page.items[0].notification.isRead) {
|
||||
unreads.markAllRead()
|
||||
}
|
||||
|
||||
return page
|
||||
},
|
||||
initialPageParam: undefined,
|
||||
getNextPageParam: lastPage => lastPage.cursor,
|
||||
@@ -99,113 +87,44 @@ export function useNotificationFeedQuery(opts?: {enabled?: boolean}) {
|
||||
})
|
||||
}
|
||||
|
||||
function groupNotifications(
|
||||
notifs: AppBskyNotificationListNotifications.Notification[],
|
||||
): FeedNotification[] {
|
||||
const groupedNotifs: FeedNotification[] = []
|
||||
for (const notif of notifs) {
|
||||
const ts = +new Date(notif.indexedAt)
|
||||
let grouped = false
|
||||
if (GROUPABLE_REASONS.includes(notif.reason)) {
|
||||
for (const groupedNotif of groupedNotifs) {
|
||||
const ts2 = +new Date(groupedNotif.notification.indexedAt)
|
||||
if (
|
||||
Math.abs(ts2 - ts) < MS_2DAY &&
|
||||
notif.reason === groupedNotif.notification.reason &&
|
||||
notif.reasonSubject === groupedNotif.notification.reasonSubject &&
|
||||
notif.author.did !== groupedNotif.notification.author.did
|
||||
) {
|
||||
groupedNotif.additional = groupedNotif.additional || []
|
||||
groupedNotif.additional.push(notif)
|
||||
grouped = true
|
||||
break
|
||||
/**
|
||||
* This helper is used by the post-thread placeholder function to
|
||||
* find a post in the query-data cache
|
||||
*/
|
||||
export function findPostInQueryData(
|
||||
queryClient: QueryClient,
|
||||
uri: string,
|
||||
): AppBskyFeedDefs.PostView | undefined {
|
||||
const generator = findAllPostsInQueryData(queryClient, uri)
|
||||
const result = generator.next()
|
||||
if (result.done) {
|
||||
return undefined
|
||||
} else {
|
||||
return result.value
|
||||
}
|
||||
}
|
||||
|
||||
export function* findAllPostsInQueryData(
|
||||
queryClient: QueryClient,
|
||||
uri: string,
|
||||
): Generator<AppBskyFeedDefs.PostView, void> {
|
||||
const queryDatas = queryClient.getQueriesData<InfiniteData<FeedPage>>({
|
||||
queryKey: ['notification-feed'],
|
||||
})
|
||||
for (const [_queryKey, queryData] of queryDatas) {
|
||||
if (!queryData?.pages) {
|
||||
continue
|
||||
}
|
||||
for (const page of queryData?.pages) {
|
||||
for (const item of page.items) {
|
||||
if (item.subject?.uri === uri) {
|
||||
yield item.subject
|
||||
}
|
||||
const quotedPost = getEmbeddedPost(item.subject?.embed)
|
||||
if (quotedPost?.uri === uri) {
|
||||
yield embedViewRecordToPostView(quotedPost)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!grouped) {
|
||||
const type = toKnownType(notif)
|
||||
groupedNotifs.push({
|
||||
_reactKey: `notif-${notif.uri}`,
|
||||
type,
|
||||
notification: notif,
|
||||
subjectUri: getSubjectUri(type, notif),
|
||||
})
|
||||
}
|
||||
}
|
||||
return groupedNotifs
|
||||
}
|
||||
|
||||
async function fetchSubjects(
|
||||
agent: BskyAgent,
|
||||
groupedNotifs: FeedNotification[],
|
||||
): Promise<Map<string, AppBskyFeedDefs.PostView>> {
|
||||
const uris = new Set<string>()
|
||||
for (const notif of groupedNotifs) {
|
||||
if (notif.subjectUri) {
|
||||
uris.add(notif.subjectUri)
|
||||
}
|
||||
}
|
||||
const uriChunks = chunk(Array.from(uris), 25)
|
||||
const postsChunks = await Promise.all(
|
||||
uriChunks.map(uris =>
|
||||
agent.app.bsky.feed.getPosts({uris}).then(res => res.data.posts),
|
||||
),
|
||||
)
|
||||
const map = new Map<string, AppBskyFeedDefs.PostView>()
|
||||
for (const post of postsChunks.flat()) {
|
||||
if (
|
||||
AppBskyFeedPost.isRecord(post.record) &&
|
||||
AppBskyFeedPost.validateRecord(post.record).success
|
||||
) {
|
||||
map.set(post.uri, post)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
function toKnownType(
|
||||
notif: AppBskyNotificationListNotifications.Notification,
|
||||
): NotificationType {
|
||||
if (notif.reason === 'like') {
|
||||
if (notif.reasonSubject?.includes('feed.generator')) {
|
||||
return 'feedgen-like'
|
||||
}
|
||||
return 'post-like'
|
||||
}
|
||||
if (
|
||||
notif.reason === 'repost' ||
|
||||
notif.reason === 'mention' ||
|
||||
notif.reason === 'reply' ||
|
||||
notif.reason === 'quote' ||
|
||||
notif.reason === 'follow'
|
||||
) {
|
||||
return notif.reason as NotificationType
|
||||
}
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
function getSubjectUri(
|
||||
type: NotificationType,
|
||||
notif: AppBskyNotificationListNotifications.Notification,
|
||||
): string | undefined {
|
||||
if (type === 'reply' || type === 'quote' || type === 'mention') {
|
||||
return notif.uri
|
||||
} else if (type === 'post-like' || type === 'repost') {
|
||||
if (
|
||||
AppBskyFeedRepost.isRecord(notif.record) ||
|
||||
AppBskyFeedLike.isRecord(notif.record)
|
||||
) {
|
||||
return typeof notif.record.subject?.uri === 'string'
|
||||
? notif.record.subject?.uri
|
||||
: undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isThreadMuted(notif: FeedNotification, mutes: string[]): boolean {
|
||||
if (!notif.subject) {
|
||||
return false
|
||||
}
|
||||
const record = notif.subject.record as AppBskyFeedPost.Record // assured in fetchSubjects()
|
||||
return mutes.includes(record.reply?.root.uri || notif.subject.uri)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
AppBskyNotificationListNotifications,
|
||||
AppBskyFeedDefs,
|
||||
} from '@atproto/api'
|
||||
|
||||
export type NotificationType =
|
||||
| 'post-like'
|
||||
| 'feedgen-like'
|
||||
| 'repost'
|
||||
| 'mention'
|
||||
| 'reply'
|
||||
| 'quote'
|
||||
| 'follow'
|
||||
| 'unknown'
|
||||
|
||||
export interface FeedNotification {
|
||||
_reactKey: string
|
||||
type: NotificationType
|
||||
notification: AppBskyNotificationListNotifications.Notification
|
||||
additional?: AppBskyNotificationListNotifications.Notification[]
|
||||
subjectUri?: string
|
||||
subject?: AppBskyFeedDefs.PostView
|
||||
}
|
||||
|
||||
export interface FeedPage {
|
||||
cursor: string | undefined
|
||||
items: FeedNotification[]
|
||||
}
|
||||
|
||||
export interface CachedFeedPage {
|
||||
sessDid: string // used to invalidate on session changes
|
||||
syncedAt: Date
|
||||
data: FeedPage | undefined
|
||||
}
|
||||
@@ -1,10 +1,20 @@
|
||||
/**
|
||||
* A kind of companion API to ./feed.ts. See that file for more info.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import * as Notifications from 'expo-notifications'
|
||||
import {useQueryClient} from '@tanstack/react-query'
|
||||
import BroadcastChannel from '#/lib/broadcast'
|
||||
import {useSession, getAgent} from '#/state/session'
|
||||
import {useModerationOpts} from '../preferences'
|
||||
import {shouldFilterNotif} from './util'
|
||||
import {fetchPage} from './util'
|
||||
import {CachedFeedPage, FeedPage} from './types'
|
||||
import {isNative} from '#/platform/detection'
|
||||
import {useMutedThreads} from '#/state/muted-threads'
|
||||
import {RQKEY as RQKEY_NOTIFS} from './feed'
|
||||
import {logger} from '#/logger'
|
||||
import {truncateAndInvalidate} from '../util'
|
||||
|
||||
const UPDATE_INTERVAL = 30 * 1e3 // 30sec
|
||||
|
||||
@@ -14,7 +24,8 @@ type StateContext = string
|
||||
|
||||
interface ApiContext {
|
||||
markAllRead: () => Promise<void>
|
||||
checkUnread: () => Promise<void>
|
||||
checkUnread: (opts?: {invalidate?: boolean}) => Promise<void>
|
||||
getCachedUnreadPage: () => FeedPage | undefined
|
||||
}
|
||||
|
||||
const stateContext = React.createContext<StateContext>('')
|
||||
@@ -22,16 +33,23 @@ const stateContext = React.createContext<StateContext>('')
|
||||
const apiContext = React.createContext<ApiContext>({
|
||||
async markAllRead() {},
|
||||
async checkUnread() {},
|
||||
getCachedUnreadPage: () => undefined,
|
||||
})
|
||||
|
||||
export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
const {hasSession} = useSession()
|
||||
const {hasSession, currentAccount} = useSession()
|
||||
const queryClient = useQueryClient()
|
||||
const moderationOpts = useModerationOpts()
|
||||
const threadMutes = useMutedThreads()
|
||||
|
||||
const [numUnread, setNumUnread] = React.useState('')
|
||||
|
||||
const checkUnreadRef = React.useRef<(() => Promise<void>) | null>(null)
|
||||
const lastSyncRef = React.useRef<Date>(new Date())
|
||||
const checkUnreadRef = React.useRef<ApiContext['checkUnread'] | null>(null)
|
||||
const cacheRef = React.useRef<CachedFeedPage>({
|
||||
sessDid: currentAccount?.did || '',
|
||||
syncedAt: new Date(),
|
||||
data: undefined,
|
||||
})
|
||||
|
||||
// periodic sync
|
||||
React.useEffect(() => {
|
||||
@@ -46,14 +64,18 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
// listen for broadcasts
|
||||
React.useEffect(() => {
|
||||
const listener = ({data}: MessageEvent) => {
|
||||
lastSyncRef.current = new Date()
|
||||
cacheRef.current = {
|
||||
sessDid: currentAccount?.did || '',
|
||||
syncedAt: new Date(),
|
||||
data: undefined,
|
||||
}
|
||||
setNumUnread(data.event)
|
||||
}
|
||||
broadcast.addEventListener('message', listener)
|
||||
return () => {
|
||||
broadcast.removeEventListener('message', listener)
|
||||
}
|
||||
}, [setNumUnread])
|
||||
}, [setNumUnread, currentAccount])
|
||||
|
||||
// create API
|
||||
const api = React.useMemo<ApiContext>(() => {
|
||||
@@ -61,7 +83,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
async markAllRead() {
|
||||
// update server
|
||||
await getAgent().updateSeenNotifications(
|
||||
lastSyncRef.current.toISOString(),
|
||||
cacheRef.current.syncedAt.toISOString(),
|
||||
)
|
||||
|
||||
// update & broadcast
|
||||
@@ -69,34 +91,59 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
broadcast.postMessage({event: ''})
|
||||
},
|
||||
|
||||
async checkUnread() {
|
||||
// count
|
||||
const res = await getAgent().listNotifications({limit: 40})
|
||||
const filtered = res.data.notifications.filter(
|
||||
notif => !notif.isRead && !shouldFilterNotif(notif, moderationOpts),
|
||||
)
|
||||
const num =
|
||||
filtered.length >= 30
|
||||
? '30+'
|
||||
: filtered.length === 0
|
||||
? ''
|
||||
: String(filtered.length)
|
||||
if (isNative) {
|
||||
Notifications.setBadgeCountAsync(Math.min(filtered.length, 30))
|
||||
async checkUnread({invalidate}: {invalidate?: boolean} = {}) {
|
||||
try {
|
||||
if (!getAgent().session) return
|
||||
|
||||
// count
|
||||
const page = await fetchPage({
|
||||
cursor: undefined,
|
||||
limit: 40,
|
||||
queryClient,
|
||||
moderationOpts,
|
||||
threadMutes,
|
||||
})
|
||||
const unreadCount = countUnread(page)
|
||||
const unreadCountStr =
|
||||
unreadCount >= 30
|
||||
? '30+'
|
||||
: unreadCount === 0
|
||||
? ''
|
||||
: String(unreadCount)
|
||||
if (isNative) {
|
||||
Notifications.setBadgeCountAsync(Math.min(unreadCount, 30))
|
||||
}
|
||||
|
||||
// track last sync
|
||||
const now = new Date()
|
||||
const lastIndexed =
|
||||
page.items[0] && new Date(page.items[0].notification.indexedAt)
|
||||
cacheRef.current = {
|
||||
sessDid: currentAccount?.did || '',
|
||||
data: page,
|
||||
syncedAt: !lastIndexed || now > lastIndexed ? now : lastIndexed,
|
||||
}
|
||||
|
||||
// update & broadcast
|
||||
setNumUnread(unreadCountStr)
|
||||
if (invalidate) {
|
||||
truncateAndInvalidate(queryClient, RQKEY_NOTIFS())
|
||||
}
|
||||
broadcast.postMessage({event: unreadCountStr})
|
||||
} catch (e) {
|
||||
logger.error('Failed to check unread notifications', {error: e})
|
||||
}
|
||||
},
|
||||
|
||||
// track last sync
|
||||
const now = new Date()
|
||||
const lastIndexed = filtered[0] && new Date(filtered[0].indexedAt)
|
||||
lastSyncRef.current =
|
||||
!lastIndexed || now > lastIndexed ? now : lastIndexed
|
||||
|
||||
// update & broadcast
|
||||
setNumUnread(num)
|
||||
broadcast.postMessage({event: num})
|
||||
getCachedUnreadPage() {
|
||||
// return cached page if was for the current user
|
||||
// (protects against session changes serving data from the past session)
|
||||
if (cacheRef.current.sessDid === currentAccount?.did) {
|
||||
return cacheRef.current.data
|
||||
}
|
||||
},
|
||||
}
|
||||
}, [setNumUnread, moderationOpts])
|
||||
}, [setNumUnread, queryClient, moderationOpts, threadMutes, currentAccount])
|
||||
checkUnreadRef.current = api.checkUnread
|
||||
|
||||
return (
|
||||
@@ -113,3 +160,20 @@ export function useUnreadNotifications() {
|
||||
export function useUnreadNotificationsApi() {
|
||||
return React.useContext(apiContext)
|
||||
}
|
||||
|
||||
function countUnread(page: FeedPage) {
|
||||
let num = 0
|
||||
for (const item of page.items) {
|
||||
if (!item.notification.isRead) {
|
||||
num++
|
||||
}
|
||||
if (item.additional) {
|
||||
for (const item2 of item.additional) {
|
||||
if (!item2.isRead) {
|
||||
num++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return num
|
||||
}
|
||||
|
||||
@@ -3,10 +3,78 @@ import {
|
||||
ModerationOpts,
|
||||
moderateProfile,
|
||||
moderatePost,
|
||||
AppBskyFeedDefs,
|
||||
AppBskyFeedPost,
|
||||
AppBskyFeedRepost,
|
||||
AppBskyFeedLike,
|
||||
} from '@atproto/api'
|
||||
import chunk from 'lodash.chunk'
|
||||
import {QueryClient} from '@tanstack/react-query'
|
||||
import {getAgent} from '../../session'
|
||||
import {precacheProfile as precacheResolvedUri} from '../resolve-uri'
|
||||
import {NotificationType, FeedNotification, FeedPage} from './types'
|
||||
|
||||
const GROUPABLE_REASONS = ['like', 'repost', 'follow']
|
||||
const MS_1HR = 1e3 * 60 * 60
|
||||
const MS_2DAY = MS_1HR * 48
|
||||
|
||||
// exported api
|
||||
// =
|
||||
|
||||
export async function fetchPage({
|
||||
cursor,
|
||||
limit,
|
||||
queryClient,
|
||||
moderationOpts,
|
||||
threadMutes,
|
||||
}: {
|
||||
cursor: string | undefined
|
||||
limit: number
|
||||
queryClient: QueryClient
|
||||
moderationOpts: ModerationOpts | undefined
|
||||
threadMutes: string[]
|
||||
}): Promise<FeedPage> {
|
||||
const res = await getAgent().listNotifications({
|
||||
limit,
|
||||
cursor,
|
||||
})
|
||||
|
||||
// filter out notifs by mod rules
|
||||
const notifs = res.data.notifications.filter(
|
||||
notif => !shouldFilterNotif(notif, moderationOpts),
|
||||
)
|
||||
|
||||
// group notifications which are essentially similar (follows, likes on a post)
|
||||
let notifsGrouped = groupNotifications(notifs)
|
||||
|
||||
// we fetch subjects of notifications (usually posts) now instead of lazily
|
||||
// in the UI to avoid relayouts
|
||||
const subjects = await fetchSubjects(notifsGrouped)
|
||||
for (const notif of notifsGrouped) {
|
||||
if (notif.subjectUri) {
|
||||
notif.subject = subjects.get(notif.subjectUri)
|
||||
if (notif.subject) {
|
||||
precacheResolvedUri(queryClient, notif.subject.author) // precache the handle->did resolution
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// apply thread muting
|
||||
notifsGrouped = notifsGrouped.filter(
|
||||
notif => !isThreadMuted(notif, threadMutes),
|
||||
)
|
||||
|
||||
return {
|
||||
cursor: res.data.cursor,
|
||||
items: notifsGrouped,
|
||||
}
|
||||
}
|
||||
|
||||
// internal methods
|
||||
// =
|
||||
|
||||
// TODO this should be in the sdk as moderateNotification -prf
|
||||
export function shouldFilterNotif(
|
||||
function shouldFilterNotif(
|
||||
notif: AppBskyNotificationListNotifications.Notification,
|
||||
moderationOpts: ModerationOpts | undefined,
|
||||
): boolean {
|
||||
@@ -36,3 +104,116 @@ export function shouldFilterNotif(
|
||||
// (this requires fetching the post)
|
||||
return false
|
||||
}
|
||||
|
||||
function groupNotifications(
|
||||
notifs: AppBskyNotificationListNotifications.Notification[],
|
||||
): FeedNotification[] {
|
||||
const groupedNotifs: FeedNotification[] = []
|
||||
for (const notif of notifs) {
|
||||
const ts = +new Date(notif.indexedAt)
|
||||
let grouped = false
|
||||
if (GROUPABLE_REASONS.includes(notif.reason)) {
|
||||
for (const groupedNotif of groupedNotifs) {
|
||||
const ts2 = +new Date(groupedNotif.notification.indexedAt)
|
||||
if (
|
||||
Math.abs(ts2 - ts) < MS_2DAY &&
|
||||
notif.reason === groupedNotif.notification.reason &&
|
||||
notif.reasonSubject === groupedNotif.notification.reasonSubject &&
|
||||
notif.author.did !== groupedNotif.notification.author.did &&
|
||||
notif.isRead === groupedNotif.notification.isRead
|
||||
) {
|
||||
groupedNotif.additional = groupedNotif.additional || []
|
||||
groupedNotif.additional.push(notif)
|
||||
grouped = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!grouped) {
|
||||
const type = toKnownType(notif)
|
||||
groupedNotifs.push({
|
||||
_reactKey: `notif-${notif.uri}`,
|
||||
type,
|
||||
notification: notif,
|
||||
subjectUri: getSubjectUri(type, notif),
|
||||
})
|
||||
}
|
||||
}
|
||||
return groupedNotifs
|
||||
}
|
||||
|
||||
async function fetchSubjects(
|
||||
groupedNotifs: FeedNotification[],
|
||||
): Promise<Map<string, AppBskyFeedDefs.PostView>> {
|
||||
const uris = new Set<string>()
|
||||
for (const notif of groupedNotifs) {
|
||||
if (notif.subjectUri) {
|
||||
uris.add(notif.subjectUri)
|
||||
}
|
||||
}
|
||||
const uriChunks = chunk(Array.from(uris), 25)
|
||||
const postsChunks = await Promise.all(
|
||||
uriChunks.map(uris =>
|
||||
getAgent()
|
||||
.app.bsky.feed.getPosts({uris})
|
||||
.then(res => res.data.posts),
|
||||
),
|
||||
)
|
||||
const map = new Map<string, AppBskyFeedDefs.PostView>()
|
||||
for (const post of postsChunks.flat()) {
|
||||
if (
|
||||
AppBskyFeedPost.isRecord(post.record) &&
|
||||
AppBskyFeedPost.validateRecord(post.record).success
|
||||
) {
|
||||
map.set(post.uri, post)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
function toKnownType(
|
||||
notif: AppBskyNotificationListNotifications.Notification,
|
||||
): NotificationType {
|
||||
if (notif.reason === 'like') {
|
||||
if (notif.reasonSubject?.includes('feed.generator')) {
|
||||
return 'feedgen-like'
|
||||
}
|
||||
return 'post-like'
|
||||
}
|
||||
if (
|
||||
notif.reason === 'repost' ||
|
||||
notif.reason === 'mention' ||
|
||||
notif.reason === 'reply' ||
|
||||
notif.reason === 'quote' ||
|
||||
notif.reason === 'follow'
|
||||
) {
|
||||
return notif.reason as NotificationType
|
||||
}
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
function getSubjectUri(
|
||||
type: NotificationType,
|
||||
notif: AppBskyNotificationListNotifications.Notification,
|
||||
): string | undefined {
|
||||
if (type === 'reply' || type === 'quote' || type === 'mention') {
|
||||
return notif.uri
|
||||
} else if (type === 'post-like' || type === 'repost') {
|
||||
if (
|
||||
AppBskyFeedRepost.isRecord(notif.record) ||
|
||||
AppBskyFeedLike.isRecord(notif.record)
|
||||
) {
|
||||
return typeof notif.record.subject?.uri === 'string'
|
||||
? notif.record.subject?.uri
|
||||
: undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isThreadMuted(notif: FeedNotification, mutes: string[]): boolean {
|
||||
if (!notif.subject) {
|
||||
return false
|
||||
}
|
||||
const record = notif.subject.record as AppBskyFeedPost.Record // assured in fetchSubjects()
|
||||
return mutes.includes(record.reply?.root.uri || notif.subject.uri)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user