Merge branch 'main' into inherit_system_theme

zio/stable
Jaz 2023-05-30 18:25:29 -07:00 committed by GitHub
commit 09ade363fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
136 changed files with 5771 additions and 2428 deletions

View File

@ -1,6 +1,10 @@
module.exports = { module.exports = {
root: true, root: true,
extends: ['@react-native-community', 'plugin:react-native-a11y/ios'], extends: [
'@react-native-community',
'plugin:react-native-a11y/ios',
'prettier',
],
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'detox'], plugins: ['@typescript-eslint', 'detox'],
ignorePatterns: [ ignorePatterns: [

View File

@ -17,7 +17,7 @@ ENV CGO_ENABLED=1
COPY . . COPY . .
# #
# Generate the Javascript webpack. # Generate the JavaScript webpack.
# #
RUN mkdir --parents $NVM_DIR && \ RUN mkdir --parents $NVM_DIR && \
wget \ wget \
@ -36,7 +36,7 @@ RUN \. "$NVM_DIR/nvm.sh" && \
RUN find ./bskyweb/static && find ./web-build/static RUN find ./bskyweb/static && find ./web-build/static
# #
# Generate the bksyweb Go binary. # Generate the bskyweb Go binary.
# #
RUN cd bskyweb/ && \ RUN cd bskyweb/ && \
go mod download && \ go mod download && \

View File

@ -2,7 +2,7 @@
Welcome friends! This is the codebase for the Bluesky Social app. It serves as a resource to engineers building on the [AT Protocol](https://atproto.com). Welcome friends! This is the codebase for the Bluesky Social app. It serves as a resource to engineers building on the [AT Protocol](https://atproto.com).
- **Web: [staging.bsky.app](https://staging.bsky.app)** - **Web: [bsky.app](https://bsky.app)**
- **iOS: [App Store](https://apps.apple.com/us/app/bluesky-social/id6444370199)** - **iOS: [App Store](https://apps.apple.com/us/app/bluesky-social/id6444370199)**
- **Android: [Play Store](https://play.google.com/store/apps/details?id=xyz.blueskyweb.app&hl=en_US&gl=US)** - **Android: [Play Store](https://play.google.com/store/apps/details?id=xyz.blueskyweb.app&hl=en_US&gl=US)**

View File

@ -1,106 +1,4 @@
import { import {LikelyType, getLikelyType} from '../../src/lib/link-meta/link-meta'
LikelyType,
getLinkMeta,
getLikelyType,
} from '../../src/lib/link-meta/link-meta'
import {exampleComHtml} from './__mocks__/exampleComHtml'
import {BskyAgent} from '@atproto/api'
import {DEFAULT_SERVICE, RootStoreModel} from '../../src/state'
describe('getLinkMeta', () => {
let rootStore: RootStoreModel
beforeEach(() => {
rootStore = new RootStoreModel(new BskyAgent({service: DEFAULT_SERVICE}))
})
const inputs = [
'',
'httpbadurl',
'https://example.com',
'https://example.com/index.html',
'https://example.com/image.png',
'https://example.com/video.avi',
'https://example.com/audio.ogg',
'https://example.com/text.txt',
'https://example.com/javascript.js',
'https://bsky.app/',
'https://bsky.app/index.html',
]
const outputs = [
{
error: 'Invalid URL',
likelyType: LikelyType.Other,
url: '',
},
{
error: 'Invalid URL',
likelyType: LikelyType.Other,
url: 'httpbadurl',
},
{
likelyType: LikelyType.HTML,
url: 'https://example.com',
title: 'Example Domain',
description: 'An example website',
},
{
likelyType: LikelyType.HTML,
url: 'https://example.com/index.html',
title: 'Example Domain',
description: 'An example website',
},
{
likelyType: LikelyType.Image,
url: 'https://example.com/image.png',
},
{
likelyType: LikelyType.Video,
url: 'https://example.com/video.avi',
},
{
likelyType: LikelyType.Audio,
url: 'https://example.com/audio.ogg',
},
{
likelyType: LikelyType.Text,
url: 'https://example.com/text.txt',
},
{
likelyType: LikelyType.Other,
url: 'https://example.com/javascript.js',
},
{
likelyType: LikelyType.AtpData,
url: '/',
},
{
likelyType: LikelyType.AtpData,
url: '/index.html',
},
{
likelyType: LikelyType.Other,
url: '',
title: '',
},
]
it('correctly handles a set of text inputs', async () => {
for (let i = 0; i < inputs.length; i++) {
global.fetch = jest.fn().mockImplementationOnce(() => {
return new Promise((resolve, _reject) => {
resolve({
ok: true,
status: 200,
text: () => exampleComHtml,
})
})
})
const input = inputs[i]
const output = await getLinkMeta(rootStore, input)
expect(output).toEqual(outputs[i])
}
})
})
describe('getLikelyType', () => { describe('getLikelyType', () => {
it('correctly handles non-parsed url', async () => { it('correctly handles non-parsed url', async () => {

View File

@ -48,7 +48,7 @@ describe('detectLinkables', () => {
'Classic article https://socket3.wordpress.com/2018/02/03/designing-windows-95s-user-interface/ ', 'Classic article https://socket3.wordpress.com/2018/02/03/designing-windows-95s-user-interface/ ',
'https://foo.com https://bar.com/whatever https://baz.com', 'https://foo.com https://bar.com/whatever https://baz.com',
'punctuation https://foo.com, https://bar.com/whatever; https://baz.com.', 'punctuation https://foo.com, https://bar.com/whatever; https://baz.com.',
'parenthentical (https://foo.com)', 'parenthetical (https://foo.com)',
'except for https://foo.com/thing_(cool)', 'except for https://foo.com/thing_(cool)',
] ]
const outputs = [ const outputs = [
@ -112,7 +112,7 @@ describe('detectLinkables', () => {
{link: 'https://baz.com'}, {link: 'https://baz.com'},
'.', '.',
], ],
['parenthentical (', {link: 'https://foo.com'}, ')'], ['parenthetical (', {link: 'https://foo.com'}, ')'],
['except for ', {link: 'https://foo.com/thing_(cool)'}], ['except for ', {link: 'https://foo.com/thing_(cool)'}],
] ]
it('correctly handles a set of text inputs', () => { it('correctly handles a set of text inputs', () => {
@ -176,16 +176,20 @@ describe('ago', () => {
new Date().setMinutes(new Date().getMinutes() - 10), new Date().setMinutes(new Date().getMinutes() - 10),
new Date().setHours(new Date().getHours() - 1), new Date().setHours(new Date().getHours() - 1),
new Date().setDate(new Date().getDate() - 1), new Date().setDate(new Date().getDate() - 1),
new Date().setDate(new Date().getDate() - 6),
new Date().setDate(new Date().getDate() - 7),
new Date().setMonth(new Date().getMonth() - 1), new Date().setMonth(new Date().getMonth() - 1),
] ]
const outputs = [ const outputs = [
new Date(1671461038).toLocaleDateString(), new Date(1671461038).toLocaleDateString('en-us', {year: 'numeric', month: 'short', day: 'numeric'}),
new Date('04 Dec 1995 00:12:00 GMT').toLocaleDateString(), new Date('04 Dec 1995 00:12:00 GMT').toLocaleDateString('en-us', {year: 'numeric', month: 'short', day: 'numeric'}),
'0s', '0s',
'10m', '10m',
'1h', '1h',
'1d', '1d',
'1mo', '6d',
new Date(new Date().setDate(new Date().getDate() - 7)).toLocaleDateString('en-us', {year: 'numeric', month: 'short', day: 'numeric'}),
new Date(new Date().setMonth(new Date().getMonth() - 1)).toLocaleDateString('en-us', {year: 'numeric', month: 'short', day: 'numeric'}),
] ]
it('correctly calculates how much time passed, in a string', () => { it('correctly calculates how much time passed, in a string', () => {

View File

@ -4,7 +4,7 @@
"slug": "bluesky", "slug": "bluesky",
"scheme": "bluesky", "scheme": "bluesky",
"owner": "blueskysocial", "owner": "blueskysocial",
"version": "1.28.0", "version": "1.29.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/icon.png", "icon": "./assets/icon.png",
"userInterfaceStyle": "light", "userInterfaceStyle": "light",
@ -40,7 +40,7 @@
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, },
"android": { "android": {
"versionCode": 14, "versionCode": 15,
"adaptiveIcon": { "adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png", "foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"

View File

@ -2,7 +2,7 @@
### SPA Bundle (monolithic static javascript file) ### SPA Bundle (monolithic static javascript file)
To build the SPA bundle (`bundle.web.js`), first get a Javascript development To build the SPA bundle (`bundle.web.js`), first get a JavaScript development
environment set up. Either follow the top-level README, or something quick environment set up. Either follow the top-level README, or something quick
like: like:

1
bskyweb/cmd/bskyweb/.gitignore vendored 100644
View File

@ -0,0 +1 @@
bskyweb

View File

@ -2,8 +2,10 @@ package main
import ( import (
"context" "context"
"encoding/json"
"fmt" "fmt"
"io/fs" "io/fs"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@ -62,6 +64,7 @@ func serve(cctx *cli.Context) error {
staticHandler := http.FileServer(func() http.FileSystem { staticHandler := http.FileServer(func() http.FileSystem {
if debug { if debug {
log.Debugf("serving static file from the local file system")
return http.FS(os.DirFS("static")) return http.FS(os.DirFS("static"))
} }
fsys, err := fs.Sub(bskyweb.StaticFS, "static") fsys, err := fs.Sub(bskyweb.StaticFS, "static")
@ -98,13 +101,22 @@ func serve(cctx *cli.Context) error {
RedirectCode: http.StatusFound, RedirectCode: http.StatusFound,
})) }))
//
// configure routes // configure routes
//
// static files
e.GET("/robots.txt", echo.WrapHandler(staticHandler)) e.GET("/robots.txt", echo.WrapHandler(staticHandler))
e.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", staticHandler))) e.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", staticHandler)))
e.GET("/.well-known/*", echo.WrapHandler(staticHandler))
// home
e.GET("/", server.WebHome) e.GET("/", server.WebHome)
// generic routes // generic routes
e.GET("/search", server.WebGeneric) e.GET("/search", server.WebGeneric)
e.GET("/search/feeds", server.WebGeneric)
e.GET("/feeds", server.WebGeneric)
e.GET("/notifications", server.WebGeneric) e.GET("/notifications", server.WebGeneric)
e.GET("/moderation", server.WebGeneric) e.GET("/moderation", server.WebGeneric)
e.GET("/moderation/mute-lists", server.WebGeneric) e.GET("/moderation/mute-lists", server.WebGeneric)
@ -112,6 +124,7 @@ func serve(cctx *cli.Context) error {
e.GET("/moderation/blocked-accounts", server.WebGeneric) e.GET("/moderation/blocked-accounts", server.WebGeneric)
e.GET("/settings", server.WebGeneric) e.GET("/settings", server.WebGeneric)
e.GET("/settings/app-passwords", server.WebGeneric) e.GET("/settings/app-passwords", server.WebGeneric)
e.GET("/settings/saved-feeds", server.WebGeneric)
e.GET("/sys/debug", server.WebGeneric) e.GET("/sys/debug", server.WebGeneric)
e.GET("/sys/log", server.WebGeneric) e.GET("/sys/log", server.WebGeneric)
e.GET("/support", server.WebGeneric) e.GET("/support", server.WebGeneric)
@ -125,6 +138,8 @@ func serve(cctx *cli.Context) error {
e.GET("/profile/:handle/follows", server.WebGeneric) e.GET("/profile/:handle/follows", server.WebGeneric)
e.GET("/profile/:handle/followers", server.WebGeneric) e.GET("/profile/:handle/followers", server.WebGeneric)
e.GET("/profile/:handle/lists/:rkey", server.WebGeneric) e.GET("/profile/:handle/lists/:rkey", server.WebGeneric)
e.GET("/profile/:handle/feed/:rkey", server.WebGeneric)
e.GET("/profile/:handle/feed/:rkey/liked-by", server.WebGeneric)
// post endpoints; only first populates info // post endpoints; only first populates info
e.GET("/profile/:handle/post/:rkey", server.WebPost) e.GET("/profile/:handle/post/:rkey", server.WebPost)
@ -132,11 +147,36 @@ func serve(cctx *cli.Context) error {
e.GET("/profile/:handle/post/:rkey/reposted-by", server.WebGeneric) e.GET("/profile/:handle/post/:rkey/reposted-by", server.WebGeneric)
// Mailmodo // Mailmodo
e.POST("/waitlist", func(c echo.Context) error { e.POST("/api/waitlist", func(c echo.Context) error {
email := strings.TrimSpace(c.FormValue("email")) type jsonError struct {
if err := mailmodo.AddToList(c.Request().Context(), mailmodoListName, email); err != nil { Error string `json:"error"`
}
// Read the API request.
type apiRequest struct {
Email string `json:"email"`
}
bodyReader := http.MaxBytesReader(c.Response(), c.Request().Body, 16*1024)
payload, err := ioutil.ReadAll(bodyReader)
if err != nil {
return err return err
} }
var req apiRequest
if err := json.Unmarshal(payload, &req); err != nil {
return c.JSON(http.StatusBadRequest, jsonError{Error: "Invalid API request"})
}
if req.Email == "" {
return c.JSON(http.StatusBadRequest, jsonError{Error: "Please enter a valid email address."})
}
if err := mailmodo.AddToList(c.Request().Context(), mailmodoListName, req.Email); err != nil {
log.Errorf("adding email to waitlist failed: %s", err)
return c.JSON(http.StatusBadRequest, jsonError{
Error: "Storing email in waitlist failed. Please enter a valid email address.",
})
}
return c.JSON(http.StatusOK, map[string]bool{"success": true}) return c.JSON(http.StatusOK, map[string]bool{"success": true})
}) })

View File

@ -0,0 +1,13 @@
{
"applinks": {
"apps": [],
"details": [
{
"appID": "B3LX46C5HS.xyz.blueskyweb.app",
"paths": [
"*"
]
}
]
}
}

View File

@ -0,0 +1,11 @@
[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "xyz.blueskyweb.app",
"sha256_cert_fingerprints":
["C1:4D:3C:6B:B5:D6:D9:AE:CF:C5:0B:BC:C1:9B:29:6D:D4:E6:87:46:36:D5:4C:1A:64:1C:14:08:BF:7E:F9:62", "FA:C6:17:45:DC:09:03:78:6F:B9:ED:E6:2A:96:2B:39:9F:73:48:F0:BB:6F:89:9B:83:32:66:75:91:03:3B:9C"]
}
}
]

View File

@ -122,8 +122,8 @@
{%- block body_all %} {%- block body_all %}
<div id="root"></div> <div id="root"></div>
<noscript> <noscript>
<h1>Javascript Required</h1> <h1>JavaScript Required</h1>
<p>This is a heavily interactive web application, and Javascript is required. Simple HTML interfaces are possible, but that is not what this is. <p>This is a heavily interactive web application, and JavaScript is required. Simple HTML interfaces are possible, but that is not what this is.
<p>Learn more about Bluesky at <a href="https://blueskyweb.xyz">blueskyweb.xyz</a> and <a href="https://atproto.com">atproto.com</a>. <p>Learn more about Bluesky at <a href="https://blueskyweb.xyz">blueskyweb.xyz</a> and <a href="https://atproto.com">atproto.com</a>.
{% block noscript_extra %}{% endblock %} {% block noscript_extra %}{% endblock %}
</noscript> </noscript>

View File

@ -26,13 +26,21 @@
- Run once: `yarn e2e:build` - Run once: `yarn e2e:build`
- Each test run: `yarn e2e:run` - Each test run: `yarn e2e:run`
- Tips - Tips
- Make sure you copy the `.env.example` to `.env` and add the appropiate tokens (e.g. `SENTRY_AUTH_TOKEN` can be created on the Sentry dashboard). If this is not required, you can remove it from `eas.json` and `package.json`, as well as any mentions in the code. - Make sure you copy the `.env.example` to `.env` and add the appropriate tokens (e.g. `SENTRY_AUTH_TOKEN` can be created on the Sentry dashboard). If this is not required, you can remove it from `eas.json` and `package.json`, as well as any mentions in the code. Please check the section below on how to remove Sentry from the codebase
- If you want to use Expo EAS on your own builds without ejecting from Expo, make sure to change the `owner` as well as `extra.eas.projectId` properties. If you do not have an Expo account, you may remove these properties. - If you want to use Expo EAS on your own builds without ejecting from Expo, make sure to change the `owner` as well as `extra.eas.projectId` properties. If you do not have an Expo account, you may remove these properties.
- `npx react-native info` Checks what has been installed. - `npx react-native info` Checks what has been installed.
- The android simulator won't be able to access localhost services unless you run `adb reverse tcp:{PORT} tcp:{PORT}` - The android simulator won't be able to access localhost services unless you run `adb reverse tcp:{PORT} tcp:{PORT}`
- For instance, the localhosted dev-wallet will need `adb reverse tcp:3001 tcp:3001` - For instance, the locally-hosted dev-wallet will need `adb reverse tcp:3001 tcp:3001`
- For some reason, the typescript compiler chokes on platform-specific files (e.g. `foo.native.ts`) but only when compiling for Web thus far. Therefore we always have one version of the file which doesn't use a platform specifier, and that should be the Web version. ([More info](https://stackoverflow.com/questions/44001050/platform-specific-import-component-in-react-native-with-typescript).) - For some reason, the typescript compiler chokes on platform-specific files (e.g. `foo.native.ts`) but only when compiling for Web thus far. Therefore we always have one version of the file which doesn't use a platform specifier, and that should be the Web version. ([More info](https://stackoverflow.com/questions/44001050/platform-specific-import-component-in-react-native-with-typescript).)
### Removing Sentry
If you are part of the Bluesky team, you should have access to our Sentry dashboard, and you shouldn't need to remove Sentry. Even if you are not part of the Bluesky team, you can create your own Sentry account and add the `SENTRY_AUTH_TOKEN` env var and add your sentry account detials to `app.json` to make the app build and run successfully. However, if that is not possible, follow these steps to remove Sentry from the project (please don't commit this code in any PR):
- `yarn remove sentry-expo @sentry/react-native`
- Remove `sentry-expo` plugin in `app.json` and also remove the `postPublish` hook in `app.json`
- Remove any mentions of `sentry` from the `App.native.tsx`, `App.web.tsx` and `Navigation.tsx` files. Also, delete `sentry.ts`
- Run `rm -rf ios android` or delete the existing `android` and `ios` folders in the project (don't worry! `yarn prebuild` gets these back)
- Run `yarn prebuild` and `yarn ios` and build the app!
## Go-Server Build ## Go-Server Build
### Prerequisites ### Prerequisites

View File

@ -13,6 +13,7 @@ const ADMIN_PASSWORD = 'admin-pass'
const SECOND = 1000 const SECOND = 1000
const MINUTE = SECOND * 60 const MINUTE = SECOND * 60
const HOUR = MINUTE * 60 const HOUR = MINUTE * 60
const DAY = HOUR * 24
export interface TestUser { export interface TestUser {
email: string email: string
@ -66,6 +67,8 @@ export async function createServer(
adminPassword: ADMIN_PASSWORD, adminPassword: ADMIN_PASSWORD,
inviteRequired, inviteRequired,
didPlcUrl: plcUrl, didPlcUrl: plcUrl,
didCacheMaxTTL: DAY,
didCacheStaleTTL: HOUR,
jwtSecret: 'jwt-secret', jwtSecret: 'jwt-secret',
availableUserDomains: ['.test'], availableUserDomains: ['.test'],
appUrlPasswordReset: 'app://forgot-password', appUrlPasswordReset: 'app://forgot-password',

View File

@ -1,6 +1,6 @@
{ {
"name": "bsky.app", "name": "bsky.app",
"version": "1.28.0", "version": "1.29.0",
"private": true, "private": true,
"scripts": { "scripts": {
"postinstall": "patch-package", "postinstall": "patch-package",
@ -22,7 +22,7 @@
"e2e:run": "detox test --configuration ios.sim.debug --take-screenshots all" "e2e:run": "detox test --configuration ios.sim.debug --take-screenshots all"
}, },
"dependencies": { "dependencies": {
"@atproto/api": "0.3.3", "@atproto/api": "0.3.8",
"@bam.tech/react-native-image-resizer": "^3.0.4", "@bam.tech/react-native-image-resizer": "^3.0.4",
"@braintree/sanitize-url": "^6.0.2", "@braintree/sanitize-url": "^6.0.2",
"@expo/webpack-config": "^18.0.1", "@expo/webpack-config": "^18.0.1",
@ -30,7 +30,7 @@
"@fortawesome/free-regular-svg-icons": "^6.1.1", "@fortawesome/free-regular-svg-icons": "^6.1.1",
"@fortawesome/free-solid-svg-icons": "^6.1.1", "@fortawesome/free-solid-svg-icons": "^6.1.1",
"@fortawesome/react-native-fontawesome": "^0.3.0", "@fortawesome/react-native-fontawesome": "^0.3.0",
"@gorhom/bottom-sheet": "^4", "@gorhom/bottom-sheet": "4.4.5",
"@mattermost/react-native-paste-input": "^0.6.0", "@mattermost/react-native-paste-input": "^0.6.0",
"@miblanchard/react-native-slider": "^2.2.0", "@miblanchard/react-native-slider": "^2.2.0",
"@notifee/react-native": "^7.4.0", "@notifee/react-native": "^7.4.0",
@ -85,12 +85,10 @@
"expo-updates": "~0.16.4", "expo-updates": "~0.16.4",
"fast-text-encoding": "^1.0.6", "fast-text-encoding": "^1.0.6",
"graphemer": "^1.4.0", "graphemer": "^1.4.0",
"he": "^1.2.0",
"history": "^5.3.0", "history": "^5.3.0",
"js-sha256": "^0.9.0", "js-sha256": "^0.9.0",
"lande": "^1.0.10", "lande": "^1.0.10",
"lodash.chunk": "^4.2.0", "lodash.chunk": "^4.2.0",
"lodash.clonedeep": "^4.5.0",
"lodash.debounce": "^4.0.8", "lodash.debounce": "^4.0.8",
"lodash.isequal": "^4.5.0", "lodash.isequal": "^4.5.0",
"lodash.omit": "^4.5.0", "lodash.omit": "^4.5.0",
@ -108,9 +106,10 @@
"react-avatar-editor": "^13.0.0", "react-avatar-editor": "^13.0.0",
"react-circular-progressbar": "^2.1.0", "react-circular-progressbar": "^2.1.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-native": "0.71.7", "react-native": "0.71.8",
"react-native-appstate-hook": "^1.0.6", "react-native-appstate-hook": "^1.0.6",
"react-native-background-fetch": "^4.1.8", "react-native-background-fetch": "^4.1.8",
"react-native-draggable-flatlist": "^4.0.1",
"react-native-drawer-layout": "^3.2.0", "react-native-drawer-layout": "^3.2.0",
"react-native-fs": "^2.20.0", "react-native-fs": "^2.20.0",
"react-native-gesture-handler": "~2.9.0", "react-native-gesture-handler": "~2.9.0",
@ -140,7 +139,7 @@
"zod": "^3.20.2" "zod": "^3.20.2"
}, },
"devDependencies": { "devDependencies": {
"@atproto/pds": "^0.1.8", "@atproto/pds": "^0.1.10",
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",
"@babel/preset-env": "^7.20.0", "@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.20.0", "@babel/runtime": "^7.20.0",
@ -152,7 +151,6 @@
"@types/he": "^1.1.2", "@types/he": "^1.1.2",
"@types/jest": "^29.4.0", "@types/jest": "^29.4.0",
"@types/lodash.chunk": "^4.2.7", "@types/lodash.chunk": "^4.2.7",
"@types/lodash.clonedeep": "^4.5.7",
"@types/lodash.debounce": "^4.0.7", "@types/lodash.debounce": "^4.0.7",
"@types/lodash.isequal": "^4.5.6", "@types/lodash.isequal": "^4.5.6",
"@types/lodash.omit": "^4.5.7", "@types/lodash.omit": "^4.5.7",

View File

@ -14,6 +14,7 @@ import {createBottomTabNavigator} from '@react-navigation/bottom-tabs'
import { import {
HomeTabNavigatorParams, HomeTabNavigatorParams,
SearchTabNavigatorParams, SearchTabNavigatorParams,
FeedsTabNavigatorParams,
NotificationsTabNavigatorParams, NotificationsTabNavigatorParams,
FlatNavigatorParams, FlatNavigatorParams,
AllNavigatorParams, AllNavigatorParams,
@ -32,14 +33,18 @@ import {useStores} from './state'
import {HomeScreen} from './view/screens/Home' import {HomeScreen} from './view/screens/Home'
import {SearchScreen} from './view/screens/Search' import {SearchScreen} from './view/screens/Search'
import {FeedsScreen} from './view/screens/Feeds'
import {NotificationsScreen} from './view/screens/Notifications' import {NotificationsScreen} from './view/screens/Notifications'
import {ModerationScreen} from './view/screens/Moderation' import {ModerationScreen} from './view/screens/Moderation'
import {ModerationMuteListsScreen} from './view/screens/ModerationMuteLists' import {ModerationMuteListsScreen} from './view/screens/ModerationMuteLists'
import {DiscoverFeedsScreen} from 'view/screens/DiscoverFeeds'
import {NotFoundScreen} from './view/screens/NotFound' import {NotFoundScreen} from './view/screens/NotFound'
import {SettingsScreen} from './view/screens/Settings' import {SettingsScreen} from './view/screens/Settings'
import {ProfileScreen} from './view/screens/Profile' import {ProfileScreen} from './view/screens/Profile'
import {ProfileFollowersScreen} from './view/screens/ProfileFollowers' import {ProfileFollowersScreen} from './view/screens/ProfileFollowers'
import {ProfileFollowsScreen} from './view/screens/ProfileFollows' import {ProfileFollowsScreen} from './view/screens/ProfileFollows'
import {CustomFeedScreen} from './view/screens/CustomFeed'
import {CustomFeedLikedByScreen} from './view/screens/CustomFeedLikedBy'
import {ProfileListScreen} from './view/screens/ProfileList' import {ProfileListScreen} from './view/screens/ProfileList'
import {PostThreadScreen} from './view/screens/PostThread' import {PostThreadScreen} from './view/screens/PostThread'
import {PostLikedByScreen} from './view/screens/PostLikedBy' import {PostLikedByScreen} from './view/screens/PostLikedBy'
@ -54,6 +59,7 @@ import {CopyrightPolicyScreen} from './view/screens/CopyrightPolicy'
import {AppPasswords} from 'view/screens/AppPasswords' import {AppPasswords} from 'view/screens/AppPasswords'
import {ModerationMutedAccounts} from 'view/screens/ModerationMutedAccounts' import {ModerationMutedAccounts} from 'view/screens/ModerationMutedAccounts'
import {ModerationBlockedAccounts} from 'view/screens/ModerationBlockedAccounts' import {ModerationBlockedAccounts} from 'view/screens/ModerationBlockedAccounts'
import {SavedFeeds} from 'view/screens/SavedFeeds'
import {getRoutingInstrumentation} from 'lib/sentry' import {getRoutingInstrumentation} from 'lib/sentry'
import {bskyTitle} from 'lib/strings/headings' import {bskyTitle} from 'lib/strings/headings'
@ -61,6 +67,7 @@ const navigationRef = createNavigationContainerRef<AllNavigatorParams>()
const HomeTab = createNativeStackNavigator<HomeTabNavigatorParams>() const HomeTab = createNativeStackNavigator<HomeTabNavigatorParams>()
const SearchTab = createNativeStackNavigator<SearchTabNavigatorParams>() const SearchTab = createNativeStackNavigator<SearchTabNavigatorParams>()
const FeedsTab = createNativeStackNavigator<FeedsTabNavigatorParams>()
const NotificationsTab = const NotificationsTab =
createNativeStackNavigator<NotificationsTabNavigatorParams>() createNativeStackNavigator<NotificationsTabNavigatorParams>()
const MyProfileTab = createNativeStackNavigator<MyProfileTabNavigatorParams>() const MyProfileTab = createNativeStackNavigator<MyProfileTabNavigatorParams>()
@ -100,6 +107,11 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
component={ModerationBlockedAccounts} component={ModerationBlockedAccounts}
options={{title: title('Blocked Accounts')}} options={{title: title('Blocked Accounts')}}
/> />
<Stack.Screen
name="DiscoverFeeds"
component={DiscoverFeedsScreen}
options={{title: title('Discover Feeds')}}
/>
<Stack.Screen <Stack.Screen
name="Settings" name="Settings"
component={SettingsScreen} component={SettingsScreen}
@ -144,6 +156,16 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
component={PostRepostedByScreen} component={PostRepostedByScreen}
options={({route}) => ({title: title(`Post by @${route.params.name}`)})} options={({route}) => ({title: title(`Post by @${route.params.name}`)})}
/> />
<Stack.Screen
name="CustomFeed"
component={CustomFeedScreen}
options={{title: title('Feed')}}
/>
<Stack.Screen
name="CustomFeedLikedBy"
component={CustomFeedLikedByScreen}
options={{title: title('Liked by')}}
/>
<Stack.Screen <Stack.Screen
name="Debug" name="Debug"
component={DebugScreen} component={DebugScreen}
@ -184,6 +206,11 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
component={AppPasswords} component={AppPasswords}
options={{title: title('App Passwords')}} options={{title: title('App Passwords')}}
/> />
<Stack.Screen
name="SavedFeeds"
component={SavedFeeds}
options={{title: title('Edit My Feeds')}}
/>
</> </>
) )
} }
@ -198,14 +225,15 @@ function TabsNavigator() {
<Tab.Navigator <Tab.Navigator
initialRouteName="HomeTab" initialRouteName="HomeTab"
backBehavior="initialRoute" backBehavior="initialRoute"
screenOptions={{headerShown: false}} screenOptions={{headerShown: false, lazy: true}}
tabBar={tabBar}> tabBar={tabBar}>
<Tab.Screen name="HomeTab" component={HomeTabNavigator} /> <Tab.Screen name="HomeTab" component={HomeTabNavigator} />
<Tab.Screen name="SearchTab" component={SearchTabNavigator} />
<Tab.Screen name="FeedsTab" component={FeedsTabNavigator} />
<Tab.Screen <Tab.Screen
name="NotificationsTab" name="NotificationsTab"
component={NotificationsTabNavigator} component={NotificationsTabNavigator}
/> />
<Tab.Screen name="SearchTab" component={SearchTabNavigator} />
<Tab.Screen name="MyProfileTab" component={MyProfileTabNavigator} /> <Tab.Screen name="MyProfileTab" component={MyProfileTabNavigator} />
</Tab.Navigator> </Tab.Navigator>
) )
@ -245,6 +273,23 @@ function SearchTabNavigator() {
) )
} }
function FeedsTabNavigator() {
const contentStyle = useColorSchemeStyle(styles.bgLight, styles.bgDark)
return (
<FeedsTab.Navigator
screenOptions={{
gestureEnabled: true,
fullScreenGestureEnabled: true,
headerShown: false,
animationDuration: 250,
contentStyle,
}}>
<FeedsTab.Screen name="Feeds" component={FeedsScreen} />
{commonScreens(FeedsTab as typeof HomeTab)}
</FeedsTab.Navigator>
)
}
function NotificationsTabNavigator() { function NotificationsTabNavigator() {
const contentStyle = useColorSchemeStyle(styles.bgLight, styles.bgDark) const contentStyle = useColorSchemeStyle(styles.bgLight, styles.bgDark)
return ( return (
@ -318,6 +363,11 @@ const FlatNavigator = observer(() => {
component={SearchScreen} component={SearchScreen}
options={{title: title('Search')}} options={{title: title('Search')}}
/> />
<Flat.Screen
name="Feeds"
component={FeedsScreen}
options={{title: title('Feeds')}}
/>
<Flat.Screen <Flat.Screen
name="Notifications" name="Notifications"
component={NotificationsScreen} component={NotificationsScreen}

View File

@ -143,9 +143,6 @@ export class FeedTuner {
} }
} }
// sort by slice roots' timestamps
slices.sort((a, b) => b.ts.localeCompare(a.ts))
for (const slice of slices) { for (const slice of slices) {
for (const item of slice.items) { for (const item of slice.items) {
this.seenUris.add(item.post.uri) this.seenUris.add(item.post.uri)

View File

@ -18,6 +18,7 @@ export interface ExternalEmbedDraft {
uri: string uri: string
isLoading: boolean isLoading: boolean
meta?: LinkMeta meta?: LinkMeta
embed?: AppBskyEmbedRecord.Main
localThumb?: ImageModel localThumb?: ImageModel
} }
@ -109,6 +110,7 @@ export async function post(store: RootStoreModel, opts: PostOpts) {
const images: AppBskyEmbedImages.Image[] = [] const images: AppBskyEmbedImages.Image[] = []
for (const image of opts.images) { for (const image of opts.images) {
opts.onStateChange?.(`Uploading image #${images.length + 1}...`) opts.onStateChange?.(`Uploading image #${images.length + 1}...`)
await image.compress()
const path = image.compressed?.path ?? image.path const path = image.compressed?.path ?? image.path
const res = await uploadBlob(store, path, 'image/jpeg') const res = await uploadBlob(store, path, 'image/jpeg')
images.push({ images.push({
@ -135,40 +137,54 @@ export async function post(store: RootStoreModel, opts: PostOpts) {
} }
if (opts.extLink && !opts.images?.length) { if (opts.extLink && !opts.images?.length) {
let thumb if (opts.extLink.embed) {
if (opts.extLink.localThumb) { embed = opts.extLink.embed
opts.onStateChange?.('Uploading link thumbnail...') } else {
let encoding let thumb
if (opts.extLink.localThumb.mime) { if (opts.extLink.localThumb) {
encoding = opts.extLink.localThumb.mime opts.onStateChange?.('Uploading link thumbnail...')
} else if (opts.extLink.localThumb.path.endsWith('.png')) { let encoding
encoding = 'image/png' if (opts.extLink.localThumb.mime) {
} else if ( encoding = opts.extLink.localThumb.mime
opts.extLink.localThumb.path.endsWith('.jpeg') || } else if (opts.extLink.localThumb.path.endsWith('.png')) {
opts.extLink.localThumb.path.endsWith('.jpg') encoding = 'image/png'
) { } else if (
encoding = 'image/jpeg' opts.extLink.localThumb.path.endsWith('.jpeg') ||
} else { opts.extLink.localThumb.path.endsWith('.jpg')
store.log.warn( ) {
'Unexpected image format for thumbnail, skipping', encoding = 'image/jpeg'
opts.extLink.localThumb.path, } else {
) store.log.warn(
'Unexpected image format for thumbnail, skipping',
opts.extLink.localThumb.path,
)
}
if (encoding) {
const thumbUploadRes = await uploadBlob(
store,
opts.extLink.localThumb.path,
encoding,
)
thumb = thumbUploadRes.data.blob
}
} }
if (encoding) {
const thumbUploadRes = await uploadBlob(
store,
opts.extLink.localThumb.path,
encoding,
)
thumb = thumbUploadRes.data.blob
}
}
if (opts.quote) { if (opts.quote) {
embed = { embed = {
$type: 'app.bsky.embed.recordWithMedia', $type: 'app.bsky.embed.recordWithMedia',
record: embed, record: embed,
media: { media: {
$type: 'app.bsky.embed.external',
external: {
uri: opts.extLink.uri,
title: opts.extLink.meta?.title || '',
description: opts.extLink.meta?.description || '',
thumb,
},
} as AppBskyEmbedExternal.Main,
} as AppBskyEmbedRecordWithMedia.Main
} else {
embed = {
$type: 'app.bsky.embed.external', $type: 'app.bsky.embed.external',
external: { external: {
uri: opts.extLink.uri, uri: opts.extLink.uri,
@ -176,18 +192,8 @@ export async function post(store: RootStoreModel, opts: PostOpts) {
description: opts.extLink.meta?.description || '', description: opts.extLink.meta?.description || '',
thumb, thumb,
}, },
} as AppBskyEmbedExternal.Main, } as AppBskyEmbedExternal.Main
} as AppBskyEmbedRecordWithMedia.Main }
} else {
embed = {
$type: 'app.bsky.embed.external',
external: {
uri: opts.extLink.uri,
title: opts.extLink.meta?.title || '',
description: opts.extLink.meta?.description || '',
thumb,
},
} as AppBskyEmbedExternal.Main
} }
} }

View File

@ -1,4 +1,2 @@
import VersionNumber from 'react-native-version-number' import VersionNumber from 'react-native-version-number'
export const appVersion = `${VersionNumber.appVersion} (${VersionNumber.buildVersion})`
export const appVersion = VersionNumber.appVersion
export const buildVersion = VersionNumber.buildVersion

View File

@ -1,3 +1,2 @@
// TODO import {version} from '../../package.json'
export const appVersion = 'TODO' export const appVersion = version
export const buildVersion = 'TODO'

View File

@ -4,6 +4,22 @@ import set from 'lodash.set'
const ongoingActions = new Set<any>() const ongoingActions = new Set<any>()
/**
* This is a TypeScript function that optimistically updates data on the client-side before sending a
* request to the server and rolling back changes if the request fails.
* @param {T} model - The object or record that needs to be updated optimistically.
* @param preUpdate - `preUpdate` is a function that is called before the server update is executed. It
* can be used to perform any necessary actions or updates on the model or UI before the server update
* is initiated.
* @param serverUpdate - `serverUpdate` is a function that returns a Promise representing the server
* update operation. This function is called after the previous state of the model has been recorded
* and the `preUpdate` function has been executed. If the server update is successful, the `postUpdate`
* function is called with the result
* @param [postUpdate] - `postUpdate` is an optional callback function that will be called after the
* server update is successful. It takes in the response from the server update as its parameter. If
* this parameter is not provided, nothing will happen after the server update.
* @returns A Promise that resolves to `void`.
*/
export const updateDataOptimistically = async < export const updateDataOptimistically = async <
T extends Record<string, any>, T extends Record<string, any>,
U, U,

View File

@ -4,6 +4,8 @@ export const FEEDBACK_FORM_URL =
export const MAX_DISPLAY_NAME = 64 export const MAX_DISPLAY_NAME = 64
export const MAX_DESCRIPTION = 256 export const MAX_DESCRIPTION = 256
export const MAX_GRAPHEME_LENGTH = 300
// Recommended is 100 per: https://www.w3.org/WAI/GL/WCAG20/tests/test3.html // Recommended is 100 per: https://www.w3.org/WAI/GL/WCAG20/tests/test3.html
// but increasing limit per user feedback // but increasing limit per user feedback
export const MAX_ALT_TEXT = 1000 export const MAX_ALT_TEXT = 1000
@ -94,8 +96,66 @@ export function SUGGESTED_FOLLOWS(serviceUrl: string) {
} }
} }
export const STAGING_DEFAULT_FEED = (rkey: string) =>
`at://did:plc:wqzurwm3kmaig6e6hnc2gqwo/app.bsky.feed.generator/${rkey}`
export const PROD_DEFAULT_FEED = (rkey: string) =>
`at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/${rkey}`
export async function DEFAULT_FEEDS(
serviceUrl: string,
resolveHandle: (name: string) => Promise<string>,
) {
if (serviceUrl.includes('localhost')) {
// local dev
const aliceDid = await resolveHandle('alice.test')
return {
pinned: [`at://${aliceDid}/app.bsky.feed.generator/alice-favs`],
saved: [`at://${aliceDid}/app.bsky.feed.generator/alice-favs`],
}
} else if (serviceUrl.includes('staging')) {
// staging
return {
pinned: [STAGING_DEFAULT_FEED('whats-hot')],
saved: [
STAGING_DEFAULT_FEED('bsky-team'),
STAGING_DEFAULT_FEED('with-friends'),
STAGING_DEFAULT_FEED('whats-hot'),
STAGING_DEFAULT_FEED('hot-classic'),
],
}
} else {
// production
return {
pinned: [
PROD_DEFAULT_FEED('whats-hot'),
PROD_DEFAULT_FEED('with-friends'),
],
saved: [
PROD_DEFAULT_FEED('bsky-team'),
PROD_DEFAULT_FEED('with-friends'),
PROD_DEFAULT_FEED('whats-hot'),
PROD_DEFAULT_FEED('hot-classic'),
],
}
}
}
export const POST_IMG_MAX = { export const POST_IMG_MAX = {
width: 2000, width: 2000,
height: 2000, height: 2000,
size: 1000000, size: 1000000,
} }
export const STAGING_LINK_META_PROXY =
'https://cardyb.staging.bsky.dev/v1/extract?url='
export const PROD_LINK_META_PROXY = 'https://cardyb.bsky.app/v1/extract?url='
export function LINK_META_PROXY(serviceUrl: string) {
if (serviceUrl.includes('localhost')) {
return STAGING_LINK_META_PROXY
} else if (serviceUrl.includes('staging')) {
return STAGING_LINK_META_PROXY
} else {
return PROD_LINK_META_PROXY
}
}

40
src/lib/haptics.ts 100644
View File

@ -0,0 +1,40 @@
import {isIOS, isWeb} from 'platform/detection'
import ReactNativeHapticFeedback, {
HapticFeedbackTypes,
} from 'react-native-haptic-feedback'
const hapticImpact: HapticFeedbackTypes = isIOS ? 'impactMedium' : 'impactLight' // Users said the medium impact was too strong on Android; see APP-537s
export class Haptics {
static default() {
if (isWeb) {
return
}
ReactNativeHapticFeedback.trigger(hapticImpact)
}
static impact(type: HapticFeedbackTypes = hapticImpact) {
if (isWeb) {
return
}
ReactNativeHapticFeedback.trigger(type)
}
static selection() {
if (isWeb) {
return
}
ReactNativeHapticFeedback.trigger('selection')
}
static notification = (type: 'success' | 'warning' | 'error') => {
if (isWeb) {
return
}
switch (type) {
case 'success':
return ReactNativeHapticFeedback.trigger('notificationSuccess')
case 'warning':
return ReactNativeHapticFeedback.trigger('notificationWarning')
case 'error':
return ReactNativeHapticFeedback.trigger('notificationError')
}
}
}

View File

@ -0,0 +1,27 @@
import {useEffect, useState} from 'react'
import {useStores} from 'state/index'
import {CustomFeedModel} from 'state/models/feeds/custom-feed'
export function useCustomFeed(uri: string): CustomFeedModel | undefined {
const store = useStores()
const [item, setItem] = useState<CustomFeedModel | undefined>()
useEffect(() => {
async function fetchView() {
const res = await store.agent.app.bsky.feed.getFeedGenerator({
feed: uri,
})
const view = res.data.view
return view
}
async function buildFeedItem() {
const view = await fetchView()
if (view) {
const temp = new CustomFeedModel(store, view)
setItem(temp)
}
}
buildFeedItem()
}, [store, uri])
return item
}

View File

@ -0,0 +1,84 @@
import {useEffect, useRef, useMemo, ForwardedRef} from 'react'
import {Platform, findNodeHandle} from 'react-native'
import type {ScrollView} from 'react-native'
import {mergeRefs} from 'lib/merge-refs'
type Props<Scrollable extends ScrollView = ScrollView> = {
cursor?: string
outerRef?: ForwardedRef<Scrollable>
}
export function useDraggableScroll<Scrollable extends ScrollView = ScrollView>({
outerRef,
cursor = 'grab',
}: Props<Scrollable> = {}) {
const ref = useRef<Scrollable>(null)
useEffect(() => {
if (Platform.OS !== 'web' || !ref.current) {
return
}
const slider = findNodeHandle(ref.current) as unknown as HTMLDivElement
if (!slider) {
return
}
let isDragging = false
let isMouseDown = false
let startX = 0
let scrollLeft = 0
const mouseDown = (e: MouseEvent) => {
isMouseDown = true
startX = e.pageX - slider.offsetLeft
scrollLeft = slider.scrollLeft
slider.style.cursor = cursor
}
const mouseUp = () => {
if (isDragging) {
slider.addEventListener('click', e => e.stopPropagation(), {once: true})
}
isMouseDown = false
isDragging = false
slider.style.cursor = 'default'
}
const mouseMove = (e: MouseEvent) => {
if (!isMouseDown) {
return
}
// Require n pixels momement before start of drag (3 in this case )
const x = e.pageX - slider.offsetLeft
if (Math.abs(x - startX) < 3) {
return
}
isDragging = true
e.preventDefault()
const walk = x - startX
slider.scrollLeft = scrollLeft - walk
}
slider.addEventListener('mousedown', mouseDown)
window.addEventListener('mouseup', mouseUp)
window.addEventListener('mousemove', mouseMove)
return () => {
slider.removeEventListener('mousedown', mouseDown)
window.removeEventListener('mouseup', mouseUp)
window.removeEventListener('mousemove', mouseMove)
}
}, [cursor])
const refs = useMemo(
() => mergeRefs(outerRef ? [ref, outerRef] : [ref]),
[ref, outerRef],
)
return {
refs,
}
}

View File

@ -6,14 +6,16 @@ export function useNavigationTabState() {
const res = { const res = {
isAtHome: getTabState(state, 'Home') !== TabState.Outside, isAtHome: getTabState(state, 'Home') !== TabState.Outside,
isAtSearch: getTabState(state, 'Search') !== TabState.Outside, isAtSearch: getTabState(state, 'Search') !== TabState.Outside,
isAtFeeds: getTabState(state, 'Feeds') !== TabState.Outside,
isAtNotifications: isAtNotifications:
getTabState(state, 'Notifications') !== TabState.Outside, getTabState(state, 'Notifications') !== TabState.Outside,
isAtMyProfile: getTabState(state, 'MyProfile') !== TabState.Outside, isAtMyProfile: getTabState(state, 'MyProfile') !== TabState.Outside,
} }
if ( if (
!res.isAtHome && !res.isAtHome &&
!res.isAtNotifications &&
!res.isAtSearch && !res.isAtSearch &&
!res.isAtFeeds &&
!res.isAtNotifications &&
!res.isAtMyProfile !res.isAtMyProfile
) { ) {
// HACK for some reason useNavigationState will give us pre-hydration results // HACK for some reason useNavigationState will give us pre-hydration results

View File

@ -1,25 +1,56 @@
import {useState} from 'react' import {useState, useCallback, useRef} from 'react'
import {NativeSyntheticEvent, NativeScrollEvent} from 'react-native' import {NativeSyntheticEvent, NativeScrollEvent} from 'react-native'
import {RootStoreModel} from 'state/index' import {RootStoreModel} from 'state/index'
import {s} from 'lib/styles'
import {isDesktopWeb} from 'platform/detection'
const DY_LIMIT = isDesktopWeb ? 30 : 10
export type OnScrollCb = ( export type OnScrollCb = (
event: NativeSyntheticEvent<NativeScrollEvent>, event: NativeSyntheticEvent<NativeScrollEvent>,
) => void ) => void
export type ResetCb = () => void
export function useOnMainScroll(store: RootStoreModel) { export function useOnMainScroll(
let [lastY, setLastY] = useState(0) store: RootStoreModel,
let isMinimal = store.shell.minimalShellMode ): [OnScrollCb, boolean, ResetCb] {
return function onMainScroll(event: NativeSyntheticEvent<NativeScrollEvent>) { let lastY = useRef(0)
const y = event.nativeEvent.contentOffset.y let [isScrolledDown, setIsScrolledDown] = useState(false)
const dy = y - (lastY || 0) return [
setLastY(y) useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
const y = event.nativeEvent.contentOffset.y
const dy = y - (lastY.current || 0)
lastY.current = y
if (!isMinimal && y > 10 && dy > 10) { if (!store.shell.minimalShellMode && y > 10 && dy > DY_LIMIT) {
store.shell.setMinimalShellMode(true) store.shell.setMinimalShellMode(true)
isMinimal = true } else if (
} else if (isMinimal && (y <= 10 || dy < -10)) { store.shell.minimalShellMode &&
(y <= 10 || dy < DY_LIMIT * -1)
) {
store.shell.setMinimalShellMode(false)
}
if (
!isScrolledDown &&
event.nativeEvent.contentOffset.y > s.window.height
) {
setIsScrolledDown(true)
} else if (
isScrolledDown &&
event.nativeEvent.contentOffset.y < s.window.height
) {
setIsScrolledDown(false)
}
},
[store, isScrolledDown],
),
isScrolledDown,
useCallback(() => {
setIsScrolledDown(false)
store.shell.setMinimalShellMode(false) store.shell.setMinimalShellMode(false)
isMinimal = false lastY.current = 1e8 // NOTE we set this very high so that the onScroll logic works right -prf
} }, [store, setIsScrolledDown]),
} ]
} }

View File

@ -1,6 +1,6 @@
import React from 'react' import React from 'react'
import {StyleProp, TextStyle, ViewStyle} from 'react-native' import {StyleProp, TextStyle, ViewStyle} from 'react-native'
import Svg, {Path, Rect, Line, Ellipse} from 'react-native-svg' import Svg, {Path, Rect, Line, Ellipse, Circle} from 'react-native-svg'
export function GridIcon({ export function GridIcon({
style, style,
@ -88,7 +88,7 @@ export function HomeIconSolid({
<Path <Path
fill="currentColor" fill="currentColor"
strokeWidth={strokeWidth} strokeWidth={strokeWidth}
d="M 23.951 2 C 23.631 2.011 23.323 2.124 23.072 2.322 L 8.859 13.52 C 7.055 14.941 6 17.114 6 19.41 L 6 38.5 C 6 39.864 7.136 41 8.5 41 L 18.5 41 C 19.864 41 21 39.864 21 38.5 L 21 28.5 C 21 28.205 21.205 28 21.5 28 L 26.5 28 C 26.795 28 27 28.205 27 28.5 L 27 38.5 C 27 39.864 28.136 41 29.5 41 L 39.5 41 C 40.864 41 42 39.864 42 38.5 L 42 19.41 C 42 17.114 40.945 14.941 39.141 13.52 L 24.928 2.322 C 24.65 2.103 24.304 1.989 23.951 2 Z" d="m 23.951,2 c -0.32,0.011 -0.628,0.124 -0.879,0.322 L 8.859,13.52 C 7.055,14.941 6,17.114 6,19.41 V 38.5 C 6,39.864 7.136,41 8.5,41 h 8 c 1.364,0 2.5,-1.136 2.5,-2.5 v -12 C 19,26.205 19.205,26 19.5,26 h 9 c 0.295,0 0.5,0.205 0.5,0.5 v 12 c 0,1.364 1.136,2.5 2.5,2.5 h 8 C 40.864,41 42,39.864 42,38.5 V 19.41 c 0,-2.296 -1.055,-4.469 -2.859,-5.89 L 24.928,2.322 C 24.65,2.103 24.304,1.989 23.951,2 Z"
/> />
</Svg> </Svg>
) )
@ -472,7 +472,7 @@ export function HeartIcon({
size = 24, size = 24,
strokeWidth = 1.5, strokeWidth = 1.5,
}: { }: {
style?: StyleProp<ViewStyle> style?: StyleProp<TextStyle>
size?: string | number size?: string | number
strokeWidth: number strokeWidth: number
}) { }) {
@ -493,7 +493,7 @@ export function HeartIconSolid({
style, style,
size = 24, size = 24,
}: { }: {
style?: StyleProp<ViewStyle> style?: StyleProp<TextStyle>
size?: string | number size?: string | number
}) { }) {
return ( return (
@ -883,3 +883,77 @@ export function HandIcon({
</Svg> </Svg>
) )
} }
export function SatelliteDishIconSolid({
style,
size,
strokeWidth = 1.5,
}: {
style?: StyleProp<ViewStyle>
size?: string | number
strokeWidth?: number
}) {
return (
<Svg
width={size || 24}
height={size || 24}
viewBox="0 0 22 22"
style={style}
fill="none"
stroke="none">
<Path
d="M16 19.6622C14.5291 20.513 12.8214 21 11 21C5.47715 21 1 16.5229 1 11C1 9.17858 1.48697 7.47088 2.33782 6.00002C3.18867 4.52915 6 7.66219 6 7.66219L14.5 16.1622C14.5 16.1622 17.4709 18.8113 16 19.6622Z"
fill="currentColor"
/>
<Path
d="M8 1.62961C9.04899 1.22255 10.1847 1 11.3704 1C16.6887 1 21 5.47715 21 11C21 12.0452 20.8456 13.053 20.5592 14"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<Path
d="M9 5.38745C9.64553 5.13695 10.3444 5 11.0741 5C14.3469 5 17 7.75517 17 11.1538C17 11.797 16.905 12.4172 16.7287 13"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<Circle cx="10" cy="12" r="2" fill="currentColor" />
</Svg>
)
}
export function SatelliteDishIcon({
style,
size,
strokeWidth = 1.5,
}: {
style?: StyleProp<TextStyle>
size?: string | number
strokeWidth?: number
}) {
return (
<Svg
fill="none"
viewBox="0 0 22 22"
strokeWidth={strokeWidth}
stroke="currentColor"
width={size}
height={size}
style={style}>
<Path d="M5.25593 8.3303L5.25609 8.33047L5.25616 8.33056L5.25621 8.33061L5.27377 8.35018L5.29289 8.3693L13.7929 16.8693L13.8131 16.8895L13.8338 16.908L13.834 16.9081L13.8342 16.9083L13.8342 16.9083L13.8345 16.9086L13.8381 16.9118L13.8574 16.9294C13.8752 16.9458 13.9026 16.9711 13.9377 17.0043C14.0081 17.0708 14.1088 17.1683 14.2258 17.2881C14.4635 17.5315 14.7526 17.8509 14.9928 18.1812C15.2067 18.4755 15.3299 18.7087 15.3817 18.8634C14.0859 19.5872 12.5926 20 11 20C6.02944 20 2 15.9706 2 11C2 9.4151 2.40883 7.9285 3.12619 6.63699C3.304 6.69748 3.56745 6.84213 3.89275 7.08309C4.24679 7.34534 4.58866 7.65673 4.84827 7.9106C4.97633 8.03583 5.08062 8.14337 5.152 8.21863C5.18763 8.25619 5.21487 8.28551 5.23257 8.30473L5.25178 8.32572L5.25571 8.33006L5.25593 8.3303ZM3.00217 6.60712C3.00217 6.6071 3.00267 6.6071 3.00372 6.60715C3.00271 6.60716 3.00218 6.60714 3.00217 6.60712Z" />
<Path
d="M8 1.62961C9.04899 1.22255 10.1847 1 11.3704 1C16.6887 1 21 5.47715 21 11C21 12.0452 20.8456 13.053 20.5592 14"
stroke-linecap="round"
/>
<Path
d="M9 5.38745C9.64553 5.13695 10.3444 5 11.0741 5C14.3469 5 17 7.75517 17 11.1538C17 11.797 16.905 12.4172 16.7287 13"
stroke-linecap="round"
/>
<Path
d="M12 12C12 12.7403 11.5978 13.3866 11 13.7324L8.26756 11C8.61337 10.4022 9.25972 10 10 10C11.1046 10 12 10.8954 12 12Z"
fill="currentColor"
stroke="none"
/>
</Svg>
)
}

View File

@ -62,7 +62,7 @@ export const CONFIGURABLE_LABEL_GROUPS: Record<
title: 'Violent / Bloody', title: 'Violent / Bloody',
subtitle: 'Gore, self-harm, torture', subtitle: 'Gore, self-harm, torture',
warning: 'Violence', warning: 'Violence',
values: ['gore', 'self-harm', 'torture', 'nsfl'], values: ['gore', 'self-harm', 'torture', 'nsfl', 'corpse'],
isAdultImagery: true, isAdultImagery: true,
}, },
hate: { hate: {

View File

@ -1,3 +1,4 @@
import * as apilib from 'lib/api/index'
import {LikelyType, LinkMeta} from './link-meta' import {LikelyType, LinkMeta} from './link-meta'
// import {match as matchRoute} from 'view/routes' // import {match as matchRoute} from 'view/routes'
import {convertBskyAppUrlIfNeeded, makeRecordUri} from '../strings/url-helpers' import {convertBskyAppUrlIfNeeded, makeRecordUri} from '../strings/url-helpers'
@ -128,3 +129,29 @@ export async function getPostAsQuote(
}, },
} }
} }
export async function getFeedAsEmbed(
store: RootStoreModel,
url: string,
): Promise<apilib.ExternalEmbedDraft> {
url = convertBskyAppUrlIfNeeded(url)
const [_0, user, _1, rkey] = url.split('/').filter(Boolean)
const feed = makeRecordUri(user, 'app.bsky.feed.generator', rkey)
const res = await store.agent.app.bsky.feed.getFeedGenerator({feed})
return {
isLoading: false,
uri: feed,
meta: {
url: feed,
likelyType: LikelyType.AtpData,
title: res.data.view.displayName,
},
embed: {
$type: 'app.bsky.embed.record',
record: {
uri: res.data.view.uri,
cid: res.data.view.cid,
},
},
}
}

View File

@ -1,8 +1,7 @@
import he from 'he'
import {isBskyAppUrl} from '../strings/url-helpers' import {isBskyAppUrl} from '../strings/url-helpers'
import {RootStoreModel} from 'state/index' import {RootStoreModel} from 'state/index'
import {extractBskyMeta} from './bsky' import {extractBskyMeta} from './bsky'
import {extractHtmlMeta} from './html' import {LINK_META_PROXY} from 'lib/constants'
export enum LikelyType { export enum LikelyType {
HTML, HTML,
@ -54,26 +53,29 @@ export async function getLinkMeta(
try { try {
const controller = new AbortController() const controller = new AbortController()
const to = setTimeout(() => controller.abort(), timeout || 5e3) const to = setTimeout(() => controller.abort(), timeout || 5e3)
const httpRes = await fetch(url, {
headers: {accept: 'text/html'}, const response = await fetch(
signal: controller.signal, `${LINK_META_PROXY(
}) store.session.currentSession?.service || '',
const httpResBody = await httpRes.text() )}${encodeURIComponent(url)}`,
)
const body = await response.json()
clearTimeout(to) clearTimeout(to)
const httpResMeta = extractHtmlMeta({
html: httpResBody, const {description, error, image, title} = body
hostname: urlp?.hostname,
pathname: urlp?.pathname, if (error !== '') {
}) throw new Error(error)
meta.title = httpResMeta.title ? he.decode(httpResMeta.title) : undefined }
meta.description = httpResMeta.description
? he.decode(httpResMeta.description) meta.description = description
: undefined meta.image = image
meta.image = httpResMeta.image meta.title = title
} catch (e) { } catch (e) {
// failed // failed
console.error(e) console.error(e)
meta.error = 'Failed to fetch link' meta.error = e instanceof Error ? e.toString() : 'Failed to fetch link'
} }
return meta return meta

View File

@ -6,52 +6,8 @@ import * as RNFS from 'react-native-fs'
import uuid from 'react-native-uuid' import uuid from 'react-native-uuid'
import * as Sharing from 'expo-sharing' import * as Sharing from 'expo-sharing'
import {Dimensions} from './types' import {Dimensions} from './types'
import {POST_IMG_MAX} from 'lib/constants'
import {isAndroid, isIOS} from 'platform/detection' import {isAndroid, isIOS} from 'platform/detection'
export async function compressAndResizeImageForPost(
image: Image,
): Promise<Image> {
const uri = `file://${image.path}`
let resized: Omit<Image, 'mime'>
for (let i = 0; i < 9; i++) {
const quality = 100 - i * 10
try {
resized = await ImageResizer.createResizedImage(
uri,
POST_IMG_MAX.width,
POST_IMG_MAX.height,
'JPEG',
quality,
undefined,
undefined,
undefined,
{mode: 'cover'},
)
} catch (err) {
throw new Error(`Failed to resize: ${err}`)
}
if (resized.size < POST_IMG_MAX.size) {
const path = await moveToPermanentPath(resized.path)
return {
path,
mime: 'image/jpeg',
size: resized.size,
height: resized.height,
width: resized.width,
}
}
}
throw new Error(
`This image is too big! We couldn't compress it down to ${POST_IMG_MAX.size} bytes`,
)
}
export async function compressIfNeeded( export async function compressIfNeeded(
img: Image, img: Image,
maxSize: number = 1000000, maxSize: number = 1000000,

View File

@ -1,25 +1,6 @@
import {Dimensions} from './types' import {Dimensions} from './types'
import {Image as RNImage} from 'react-native-image-crop-picker' import {Image as RNImage} from 'react-native-image-crop-picker'
import {getDataUriSize, blobToDataUri} from './util' import {getDataUriSize, blobToDataUri} from './util'
import {POST_IMG_MAX} from 'lib/constants'
export async function compressAndResizeImageForPost({
path,
width,
height,
}: {
path: string
width: number
height: number
}): Promise<RNImage> {
// Compression is handled in `doResize` via `quality`
return await doResize(path, {
width,
height,
maxSize: POST_IMG_MAX.size,
mode: 'stretch',
})
}
export async function compressIfNeeded( export async function compressIfNeeded(
img: RNImage, img: RNImage,

View File

@ -2,7 +2,7 @@ import {RootStoreModel} from 'state/index'
import {Image as RNImage} from 'react-native-image-crop-picker' import {Image as RNImage} from 'react-native-image-crop-picker'
import RNFS from 'react-native-fs' import RNFS from 'react-native-fs'
import {CropperOptions} from './types' import {CropperOptions} from './types'
import {compressAndResizeImageForPost} from './manip' import {compressIfNeeded} from './manip'
let _imageCounter = 0 let _imageCounter = 0
async function getFile() { async function getFile() {
@ -13,7 +13,7 @@ async function getFile() {
.join('/'), .join('/'),
) )
const file = files[_imageCounter++ % files.length] const file = files[_imageCounter++ % files.length]
return await compressAndResizeImageForPost({ return await compressIfNeeded({
path: file.path, path: file.path,
mime: 'image/jpeg', mime: 'image/jpeg',
size: file.size, size: file.size,

View File

@ -1,5 +1,3 @@
import {Dimensions} from './types'
export function extractDataUriMime(uri: string): string { export function extractDataUriMime(uri: string): string {
return uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')) return uri.substring(uri.indexOf(':') + 1, uri.indexOf(';'))
} }
@ -10,21 +8,6 @@ export function getDataUriSize(uri: string): number {
return Math.round((uri.length * 3) / 4) return Math.round((uri.length * 3) / 4)
} }
export function scaleDownDimensions(
dim: Dimensions,
max: Dimensions,
): Dimensions {
if (dim.width < max.width && dim.height < max.height) {
return dim
}
const wScale = dim.width > max.width ? max.width / dim.width : 1
const hScale = dim.height > max.height ? max.height / dim.height : 1
if (wScale < hScale) {
return {width: dim.width * wScale, height: dim.height * wScale}
}
return {width: dim.width * hScale, height: dim.height * hScale}
}
export function isUriImage(uri: string) { export function isUriImage(uri: string) {
return /\.(jpg|jpeg|png).*$/.test(uri) return /\.(jpg|jpeg|png).*$/.test(uri)
} }

View File

@ -0,0 +1,27 @@
/**
* This TypeScript function merges multiple React refs into a single ref callback.
* When developing low level UI components, it is common to have to use a local ref
* but also support an external one using React.forwardRef.
* Natively, React does not offer a way to set two refs inside the ref property. This is the goal of this small utility.
* Today a ref can be a function or an object, tomorrow it could be another thing, who knows.
* This utility handles compatibility for you.
* This function is inspired by https://github.com/gregberge/react-merge-refs
* @param refs - An array of React refs, which can be either `React.MutableRefObject<T>` or
* `React.LegacyRef<T>`. These refs are used to store references to DOM elements or React components.
* The `mergeRefs` function takes in an array of these refs and returns a callback function that
* @returns The function `mergeRefs` is being returned. It takes an array of mutable or legacy refs and
* returns a ref callback function that can be used to merge multiple refs into a single ref.
*/
export function mergeRefs<T = any>(
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>,
): React.RefCallback<T> {
return value => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(value)
} else if (ref != null) {
;(ref as React.MutableRefObject<T | null>).current = value
}
})
}
}

View File

@ -41,26 +41,26 @@ export function displayNotification(
} }
export function displayNotificationFromModel( export function displayNotificationFromModel(
notif: NotificationsFeedItemModel, notification: NotificationsFeedItemModel,
) { ) {
let author = sanitizeDisplayName( let author = sanitizeDisplayName(
notif.author.displayName || notif.author.handle, notification.author.displayName || notification.author.handle,
) )
let title: string let title: string
let body: string = '' let body: string = ''
if (notif.isLike) { if (notification.isLike) {
title = `${author} liked your post` title = `${author} liked your post`
body = notif.additionalPost?.thread?.postRecord?.text || '' body = notification.additionalPost?.thread?.postRecord?.text || ''
} else if (notif.isRepost) { } else if (notification.isRepost) {
title = `${author} reposted your post` title = `${author} reposted your post`
body = notif.additionalPost?.thread?.postRecord?.text || '' body = notification.additionalPost?.thread?.postRecord?.text || ''
} else if (notif.isMention) { } else if (notification.isMention) {
title = `${author} mentioned you` title = `${author} mentioned you`
body = notif.additionalPost?.thread?.postRecord?.text || '' body = notification.additionalPost?.thread?.postRecord?.text || ''
} else if (notif.isReply) { } else if (notification.isReply) {
title = `${author} replied to your post` title = `${author} replied to your post`
body = notif.additionalPost?.thread?.postRecord?.text || '' body = notification.additionalPost?.thread?.postRecord?.text || ''
} else if (notif.isFollow) { } else if (notification.isFollow) {
title = 'New follower!' title = 'New follower!'
body = `${author} has followed you` body = `${author} has followed you`
} else { } else {
@ -68,10 +68,12 @@ export function displayNotificationFromModel(
} }
let image let image
if ( if (
AppBskyEmbedImages.isView(notif.additionalPost?.thread?.post.embed) && AppBskyEmbedImages.isView(
notif.additionalPost?.thread?.post.embed.images[0]?.thumb notification.additionalPost?.thread?.post.embed,
) &&
notification.additionalPost?.thread?.post.embed.images[0]?.thumb
) { ) {
image = notif.additionalPost.thread.post.embed.images[0].thumb image = notification.additionalPost.thread.post.embed.images[0].thumb
} }
return displayNotification(title, body, image) return displayNotification(title, body, image)
} }

View File

@ -11,7 +11,7 @@ export function getCurrentRoute(state: State) {
export function isStateAtTabRoot(state: State | undefined) { export function isStateAtTabRoot(state: State | undefined) {
if (!state) { if (!state) {
// NOTE // NOTE
// if state is not defined it's because init is occuring // if state is not defined it's because init is occurring
// and therefore we can safely assume we're at root // and therefore we can safely assume we're at root
// -prf // -prf
return true return true

View File

@ -9,6 +9,7 @@ export type CommonNavigatorParams = {
ModerationMuteLists: undefined ModerationMuteLists: undefined
ModerationMutedAccounts: undefined ModerationMutedAccounts: undefined
ModerationBlockedAccounts: undefined ModerationBlockedAccounts: undefined
DiscoverFeeds: undefined
Settings: undefined Settings: undefined
Profile: {name: string; hideBackButton?: boolean} Profile: {name: string; hideBackButton?: boolean}
ProfileFollowers: {name: string} ProfileFollowers: {name: string}
@ -17,6 +18,8 @@ export type CommonNavigatorParams = {
PostThread: {name: string; rkey: string} PostThread: {name: string; rkey: string}
PostLikedBy: {name: string; rkey: string} PostLikedBy: {name: string; rkey: string}
PostRepostedBy: {name: string; rkey: string} PostRepostedBy: {name: string; rkey: string}
CustomFeed: {name: string; rkey: string}
CustomFeedLikedBy: {name: string; rkey: string}
Debug: undefined Debug: undefined
Log: undefined Log: undefined
Support: undefined Support: undefined
@ -25,11 +28,13 @@ export type CommonNavigatorParams = {
CommunityGuidelines: undefined CommunityGuidelines: undefined
CopyrightPolicy: undefined CopyrightPolicy: undefined
AppPasswords: undefined AppPasswords: undefined
SavedFeeds: undefined
} }
export type BottomTabNavigatorParams = CommonNavigatorParams & { export type BottomTabNavigatorParams = CommonNavigatorParams & {
HomeTab: undefined HomeTab: undefined
SearchTab: undefined SearchTab: undefined
FeedsTab: undefined
NotificationsTab: undefined NotificationsTab: undefined
MyProfileTab: undefined MyProfileTab: undefined
} }
@ -42,6 +47,10 @@ export type SearchTabNavigatorParams = CommonNavigatorParams & {
Search: {q?: string} Search: {q?: string}
} }
export type FeedsTabNavigatorParams = CommonNavigatorParams & {
Feeds: undefined
}
export type NotificationsTabNavigatorParams = CommonNavigatorParams & { export type NotificationsTabNavigatorParams = CommonNavigatorParams & {
Notifications: undefined Notifications: undefined
} }
@ -53,6 +62,7 @@ export type MyProfileTabNavigatorParams = CommonNavigatorParams & {
export type FlatNavigatorParams = CommonNavigatorParams & { export type FlatNavigatorParams = CommonNavigatorParams & {
Home: undefined Home: undefined
Search: {q?: string} Search: {q?: string}
Feeds: undefined
Notifications: undefined Notifications: undefined
} }
@ -61,6 +71,8 @@ export type AllNavigatorParams = CommonNavigatorParams & {
Home: undefined Home: undefined
SearchTab: undefined SearchTab: undefined
Search: {q?: string} Search: {q?: string}
FeedsTab: undefined
Feeds: undefined
NotificationsTab: undefined NotificationsTab: undefined
Notifications: undefined Notifications: undefined
MyProfileTab: undefined MyProfileTab: undefined

View File

@ -27,7 +27,7 @@ export function detectLinkables(text: string): DetectedLinkable[] {
matchValue = matchValue.slice(1) matchValue = matchValue.slice(1)
} }
// strip ending puncuation // strip ending punctuation
if (/[.,;!?]$/.test(matchValue)) { if (/[.,;!?]$/.test(matchValue)) {
matchValue = matchValue.slice(0, -1) matchValue = matchValue.slice(0, -1)
} }

View File

@ -1,8 +1,8 @@
const MINUTE = 60 const MINUTE = 60
const HOUR = MINUTE * 60 const HOUR = MINUTE * 60
const DAY = HOUR * 24 const DAY = HOUR * 24
const MONTH = DAY * 28 const WEEK = DAY * 7
const YEAR = DAY * 365
export function ago(date: number | string | Date): string { export function ago(date: number | string | Date): string {
let ts: number let ts: number
if (typeof date === 'string') { if (typeof date === 'string') {
@ -19,12 +19,14 @@ export function ago(date: number | string | Date): string {
return `${Math.floor(diffSeconds / MINUTE)}m` return `${Math.floor(diffSeconds / MINUTE)}m`
} else if (diffSeconds < DAY) { } else if (diffSeconds < DAY) {
return `${Math.floor(diffSeconds / HOUR)}h` return `${Math.floor(diffSeconds / HOUR)}h`
} else if (diffSeconds < MONTH) { } else if (diffSeconds < WEEK) {
return `${Math.floor(diffSeconds / DAY)}d` return `${Math.floor(diffSeconds / DAY)}d`
} else if (diffSeconds < YEAR) {
return `${Math.floor(diffSeconds / MONTH)}mo`
} else { } else {
return new Date(ts).toLocaleDateString() return new Date(ts).toLocaleDateString('en-us', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
} }
} }

View File

@ -82,6 +82,18 @@ export function isBskyPostUrl(url: string): boolean {
return false return false
} }
export function isBskyCustomFeedUrl(url: string): boolean {
if (isBskyAppUrl(url)) {
try {
const urlp = new URL(url)
return /profile\/(?<name>[^/]+)\/feed\/(?<rkey>[^/]+)/i.test(
urlp.pathname,
)
} catch {}
}
return false
}
export function convertBskyAppUrlIfNeeded(url: string): string { export function convertBskyAppUrlIfNeeded(url: string): string {
if (isBskyAppUrl(url)) { if (isBskyAppUrl(url)) {
try { try {

View File

@ -1,4 +1,4 @@
import {StyleProp, StyleSheet, TextStyle} from 'react-native' import {Dimensions, StyleProp, StyleSheet, TextStyle} from 'react-native'
import {Theme, TypographyVariant} from './ThemeContext' import {Theme, TypographyVariant} from './ThemeContext'
import {isMobileWeb} from 'platform/detection' import {isMobileWeb} from 'platform/detection'
@ -52,6 +52,7 @@ export const colors = {
green5: '#082b03', green5: '#082b03',
unreadNotifBg: '#ebf6ff', unreadNotifBg: '#ebf6ff',
brandBlue: '#0066FF',
} }
export const gradients = { export const gradients = {
@ -169,6 +170,10 @@ export const s = StyleSheet.create({
w100pct: {width: '100%'}, w100pct: {width: '100%'},
h100pct: {height: '100%'}, h100pct: {height: '100%'},
hContentRegion: isMobileWeb ? {flex: 1} : {height: '100%'}, hContentRegion: isMobileWeb ? {flex: 1} : {height: '100%'},
window: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
// text align // text align
textLeft: {textAlign: 'left'}, textLeft: {textAlign: 'left'},
@ -214,6 +219,8 @@ export const s = StyleSheet.create({
green3: {color: colors.green3}, green3: {color: colors.green3},
green4: {color: colors.green4}, green4: {color: colors.green4},
green5: {color: colors.green5}, green5: {color: colors.green5},
brandBlue: {color: colors.brandBlue},
}) })
export function lh( export function lh(

View File

@ -4,7 +4,7 @@ import {H3, H4, P, UL, LI, A, EM, OL} from 'view/com/util/Html'
export default function () { export default function () {
return ( return (
<> <>
<H4>Last Updated:&nbsp;2023/04/06</H4> <H4>Last Updated:&nbsp;April 6, 2023</H4>
<P> <P>
The Bluesky app is built on a decentralized social networking protocol, The Bluesky app is built on a decentralized social networking protocol,
the AT Protocol (atproto). Atproto is an open protocol that supports the AT Protocol (atproto). Atproto is an open protocol that supports

View File

@ -4,7 +4,7 @@ import {H3, H4, P, UL, LI, A} from 'view/com/util/Html'
export default function () { export default function () {
return ( return (
<> <>
<H4>Last Updated:&nbsp;2023/04/06</H4> <H4>Last Updated:&nbsp;April 6, 2023</H4>
<P>Notification of Copyright Infringement</P> <P>Notification of Copyright Infringement</P>
<P> <P>
Bluesky, PBLLC d.b.a. Bluesky (&ldquo;Bluesky&rdquo;) respects the Bluesky, PBLLC d.b.a. Bluesky (&ldquo;Bluesky&rdquo;) respects the

View File

@ -4,7 +4,7 @@ import {H2, H4, P, UL, LI, A} from 'view/com/util/Html'
export default function () { export default function () {
return ( return (
<> <>
<H4>Last Updated:&nbsp;2023/02/02</H4> <H4>Last Updated:&nbsp;February 2, 2023</H4>
<P> <P>
This Privacy Policy is designed to help you understand how Bluesky, This Privacy Policy is designed to help you understand how Bluesky,
PBLLC d.b.a. Bluesky (Bluesky, &nbsp;we, us, or&nbsp;our) PBLLC d.b.a. Bluesky (Bluesky, &nbsp;we, us, or&nbsp;our)

View File

@ -4,7 +4,7 @@ import {H4, P, OL, LI, A, STRONG, EM, UL} from 'view/com/util/Html'
export default function () { export default function () {
return ( return (
<> <>
<H4>Last Updated:&nbsp;2023/04/06</H4> <H4>Last Updated:&nbsp;April 6, 2023</H4>
<P> <P>
Welcome to the Bluesky, PBLLC d.b.a. Bluesky (&ldquo;Bluesky&rdquo;, Welcome to the Bluesky, PBLLC d.b.a. Bluesky (&ldquo;Bluesky&rdquo;,
&ldquo;we&rdquo;, or &ldquo;us&rdquo;) website located at{' '} &ldquo;we&rdquo;, or &ldquo;us&rdquo;) website located at{' '}

View File

@ -23,7 +23,7 @@ globalThis.atob = (str: string): string => {
) )
} }
// Adding the padding if missing, for semplicity // Adding the padding if missing, for simplicity
str += '=='.slice(2 - (str.length & 3)) str += '=='.slice(2 - (str.length & 3))
var bitmap, var bitmap,
result = '', result = '',

View File

@ -3,6 +3,8 @@ import {Router} from 'lib/routes/router'
export const router = new Router({ export const router = new Router({
Home: '/', Home: '/',
Search: '/search', Search: '/search',
Feeds: '/feeds',
DiscoverFeeds: '/search/feeds',
Notifications: '/notifications', Notifications: '/notifications',
Settings: '/settings', Settings: '/settings',
Moderation: '/moderation', Moderation: '/moderation',
@ -16,9 +18,12 @@ export const router = new Router({
PostThread: '/profile/:name/post/:rkey', PostThread: '/profile/:name/post/:rkey',
PostLikedBy: '/profile/:name/post/:rkey/liked-by', PostLikedBy: '/profile/:name/post/:rkey/liked-by',
PostRepostedBy: '/profile/:name/post/:rkey/reposted-by', PostRepostedBy: '/profile/:name/post/:rkey/reposted-by',
CustomFeed: '/profile/:name/feed/:rkey',
CustomFeedLikedBy: '/profile/:name/feed/:rkey/liked-by',
Debug: '/sys/debug', Debug: '/sys/debug',
Log: '/sys/log', Log: '/sys/log',
AppPasswords: '/settings/app-passwords', AppPasswords: '/settings/app-passwords',
SavedFeeds: '/settings/saved-feeds',
Support: '/support', Support: '/support',
PrivacyPolicy: '/support/privacy', PrivacyPolicy: '/support/privacy',
TermsOfService: '/support/tos', TermsOfService: '/support/tos',

View File

@ -16,6 +16,7 @@ export class ImageSizesCache {
if (Dimensions) { if (Dimensions) {
return Dimensions return Dimensions
} }
const prom = const prom =
this.activeRequests.get(uri) || this.activeRequests.get(uri) ||
new Promise<Dimensions>(resolve => { new Promise<Dimensions>(resolve => {

View File

@ -118,7 +118,7 @@ export class PostThreadItemModel {
assignTreeModels( assignTreeModels(
v: AppBskyFeedDefs.ThreadViewPost, v: AppBskyFeedDefs.ThreadViewPost,
higlightedPostUri: string, highlightedPostUri: string,
includeParent = true, includeParent = true,
includeChildren = true, includeChildren = true,
) { ) {
@ -130,7 +130,12 @@ export class PostThreadItemModel {
parentModel._showChildReplyLine = true parentModel._showChildReplyLine = true
if (v.parent.parent) { if (v.parent.parent) {
parentModel._showParentReplyLine = true parentModel._showParentReplyLine = true
parentModel.assignTreeModels(v.parent, higlightedPostUri, true, false) parentModel.assignTreeModels(
v.parent,
highlightedPostUri,
true,
false,
)
} }
this.parent = parentModel this.parent = parentModel
} else if (AppBskyFeedDefs.isNotFoundPost(v.parent)) { } else if (AppBskyFeedDefs.isNotFoundPost(v.parent)) {
@ -147,10 +152,10 @@ export class PostThreadItemModel {
const itemModel = new PostThreadItemModel(this.rootStore, item) const itemModel = new PostThreadItemModel(this.rootStore, item)
itemModel._depth = this._depth + 1 itemModel._depth = this._depth + 1
itemModel._showParentReplyLine = itemModel._showParentReplyLine =
itemModel.parentUri !== higlightedPostUri && replies.length === 0 itemModel.parentUri !== highlightedPostUri && replies.length === 0
if (item.replies?.length) { if (item.replies?.length) {
itemModel._showChildReplyLine = true itemModel._showChildReplyLine = true
itemModel.assignTreeModels(item, higlightedPostUri, false, true) itemModel.assignTreeModels(item, highlightedPostUri, false, true)
} }
replies.push(itemModel) replies.push(itemModel)
} else if (AppBskyFeedDefs.isNotFoundPost(item)) { } else if (AppBskyFeedDefs.isNotFoundPost(item)) {

View File

@ -0,0 +1,97 @@
import {makeAutoObservable} from 'mobx'
import {AppBskyUnspeccedGetPopularFeedGenerators} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {bundleAsync} from 'lib/async/bundle'
import {cleanError} from 'lib/strings/errors'
import {CustomFeedModel} from '../feeds/custom-feed'
export class FeedsDiscoveryModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
error = ''
// data
feeds: CustomFeedModel[] = []
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
get hasMore() {
return false
}
get hasContent() {
return this.feeds.length > 0
}
get hasError() {
return this.error !== ''
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
// public api
// =
refresh = bundleAsync(async () => {
this._xLoading()
try {
const res =
await this.rootStore.agent.app.bsky.unspecced.getPopularFeedGenerators(
{},
)
this._replaceAll(res)
this._xIdle()
} catch (e: any) {
this._xIdle(e)
}
})
clear() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.error = ''
this.feeds = []
}
// state transitions
// =
_xLoading() {
this.isLoading = true
this.isRefreshing = true
this.error = ''
}
_xIdle(err?: any) {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
this.error = cleanError(err)
if (err) {
this.rootStore.log.error('Failed to fetch popular feeds', err)
}
}
// helper functions
// =
_replaceAll(res: AppBskyUnspeccedGetPopularFeedGenerators.Response) {
this.feeds = []
for (const f of res.data.feeds) {
this.feeds.push(new CustomFeedModel(this.rootStore, f))
}
}
}

View File

@ -0,0 +1,120 @@
import {AppBskyFeedDefs} from '@atproto/api'
import {makeAutoObservable, runInAction} from 'mobx'
import {RootStoreModel} from 'state/models/root-store'
import {sanitizeDisplayName} from 'lib/strings/display-names'
import {updateDataOptimistically} from 'lib/async/revertible'
export class CustomFeedModel {
// data
_reactKey: string
data: AppBskyFeedDefs.GeneratorView
isOnline: boolean
isValid: boolean
constructor(
public rootStore: RootStoreModel,
view: AppBskyFeedDefs.GeneratorView,
isOnline?: boolean,
isValid?: boolean,
) {
this._reactKey = view.uri
this.data = view
this.isOnline = isOnline ?? true
this.isValid = isValid ?? true
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
// local actions
// =
get uri() {
return this.data.uri
}
get displayName() {
if (this.data.displayName) {
return sanitizeDisplayName(this.data.displayName)
}
return `Feed by @${this.data.creator.handle}`
}
get isSaved() {
return this.rootStore.preferences.savedFeeds.includes(this.uri)
}
get isLiked() {
return this.data.viewer?.like
}
// public apis
// =
async save() {
await this.rootStore.preferences.addSavedFeed(this.uri)
}
async unsave() {
await this.rootStore.preferences.removeSavedFeed(this.uri)
}
async like() {
try {
await updateDataOptimistically(
this.data,
() => {
this.data.viewer = this.data.viewer || {}
this.data.viewer.like = 'pending'
this.data.likeCount = (this.data.likeCount || 0) + 1
},
() => this.rootStore.agent.like(this.data.uri, this.data.cid),
res => {
this.data.viewer = this.data.viewer || {}
this.data.viewer.like = res.uri
},
)
} catch (e: any) {
this.rootStore.log.error('Failed to like feed', e)
}
}
async unlike() {
if (!this.data.viewer?.like) {
return
}
try {
const likeUri = this.data.viewer.like
await updateDataOptimistically(
this.data,
() => {
this.data.viewer = this.data.viewer || {}
this.data.viewer.like = undefined
this.data.likeCount = (this.data.likeCount || 1) - 1
},
() => this.rootStore.agent.deleteLike(likeUri),
)
} catch (e: any) {
this.rootStore.log.error('Failed to unlike feed', e)
}
}
async reload() {
const res = await this.rootStore.agent.app.bsky.feed.getFeedGenerator({
feed: this.data.uri,
})
runInAction(() => {
this.data = res.data.view
this.isOnline = res.data.isOnline
this.isValid = res.data.isValid
})
}
serialize() {
return JSON.stringify(this.data)
}
}

View File

@ -0,0 +1,216 @@
import {makeAutoObservable, runInAction} from 'mobx'
import {AtUri} from '@atproto/api'
import {bundleAsync} from 'lib/async/bundle'
import {RootStoreModel} from '../root-store'
import {CustomFeedModel} from './custom-feed'
import {PostsFeedModel} from './posts'
import {PostsFeedSliceModel} from './post'
const FEED_PAGE_SIZE = 5
const FEEDS_PAGE_SIZE = 3
export type MultiFeedItem =
| {
_reactKey: string
type: 'header'
}
| {
_reactKey: string
type: 'feed-header'
avatar: string | undefined
title: string
}
| {
_reactKey: string
type: 'feed-slice'
slice: PostsFeedSliceModel
}
| {
_reactKey: string
type: 'feed-loading'
}
| {
_reactKey: string
type: 'feed-error'
error: string
}
| {
_reactKey: string
type: 'feed-footer'
title: string
uri: string
}
| {
_reactKey: string
type: 'footer'
}
export class PostsMultiFeedModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
hasMore = true
// data
feedInfos: CustomFeedModel[] = []
feeds: PostsFeedModel[] = []
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(this, {rootStore: false}, {autoBind: true})
}
get hasContent() {
return this.feeds.length !== 0
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
get items() {
const items: MultiFeedItem[] = [{_reactKey: '__header__', type: 'header'}]
for (let i = 0; i < this.feedInfos.length; i++) {
if (!this.feeds[i]) {
break
}
const feed = this.feeds[i]
const feedInfo = this.feedInfos[i]
const urip = new AtUri(feedInfo.uri)
items.push({
_reactKey: `__feed_header_${i}__`,
type: 'feed-header',
avatar: feedInfo.data.avatar,
title: feedInfo.displayName,
})
if (feed.isLoading) {
items.push({
_reactKey: `__feed_loading_${i}__`,
type: 'feed-loading',
})
} else if (feed.hasError) {
items.push({
_reactKey: `__feed_error_${i}__`,
type: 'feed-error',
error: feed.error,
})
} else {
for (let j = 0; j < feed.slices.length; j++) {
items.push({
_reactKey: `__feed_slice_${i}_${j}__`,
type: 'feed-slice',
slice: feed.slices[j],
})
}
}
items.push({
_reactKey: `__feed_footer_${i}__`,
type: 'feed-footer',
title: feedInfo.displayName,
uri: `/profile/${feedInfo.data.creator.did}/feed/${urip.rkey}`,
})
}
if (!this.hasMore) {
items.push({_reactKey: '__footer__', type: 'footer'})
}
return items
}
// public api
// =
/**
* Nuke all data
*/
clear() {
this.rootStore.log.debug('MultiFeedModel:clear')
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.hasMore = true
this.feeds = []
}
/**
* Register any event listeners. Returns a cleanup function.
*/
registerListeners() {
const sub = this.rootStore.onPostDeleted(this.onPostDeleted.bind(this))
return () => sub.remove()
}
/**
* Reset and load
*/
async refresh() {
this.feedInfos = this.rootStore.me.savedFeeds.all.slice() // capture current feeds
await this.loadMore(true)
}
/**
* Load more posts to the end of the feed
*/
loadMore = bundleAsync(async (isRefreshing: boolean = false) => {
if (!isRefreshing && !this.hasMore) {
return
}
if (isRefreshing) {
this.isRefreshing = true // set optimistically for UI
this.feeds = []
}
this._xLoading(isRefreshing)
const start = this.feeds.length
const newFeeds: PostsFeedModel[] = []
for (
let i = start;
i < start + FEEDS_PAGE_SIZE && i < this.feedInfos.length;
i++
) {
const feed = new PostsFeedModel(this.rootStore, 'custom', {
feed: this.feedInfos[i].uri,
})
feed.pageSize = FEED_PAGE_SIZE
await feed.setup()
newFeeds.push(feed)
}
runInAction(() => {
this.feeds = this.feeds.concat(newFeeds)
this.hasMore = this.feeds.length < this.feedInfos.length
})
this._xIdle()
})
/**
* Attempt to load more again after a failure
*/
async retryLoadMore() {
this.hasMore = true
return this.loadMore()
}
/**
* Removes posts from the feed upon deletion.
*/
onPostDeleted(uri: string) {
for (const f of this.feeds) {
f.onPostDeleted(uri)
}
}
// state transitions
// =
_xLoading(isRefreshing = false) {
this.isLoading = true
this.isRefreshing = isRefreshing
}
_xIdle() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
}
// helper functions
// =
}

View File

@ -181,7 +181,7 @@ export class NotificationsFeedItemModel {
return false return false
} }
get additionaDataUri(): string | undefined { get additionalDataUri(): string | undefined {
if (this.isReply || this.isQuote || this.isMention) { if (this.isReply || this.isQuote || this.isMention) {
return this.uri return this.uri
} else if (this.isLike || this.isRepost) { } else if (this.isLike || this.isRepost) {
@ -290,7 +290,9 @@ export class NotificationsFeedModel {
} }
get hasNewLatest() { get hasNewLatest() {
return this.queuedNotifications && this.queuedNotifications?.length > 0 return Boolean(
this.queuedNotifications && this.queuedNotifications?.length > 0,
)
} }
get unreadCountLabel(): string { get unreadCountLabel(): string {
@ -490,7 +492,7 @@ export class NotificationsFeedModel {
'mostRecent', 'mostRecent',
res.data.notifications[0], res.data.notifications[0],
) )
const addedUri = notif.additionaDataUri const addedUri = notif.additionalDataUri
if (addedUri) { if (addedUri) {
const postsRes = await this.rootStore.agent.app.bsky.feed.getPosts({ const postsRes = await this.rootStore.agent.app.bsky.feed.getPosts({
uris: [addedUri], uris: [addedUri],
@ -583,7 +585,7 @@ export class NotificationsFeedModel {
`item-${_idCounter++}`, `item-${_idCounter++}`,
item, item,
) )
const uri = itemModel.additionaDataUri const uri = itemModel.additionalDataUri
if (uri) { if (uri) {
const models = addedPostMap.get(uri) || [] const models = addedPostMap.get(uri) || []
models.push(itemModel) models.push(itemModel)

View File

@ -0,0 +1,265 @@
import {makeAutoObservable} from 'mobx'
import {AppBskyFeedDefs, AppBskyFeedPost, RichText} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {updateDataOptimistically} from 'lib/async/revertible'
import {PostLabelInfo, PostModeration} from 'lib/labeling/types'
import {FeedViewPostsSlice} from 'lib/api/feed-manip'
import {
getEmbedLabels,
getEmbedMuted,
getEmbedMutedByList,
getEmbedBlocking,
getEmbedBlockedBy,
getPostModeration,
filterAccountLabels,
filterProfileLabels,
mergePostModerations,
} from 'lib/labeling/helpers'
type FeedViewPost = AppBskyFeedDefs.FeedViewPost
type ReasonRepost = AppBskyFeedDefs.ReasonRepost
type PostView = AppBskyFeedDefs.PostView
let _idCounter = 0
export class PostsFeedItemModel {
// ui state
_reactKey: string = ''
// data
post: PostView
postRecord?: AppBskyFeedPost.Record
reply?: FeedViewPost['reply']
reason?: FeedViewPost['reason']
richText?: RichText
constructor(
public rootStore: RootStoreModel,
reactKey: string,
v: FeedViewPost,
) {
this._reactKey = reactKey
this.post = v.post
if (AppBskyFeedPost.isRecord(this.post.record)) {
const valid = AppBskyFeedPost.validateRecord(this.post.record)
if (valid.success) {
this.postRecord = this.post.record
this.richText = new RichText(this.postRecord, {cleanNewlines: true})
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'Received an invalid app.bsky.feed.post record',
valid.error,
)
}
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'app.bsky.feed.getTimeline or app.bsky.feed.getAuthorFeed served an unexpected record type',
this.post.record,
)
}
this.reply = v.reply
this.reason = v.reason
makeAutoObservable(this, {rootStore: false})
}
get rootUri(): string {
if (this.reply?.root.uri) {
return this.reply.root.uri
}
return this.post.uri
}
get isThreadMuted() {
return this.rootStore.mutedThreads.uris.has(this.rootUri)
}
get labelInfo(): PostLabelInfo {
return {
postLabels: (this.post.labels || []).concat(
getEmbedLabels(this.post.embed),
),
accountLabels: filterAccountLabels(this.post.author.labels),
profileLabels: filterProfileLabels(this.post.author.labels),
isMuted:
this.post.author.viewer?.muted ||
getEmbedMuted(this.post.embed) ||
false,
mutedByList:
this.post.author.viewer?.mutedByList ||
getEmbedMutedByList(this.post.embed),
isBlocking:
!!this.post.author.viewer?.blocking ||
getEmbedBlocking(this.post.embed) ||
false,
isBlockedBy:
!!this.post.author.viewer?.blockedBy ||
getEmbedBlockedBy(this.post.embed) ||
false,
}
}
get moderation(): PostModeration {
return getPostModeration(this.rootStore, this.labelInfo)
}
copy(v: FeedViewPost) {
this.post = v.post
this.reply = v.reply
this.reason = v.reason
}
copyMetrics(v: FeedViewPost) {
this.post.replyCount = v.post.replyCount
this.post.repostCount = v.post.repostCount
this.post.likeCount = v.post.likeCount
this.post.viewer = v.post.viewer
}
get reasonRepost(): ReasonRepost | undefined {
if (this.reason?.$type === 'app.bsky.feed.defs#reasonRepost') {
return this.reason as ReasonRepost
}
}
async toggleLike() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer.like) {
const url = this.post.viewer.like
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) - 1
this.post.viewer!.like = undefined
},
() => this.rootStore.agent.deleteLike(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) + 1
this.post.viewer!.like = 'pending'
},
() => this.rootStore.agent.like(this.post.uri, this.post.cid),
res => {
this.post.viewer!.like = res.uri
},
)
}
}
async toggleRepost() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer?.repost) {
const url = this.post.viewer.repost
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) - 1
this.post.viewer!.repost = undefined
},
() => this.rootStore.agent.deleteRepost(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) + 1
this.post.viewer!.repost = 'pending'
},
() => this.rootStore.agent.repost(this.post.uri, this.post.cid),
res => {
this.post.viewer!.repost = res.uri
},
)
}
}
async toggleThreadMute() {
if (this.isThreadMuted) {
this.rootStore.mutedThreads.uris.delete(this.rootUri)
} else {
this.rootStore.mutedThreads.uris.add(this.rootUri)
}
}
async delete() {
await this.rootStore.agent.deletePost(this.post.uri)
this.rootStore.emitPostDeleted(this.post.uri)
}
}
export class PostsFeedSliceModel {
// ui state
_reactKey: string = ''
// data
items: PostsFeedItemModel[] = []
constructor(
public rootStore: RootStoreModel,
reactKey: string,
slice: FeedViewPostsSlice,
) {
this._reactKey = reactKey
for (const item of slice.items) {
this.items.push(
new PostsFeedItemModel(rootStore, `slice-${_idCounter++}`, item),
)
}
makeAutoObservable(this, {rootStore: false})
}
get uri() {
if (this.isReply) {
return this.items[1].post.uri
}
return this.items[0].post.uri
}
get isThread() {
return (
this.items.length > 1 &&
this.items.every(
item => item.post.author.did === this.items[0].post.author.did,
)
)
}
get isReply() {
return this.items.length > 1 && !this.isThread
}
get rootItem() {
if (this.isReply) {
return this.items[1]
}
return this.items[0]
}
get moderation() {
return mergePostModerations(this.items.map(item => item.moderation))
}
containsUri(uri: string) {
return !!this.items.find(item => item.post.uri === uri)
}
isThreadParentAt(i: number) {
if (this.items.length === 1) {
return false
}
return i < this.items.length - 1
}
isThreadChildAt(i: number) {
if (this.items.length === 1) {
return false
}
return i > 0
}
}

View File

@ -1,11 +1,8 @@
import {makeAutoObservable, runInAction} from 'mobx' import {makeAutoObservable, runInAction} from 'mobx'
import { import {
AppBskyFeedGetTimeline as GetTimeline, AppBskyFeedGetTimeline as GetTimeline,
AppBskyFeedDefs,
AppBskyFeedPost,
AppBskyFeedGetAuthorFeed as GetAuthorFeed, AppBskyFeedGetAuthorFeed as GetAuthorFeed,
RichText, AppBskyFeedGetFeed as GetCustomFeed,
jsonToLex,
} from '@atproto/api' } from '@atproto/api'
import AwaitLock from 'await-lock' import AwaitLock from 'await-lock'
import {bundleAsync} from 'lib/async/bundle' import {bundleAsync} from 'lib/async/bundle'
@ -19,269 +16,11 @@ import {
mergePosts, mergePosts,
} from 'lib/api/build-suggested-posts' } from 'lib/api/build-suggested-posts'
import {FeedTuner, FeedViewPostsSlice} from 'lib/api/feed-manip' import {FeedTuner, FeedViewPostsSlice} from 'lib/api/feed-manip'
import {updateDataOptimistically} from 'lib/async/revertible' import {PostsFeedSliceModel} from './post'
import {PostLabelInfo, PostModeration} from 'lib/labeling/types'
import {
getEmbedLabels,
getEmbedMuted,
getEmbedMutedByList,
getEmbedBlocking,
getEmbedBlockedBy,
getPostModeration,
mergePostModerations,
filterAccountLabels,
filterProfileLabels,
} from 'lib/labeling/helpers'
type FeedViewPost = AppBskyFeedDefs.FeedViewPost
type ReasonRepost = AppBskyFeedDefs.ReasonRepost
type PostView = AppBskyFeedDefs.PostView
const PAGE_SIZE = 30 const PAGE_SIZE = 30
let _idCounter = 0 let _idCounter = 0
export class PostsFeedItemModel {
// ui state
_reactKey: string = ''
// data
post: PostView
postRecord?: AppBskyFeedPost.Record
reply?: FeedViewPost['reply']
reason?: FeedViewPost['reason']
richText?: RichText
constructor(
public rootStore: RootStoreModel,
reactKey: string,
v: FeedViewPost,
) {
this._reactKey = reactKey
this.post = v.post
if (AppBskyFeedPost.isRecord(this.post.record)) {
const valid = AppBskyFeedPost.validateRecord(this.post.record)
if (valid.success) {
this.postRecord = this.post.record
this.richText = new RichText(this.postRecord, {cleanNewlines: true})
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'Received an invalid app.bsky.feed.post record',
valid.error,
)
}
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'app.bsky.feed.getTimeline or app.bsky.feed.getAuthorFeed served an unexpected record type',
this.post.record,
)
}
this.reply = v.reply
this.reason = v.reason
makeAutoObservable(this, {rootStore: false})
}
get rootUri(): string {
if (this.reply?.root.uri) {
return this.reply.root.uri
}
return this.post.uri
}
get isThreadMuted() {
return this.rootStore.mutedThreads.uris.has(this.rootUri)
}
get labelInfo(): PostLabelInfo {
return {
postLabels: (this.post.labels || []).concat(
getEmbedLabels(this.post.embed),
),
accountLabels: filterAccountLabels(this.post.author.labels),
profileLabels: filterProfileLabels(this.post.author.labels),
isMuted:
this.post.author.viewer?.muted ||
getEmbedMuted(this.post.embed) ||
false,
mutedByList:
this.post.author.viewer?.mutedByList ||
getEmbedMutedByList(this.post.embed),
isBlocking:
!!this.post.author.viewer?.blocking ||
getEmbedBlocking(this.post.embed) ||
false,
isBlockedBy:
!!this.post.author.viewer?.blockedBy ||
getEmbedBlockedBy(this.post.embed) ||
false,
}
}
get moderation(): PostModeration {
return getPostModeration(this.rootStore, this.labelInfo)
}
copy(v: FeedViewPost) {
this.post = v.post
this.reply = v.reply
this.reason = v.reason
}
copyMetrics(v: FeedViewPost) {
this.post.replyCount = v.post.replyCount
this.post.repostCount = v.post.repostCount
this.post.likeCount = v.post.likeCount
this.post.viewer = v.post.viewer
}
get reasonRepost(): ReasonRepost | undefined {
if (this.reason?.$type === 'app.bsky.feed.defs#reasonRepost') {
return this.reason as ReasonRepost
}
}
async toggleLike() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer.like) {
const url = this.post.viewer.like
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) - 1
this.post.viewer!.like = undefined
},
() => this.rootStore.agent.deleteLike(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) + 1
this.post.viewer!.like = 'pending'
},
() => this.rootStore.agent.like(this.post.uri, this.post.cid),
res => {
this.post.viewer!.like = res.uri
},
)
}
}
async toggleRepost() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer?.repost) {
const url = this.post.viewer.repost
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) - 1
this.post.viewer!.repost = undefined
},
() => this.rootStore.agent.deleteRepost(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) + 1
this.post.viewer!.repost = 'pending'
},
() => this.rootStore.agent.repost(this.post.uri, this.post.cid),
res => {
this.post.viewer!.repost = res.uri
},
)
}
}
async toggleThreadMute() {
if (this.isThreadMuted) {
this.rootStore.mutedThreads.uris.delete(this.rootUri)
} else {
this.rootStore.mutedThreads.uris.add(this.rootUri)
}
}
async delete() {
await this.rootStore.agent.deletePost(this.post.uri)
this.rootStore.emitPostDeleted(this.post.uri)
}
}
export class PostsFeedSliceModel {
// ui state
_reactKey: string = ''
// data
items: PostsFeedItemModel[] = []
constructor(
public rootStore: RootStoreModel,
reactKey: string,
slice: FeedViewPostsSlice,
) {
this._reactKey = reactKey
for (const item of slice.items) {
this.items.push(
new PostsFeedItemModel(rootStore, `item-${_idCounter++}`, item),
)
}
makeAutoObservable(this, {rootStore: false})
}
get uri() {
if (this.isReply) {
return this.items[1].post.uri
}
return this.items[0].post.uri
}
get isThread() {
return (
this.items.length > 1 &&
this.items.every(
item => item.post.author.did === this.items[0].post.author.did,
)
)
}
get isReply() {
return this.items.length > 1 && !this.isThread
}
get rootItem() {
if (this.isReply) {
return this.items[1]
}
return this.items[0]
}
get moderation() {
return mergePostModerations(this.items.map(item => item.moderation))
}
containsUri(uri: string) {
return !!this.items.find(item => item.post.uri === uri)
}
isThreadParentAt(i: number) {
if (this.items.length === 1) {
return false
}
return i < this.items.length - 1
}
isThreadChildAt(i: number) {
if (this.items.length === 1) {
return false
}
return i > 0
}
}
export class PostsFeedModel { export class PostsFeedModel {
// state // state
isLoading = false isLoading = false
@ -297,6 +36,7 @@ export class PostsFeedModel {
loadMoreCursor: string | undefined loadMoreCursor: string | undefined
pollCursor: string | undefined pollCursor: string | undefined
tuner = new FeedTuner() tuner = new FeedTuner()
pageSize = PAGE_SIZE
// used to linearize async modifications to state // used to linearize async modifications to state
lock = new AwaitLock() lock = new AwaitLock()
@ -309,8 +49,11 @@ export class PostsFeedModel {
constructor( constructor(
public rootStore: RootStoreModel, public rootStore: RootStoreModel,
public feedType: 'home' | 'author' | 'suggested' | 'goodstuff', public feedType: 'home' | 'author' | 'suggested' | 'custom',
params: GetTimeline.QueryParams | GetAuthorFeed.QueryParams, params:
| GetTimeline.QueryParams
| GetAuthorFeed.QueryParams
| GetCustomFeed.QueryParams,
) { ) {
makeAutoObservable( makeAutoObservable(
this, this,
@ -387,10 +130,9 @@ export class PostsFeedModel {
} }
get feedTuners() { get feedTuners() {
if (this.feedType === 'goodstuff') { if (this.feedType === 'custom') {
return [ return [
FeedTuner.dedupReposts, FeedTuner.dedupReposts,
FeedTuner.likedRepliesOnly,
FeedTuner.preferredLangOnly( FeedTuner.preferredLangOnly(
this.rootStore.preferences.contentLanguages, this.rootStore.preferences.contentLanguages,
), ),
@ -416,7 +158,7 @@ export class PostsFeedModel {
this.tuner.reset() this.tuner.reset()
this._xLoading(isRefreshing) this._xLoading(isRefreshing)
try { try {
const res = await this._getFeed({limit: PAGE_SIZE}) const res = await this._getFeed({limit: this.pageSize})
await this._replaceAll(res) await this._replaceAll(res)
this._xIdle() this._xIdle()
} catch (e: any) { } catch (e: any) {
@ -455,7 +197,7 @@ export class PostsFeedModel {
try { try {
const res = await this._getFeed({ const res = await this._getFeed({
cursor: this.loadMoreCursor, cursor: this.loadMoreCursor,
limit: PAGE_SIZE, limit: this.pageSize,
}) })
await this._appendAll(res) await this._appendAll(res)
this._xIdle() this._xIdle()
@ -524,7 +266,7 @@ export class PostsFeedModel {
if (this.hasNewLatest || this.feedType === 'suggested') { if (this.hasNewLatest || this.feedType === 'suggested') {
return return
} }
const res = await this._getFeed({limit: PAGE_SIZE}) const res = await this._getFeed({limit: this.pageSize})
const tuner = new FeedTuner() const tuner = new FeedTuner()
const slices = tuner.tune(res.data.feed, this.feedTuners) const slices = tuner.tune(res.data.feed, this.feedTuners)
this.setHasNewLatest(slices[0]?.uri !== this.slices[0]?.uri) this.setHasNewLatest(slices[0]?.uri !== this.slices[0]?.uri)
@ -599,13 +341,15 @@ export class PostsFeedModel {
// helper functions // helper functions
// = // =
async _replaceAll(res: GetTimeline.Response | GetAuthorFeed.Response) { async _replaceAll(
res: GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response,
) {
this.pollCursor = res.data.feed[0]?.post.uri this.pollCursor = res.data.feed[0]?.post.uri
return this._appendAll(res, true) return this._appendAll(res, true)
} }
async _appendAll( async _appendAll(
res: GetTimeline.Response | GetAuthorFeed.Response, res: GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response,
replace = false, replace = false,
) { ) {
this.loadMoreCursor = res.data.cursor this.loadMoreCursor = res.data.cursor
@ -644,7 +388,9 @@ export class PostsFeedModel {
}) })
} }
_updateAll(res: GetTimeline.Response | GetAuthorFeed.Response) { _updateAll(
res: GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response,
) {
for (const item of res.data.feed) { for (const item of res.data.feed) {
const existingSlice = this.slices.find(slice => const existingSlice = this.slices.find(slice =>
slice.containsUri(item.post.uri), slice.containsUri(item.post.uri),
@ -661,8 +407,13 @@ export class PostsFeedModel {
} }
protected async _getFeed( protected async _getFeed(
params: GetTimeline.QueryParams | GetAuthorFeed.QueryParams = {}, params:
): Promise<GetTimeline.Response | GetAuthorFeed.Response> { | GetTimeline.QueryParams
| GetAuthorFeed.QueryParams
| GetCustomFeed.QueryParams,
): Promise<
GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response
> {
params = Object.assign({}, this.params, params) params = Object.assign({}, this.params, params)
if (this.feedType === 'suggested') { if (this.feedType === 'suggested') {
const responses = await getMultipleAuthorsPosts( const responses = await getMultipleAuthorsPosts(
@ -684,61 +435,31 @@ export class PostsFeedModel {
} }
} else if (this.feedType === 'home') { } else if (this.feedType === 'home') {
return this.rootStore.agent.getTimeline(params as GetTimeline.QueryParams) return this.rootStore.agent.getTimeline(params as GetTimeline.QueryParams)
} else if (this.feedType === 'goodstuff') { } else if (this.feedType === 'custom') {
const res = await getGoodStuff( this.checkIfCustomFeedIsOnlineAndValid(
this.rootStore.session.currentSession?.accessJwt || '', params as GetCustomFeed.QueryParams,
params as GetTimeline.QueryParams,
) )
res.data.feed = (res.data.feed || []).filter( return this.rootStore.agent.app.bsky.feed.getFeed(
item => !item.post.author.viewer?.muted, params as GetCustomFeed.QueryParams,
) )
return res
} else { } else {
return this.rootStore.agent.getAuthorFeed( return this.rootStore.agent.getAuthorFeed(
params as GetAuthorFeed.QueryParams, params as GetAuthorFeed.QueryParams,
) )
} }
} }
}
// HACK private async checkIfCustomFeedIsOnlineAndValid(
// temporary off-spec route to get the good stuff params: GetCustomFeed.QueryParams,
// -prf ) {
async function getGoodStuff( const res = await this.rootStore.agent.app.bsky.feed.getFeedGenerator({
accessJwt: string, feed: params.feed,
params: GetTimeline.QueryParams, })
): Promise<GetTimeline.Response> { if (!res.data.isOnline || !res.data.isValid) {
const controller = new AbortController() runInAction(() => {
const to = setTimeout(() => controller.abort(), 15e3) this.error =
'This custom feed is not online or may be experiencing issues.'
const uri = new URL('https://bsky.social/xrpc/app.bsky.unspecced.getPopular') })
let k: keyof GetTimeline.QueryParams
for (k in params) {
if (typeof params[k] !== 'undefined') {
uri.searchParams.set(k, String(params[k]))
} }
} }
const res = await fetch(String(uri), {
method: 'get',
headers: {
accept: 'application/json',
authorization: `Bearer ${accessJwt}`,
},
signal: controller.signal,
})
const resHeaders: Record<string, string> = {}
res.headers.forEach((value: string, key: string) => {
resHeaders[key] = value
})
let resBody = await res.json()
clearTimeout(to)
return {
success: res.status === 200,
headers: resHeaders,
data: jsonToLex(resBody),
}
} }

View File

@ -0,0 +1,120 @@
import {makeAutoObservable} from 'mobx'
import {AppBskyFeedGetActorFeeds as GetActorFeeds} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {bundleAsync} from 'lib/async/bundle'
import {cleanError} from 'lib/strings/errors'
import {CustomFeedModel} from '../feeds/custom-feed'
const PAGE_SIZE = 30
export class ActorFeedsModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
error = ''
hasMore = true
loadMoreCursor?: string
// data
feeds: CustomFeedModel[] = []
constructor(
public rootStore: RootStoreModel,
public params: GetActorFeeds.QueryParams,
) {
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
get hasContent() {
return this.feeds.length > 0
}
get hasError() {
return this.error !== ''
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
// public api
// =
async refresh() {
return this.loadMore(true)
}
clear() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.error = ''
this.hasMore = true
this.loadMoreCursor = undefined
this.feeds = []
}
loadMore = bundleAsync(async (replace: boolean = false) => {
if (!replace && !this.hasMore) {
return
}
this._xLoading(replace)
try {
const res = await this.rootStore.agent.app.bsky.feed.getActorFeeds({
actor: this.params.actor,
limit: PAGE_SIZE,
cursor: replace ? undefined : this.loadMoreCursor,
})
if (replace) {
this._replaceAll(res)
} else {
this._appendAll(res)
}
this._xIdle()
} catch (e: any) {
this._xIdle(e)
}
})
// state transitions
// =
_xLoading(isRefreshing = false) {
this.isLoading = true
this.isRefreshing = isRefreshing
this.error = ''
}
_xIdle(err?: any) {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
this.error = cleanError(err)
if (err) {
this.rootStore.log.error('Failed to fetch user followers', err)
}
}
// helper functions
// =
_replaceAll(res: GetActorFeeds.Response) {
this.feeds = []
this._appendAll(res)
}
_appendAll(res: GetActorFeeds.Response) {
this.loadMoreCursor = res.data.cursor
this.hasMore = !!this.loadMoreCursor
for (const f of res.data.feeds) {
this.feeds.push(new CustomFeedModel(this.rootStore, f))
}
}
}

View File

@ -27,6 +27,7 @@ function genId(): string {
export class LogModel { export class LogModel {
entries: LogEntry[] = [] entries: LogEntry[] = []
timers = new Map<string, number>()
constructor() { constructor() {
makeAutoObservable(this) makeAutoObservable(this)
@ -74,6 +75,21 @@ export class LogModel {
ts: Date.now(), ts: Date.now(),
}) })
} }
time = (label = 'default') => {
this.timers.set(label, performance.now())
}
timeEnd = (label = 'default', warn = false) => {
const endTime = performance.now()
if (this.timers.has(label)) {
const elapsedTime = endTime - this.timers.get(label)!
console.log(`${label}: ${elapsedTime.toFixed(3)}ms`)
this.timers.delete(label)
} else {
warn && console.warn(`Timer with label '${label}' does not exist.`)
}
}
} }
function detailsToStr(details?: any) { function detailsToStr(details?: any) {

View File

@ -8,6 +8,7 @@ import {PostsFeedModel} from './feeds/posts'
import {NotificationsFeedModel} from './feeds/notifications' import {NotificationsFeedModel} from './feeds/notifications'
import {MyFollowsCache} from './cache/my-follows' import {MyFollowsCache} from './cache/my-follows'
import {isObj, hasProp} from 'lib/type-guards' import {isObj, hasProp} from 'lib/type-guards'
import {SavedFeedsModel} from './ui/saved-feeds'
const PROFILE_UPDATE_INTERVAL = 10 * 60 * 1e3 // 10min const PROFILE_UPDATE_INTERVAL = 10 * 60 * 1e3 // 10min
const NOTIFS_UPDATE_INTERVAL = 30 * 1e3 // 30sec const NOTIFS_UPDATE_INTERVAL = 30 * 1e3 // 30sec
@ -21,6 +22,7 @@ export class MeModel {
followsCount: number | undefined followsCount: number | undefined
followersCount: number | undefined followersCount: number | undefined
mainFeed: PostsFeedModel mainFeed: PostsFeedModel
savedFeeds: SavedFeedsModel
notifications: NotificationsFeedModel notifications: NotificationsFeedModel
follows: MyFollowsCache follows: MyFollowsCache
invites: ComAtprotoServerDefs.InviteCode[] = [] invites: ComAtprotoServerDefs.InviteCode[] = []
@ -43,12 +45,14 @@ export class MeModel {
}) })
this.notifications = new NotificationsFeedModel(this.rootStore) this.notifications = new NotificationsFeedModel(this.rootStore)
this.follows = new MyFollowsCache(this.rootStore) this.follows = new MyFollowsCache(this.rootStore)
this.savedFeeds = new SavedFeedsModel(this.rootStore)
} }
clear() { clear() {
this.mainFeed.clear() this.mainFeed.clear()
this.notifications.clear() this.notifications.clear()
this.follows.clear() this.follows.clear()
this.savedFeeds.clear()
this.did = '' this.did = ''
this.handle = '' this.handle = ''
this.displayName = '' this.displayName = ''
@ -110,6 +114,7 @@ export class MeModel {
/* dont await */ this.notifications.setup().catch(e => { /* dont await */ this.notifications.setup().catch(e => {
this.rootStore.log.error('Failed to setup notifications model', e) this.rootStore.log.error('Failed to setup notifications model', e)
}) })
/* dont await */ this.savedFeeds.refresh(true)
this.rootStore.emitSessionLoaded() this.rootStore.emitSessionLoaded()
await this.fetchInviteCodes() await this.fetchInviteCodes()
await this.fetchAppPasswords() await this.fetchAppPasswords()
@ -119,6 +124,7 @@ export class MeModel {
} }
async updateIfNeeded() { async updateIfNeeded() {
/* dont await */ this.savedFeeds.refresh(true)
if (Date.now() - this.lastProfileStateUpdate > PROFILE_UPDATE_INTERVAL) { if (Date.now() - this.lastProfileStateUpdate > PROFILE_UPDATE_INTERVAL) {
this.rootStore.log.debug('Updating me profile information') this.rootStore.log.debug('Updating me profile information')
this.lastProfileStateUpdate = Date.now() this.lastProfileStateUpdate = Date.now()

View File

@ -4,7 +4,6 @@ import {ImageModel} from './image'
import {Image as RNImage} from 'react-native-image-crop-picker' import {Image as RNImage} from 'react-native-image-crop-picker'
import {openPicker} from 'lib/media/picker' import {openPicker} from 'lib/media/picker'
import {getImageDim} from 'lib/media/manip' import {getImageDim} from 'lib/media/manip'
import {getDataUriSize} from 'lib/media/util'
import {isNative} from 'platform/detection' import {isNative} from 'platform/detection'
export class GalleryModel { export class GalleryModel {
@ -24,13 +23,7 @@ export class GalleryModel {
return this.images.length return this.images.length
} }
get paths() { async add(image_: Omit<RNImage, 'size'>) {
return this.images.map(image =>
image.compressed === undefined ? image.path : image.compressed.path,
)
}
async add(image_: RNImage) {
if (this.size >= 4) { if (this.size >= 4) {
return return
} }
@ -39,15 +32,9 @@ export class GalleryModel {
if (!this.images.some(i => i.path === image_.path)) { if (!this.images.some(i => i.path === image_.path)) {
const image = new ImageModel(this.rootStore, image_) const image = new ImageModel(this.rootStore, image_)
if (!isNative) { // Initial resize
await image.manipulate({}) image.manipulate({})
} else { this.images.push(image)
await image.compress()
}
runInAction(() => {
this.images.push(image)
})
} }
} }
@ -70,11 +57,10 @@ export class GalleryModel {
const {width, height} = await getImageDim(uri) const {width, height} = await getImageDim(uri)
const image: RNImage = { const image = {
path: uri, path: uri,
height, height,
width, width,
size: getDataUriSize(uri),
mime: 'image/jpeg', mime: 'image/jpeg',
} }

View File

@ -3,14 +3,11 @@ import {RootStoreModel} from 'state/index'
import {makeAutoObservable, runInAction} from 'mobx' import {makeAutoObservable, runInAction} from 'mobx'
import {POST_IMG_MAX} from 'lib/constants' import {POST_IMG_MAX} from 'lib/constants'
import * as ImageManipulator from 'expo-image-manipulator' import * as ImageManipulator from 'expo-image-manipulator'
import {getDataUriSize, scaleDownDimensions} from 'lib/media/util' import {getDataUriSize} from 'lib/media/util'
import {openCropper} from 'lib/media/picker' import {openCropper} from 'lib/media/picker'
import {ActionCrop, FlipType, SaveFormat} from 'expo-image-manipulator' import {ActionCrop, FlipType, SaveFormat} from 'expo-image-manipulator'
import {Position} from 'react-avatar-editor' import {Position} from 'react-avatar-editor'
import {compressAndResizeImageForPost} from 'lib/media/manip' import {Dimensions} from 'lib/media/types'
// TODO: EXIF embed
// Cases to consider: ExternalEmbed
export interface ImageManipulationAttributes { export interface ImageManipulationAttributes {
aspectRatio?: '4:3' | '1:1' | '3:4' | 'None' aspectRatio?: '4:3' | '1:1' | '3:4' | 'None'
@ -21,17 +18,16 @@ export interface ImageManipulationAttributes {
flipVertical?: boolean flipVertical?: boolean
} }
export class ImageModel implements RNImage { const MAX_IMAGE_SIZE_IN_BYTES = 976560
export class ImageModel implements Omit<RNImage, 'size'> {
path: string path: string
mime = 'image/jpeg' mime = 'image/jpeg'
width: number width: number
height: number height: number
size: number
altText = '' altText = ''
cropped?: RNImage = undefined cropped?: RNImage = undefined
compressed?: RNImage = undefined compressed?: RNImage = undefined
scaledWidth: number = POST_IMG_MAX.width
scaledHeight: number = POST_IMG_MAX.height
// Web manipulation // Web manipulation
prev?: RNImage prev?: RNImage
@ -44,7 +40,7 @@ export class ImageModel implements RNImage {
} }
prevAttributes: ImageManipulationAttributes = {} prevAttributes: ImageManipulationAttributes = {}
constructor(public rootStore: RootStoreModel, image: RNImage) { constructor(public rootStore: RootStoreModel, image: Omit<RNImage, 'size'>) {
makeAutoObservable(this, { makeAutoObservable(this, {
rootStore: false, rootStore: false,
}) })
@ -52,19 +48,8 @@ export class ImageModel implements RNImage {
this.path = image.path this.path = image.path
this.width = image.width this.width = image.width
this.height = image.height this.height = image.height
this.size = image.size
this.calcScaledDimensions()
} }
// TODO: Revisit compression factor due to updated sizing with zoom
// get compressionFactor() {
// const MAX_IMAGE_SIZE_IN_BYTES = 976560
// return this.size < MAX_IMAGE_SIZE_IN_BYTES
// ? 1
// : MAX_IMAGE_SIZE_IN_BYTES / this.size
// }
setRatio(aspectRatio: ImageManipulationAttributes['aspectRatio']) { setRatio(aspectRatio: ImageManipulationAttributes['aspectRatio']) {
this.attributes.aspectRatio = aspectRatio this.attributes.aspectRatio = aspectRatio
} }
@ -93,8 +78,24 @@ export class ImageModel implements RNImage {
} }
} }
getDisplayDimensions( getUploadDimensions(
as: ImageManipulationAttributes['aspectRatio'] = '1:1', dimensions: Dimensions,
maxDimensions: Dimensions = POST_IMG_MAX,
as: ImageManipulationAttributes['aspectRatio'] = 'None',
) {
const {width, height} = dimensions
const {width: maxWidth, height: maxHeight} = maxDimensions
return width < maxWidth && height < maxHeight
? {
width,
height,
}
: this.getResizedDimensions(as, POST_IMG_MAX.width)
}
getResizedDimensions(
as: ImageManipulationAttributes['aspectRatio'] = 'None',
maxSide: number, maxSide: number,
) { ) {
const ratioMultiplier = this.ratioMultipliers[as] const ratioMultiplier = this.ratioMultipliers[as]
@ -119,59 +120,70 @@ export class ImageModel implements RNImage {
} }
} }
calcScaledDimensions() {
const {width, height} = scaleDownDimensions(
{width: this.width, height: this.height},
POST_IMG_MAX,
)
this.scaledWidth = width
this.scaledHeight = height
}
async setAltText(altText: string) { async setAltText(altText: string) {
this.altText = altText this.altText = altText
} }
// Only for mobile // Only compress prior to upload
async compress() {
for (let i = 10; i > 0; i--) {
// Float precision
const factor = Math.round(i) / 10
const compressed = await ImageManipulator.manipulateAsync(
this.cropped?.path ?? this.path,
undefined,
{
compress: factor,
base64: true,
format: SaveFormat.JPEG,
},
)
if (compressed.base64 !== undefined) {
const size = getDataUriSize(compressed.base64)
if (size < MAX_IMAGE_SIZE_IN_BYTES) {
runInAction(() => {
this.compressed = {
mime: 'image/jpeg',
path: compressed.uri,
size,
...compressed,
}
})
return
}
}
}
// Compression fails when removing redundant information is not possible.
// This can be tested with images that have high variance in noise.
throw new Error('Failed to compress image')
}
// Mobile
async crop() { async crop() {
try { try {
const cropped = await openCropper({ // openCropper requires an output width and height hence
// getting upload dimensions before cropping is necessary.
const {width, height} = this.getUploadDimensions({
width: this.width,
height: this.height,
})
const cropped = await openCropper(this.rootStore, {
mediaType: 'photo', mediaType: 'photo',
path: this.path, path: this.path,
freeStyleCropEnabled: true, freeStyleCropEnabled: true,
width: this.scaledWidth,
height: this.scaledHeight,
})
runInAction(() => {
this.cropped = cropped
this.compress()
})
} catch (err) {
this.rootStore.log.error('Failed to crop photo', err)
}
}
async compress() {
try {
const {width, height} = scaleDownDimensions(
this.cropped
? {width: this.cropped.width, height: this.cropped.height}
: {width: this.width, height: this.height},
POST_IMG_MAX,
)
// TODO: Revisit this - currently iOS uses this as well
const compressed = await compressAndResizeImageForPost({
...(this.cropped === undefined ? this : this.cropped),
width, width,
height, height,
}) })
runInAction(() => { runInAction(() => {
this.compressed = compressed this.cropped = cropped
}) })
} catch (err) { } catch (err) {
this.rootStore.log.error('Failed to compress photo', err) this.rootStore.log.error('Failed to crop photo', err)
} }
} }
@ -181,6 +193,9 @@ export class ImageModel implements RNImage {
crop?: ActionCrop['crop'] crop?: ActionCrop['crop']
} & ImageManipulationAttributes, } & ImageManipulationAttributes,
) { ) {
let uploadWidth: number | undefined
let uploadHeight: number | undefined
const {aspectRatio, crop, position, scale} = attributes const {aspectRatio, crop, position, scale} = attributes
const modifiers = [] const modifiers = []
@ -197,14 +212,34 @@ export class ImageModel implements RNImage {
} }
if (crop !== undefined) { if (crop !== undefined) {
const croppedHeight = crop.height * this.height
const croppedWidth = crop.width * this.width
modifiers.push({ modifiers.push({
crop: { crop: {
originX: crop.originX * this.width, originX: crop.originX * this.width,
originY: crop.originY * this.height, originY: crop.originY * this.height,
height: crop.height * this.height, height: croppedHeight,
width: crop.width * this.width, width: croppedWidth,
}, },
}) })
const uploadDimensions = this.getUploadDimensions(
{width: croppedWidth, height: croppedHeight},
POST_IMG_MAX,
aspectRatio,
)
uploadWidth = uploadDimensions.width
uploadHeight = uploadDimensions.height
} else {
const uploadDimensions = this.getUploadDimensions(
{width: this.width, height: this.height},
POST_IMG_MAX,
aspectRatio,
)
uploadWidth = uploadDimensions.width
uploadHeight = uploadDimensions.height
} }
if (scale !== undefined) { if (scale !== undefined) {
@ -222,36 +257,40 @@ export class ImageModel implements RNImage {
const ratioMultiplier = const ratioMultiplier =
this.ratioMultipliers[this.attributes.aspectRatio ?? '1:1'] this.ratioMultipliers[this.attributes.aspectRatio ?? '1:1']
const MAX_SIDE = 2000
const result = await ImageManipulator.manipulateAsync( const result = await ImageManipulator.manipulateAsync(
this.path, this.path,
[ [
...modifiers, ...modifiers,
{resize: ratioMultiplier > 1 ? {width: MAX_SIDE} : {height: MAX_SIDE}}, {
resize:
ratioMultiplier > 1 ? {width: uploadWidth} : {height: uploadHeight},
},
], ],
{ {
compress: 0.9, base64: true,
format: SaveFormat.JPEG, format: SaveFormat.JPEG,
}, },
) )
runInAction(() => { runInAction(() => {
this.compressed = { this.cropped = {
mime: 'image/jpeg', mime: 'image/jpeg',
path: result.uri, path: result.uri,
size: getDataUriSize(result.uri), size:
result.base64 !== undefined
? getDataUriSize(result.base64)
: MAX_IMAGE_SIZE_IN_BYTES + 999, // shouldn't hit this unless manipulation fails
...result, ...result,
} }
}) })
} }
resetCompressed() { resetCropped() {
this.manipulate({}) this.manipulate({})
} }
previous() { previous() {
this.compressed = this.prev this.cropped = this.prev
this.attributes = this.prevAttributes this.attributes = this.prevAttributes
} }
} }

View File

@ -187,7 +187,7 @@ export class SessionModel {
account => account.service === service && account.did === did, account => account.service === service && account.did === did,
) )
// fall back to any pre-existing access tokens // fall back to any preexisting access tokens
let refreshJwt = session?.refreshJwt || existingAccount?.refreshJwt let refreshJwt = session?.refreshJwt || existingAccount?.refreshJwt
let accessJwt = session?.accessJwt || existingAccount?.accessJwt let accessJwt = session?.accessJwt || existingAccount?.accessJwt
if (event === 'expired') { if (event === 'expired') {
@ -247,7 +247,7 @@ export class SessionModel {
const res = await agent.getProfile({actor: did}).catch(_e => undefined) const res = await agent.getProfile({actor: did}).catch(_e => undefined)
if (res) { if (res) {
return { return {
dispayName: res.data.displayName, displayName: res.data.displayName,
aviUrl: res.data.avatar, aviUrl: res.data.avatar,
} }
} }

View File

@ -11,6 +11,7 @@ import {
ALWAYS_FILTER_LABEL_GROUP, ALWAYS_FILTER_LABEL_GROUP,
ALWAYS_WARN_LABEL_GROUP, ALWAYS_WARN_LABEL_GROUP,
} from 'lib/labeling/const' } from 'lib/labeling/const'
import {DEFAULT_FEEDS} from 'lib/constants'
import {isIOS} from 'platform/detection' import {isIOS} from 'platform/detection'
const deviceLocales = getLocales() const deviceLocales = getLocales()
@ -25,6 +26,7 @@ const LABEL_GROUPS = [
'spam', 'spam',
'impersonation', 'impersonation',
] ]
const VISIBILITY_VALUES = ['show', 'warn', 'hide']
export class LabelPreferencesModel { export class LabelPreferencesModel {
nsfw: LabelPreference = 'hide' nsfw: LabelPreference = 'hide'
@ -45,6 +47,8 @@ export class PreferencesModel {
contentLanguages: string[] = contentLanguages: string[] =
deviceLocales?.map?.(locale => locale.languageCode) || [] deviceLocales?.map?.(locale => locale.languageCode) || []
contentLabels = new LabelPreferencesModel() contentLabels = new LabelPreferencesModel()
savedFeeds: string[] = []
pinnedFeeds: string[] = []
constructor(public rootStore: RootStoreModel) { constructor(public rootStore: RootStoreModel) {
makeAutoObservable(this, {}, {autoBind: true}) makeAutoObservable(this, {}, {autoBind: true})
@ -54,9 +58,16 @@ export class PreferencesModel {
return { return {
contentLanguages: this.contentLanguages, contentLanguages: this.contentLanguages,
contentLabels: this.contentLabels, contentLabels: this.contentLabels,
savedFeeds: this.savedFeeds,
pinnedFeeds: this.pinnedFeeds,
} }
} }
/**
* The function hydrates an object with properties related to content languages, labels, saved feeds,
* and pinned feeds that it gets from the parameter `v` (probably local storage)
* @param {unknown} v - the data object to hydrate from
*/
hydrate(v: unknown) { hydrate(v: unknown) {
if (isObj(v)) { if (isObj(v)) {
if ( if (
@ -72,10 +83,29 @@ export class PreferencesModel {
// default to the device languages // default to the device languages
this.contentLanguages = deviceLocales.map(locale => locale.languageCode) this.contentLanguages = deviceLocales.map(locale => locale.languageCode)
} }
if (
hasProp(v, 'savedFeeds') &&
Array.isArray(v.savedFeeds) &&
typeof v.savedFeeds.every(item => typeof item === 'string')
) {
this.savedFeeds = v.savedFeeds
}
if (
hasProp(v, 'pinnedFeeds') &&
Array.isArray(v.pinnedFeeds) &&
typeof v.pinnedFeeds.every(item => typeof item === 'string')
) {
this.pinnedFeeds = v.pinnedFeeds
}
} }
} }
/**
* This function fetches preferences and sets defaults for missing items.
*/
async sync() { async sync() {
// fetch preferences
let hasSavedFeedsPref = false
const res = await this.rootStore.agent.app.bsky.actor.getPreferences({}) const res = await this.rootStore.agent.app.bsky.actor.getPreferences({})
runInAction(() => { runInAction(() => {
for (const pref of res.data.preferences) { for (const pref of res.data.preferences) {
@ -88,22 +118,83 @@ export class PreferencesModel {
AppBskyActorDefs.isContentLabelPref(pref) && AppBskyActorDefs.isContentLabelPref(pref) &&
AppBskyActorDefs.validateAdultContentPref(pref).success AppBskyActorDefs.validateAdultContentPref(pref).success
) { ) {
if (LABEL_GROUPS.includes(pref.label)) { if (
this.contentLabels[pref.label] = pref.visibility LABEL_GROUPS.includes(pref.label) &&
VISIBILITY_VALUES.includes(pref.visibility)
) {
this.contentLabels[pref.label as keyof LabelPreferencesModel] =
pref.visibility as LabelPreference
} }
} else if (
AppBskyActorDefs.isSavedFeedsPref(pref) &&
AppBskyActorDefs.validateSavedFeedsPref(pref).success
) {
this.savedFeeds = pref.saved
this.pinnedFeeds = pref.pinned
hasSavedFeedsPref = true
} }
} }
}) })
// set defaults on missing items
if (!hasSavedFeedsPref) {
const {saved, pinned} = await DEFAULT_FEEDS(
this.rootStore.agent.service.toString(),
(handle: string) =>
this.rootStore.agent
.resolveHandle({handle})
.then(({data}) => data.did),
)
runInAction(() => {
this.savedFeeds = saved
this.pinnedFeeds = pinned
})
res.data.preferences.push({
$type: 'app.bsky.actor.defs#savedFeedsPref',
saved,
pinned,
})
await this.rootStore.agent.app.bsky.actor.putPreferences({
preferences: res.data.preferences,
})
/* dont await */ this.rootStore.me.savedFeeds.refresh()
}
} }
async update(cb: (prefs: AppBskyActorDefs.Preferences) => void) { /**
* This function updates the preferences of a user and allows for a callback function to be executed
* before the update.
* @param cb - cb is a callback function that takes in a single parameter of type
* AppBskyActorDefs.Preferences and returns either a boolean or void. This callback function is used to
* update the preferences of the user. The function is called with the current preferences as an
* argument and if the callback returns false, the preferences are not updated.
* @returns void
*/
async update(cb: (prefs: AppBskyActorDefs.Preferences) => boolean | void) {
const res = await this.rootStore.agent.app.bsky.actor.getPreferences({}) const res = await this.rootStore.agent.app.bsky.actor.getPreferences({})
cb(res.data.preferences) if (cb(res.data.preferences) === false) {
return
}
await this.rootStore.agent.app.bsky.actor.putPreferences({ await this.rootStore.agent.app.bsky.actor.putPreferences({
preferences: res.data.preferences, preferences: res.data.preferences,
}) })
} }
/**
* This function resets the preferences to an empty array of no preferences.
*/
async reset() {
runInAction(() => {
this.contentLabels = new LabelPreferencesModel()
this.contentLanguages = deviceLocales.map(locale => locale.languageCode)
this.savedFeeds = []
this.pinnedFeeds = []
})
await this.rootStore.agent.app.bsky.actor.putPreferences({
preferences: [],
})
}
hasContentLanguage(code2: string) { hasContentLanguage(code2: string) {
return this.contentLanguages.includes(code2) return this.contentLanguages.includes(code2)
} }
@ -200,4 +291,62 @@ export class PreferencesModel {
} }
return res return res
} }
setFeeds(saved: string[], pinned: string[]) {
this.savedFeeds = saved
this.pinnedFeeds = pinned
}
async setSavedFeeds(saved: string[], pinned: string[]) {
const oldSaved = this.savedFeeds
const oldPinned = this.pinnedFeeds
this.setFeeds(saved, pinned)
try {
await this.update((prefs: AppBskyActorDefs.Preferences) => {
const existing = prefs.find(
pref =>
AppBskyActorDefs.isSavedFeedsPref(pref) &&
AppBskyActorDefs.validateSavedFeedsPref(pref).success,
)
if (existing) {
existing.saved = saved
existing.pinned = pinned
} else {
prefs.push({
$type: 'app.bsky.actor.defs#savedFeedsPref',
saved,
pinned,
})
}
})
} catch (e) {
runInAction(() => {
this.savedFeeds = oldSaved
this.pinnedFeeds = oldPinned
})
throw e
}
}
async addSavedFeed(v: string) {
return this.setSavedFeeds([...this.savedFeeds, v], this.pinnedFeeds)
}
async removeSavedFeed(v: string) {
return this.setSavedFeeds(
this.savedFeeds.filter(uri => uri !== v),
this.pinnedFeeds.filter(uri => uri !== v),
)
}
async addPinnedFeed(v: string) {
return this.setSavedFeeds(this.savedFeeds, [...this.pinnedFeeds, v])
}
async removePinnedFeed(v: string) {
return this.setSavedFeeds(
this.savedFeeds,
this.pinnedFeeds.filter(uri => uri !== v),
)
}
} }

View File

@ -2,20 +2,16 @@ import {makeAutoObservable} from 'mobx'
import {RootStoreModel} from '../root-store' import {RootStoreModel} from '../root-store'
import {ProfileModel} from '../content/profile' import {ProfileModel} from '../content/profile'
import {PostsFeedModel} from '../feeds/posts' import {PostsFeedModel} from '../feeds/posts'
import {ActorFeedsModel} from '../lists/actor-feeds'
import {ListsListModel} from '../lists/lists-list' import {ListsListModel} from '../lists/lists-list'
export enum Sections { export enum Sections {
Posts = 'Posts', Posts = 'Posts',
PostsWithReplies = 'Posts & replies', PostsWithReplies = 'Posts & replies',
CustomAlgorithms = 'Feeds',
Lists = 'Lists', Lists = 'Lists',
} }
const USER_SELECTOR_ITEMS = [
Sections.Posts,
Sections.PostsWithReplies,
Sections.Lists,
]
export interface ProfileUiParams { export interface ProfileUiParams {
user: string user: string
} }
@ -28,6 +24,7 @@ export class ProfileUiModel {
// data // data
profile: ProfileModel profile: ProfileModel
feed: PostsFeedModel feed: PostsFeedModel
algos: ActorFeedsModel
lists: ListsListModel lists: ListsListModel
// ui state // ui state
@ -50,10 +47,11 @@ export class ProfileUiModel {
actor: params.user, actor: params.user,
limit: 10, limit: 10,
}) })
this.algos = new ActorFeedsModel(rootStore, {actor: params.user})
this.lists = new ListsListModel(rootStore, params.user) this.lists = new ListsListModel(rootStore, params.user)
} }
get currentView(): PostsFeedModel | ListsListModel { get currentView(): PostsFeedModel | ActorFeedsModel | ListsListModel {
if ( if (
this.selectedView === Sections.Posts || this.selectedView === Sections.Posts ||
this.selectedView === Sections.PostsWithReplies this.selectedView === Sections.PostsWithReplies
@ -62,6 +60,9 @@ export class ProfileUiModel {
} else if (this.selectedView === Sections.Lists) { } else if (this.selectedView === Sections.Lists) {
return this.lists return this.lists
} }
if (this.selectedView === Sections.CustomAlgorithms) {
return this.algos
}
throw new Error(`Invalid selector value: ${this.selectedViewIndex}`) throw new Error(`Invalid selector value: ${this.selectedViewIndex}`)
} }
@ -75,7 +76,14 @@ export class ProfileUiModel {
} }
get selectorItems() { get selectorItems() {
return USER_SELECTOR_ITEMS const items = [Sections.Posts, Sections.PostsWithReplies]
if (this.algos.hasLoaded && !this.algos.isEmpty) {
items.push(Sections.CustomAlgorithms)
}
if (this.lists.hasLoaded && !this.lists.isEmpty) {
items.push(Sections.Lists)
}
return items
} }
get selectedView() { get selectedView() {
@ -84,9 +92,11 @@ export class ProfileUiModel {
get uiItems() { get uiItems() {
let arr: any[] = [] let arr: any[] = []
// if loading, return loading item to show loading spinner
if (this.isInitialLoading) { if (this.isInitialLoading) {
arr = arr.concat([ProfileUiModel.LOADING_ITEM]) arr = arr.concat([ProfileUiModel.LOADING_ITEM])
} else if (this.currentView.hasError) { } else if (this.currentView.hasError) {
// if error, return error item to show error message
arr = arr.concat([ arr = arr.concat([
{ {
_reactKey: '__error__', _reactKey: '__error__',
@ -94,12 +104,16 @@ export class ProfileUiModel {
}, },
]) ])
} else { } else {
// not loading, no error, show content
if ( if (
this.selectedView === Sections.Posts || this.selectedView === Sections.Posts ||
this.selectedView === Sections.PostsWithReplies this.selectedView === Sections.PostsWithReplies ||
this.selectedView === Sections.CustomAlgorithms
) { ) {
if (this.feed.hasContent) { if (this.feed.hasContent) {
if (this.selectedView === Sections.Posts) { if (this.selectedView === Sections.CustomAlgorithms) {
arr = this.algos.feeds
} else if (this.selectedView === Sections.Posts) {
arr = this.feed.nonReplyFeed arr = this.feed.nonReplyFeed
} else { } else {
arr = this.feed.slices.slice() arr = this.feed.slices.slice()
@ -117,6 +131,7 @@ export class ProfileUiModel {
arr = arr.concat([ProfileUiModel.EMPTY_ITEM]) arr = arr.concat([ProfileUiModel.EMPTY_ITEM])
} }
} else { } else {
// fallback, add empty item, to show empty message
arr = arr.concat([ProfileUiModel.EMPTY_ITEM]) arr = arr.concat([ProfileUiModel.EMPTY_ITEM])
} }
} }
@ -151,6 +166,7 @@ export class ProfileUiModel {
.setup() .setup()
.catch(err => this.rootStore.log.error('Failed to fetch feed', err)), .catch(err => this.rootStore.log.error('Failed to fetch feed', err)),
]) ])
this.algos.refresh()
// HACK: need to use the DID as a param, not the username -prf // HACK: need to use the DID as a param, not the username -prf
this.lists.source = this.profile.did this.lists.source = this.profile.did
this.lists this.lists

View File

@ -0,0 +1,185 @@
import {makeAutoObservable, runInAction} from 'mobx'
import {AppBskyFeedDefs} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {bundleAsync} from 'lib/async/bundle'
import {cleanError} from 'lib/strings/errors'
import {CustomFeedModel} from '../feeds/custom-feed'
export class SavedFeedsModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
error = ''
// data
feeds: CustomFeedModel[] = []
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
get hasContent() {
return this.feeds.length > 0
}
get hasError() {
return this.error !== ''
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
get pinned() {
return this.rootStore.preferences.pinnedFeeds
.map(uri => this.feeds.find(f => f.uri === uri) as CustomFeedModel)
.filter(Boolean)
}
get unpinned() {
return this.feeds.filter(f => !this.isPinned(f))
}
get all() {
return this.pinned.concat(this.unpinned)
}
get pinnedFeedNames() {
return this.pinned.map(f => f.displayName)
}
// public api
// =
clear() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.error = ''
this.feeds = []
}
refresh = bundleAsync(async (quietRefresh = false) => {
this._xLoading(!quietRefresh)
try {
let feeds: AppBskyFeedDefs.GeneratorView[] = []
for (
let i = 0;
i < this.rootStore.preferences.savedFeeds.length;
i += 25
) {
const res = await this.rootStore.agent.app.bsky.feed.getFeedGenerators({
feeds: this.rootStore.preferences.savedFeeds.slice(i, 25),
})
feeds = feeds.concat(res.data.feeds)
}
runInAction(() => {
this.feeds = feeds.map(f => new CustomFeedModel(this.rootStore, f))
})
this._xIdle()
} catch (e: any) {
this._xIdle(e)
}
})
async save(feed: CustomFeedModel) {
try {
await feed.save()
runInAction(() => {
this.feeds = [
...this.feeds,
new CustomFeedModel(this.rootStore, feed.data),
]
})
} catch (e: any) {
this.rootStore.log.error('Failed to save feed', e)
}
}
async unsave(feed: CustomFeedModel) {
const uri = feed.uri
try {
if (this.isPinned(feed)) {
await this.rootStore.preferences.removePinnedFeed(uri)
}
await feed.unsave()
runInAction(() => {
this.feeds = this.feeds.filter(f => f.data.uri !== uri)
})
} catch (e: any) {
this.rootStore.log.error('Failed to unsave feed', e)
}
}
async togglePinnedFeed(feed: CustomFeedModel) {
if (!this.isPinned(feed)) {
return this.rootStore.preferences.addPinnedFeed(feed.uri)
} else {
return this.rootStore.preferences.removePinnedFeed(feed.uri)
}
}
async reorderPinnedFeeds(feeds: CustomFeedModel[]) {
return this.rootStore.preferences.setSavedFeeds(
this.rootStore.preferences.savedFeeds,
feeds.filter(feed => this.isPinned(feed)).map(feed => feed.uri),
)
}
isPinned(feedOrUri: CustomFeedModel | string) {
let uri: string
if (typeof feedOrUri === 'string') {
uri = feedOrUri
} else {
uri = feedOrUri.uri
}
return this.rootStore.preferences.pinnedFeeds.includes(uri)
}
async movePinnedFeed(item: CustomFeedModel, direction: 'up' | 'down') {
const pinned = this.rootStore.preferences.pinnedFeeds.slice()
const index = pinned.indexOf(item.uri)
if (index === -1) {
return
}
if (direction === 'up' && index !== 0) {
const temp = pinned[index]
pinned[index] = pinned[index - 1]
pinned[index - 1] = temp
} else if (direction === 'down' && index < pinned.length - 1) {
const temp = pinned[index]
pinned[index] = pinned[index + 1]
pinned[index + 1] = temp
}
await this.rootStore.preferences.setSavedFeeds(
this.rootStore.preferences.savedFeeds,
pinned,
)
}
// state transitions
// =
_xLoading(isRefreshing = false) {
this.isLoading = true
this.isRefreshing = isRefreshing
this.error = ''
}
_xIdle(err?: any) {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
this.error = cleanError(err)
if (err) {
this.rootStore.log.error('Failed to fetch user feeds', err)
}
}
}

View File

@ -119,7 +119,7 @@ export type Modal =
// Moderation // Moderation
| ReportAccountModal | ReportAccountModal
| ReportPostModal | ReportPostModal
| CreateMuteListModal | CreateOrEditMuteListModal
| ListAddRemoveUserModal | ListAddRemoveUserModal
// Posts // Posts

View File

@ -32,7 +32,7 @@ export const Step1 = observer(({model}: {model: CreateAccountModel}) => {
model.setServiceDescription(undefined) model.setServiceDescription(undefined)
}, [setIsDefaultSelected, model]) }, [setIsDefaultSelected, model])
const fetchServiceDesription = React.useMemo( const fetchServiceDescription = React.useMemo(
() => debounce(() => model.fetchServiceDescription(), 1e3), () => debounce(() => model.fetchServiceDescription(), 1e3),
[model], [model],
) )
@ -40,9 +40,9 @@ export const Step1 = observer(({model}: {model: CreateAccountModel}) => {
const onChangeServiceUrl = React.useCallback( const onChangeServiceUrl = React.useCallback(
(v: string) => { (v: string) => {
model.setServiceUrl(v) model.setServiceUrl(v)
fetchServiceDesription() fetchServiceDescription()
}, },
[model, fetchServiceDesription], [model, fetchServiceDescription],
) )
const onDebugChangeServiceUrl = React.useCallback( const onDebugChangeServiceUrl = React.useCallback(

View File

@ -420,6 +420,7 @@ const LoginForm = ({
textContentType="oneTimeCode" textContentType="oneTimeCode"
value={password} value={password}
onChangeText={setPassword} onChangeText={setPassword}
onSubmitEditing={onPressNext}
editable={!isProcessing} editable={!isProcessing}
accessibilityLabel="Password" accessibilityLabel="Password"
accessibilityHint={ accessibilityHint={

View File

@ -37,8 +37,7 @@ import {useExternalLinkFetch} from './useExternalLinkFetch'
import {isDesktopWeb, isAndroid} from 'platform/detection' import {isDesktopWeb, isAndroid} from 'platform/detection'
import {GalleryModel} from 'state/models/media/gallery' import {GalleryModel} from 'state/models/media/gallery'
import {Gallery} from './photos/Gallery' import {Gallery} from './photos/Gallery'
import {MAX_GRAPHEME_LENGTH} from 'lib/constants'
const MAX_GRAPHEME_LENGTH = 300
type Props = ComposerOpts & { type Props = ComposerOpts & {
onClose: () => void onClose: () => void
@ -310,7 +309,7 @@ export const ComposePost = observer(function ComposePost({
onError={setError} onError={setError}
accessible={true} accessible={true}
accessibilityLabel="Write post" accessibilityLabel="Write post"
accessibilityHint="Compose posts up to 300 characters in length" accessibilityHint={`Compose posts up to ${MAX_GRAPHEME_LENGTH} characters in length`}
/> />
</View> </View>

View File

@ -7,9 +7,9 @@ import ProgressCircle from 'react-native-progress/Circle'
import ProgressPie from 'react-native-progress/Pie' import ProgressPie from 'react-native-progress/Pie'
import {s} from 'lib/styles' import {s} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {MAX_GRAPHEME_LENGTH} from 'lib/constants'
const MAX_LENGTH = 300 const DANGER_LENGTH = MAX_GRAPHEME_LENGTH
const DANGER_LENGTH = MAX_LENGTH
export function CharProgress({count}: {count: number}) { export function CharProgress({count}: {count: number}) {
const pal = usePalette('default') const pal = usePalette('default')
@ -17,7 +17,9 @@ export function CharProgress({count}: {count: number}) {
const circleColor = count > DANGER_LENGTH ? '#e60000' : pal.colors.link const circleColor = count > DANGER_LENGTH ? '#e60000' : pal.colors.link
return ( return (
<> <>
<Text style={[s.mr10, {color: textColor}]}>{MAX_LENGTH - count}</Text> <Text style={[s.mr10, {color: textColor}]}>
{MAX_GRAPHEME_LENGTH - count}
</Text>
<View> <View>
{count > DANGER_LENGTH ? ( {count > DANGER_LENGTH ? (
<ProgressPie <ProgressPie
@ -25,7 +27,10 @@ export function CharProgress({count}: {count: number}) {
borderWidth={4} borderWidth={4}
borderColor={circleColor} borderColor={circleColor}
color={circleColor} color={circleColor}
progress={Math.min((count - MAX_LENGTH) / MAX_LENGTH, 1)} progress={Math.min(
(count - MAX_GRAPHEME_LENGTH) / MAX_GRAPHEME_LENGTH,
1,
)}
/> />
) : ( ) : (
<ProgressCircle <ProgressCircle
@ -33,7 +38,7 @@ export function CharProgress({count}: {count: number}) {
borderWidth={1} borderWidth={1}
borderColor={pal.colors.border} borderColor={pal.colors.border}
color={circleColor} color={circleColor}
progress={count / MAX_LENGTH} progress={count / MAX_GRAPHEME_LENGTH}
/> />
)} )}
</View> </View>

View File

@ -104,63 +104,61 @@ export const Gallery = observer(function ({gallery}: Props) {
return !gallery.isEmpty ? ( return !gallery.isEmpty ? (
<View testID="selectedPhotosView" style={styles.gallery}> <View testID="selectedPhotosView" style={styles.gallery}>
{gallery.images.map(image => {gallery.images.map(image => (
image.compressed !== undefined ? ( <View key={`selected-image-${image.path}`} style={[imageStyle]}>
<View key={`selected-image-${image.path}`} style={[imageStyle]}> <TouchableOpacity
testID="altTextButton"
accessibilityRole="button"
accessibilityLabel="Add alt text"
accessibilityHint=""
onPress={() => {
handleAddImageAltText(image)
}}
style={imageControlLabelStyle}>
<Text style={styles.imageControlTextContent}>ALT</Text>
</TouchableOpacity>
<View style={imageControlsSubgroupStyle}>
<TouchableOpacity <TouchableOpacity
testID="altTextButton" testID="editPhotoButton"
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel="Add alt text" accessibilityLabel="Edit image"
accessibilityHint="" accessibilityHint=""
onPress={() => { onPress={() => {
handleAddImageAltText(image) handleEditPhoto(image)
}} }}
style={imageControlLabelStyle}> style={styles.imageControl}>
<Text style={styles.imageControlTextContent}>ALT</Text> <FontAwesomeIcon
icon="pen"
size={12}
style={{color: colors.white}}
/>
</TouchableOpacity>
<TouchableOpacity
testID="removePhotoButton"
accessibilityRole="button"
accessibilityLabel="Remove image"
accessibilityHint=""
onPress={() => handleRemovePhoto(image)}
style={styles.imageControl}>
<FontAwesomeIcon
icon="xmark"
size={16}
style={{color: colors.white}}
/>
</TouchableOpacity> </TouchableOpacity>
<View style={imageControlsSubgroupStyle}>
<TouchableOpacity
testID="editPhotoButton"
accessibilityRole="button"
accessibilityLabel="Edit image"
accessibilityHint=""
onPress={() => {
handleEditPhoto(image)
}}
style={styles.imageControl}>
<FontAwesomeIcon
icon="pen"
size={12}
style={{color: colors.white}}
/>
</TouchableOpacity>
<TouchableOpacity
testID="removePhotoButton"
accessibilityRole="button"
accessibilityLabel="Remove image"
accessibilityHint=""
onPress={() => handleRemovePhoto(image)}
style={styles.imageControl}>
<FontAwesomeIcon
icon="xmark"
size={16}
style={{color: colors.white}}
/>
</TouchableOpacity>
</View>
<Image
testID="selectedPhotoImage"
style={[styles.image, imageStyle] as ImageStyle}
source={{
uri: image.compressed.path,
}}
accessible={true}
accessibilityIgnoresInvertColors
/>
</View> </View>
) : null,
)} <Image
testID="selectedPhotoImage"
style={[styles.image, imageStyle] as ImageStyle}
source={{
uri: image.cropped?.path ?? image.path,
}}
accessible={true}
accessibilityIgnoresInvertColors
/>
</View>
))}
</View> </View>
) : null ) : null
}) })

View File

@ -2,9 +2,9 @@ import {useState, useEffect} from 'react'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import * as apilib from 'lib/api/index' import * as apilib from 'lib/api/index'
import {getLinkMeta} from 'lib/link-meta/link-meta' import {getLinkMeta} from 'lib/link-meta/link-meta'
import {getPostAsQuote} from 'lib/link-meta/bsky' import {getPostAsQuote, getFeedAsEmbed} from 'lib/link-meta/bsky'
import {downloadAndResize} from 'lib/media/manip' import {downloadAndResize} from 'lib/media/manip'
import {isBskyPostUrl} from 'lib/strings/url-helpers' import {isBskyPostUrl, isBskyCustomFeedUrl} from 'lib/strings/url-helpers'
import {ComposerOpts} from 'state/models/ui/shell' import {ComposerOpts} from 'state/models/ui/shell'
import {POST_IMG_MAX} from 'lib/constants' import {POST_IMG_MAX} from 'lib/constants'
@ -41,6 +41,24 @@ export function useExternalLinkFetch({
setExtLink(undefined) setExtLink(undefined)
}, },
) )
} else if (isBskyCustomFeedUrl(extLink.uri)) {
getFeedAsEmbed(store, extLink.uri).then(
({embed, meta}) => {
if (aborted) {
return
}
setExtLink({
uri: extLink.uri,
isLoading: false,
meta,
embed,
})
},
err => {
store.log.error('Failed to fetch feed for embedding', {err})
setExtLink(undefined)
},
)
} else { } else {
getLinkMeta(store, extLink.uri).then(meta => { getLinkMeta(store, extLink.uri).then(meta => {
if (aborted) { if (aborted) {

View File

@ -0,0 +1,162 @@
import React from 'react'
import {
Pressable,
StyleProp,
StyleSheet,
View,
ViewStyle,
TouchableOpacity,
} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {Text} from '../util/text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles'
import {UserAvatar} from '../util/UserAvatar'
import {observer} from 'mobx-react-lite'
import {CustomFeedModel} from 'state/models/feeds/custom-feed'
import {useNavigation} from '@react-navigation/native'
import {NavigationProp} from 'lib/routes/types'
import {useStores} from 'state/index'
import {pluralize} from 'lib/strings/helpers'
import {AtUri} from '@atproto/api'
import * as Toast from 'view/com/util/Toast'
export const CustomFeed = observer(
({
item,
style,
showSaveBtn = false,
showDescription = false,
showLikes = false,
}: {
item: CustomFeedModel
style?: StyleProp<ViewStyle>
showSaveBtn?: boolean
showDescription?: boolean
showLikes?: boolean
}) => {
const store = useStores()
const pal = usePalette('default')
const navigation = useNavigation<NavigationProp>()
const onToggleSaved = React.useCallback(async () => {
if (item.isSaved) {
store.shell.openModal({
name: 'confirm',
title: 'Remove from my feeds',
message: `Remove ${item.displayName} from my feeds?`,
onPressConfirm: async () => {
try {
await store.me.savedFeeds.unsave(item)
Toast.show('Removed from my feeds')
} catch (e) {
Toast.show('There was an issue contacting your server')
store.log.error('Failed to unsave feed', {e})
}
},
})
} else {
try {
await store.me.savedFeeds.save(item)
Toast.show('Added to my feeds')
} catch (e) {
Toast.show('There was an issue contacting your server')
store.log.error('Failed to save feed', {e})
}
}
}, [store, item])
return (
<TouchableOpacity
accessibilityRole="button"
style={[styles.container, pal.border, style]}
onPress={() => {
navigation.navigate('CustomFeed', {
name: item.data.creator.did,
rkey: new AtUri(item.data.uri).rkey,
})
}}
key={item.data.uri}>
<View style={[styles.headerContainer]}>
<View style={[s.mr10]}>
<UserAvatar type="algo" size={36} avatar={item.data.avatar} />
</View>
<View style={[styles.headerTextContainer]}>
<Text style={[pal.text, s.bold]} numberOfLines={3}>
{item.displayName}
</Text>
<Text style={[pal.textLight]} numberOfLines={3}>
by @{item.data.creator.handle}
</Text>
</View>
{showSaveBtn && (
<View>
<Pressable
accessibilityRole="button"
accessibilityLabel={
item.isSaved ? 'Remove from my feeds' : 'Add to my feeds'
}
accessibilityHint=""
onPress={onToggleSaved}
hitSlop={15}
style={styles.btn}>
{item.isSaved ? (
<FontAwesomeIcon
icon={['far', 'trash-can']}
size={19}
color={pal.colors.icon}
/>
) : (
<FontAwesomeIcon
icon="plus"
size={18}
color={pal.colors.link}
/>
)}
</Pressable>
</View>
)}
</View>
{showDescription && item.data.description ? (
<Text style={[pal.textLight, styles.description]} numberOfLines={3}>
{item.data.description}
</Text>
) : null}
{showLikes ? (
<Text type="sm-medium" style={[pal.text, pal.textLight]}>
Liked by {item.data.likeCount || 0}{' '}
{pluralize(item.data.likeCount || 0, 'user')}
</Text>
) : null}
</TouchableOpacity>
)
},
)
const styles = StyleSheet.create({
container: {
paddingHorizontal: 18,
paddingVertical: 20,
flexDirection: 'column',
flex: 1,
borderTopWidth: 1,
gap: 14,
},
headerContainer: {
flexDirection: 'row',
},
headerTextContainer: {
flexDirection: 'column',
columnGap: 4,
flex: 1,
},
description: {
flex: 1,
flexWrap: 'wrap',
},
btn: {
paddingVertical: 6,
},
})

View File

@ -65,30 +65,34 @@ function LightboxInner({
const canGoLeft = index >= 1 const canGoLeft = index >= 1
const canGoRight = index < imgs.length - 1 const canGoRight = index < imgs.length - 1
const onPressLeft = () => { const onPressLeft = useCallback(() => {
if (canGoLeft) { if (canGoLeft) {
setIndex(index - 1) setIndex(index - 1)
} }
} }, [index, canGoLeft])
const onPressRight = () => { const onPressRight = useCallback(() => {
if (canGoRight) { if (canGoRight) {
setIndex(index + 1) setIndex(index + 1)
} }
} }, [index, canGoRight])
const onEscape = useCallback( const onKeyDown = useCallback(
(e: KeyboardEvent) => { (e: KeyboardEvent) => {
if (e.key === 'Escape') { if (e.key === 'Escape') {
onClose() onClose()
} else if (e.key === 'ArrowLeft') {
onPressLeft()
} else if (e.key === 'ArrowRight') {
onPressRight()
} }
}, },
[onClose], [onClose, onPressLeft, onPressRight],
) )
useEffect(() => { useEffect(() => {
window.addEventListener('keydown', onEscape) window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onEscape) return () => window.removeEventListener('keydown', onKeyDown)
}, [onEscape]) }, [onKeyDown])
return ( return (
<View style={styles.mask}> <View style={styles.mask}>

View File

@ -60,7 +60,7 @@ export const ListCard = ({
anchorNoUnderline> anchorNoUnderline>
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<UserAvatar size={40} avatar={list.avatar} /> <UserAvatar type="list" size={40} avatar={list.avatar} />
</View> </View>
<View style={styles.layoutContent}> <View style={styles.layoutContent}>
<Text <Text

View File

@ -341,7 +341,7 @@ const ListHeader = observer(
)} )}
</View> </View>
<View> <View>
<UserAvatar avatar={list.avatar} size={64} /> <UserAvatar type="list" avatar={list.avatar} size={64} />
</View> </View>
</View> </View>
<View style={[styles.fakeSelector, pal.border]}> <View style={[styles.fakeSelector, pal.border]}>

View File

@ -52,8 +52,8 @@ export const Component = observer(({}: {}) => {
Adult content can only be enabled via the Web at{' '} Adult content can only be enabled via the Web at{' '}
<TextLink <TextLink
style={pal.link} style={pal.link}
href="https://staging.bsky.app" href="https://bsky.app"
text="staging.bsky.app" text="bsky.app"
/> />
. .
</Text> </Text>

View File

@ -41,8 +41,8 @@ export function Component({}: {}) {
<View testID="contentLanguagesModal" style={[pal.view, styles.container]}> <View testID="contentLanguagesModal" style={[pal.view, styles.container]}>
<Text style={[pal.text, styles.title]}>Content Languages</Text> <Text style={[pal.text, styles.title]}>Content Languages</Text>
<Text style={[pal.text, styles.description]}> <Text style={[pal.text, styles.description]}>
Which languages would you like to see in the What's Hot feed? (Leave Which languages would you like to see in the your feed? (Leave them all
them all unchecked to see any language.) unchecked to see any language.)
</Text> </Text>
<ScrollView style={styles.scrollContainer}> <ScrollView style={styles.scrollContainer}>
{languages.map(lang => ( {languages.map(lang => (

View File

@ -143,6 +143,7 @@ export function Component({
<Text style={[styles.label, pal.text]}>List Avatar</Text> <Text style={[styles.label, pal.text]}>List Avatar</Text>
<View style={[styles.avi, {borderColor: pal.colors.background}]}> <View style={[styles.avi, {borderColor: pal.colors.background}]}>
<UserAvatar <UserAvatar
type="list"
size={80} size={80}
avatar={avatar} avatar={avatar}
onSelectNewAvatar={onSelectNewAvatar} onSelectNewAvatar={onSelectNewAvatar}

View File

@ -118,9 +118,9 @@ export const Component = observer(function ({image, gallery}: Props) {
) )
useEffect(() => { useEffect(() => {
image.prev = image.compressed image.prev = image.cropped
image.prevAttributes = image.attributes image.prevAttributes = image.attributes
image.resetCompressed() image.resetCropped()
}, [image]) }, [image])
const onCloseModal = useCallback(() => { const onCloseModal = useCallback(() => {
@ -152,7 +152,7 @@ export const Component = observer(function ({image, gallery}: Props) {
: {}), : {}),
}) })
image.prev = image.compressed image.prev = image.cropped
image.prevAttributes = image.attributes image.prevAttributes = image.attributes
onCloseModal() onCloseModal()
}, [altText, image, position, scale, onCloseModal]) }, [altText, image, position, scale, onCloseModal])
@ -168,8 +168,7 @@ export const Component = observer(function ({image, gallery}: Props) {
} }
}, []) }, [])
// Prevents preliminary flash when transformations are being applied if (image.cropped === undefined) {
if (image.compressed === undefined) {
return null return null
} }
@ -177,7 +176,7 @@ export const Component = observer(function ({image, gallery}: Props) {
windowDimensions.width > 500 ? 410 : windowDimensions.width - 80 windowDimensions.width > 500 ? 410 : windowDimensions.width - 80
const sideLength = isDesktopWeb ? 300 : computedWidth const sideLength = isDesktopWeb ? 300 : computedWidth
const dimensions = image.getDisplayDimensions(aspectRatio, sideLength) const dimensions = image.getResizedDimensions(aspectRatio, sideLength)
const imgContainerStyles = {width: sideLength, height: sideLength} const imgContainerStyles = {width: sideLength, height: sideLength}
const imgControlStyles = { const imgControlStyles = {
@ -196,7 +195,7 @@ export const Component = observer(function ({image, gallery}: Props) {
<ImageEditor <ImageEditor
ref={editorRef} ref={editorRef}
style={styles.imgEditor} style={styles.imgEditor}
image={image.compressed.path} image={image.cropped.path}
scale={scale} scale={scale}
border={0} border={0}
position={position} position={position}

View File

@ -15,6 +15,7 @@ import * as RepostModal from './Repost'
import * as CreateOrEditMuteListModal from './CreateOrEditMuteList' import * as CreateOrEditMuteListModal from './CreateOrEditMuteList'
import * as ListAddRemoveUserModal from './ListAddRemoveUser' import * as ListAddRemoveUserModal from './ListAddRemoveUser'
import * as AltImageModal from './AltImage' import * as AltImageModal from './AltImage'
import * as EditImageModal from './AltImage'
import * as ReportAccountModal from './ReportAccount' import * as ReportAccountModal from './ReportAccount'
import * as DeleteAccountModal from './DeleteAccount' import * as DeleteAccountModal from './DeleteAccount'
import * as ChangeHandleModal from './ChangeHandle' import * as ChangeHandleModal from './ChangeHandle'
@ -83,6 +84,9 @@ export const ModalsContainer = observer(function ModalsContainer() {
} else if (activeModal?.name === 'alt-text-image') { } else if (activeModal?.name === 'alt-text-image') {
snapPoints = AltImageModal.snapPoints snapPoints = AltImageModal.snapPoints
element = <AltImageModal.Component {...activeModal} /> element = <AltImageModal.Component {...activeModal} />
} else if (activeModal?.name === 'edit-image') {
snapPoints = AltImageModal.snapPoints
element = <EditImageModal.Component {...activeModal} />
} else if (activeModal?.name === 'change-handle') { } else if (activeModal?.name === 'change-handle') {
snapPoints = ChangeHandleModal.snapPoints snapPoints = ChangeHandleModal.snapPoints
element = <ChangeHandleModal.Component {...activeModal} /> element = <ChangeHandleModal.Component {...activeModal} />
@ -119,7 +123,7 @@ export const ModalsContainer = observer(function ModalsContainer() {
snapPoints={snapPoints} snapPoints={snapPoints}
index={store.shell.isModalActive ? 0 : -1} index={store.shell.isModalActive ? 0 : -1}
enablePanDownToClose enablePanDownToClose
keyboardBehavior="extend" android_keyboardInputMode="adjustResize"
keyboardBlurBehavior="restore" keyboardBlurBehavior="restore"
backdropComponent={ backdropComponent={
store.shell.isModalActive ? createCustomBackdrop(onClose) : undefined store.shell.isModalActive ? createCustomBackdrop(onClose) : undefined

View File

@ -1,11 +0,0 @@
/**
* NOTE
* This modal is used only in the web build
* Native uses a third-party library
*/
export const snapPoints = ['0%']
export function Component() {
return null
}

View File

@ -154,6 +154,7 @@ export const Feed = observer(function Feed({
onEndReached={onEndReached} onEndReached={onEndReached}
onEndReachedThreshold={0.6} onEndReachedThreshold={0.6}
onScroll={onScroll} onScroll={onScroll}
scrollEventThrottle={100}
contentContainerStyle={s.contentContainer} contentContainerStyle={s.contentContainer}
/> />
) : null} ) : null}

View File

@ -0,0 +1,15 @@
import {useDraggableScroll} from 'lib/hooks/useDraggableScrollView'
import React, {ComponentProps} from 'react'
import {ScrollView} from 'react-native'
export const DraggableScrollView = React.forwardRef<
ScrollView,
ComponentProps<typeof ScrollView>
>(function DraggableScrollView(props, ref) {
const {refs} = useDraggableScroll<ScrollView>({
outerRef: ref,
cursor: 'grab', // optional, default
})
return <ScrollView ref={refs} horizontal {...props} />
})

View File

@ -1,4 +1,4 @@
import React from 'react' import React, {useMemo} from 'react'
import {Animated, StyleSheet} from 'react-native' import {Animated, StyleSheet} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {TabBar} from 'view/com/pager/TabBar' import {TabBar} from 'view/com/pager/TabBar'
@ -27,6 +27,10 @@ const FeedsTabBarDesktop = observer(
props: RenderTabBarFnProps & {testID?: string; onPressSelected: () => void}, props: RenderTabBarFnProps & {testID?: string; onPressSelected: () => void},
) => { ) => {
const store = useStores() const store = useStores()
const items = useMemo(
() => ['Following', ...store.me.savedFeeds.pinnedFeedNames],
[store.me.savedFeeds.pinnedFeedNames],
)
const pal = usePalette('default') const pal = usePalette('default')
const interp = useAnimatedValue(0) const interp = useAnimatedValue(0)
@ -44,13 +48,14 @@ const FeedsTabBarDesktop = observer(
{translateY: Animated.multiply(interp, -100)}, {translateY: Animated.multiply(interp, -100)},
], ],
} }
return ( return (
// @ts-ignore the type signature for transform wrong here, translateX and translateY need to be in separate objects -prf // @ts-ignore the type signature for transform wrong here, translateX and translateY need to be in separate objects -prf
<Animated.View style={[pal.view, styles.tabBar, transform]}> <Animated.View style={[pal.view, styles.tabBar, transform]}>
<TabBar <TabBar
key={items.join(',')}
{...props} {...props}
items={['Following', "What's hot"]} items={items}
indicatorPosition="bottom"
indicatorColor={pal.colors.link} indicatorColor={pal.colors.link}
/> />
</Animated.View> </Animated.View>

View File

@ -1,12 +1,17 @@
import React from 'react' import React, {useMemo} from 'react'
import {Animated, StyleSheet, TouchableOpacity} from 'react-native' import {Animated, StyleSheet, TouchableOpacity, View} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {TabBar} from 'view/com/pager/TabBar' import {TabBar} from 'view/com/pager/TabBar'
import {RenderTabBarFnProps} from 'view/com/pager/Pager' import {RenderTabBarFnProps} from 'view/com/pager/Pager'
import {UserAvatar} from '../util/UserAvatar'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {useAnimatedValue} from 'lib/hooks/useAnimatedValue' import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
import {useColorSchemeStyle} from 'lib/hooks/useColorSchemeStyle'
import {Link} from '../util/Link'
import {Text} from '../util/text/Text'
import {CogIcon} from 'lib/icons'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {s} from 'lib/styles'
export const FeedsTabBar = observer( export const FeedsTabBar = observer(
( (
@ -28,25 +33,51 @@ export const FeedsTabBar = observer(
transform: [{translateY: Animated.multiply(interp, -100)}], transform: [{translateY: Animated.multiply(interp, -100)}],
} }
const brandBlue = useColorSchemeStyle(s.brandBlue, s.blue3)
const onPressAvi = React.useCallback(() => { const onPressAvi = React.useCallback(() => {
store.shell.openDrawer() store.shell.openDrawer()
}, [store]) }, [store])
const items = useMemo(
() => ['Following', ...store.me.savedFeeds.pinnedFeedNames],
[store.me.savedFeeds.pinnedFeedNames],
)
return ( return (
<Animated.View style={[pal.view, pal.border, styles.tabBar, transform]}> <Animated.View style={[pal.view, pal.border, styles.tabBar, transform]}>
<TouchableOpacity <View style={[pal.view, styles.topBar]}>
testID="viewHeaderDrawerBtn" <View style={[pal.view]}>
style={styles.tabBarAvi} <TouchableOpacity
onPress={onPressAvi} testID="viewHeaderDrawerBtn"
accessibilityRole="button" onPress={onPressAvi}
accessibilityLabel="Open navigation" accessibilityRole="button"
accessibilityHint="Access profile and other navigation links"> accessibilityLabel="Open navigation"
<UserAvatar avatar={store.me.avatar} size={30} /> accessibilityHint="Access profile and other navigation links"
</TouchableOpacity> hitSlop={10}>
<FontAwesomeIcon
icon="bars"
size={18}
color={pal.colors.textLight}
/>
</TouchableOpacity>
</View>
<Text style={[brandBlue, s.bold, styles.title]}>Bluesky</Text>
<View style={[pal.view]}>
<Link
href="/settings/saved-feeds"
hitSlop={10}
accessibilityRole="button"
accessibilityLabel="Edit Saved Feeds"
accessibilityHint="Opens screen to edit Saved Feeds">
<CogIcon size={21} strokeWidth={2} style={pal.textLight} />
</Link>
</View>
</View>
<TabBar <TabBar
key={items.join(',')}
{...props} {...props}
items={['Following', "What's hot"]} items={items}
indicatorPosition="bottom"
indicatorColor={pal.colors.link} indicatorColor={pal.colors.link}
/> />
</Animated.View> </Animated.View>
@ -61,13 +92,20 @@ const styles = StyleSheet.create({
left: 0, left: 0,
right: 0, right: 0,
top: 0, top: 0,
flexDirection: 'row', flexDirection: 'column',
alignItems: 'center', alignItems: 'center',
paddingHorizontal: 18,
borderBottomWidth: 1, borderBottomWidth: 1,
}, },
tabBarAvi: { topBar: {
marginTop: 1, flexDirection: 'row',
marginRight: 18, justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 18,
paddingTop: 8,
paddingBottom: 2,
width: '100%',
},
title: {
fontSize: 21,
}, },
}) })

View File

@ -1,16 +1,17 @@
import React from 'react' import React, {forwardRef} from 'react'
import {Animated, View} from 'react-native' import {Animated, View} from 'react-native'
import PagerView, {PagerViewOnPageSelectedEvent} from 'react-native-pager-view' import PagerView, {PagerViewOnPageSelectedEvent} from 'react-native-pager-view'
import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
import {s} from 'lib/styles' import {s} from 'lib/styles'
export type PageSelectedEvent = PagerViewOnPageSelectedEvent export type PageSelectedEvent = PagerViewOnPageSelectedEvent
const AnimatedPagerView = Animated.createAnimatedComponent(PagerView) const AnimatedPagerView = Animated.createAnimatedComponent(PagerView)
export interface PagerRef {
setPage: (index: number) => void
}
export interface RenderTabBarFnProps { export interface RenderTabBarFnProps {
selectedPage: number selectedPage: number
position: Animated.Value
offset: Animated.Value
onSelect?: (index: number) => void onSelect?: (index: number) => void
} }
export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element
@ -22,68 +23,60 @@ interface Props {
onPageSelected?: (index: number) => void onPageSelected?: (index: number) => void
testID?: string testID?: string
} }
export const Pager = ({ export const Pager = forwardRef<PagerRef, React.PropsWithChildren<Props>>(
children, (
tabBarPosition = 'top', {
initialPage = 0, children,
renderTabBar, tabBarPosition = 'top',
onPageSelected, initialPage = 0,
testID, renderTabBar,
}: React.PropsWithChildren<Props>) => { onPageSelected,
const [selectedPage, setSelectedPage] = React.useState(0) testID,
const position = useAnimatedValue(0) }: React.PropsWithChildren<Props>,
const offset = useAnimatedValue(0) ref,
const pagerView = React.useRef<PagerView>() ) => {
const [selectedPage, setSelectedPage] = React.useState(0)
const pagerView = React.useRef<PagerView>()
const onPageSelectedInner = React.useCallback( React.useImperativeHandle(ref, () => ({
(e: PageSelectedEvent) => { setPage: (index: number) => pagerView.current?.setPage(index),
setSelectedPage(e.nativeEvent.position) }))
onPageSelected?.(e.nativeEvent.position)
},
[setSelectedPage, onPageSelected],
)
const onTabBarSelect = React.useCallback( const onPageSelectedInner = React.useCallback(
(index: number) => { (e: PageSelectedEvent) => {
pagerView.current?.setPage(index) setSelectedPage(e.nativeEvent.position)
}, onPageSelected?.(e.nativeEvent.position)
[pagerView], },
) [setSelectedPage, onPageSelected],
)
return ( const onTabBarSelect = React.useCallback(
<View testID={testID}> (index: number) => {
{tabBarPosition === 'top' && pagerView.current?.setPage(index)
renderTabBar({ },
selectedPage, [pagerView],
position, )
offset,
onSelect: onTabBarSelect, return (
})} <View testID={testID}>
<AnimatedPagerView {tabBarPosition === 'top' &&
ref={pagerView} renderTabBar({
style={s.h100pct} selectedPage,
initialPage={initialPage} onSelect: onTabBarSelect,
onPageSelected={onPageSelectedInner} })}
onPageScroll={Animated.event( <AnimatedPagerView
[ ref={pagerView}
{ style={s.h100pct}
nativeEvent: { initialPage={initialPage}
position: position, onPageSelected={onPageSelectedInner}>
offset: offset, {children}
}, </AnimatedPagerView>
}, {tabBarPosition === 'bottom' &&
], renderTabBar({
{useNativeDriver: true}, selectedPage,
)}> onSelect: onTabBarSelect,
{children} })}
</AnimatedPagerView> </View>
{tabBarPosition === 'bottom' && )
renderTabBar({ },
selectedPage, )
position,
offset,
onSelect: onTabBarSelect,
})}
</View>
)
}

View File

@ -1,12 +1,9 @@
import React from 'react' import React from 'react'
import {Animated, View} from 'react-native' import {View} from 'react-native'
import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
import {s} from 'lib/styles' import {s} from 'lib/styles'
export interface RenderTabBarFnProps { export interface RenderTabBarFnProps {
selectedPage: number selectedPage: number
position: Animated.Value
offset: Animated.Value
onSelect?: (index: number) => void onSelect?: (index: number) => void
} }
export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element
@ -17,53 +14,51 @@ interface Props {
renderTabBar: RenderTabBarFn renderTabBar: RenderTabBarFn
onPageSelected?: (index: number) => void onPageSelected?: (index: number) => void
} }
export const Pager = ({ export const Pager = React.forwardRef(
children, (
tabBarPosition = 'top', {
initialPage = 0, children,
renderTabBar, tabBarPosition = 'top',
onPageSelected, initialPage = 0,
}: React.PropsWithChildren<Props>) => { renderTabBar,
const [selectedPage, setSelectedPage] = React.useState(initialPage) onPageSelected,
const position = useAnimatedValue(0) }: React.PropsWithChildren<Props>,
const offset = useAnimatedValue(0) ref,
) => {
const [selectedPage, setSelectedPage] = React.useState(initialPage)
const onTabBarSelect = React.useCallback( React.useImperativeHandle(ref, () => ({
(index: number) => { setPage: (index: number) => setSelectedPage(index),
setSelectedPage(index) }))
onPageSelected?.(index)
Animated.timing(position, {
toValue: index,
duration: 200,
useNativeDriver: true,
}).start()
},
[setSelectedPage, onPageSelected, position],
)
return ( const onTabBarSelect = React.useCallback(
<View> (index: number) => {
{tabBarPosition === 'top' && setSelectedPage(index)
renderTabBar({ onPageSelected?.(index)
selectedPage, },
position, [setSelectedPage, onPageSelected],
offset, )
onSelect: onTabBarSelect,
})} return (
{React.Children.map(children, (child, i) => ( <View>
<View {tabBarPosition === 'top' &&
style={selectedPage === i ? undefined : s.hidden} renderTabBar({
key={`page-${i}`}> selectedPage,
{child} onSelect: onTabBarSelect,
</View> })}
))} {React.Children.map(children, (child, i) => (
{tabBarPosition === 'bottom' && <View
renderTabBar({ style={selectedPage === i ? undefined : s.hidden}
selectedPage, key={`page-${i}`}>
position, {child}
offset, </View>
onSelect: onTabBarSelect, ))}
})} {tabBarPosition === 'bottom' &&
</View> renderTabBar({
) selectedPage,
} onSelect: onTabBarSelect,
})}
</View>
)
},
)

View File

@ -1,22 +1,22 @@
import React, {createRef, useState, useMemo, useRef} from 'react' import React, {
import {Animated, StyleSheet, View} from 'react-native' useRef,
createRef,
useMemo,
useEffect,
useState,
useCallback,
} from 'react'
import {StyleSheet, View, ScrollView} from 'react-native'
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'
import {PressableWithHover} from '../util/PressableWithHover' import {PressableWithHover} from '../util/PressableWithHover'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {isDesktopWeb} from 'platform/detection' import {isDesktopWeb, isMobileWeb} from 'platform/detection'
import {DraggableScrollView} from './DraggableScrollView'
interface Layout {
x: number
width: number
}
export interface TabBarProps { export interface TabBarProps {
testID?: string testID?: string
selectedPage: number selectedPage: number
items: string[] items: string[]
position: Animated.Value
offset: Animated.Value
indicatorPosition?: 'top' | 'bottom'
indicatorColor?: string indicatorColor?: string
onSelect?: (index: number) => void onSelect?: (index: number) => void
onPressSelected?: () => void onPressSelected?: () => void
@ -26,69 +26,27 @@ export function TabBar({
testID, testID,
selectedPage, selectedPage,
items, items,
position,
offset,
indicatorPosition = 'bottom',
indicatorColor, indicatorColor,
onSelect, onSelect,
onPressSelected, onPressSelected,
}: TabBarProps) { }: TabBarProps) {
const pal = usePalette('default') const pal = usePalette('default')
const [itemLayouts, setItemLayouts] = useState<Layout[]>( const scrollElRef = useRef<ScrollView>(null)
items.map(() => ({x: 0, width: 0})), const [itemXs, setItemXs] = useState<number[]>([])
)
const itemRefs = useMemo( const itemRefs = useMemo(
() => Array.from({length: items.length}).map(() => createRef<View>()), () => Array.from({length: items.length}).map(() => createRef<View>()),
[items.length], [items.length],
) )
const panX = Animated.add(position, offset) const indicatorStyle = useMemo(
const containerRef = useRef<View>(null) () => ({borderBottomColor: indicatorColor || pal.colors.link}),
[indicatorColor, pal],
)
const indicatorStyle = { useEffect(() => {
backgroundColor: indicatorColor || pal.colors.link, scrollElRef.current?.scrollTo({x: itemXs[selectedPage] || 0})
bottom: }, [scrollElRef, itemXs, selectedPage])
indicatorPosition === 'bottom' ? (isDesktopWeb ? 0 : -1) : undefined,
top: indicatorPosition === 'top' ? (isDesktopWeb ? 0 : -1) : undefined,
transform: [
{
translateX: panX.interpolate({
inputRange: items.map((_item, i) => i),
outputRange: itemLayouts.map(l => l.x + l.width / 2),
}),
},
{
scaleX: panX.interpolate({
inputRange: items.map((_item, i) => i),
outputRange: itemLayouts.map(l => l.width),
}),
},
],
}
const onLayout = React.useCallback(() => { const onPressItem = useCallback(
const promises = []
for (let i = 0; i < items.length; i++) {
promises.push(
new Promise<Layout>(resolve => {
if (!containerRef.current || !itemRefs[i].current) {
return resolve({x: 0, width: 0})
}
itemRefs[i].current?.measureLayout(
containerRef.current,
(x: number, _y: number, width: number) => {
resolve({x, width})
},
)
}),
)
}
Promise.all(promises).then((layouts: Layout[]) => {
setItemLayouts(layouts)
})
}, [containerRef, itemRefs, setItemLayouts, items.length])
const onPressItem = React.useCallback(
(index: number) => { (index: number) => {
onSelect?.(index) onSelect?.(index)
if (index === selectedPage) { if (index === selectedPage) {
@ -98,33 +56,51 @@ export function TabBar({
[onSelect, onPressSelected, selectedPage], [onSelect, onPressSelected, selectedPage],
) )
const onLayout = React.useCallback(() => {
const promises = []
for (let i = 0; i < items.length; i++) {
promises.push(
new Promise<number>(resolve => {
if (!itemRefs[i].current) {
return resolve(0)
}
itemRefs[i].current?.measure((x: number) => resolve(x))
}),
)
}
Promise.all(promises).then((Xs: number[]) => {
setItemXs(Xs)
})
}, [itemRefs, setItemXs, items.length])
return ( return (
<View <View testID={testID} style={[pal.view, styles.outer]}>
testID={testID} <DraggableScrollView
style={[pal.view, styles.outer]} horizontal={true}
onLayout={onLayout} showsHorizontalScrollIndicator={false}
ref={containerRef}> ref={scrollElRef}
<Animated.View style={[styles.indicator, indicatorStyle]} /> contentContainerStyle={styles.contentContainer}
{items.map((item, i) => { onLayout={onLayout}>
const selected = i === selectedPage {items.map((item, i) => {
return ( const selected = i === selectedPage
<PressableWithHover return (
ref={itemRefs[i]} <PressableWithHover
key={item} ref={itemRefs[i]}
style={ key={item}
indicatorPosition === 'top' ? styles.itemTop : styles.itemBottom style={[styles.item, selected && indicatorStyle]}
} hoverStyle={pal.viewLight}
hoverStyle={pal.viewLight} onPress={() => onPressItem(i)}>
onPress={() => onPressItem(i)}> <Text
<Text type={isDesktopWeb ? 'xl-bold' : 'lg-bold'}
type="xl-bold" testID={testID ? `${testID}-${item}` : undefined}
testID={testID ? `${testID}-${item}` : undefined} style={selected ? pal.text : pal.textLight}>
style={selected ? pal.text : pal.textLight}> {item}
{item} </Text>
</Text> </PressableWithHover>
</PressableWithHover> )
) })}
})} </DraggableScrollView>
</View> </View>
) )
} }
@ -133,45 +109,39 @@ const styles = isDesktopWeb
? StyleSheet.create({ ? StyleSheet.create({
outer: { outer: {
flexDirection: 'row', flexDirection: 'row',
paddingHorizontal: 18, width: 598,
}, },
itemTop: { contentContainer: {
paddingTop: 16, columnGap: 8,
paddingBottom: 14, marginLeft: 14,
paddingHorizontal: 12, paddingRight: 14,
backgroundColor: 'transparent',
}, },
itemBottom: { item: {
paddingTop: 14, paddingTop: 14,
paddingBottom: 16, paddingBottom: 12,
paddingHorizontal: 12, paddingHorizontal: 10,
}, borderBottomWidth: 3,
indicator: { borderBottomColor: 'transparent',
position: 'absolute',
left: 0,
width: 1,
height: 3,
zIndex: 1,
}, },
}) })
: StyleSheet.create({ : StyleSheet.create({
outer: { outer: {
flex: 1,
flexDirection: 'row', flexDirection: 'row',
paddingHorizontal: 14, backgroundColor: 'transparent',
}, },
itemTop: { contentContainer: {
columnGap: isMobileWeb ? 0 : 20,
marginLeft: isMobileWeb ? 0 : 18,
paddingRight: isMobileWeb ? 0 : 36,
backgroundColor: 'transparent',
},
item: {
paddingTop: 10, paddingTop: 10,
paddingBottom: 10, paddingBottom: 10,
marginRight: 24, paddingHorizontal: isMobileWeb ? 8 : 0,
}, borderBottomWidth: 3,
itemBottom: { borderBottomColor: 'transparent',
paddingTop: 8,
paddingBottom: 12,
marginRight: 24,
},
indicator: {
position: 'absolute',
left: 0,
width: 1,
height: 3,
}, },
}) })

View File

@ -1,4 +1,4 @@
import React from 'react' import React, {useCallback, useMemo} from 'react'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {Linking, StyleSheet, View} from 'react-native' import {Linking, StyleSheet, View} from 'react-native'
import Clipboard from '@react-native-clipboard/clipboard' import Clipboard from '@react-native-clipboard/clipboard'
@ -99,7 +99,11 @@ export const PostThreadItem = observer(function PostThreadItem({
const onOpenTranslate = React.useCallback(() => { const onOpenTranslate = React.useCallback(() => {
Linking.openURL( Linking.openURL(
encodeURI(`https://translate.google.com/#auto|en|${record?.text || ''}`), encodeURI(
`https://translate.google.com/?sl=auto&tl=en&text=${
record?.text || ''
}`,
),
) )
}, [record]) }, [record])
@ -129,6 +133,40 @@ export const PostThreadItem = observer(function PostThreadItem({
) )
}, [item, store]) }, [item, store])
const accessibilityActions = useMemo(
() => [
{
name: 'reply',
label: 'Reply',
},
{
name: 'repost',
label: item.post.viewer?.repost ? 'Undo repost' : 'Repost',
},
{name: 'like', label: item.post.viewer?.like ? 'Unlike' : 'Like'},
],
[item.post.viewer?.like, item.post.viewer?.repost],
)
const onAccessibilityAction = useCallback(
event => {
switch (event.nativeEvent.actionName) {
case 'like':
onPressToggleLike()
break
case 'reply':
onPressReply()
break
case 'repost':
onPressToggleRepost()
break
default:
break
}
},
[onPressReply, onPressToggleLike, onPressToggleRepost],
)
if (!record) { if (!record) {
return <ErrorMessage message="Invalid or unsupported post record" /> return <ErrorMessage message="Invalid or unsupported post record" />
} }
@ -150,7 +188,9 @@ export const PostThreadItem = observer(function PostThreadItem({
<PostHider <PostHider
testID={`postThreadItem-by-${item.post.author.handle}`} testID={`postThreadItem-by-${item.post.author.handle}`}
style={[styles.outer, styles.outerHighlighted, pal.border, pal.view]} style={[styles.outer, styles.outerHighlighted, pal.border, pal.view]}
moderation={item.moderation.thread}> moderation={item.moderation.thread}
accessibilityActions={accessibilityActions}
onAccessibilityAction={onAccessibilityAction}>
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<Link <Link
@ -320,7 +360,9 @@ export const PostThreadItem = observer(function PostThreadItem({
pal.view, pal.view,
item._showParentReplyLine && styles.noTopBorder, item._showParentReplyLine && styles.noTopBorder,
]} ]}
moderation={item.moderation.thread}> moderation={item.moderation.thread}
accessibilityActions={accessibilityActions}
onAccessibilityAction={onAccessibilityAction}>
{item._showParentReplyLine && ( {item._showParentReplyLine && (
<View <View
style={[ style={[

View File

@ -1,4 +1,4 @@
import React, {useState, useEffect} from 'react' import React, {useCallback, useEffect, useMemo, useState} from 'react'
import { import {
ActivityIndicator, ActivityIndicator,
Linking, Linking,
@ -170,7 +170,9 @@ const PostLoaded = observer(
const onOpenTranslate = React.useCallback(() => { const onOpenTranslate = React.useCallback(() => {
Linking.openURL( Linking.openURL(
encodeURI( encodeURI(
`https://translate.google.com/#auto|en|${record?.text || ''}`, `https://translate.google.com/?sl=auto&tl=en&text=${
record?.text || ''
}`,
), ),
) )
}, [record]) }, [record])
@ -203,11 +205,47 @@ const PostLoaded = observer(
) )
}, [item, setDeleted, store]) }, [item, setDeleted, store])
const accessibilityActions = useMemo(
() => [
{
name: 'reply',
label: 'Reply',
},
{
name: 'repost',
label: item.post.viewer?.repost ? 'Undo repost' : 'Repost',
},
{name: 'like', label: item.post.viewer?.like ? 'Unlike' : 'Like'},
],
[item.post.viewer?.like, item.post.viewer?.repost],
)
const onAccessibilityAction = useCallback(
event => {
switch (event.nativeEvent.actionName) {
case 'like':
onPressToggleLike()
break
case 'reply':
onPressReply()
break
case 'repost':
onPressToggleRepost()
break
default:
break
}
},
[onPressReply, onPressToggleLike, onPressToggleRepost],
)
return ( return (
<PostHider <PostHider
href={itemHref} href={itemHref}
style={[styles.outer, pal.view, pal.border, style]} style={[styles.outer, pal.view, pal.border, style]}
moderation={item.moderation.list}> moderation={item.moderation.list}
accessibilityActions={accessibilityActions}
onAccessibilityAction={onAccessibilityAction}>
{showReplyLine && <View style={styles.replyLine} />} {showReplyLine && <View style={styles.replyLine} />}
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>

View File

@ -1,5 +1,6 @@
import React from 'react' import React from 'react'
import {StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {useNavigation} from '@react-navigation/native'
import { import {
FontAwesomeIcon, FontAwesomeIcon,
FontAwesomeIconStyle, FontAwesomeIconStyle,
@ -7,18 +8,24 @@ import {
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'
import {Button} from '../util/forms/Button' import {Button} from '../util/forms/Button'
import {MagnifyingGlassIcon} from 'lib/icons' import {MagnifyingGlassIcon} from 'lib/icons'
import {useStores} from 'state/index' import {NavigationProp} from 'lib/routes/types'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles' import {s} from 'lib/styles'
import {isWeb} from 'platform/detection'
export function WhatsHotEmptyState() { export function CustomFeedEmptyState() {
const pal = usePalette('default') const pal = usePalette('default')
const palInverted = usePalette('inverted') const palInverted = usePalette('inverted')
const store = useStores() const navigation = useNavigation<NavigationProp>()
const onPressSettings = React.useCallback(() => { const onPressFindAccounts = React.useCallback(() => {
store.shell.openModal({name: 'content-languages-settings'}) if (isWeb) {
}, [store]) navigation.navigate('Search', {})
} else {
navigation.navigate('SearchTab')
navigation.popToTop()
}
}, [navigation])
return ( return (
<View style={styles.emptyContainer}> <View style={styles.emptyContainer}>
@ -26,12 +33,15 @@ export function WhatsHotEmptyState() {
<MagnifyingGlassIcon style={[styles.emptyIcon, pal.text]} size={62} /> <MagnifyingGlassIcon style={[styles.emptyIcon, pal.text]} size={62} />
</View> </View>
<Text type="xl-medium" style={[s.textCenter, pal.text]}> <Text type="xl-medium" style={[s.textCenter, pal.text]}>
Your What's Hot feed is empty! This is because there aren't enough users This feed is empty! You may need to follow more users or tune your
posting in your selected language. language settings.
</Text> </Text>
<Button type="inverted" style={styles.emptyBtn} onPress={onPressSettings}> <Button
type="inverted"
style={styles.emptyBtn}
onPress={onPressFindAccounts}>
<Text type="lg-medium" style={palInverted.text}> <Text type="lg-medium" style={palInverted.text}>
Update my settings Find accounts to follow
</Text> </Text>
<FontAwesomeIcon <FontAwesomeIcon
icon="angle-right" icon="angle-right"

View File

@ -18,6 +18,7 @@ import {OnScrollCb} from 'lib/hooks/useOnMainScroll'
import {s} from 'lib/styles' import {s} from 'lib/styles'
import {useAnalytics} from 'lib/analytics' import {useAnalytics} from 'lib/analytics'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
const LOADING_ITEM = {_reactKey: '__loading__'} const LOADING_ITEM = {_reactKey: '__loading__'}
const EMPTY_FEED_ITEM = {_reactKey: '__empty__'} const EMPTY_FEED_ITEM = {_reactKey: '__empty__'}
@ -31,9 +32,12 @@ export const Feed = observer(function Feed({
scrollElRef, scrollElRef,
onPressTryAgain, onPressTryAgain,
onScroll, onScroll,
scrollEventThrottle,
renderEmptyState, renderEmptyState,
testID, testID,
headerOffset = 0, headerOffset = 0,
ListHeaderComponent,
extraData,
}: { }: {
feed: PostsFeedModel feed: PostsFeedModel
style?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle>
@ -41,11 +45,15 @@ export const Feed = observer(function Feed({
scrollElRef?: MutableRefObject<FlatList<any> | null> scrollElRef?: MutableRefObject<FlatList<any> | null>
onPressTryAgain?: () => void onPressTryAgain?: () => void
onScroll?: OnScrollCb onScroll?: OnScrollCb
scrollEventThrottle?: number
renderEmptyState?: () => JSX.Element renderEmptyState?: () => JSX.Element
testID?: string testID?: string
headerOffset?: number headerOffset?: number
ListHeaderComponent?: () => JSX.Element
extraData?: any
}) { }) {
const pal = usePalette('default') const pal = usePalette('default')
const theme = useTheme()
const {track} = useAnalytics() const {track} = useAnalytics()
const [isRefreshing, setIsRefreshing] = React.useState(false) const [isRefreshing, setIsRefreshing] = React.useState(false)
@ -163,6 +171,7 @@ export const Feed = observer(function Feed({
keyExtractor={item => item._reactKey} keyExtractor={item => item._reactKey}
renderItem={renderItem} renderItem={renderItem}
ListFooterComponent={FeedFooter} ListFooterComponent={FeedFooter}
ListHeaderComponent={ListHeaderComponent}
refreshControl={ refreshControl={
<RefreshControl <RefreshControl
refreshing={isRefreshing} refreshing={isRefreshing}
@ -175,10 +184,13 @@ export const Feed = observer(function Feed({
contentContainerStyle={s.contentContainer} contentContainerStyle={s.contentContainer}
style={{paddingTop: headerOffset}} style={{paddingTop: headerOffset}}
onScroll={onScroll} onScroll={onScroll}
scrollEventThrottle={scrollEventThrottle}
indicatorStyle={theme.colorScheme === 'dark' ? 'white' : 'black'}
onEndReached={onEndReached} onEndReached={onEndReached}
onEndReachedThreshold={0.6} onEndReachedThreshold={0.6}
removeClippedSubviews={true} removeClippedSubviews={true}
contentOffset={{x: 0, y: headerOffset * -1}} contentOffset={{x: 0, y: headerOffset * -1}}
extraData={extraData}
// @ts-ignore our .web version only -prf // @ts-ignore our .web version only -prf
desktopFixedHeight desktopFixedHeight
/> />

View File

@ -1,4 +1,4 @@
import React, {useMemo, useState} from 'react' import React, {useCallback, useMemo, useState} from 'react'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {Linking, StyleSheet, View} from 'react-native' import {Linking, StyleSheet, View} from 'react-native'
import Clipboard from '@react-native-clipboard/clipboard' import Clipboard from '@react-native-clipboard/clipboard'
@ -99,7 +99,11 @@ export const FeedItem = observer(function ({
const onOpenTranslate = React.useCallback(() => { const onOpenTranslate = React.useCallback(() => {
Linking.openURL( Linking.openURL(
encodeURI(`https://translate.google.com/#auto|en|${record?.text || ''}`), encodeURI(
`https://translate.google.com/?sl=auto&tl=en&text=${
record?.text || ''
}`,
),
) )
}, [record]) }, [record])
@ -154,12 +158,48 @@ export const FeedItem = observer(function ({
moderation = {behavior: ModerationBehaviorCode.Show} moderation = {behavior: ModerationBehaviorCode.Show}
} }
const accessibilityActions = useMemo(
() => [
{
name: 'reply',
label: 'Reply',
},
{
name: 'repost',
label: item.post.viewer?.repost ? 'Undo repost' : 'Repost',
},
{name: 'like', label: item.post.viewer?.like ? 'Unlike' : 'Like'},
],
[item.post.viewer?.like, item.post.viewer?.repost],
)
const onAccessibilityAction = useCallback(
event => {
switch (event.nativeEvent.actionName) {
case 'like':
onPressToggleLike()
break
case 'reply':
onPressReply()
break
case 'repost':
onPressToggleRepost()
break
default:
break
}
},
[onPressReply, onPressToggleLike, onPressToggleRepost],
)
return ( return (
<PostHider <PostHider
testID={`feedItem-by-${item.post.author.handle}`} testID={`feedItem-by-${item.post.author.handle}`}
style={outerStyles} style={outerStyles}
href={itemHref} href={itemHref}
moderation={moderation}> moderation={moderation}
accessibilityActions={accessibilityActions}
onAccessibilityAction={onAccessibilityAction}>
{isThreadChild && ( {isThreadChild && (
<View <View
style={[styles.topReplyLine, {borderColor: pal.colors.replyLine}]} style={[styles.topReplyLine, {borderColor: pal.colors.replyLine}]}

View File

@ -1,6 +1,6 @@
import React from 'react' import React from 'react'
import {StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {PostsFeedSliceModel} from 'state/models/feeds/posts' import {PostsFeedSliceModel} from 'state/models/feeds/post'
import {AtUri} from '@atproto/api' import {AtUri} from '@atproto/api'
import {Link} from '../util/Link' import {Link} from '../util/Link'
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'

View File

@ -11,6 +11,7 @@ import {MagnifyingGlassIcon} from 'lib/icons'
import {NavigationProp} from 'lib/routes/types' import {NavigationProp} from 'lib/routes/types'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles' import {s} from 'lib/styles'
import {isWeb} from 'platform/detection'
export function FollowingEmptyState() { export function FollowingEmptyState() {
const pal = usePalette('default') const pal = usePalette('default')
@ -18,8 +19,12 @@ export function FollowingEmptyState() {
const navigation = useNavigation<NavigationProp>() const navigation = useNavigation<NavigationProp>()
const onPressFindAccounts = React.useCallback(() => { const onPressFindAccounts = React.useCallback(() => {
navigation.navigate('SearchTab') if (isWeb) {
navigation.popToTop() navigation.navigate('Search', {})
} else {
navigation.navigate('SearchTab')
navigation.popToTop()
}
}, [navigation]) }, [navigation])
return ( return (

View File

@ -0,0 +1,246 @@
import React, {MutableRefObject} from 'react'
import {observer} from 'mobx-react-lite'
import {
ActivityIndicator,
RefreshControl,
StyleProp,
StyleSheet,
View,
ViewStyle,
} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {FlatList} from '../util/Views'
import {PostFeedLoadingPlaceholder} from '../util/LoadingPlaceholder'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {PostsMultiFeedModel, MultiFeedItem} from 'state/models/feeds/multi-feed'
import {FeedSlice} from './FeedSlice'
import {Text} from '../util/text/Text'
import {Link} from '../util/Link'
import {UserAvatar} from '../util/UserAvatar'
import {OnScrollCb} from 'lib/hooks/useOnMainScroll'
import {s} from 'lib/styles'
import {useAnalytics} from 'lib/analytics'
import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
import {isDesktopWeb} from 'platform/detection'
import {CogIcon} from 'lib/icons'
export const MultiFeed = observer(function Feed({
multifeed,
style,
showPostFollowBtn,
scrollElRef,
onScroll,
scrollEventThrottle,
testID,
headerOffset = 0,
extraData,
}: {
multifeed: PostsMultiFeedModel
style?: StyleProp<ViewStyle>
showPostFollowBtn?: boolean
scrollElRef?: MutableRefObject<FlatList<any> | null>
onPressTryAgain?: () => void
onScroll?: OnScrollCb
scrollEventThrottle?: number
renderEmptyState?: () => JSX.Element
testID?: string
headerOffset?: number
extraData?: any
}) {
const pal = usePalette('default')
const theme = useTheme()
const {track} = useAnalytics()
const [isRefreshing, setIsRefreshing] = React.useState(false)
// events
// =
const onRefresh = React.useCallback(async () => {
track('MultiFeed:onRefresh')
setIsRefreshing(true)
try {
await multifeed.refresh()
} catch (err) {
multifeed.rootStore.log.error('Failed to refresh posts feed', err)
}
setIsRefreshing(false)
}, [multifeed, track, setIsRefreshing])
const onEndReached = React.useCallback(async () => {
track('MultiFeed:onEndReached')
try {
await multifeed.loadMore()
} catch (err) {
multifeed.rootStore.log.error('Failed to load more posts', err)
}
}, [multifeed, track])
// rendering
// =
const renderItem = React.useCallback(
({item}: {item: MultiFeedItem}) => {
if (item.type === 'header') {
if (isDesktopWeb) {
return (
<View style={[pal.view, pal.border, styles.headerDesktop]}>
<Text type="2xl-bold" style={pal.text}>
My Feeds
</Text>
<Link href="/settings/saved-feeds">
<CogIcon strokeWidth={1.5} style={pal.icon} size={28} />
</Link>
</View>
)
}
return <View style={[styles.header, pal.border]} />
} else if (item.type === 'feed-header') {
return (
<View style={styles.feedHeader}>
<UserAvatar type="algo" avatar={item.avatar} size={28} />
<Text type="title-lg" style={[pal.text, styles.feedHeaderTitle]}>
{item.title}
</Text>
</View>
)
} else if (item.type === 'feed-slice') {
return (
<FeedSlice slice={item.slice} showFollowBtn={showPostFollowBtn} />
)
} else if (item.type === 'feed-loading') {
return <PostFeedLoadingPlaceholder />
} else if (item.type === 'feed-error') {
return <ErrorMessage message={item.error} />
} else if (item.type === 'feed-footer') {
return (
<Link
href={item.uri}
style={[styles.feedFooter, pal.border, pal.view]}>
<Text type="lg" style={pal.link}>
See more from {item.title}
</Text>
<FontAwesomeIcon
icon="angle-right"
size={18}
color={pal.colors.link}
/>
</Link>
)
} else if (item.type === 'footer') {
return (
<Link style={[styles.footerLink, pal.viewLight]} href="/search/feeds">
<FontAwesomeIcon icon="search" size={18} color={pal.colors.text} />
<Text type="xl-medium" style={pal.text}>
Discover new feeds
</Text>
</Link>
)
}
return null
},
[showPostFollowBtn, pal],
)
const FeedFooter = React.useCallback(
() =>
multifeed.isLoading && !isRefreshing ? (
<View style={styles.loadMore}>
<ActivityIndicator color={pal.colors.text} />
</View>
) : (
<View />
),
[multifeed.isLoading, isRefreshing, pal],
)
return (
<View testID={testID} style={style}>
{multifeed.items.length > 0 && (
<FlatList
testID={testID ? `${testID}-flatlist` : undefined}
ref={scrollElRef}
data={multifeed.items}
keyExtractor={item => item._reactKey}
renderItem={renderItem}
ListFooterComponent={FeedFooter}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={onRefresh}
tintColor={pal.colors.text}
titleColor={pal.colors.text}
progressViewOffset={headerOffset}
/>
}
contentContainerStyle={s.contentContainer}
style={[{paddingTop: headerOffset}, pal.view, styles.container]}
onScroll={onScroll}
scrollEventThrottle={scrollEventThrottle}
indicatorStyle={theme.colorScheme === 'dark' ? 'white' : 'black'}
onEndReached={onEndReached}
onEndReachedThreshold={0.6}
removeClippedSubviews={true}
contentOffset={{x: 0, y: headerOffset * -1}}
extraData={extraData}
// @ts-ignore our .web version only -prf
desktopFixedHeight
/>
)}
</View>
)
})
const styles = StyleSheet.create({
container: {
height: '100%',
},
header: {
borderTopWidth: 1,
marginBottom: 4,
},
headerDesktop: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
borderBottomWidth: 1,
marginBottom: 4,
paddingHorizontal: 16,
paddingVertical: 8,
},
feedHeader: {
flexDirection: 'row',
gap: 8,
alignItems: 'center',
paddingHorizontal: 16,
paddingBottom: 8,
marginTop: 12,
},
feedHeaderTitle: {
fontWeight: 'bold',
},
feedFooter: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 16,
paddingVertical: 16,
marginBottom: 12,
borderTopWidth: 1,
borderBottomWidth: 1,
},
footerLink: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8,
paddingHorizontal: 14,
paddingVertical: 12,
marginHorizontal: 8,
marginBottom: 8,
gap: 8,
},
loadMore: {
paddingTop: 10,
},
})

View File

@ -33,7 +33,7 @@ export const FollowButton = observer(
store.me.follows.removeFollow(did) store.me.follows.removeFollow(did)
onToggleFollow?.(false) onToggleFollow?.(false)
} catch (e: any) { } catch (e: any) {
store.log.error('Failed fo delete follow', e) store.log.error('Failed to delete follow', e)
Toast.show('An issue occurred, please try again.') Toast.show('An issue occurred, please try again.')
} }
} else if (updatedFollowState === FollowState.NotFollowing) { } else if (updatedFollowState === FollowState.NotFollowing) {
@ -42,7 +42,7 @@ export const FollowButton = observer(
store.me.follows.addFollow(did, res.uri) store.me.follows.addFollow(did, res.uri)
onToggleFollow?.(true) onToggleFollow?.(true)
} catch (e: any) { } catch (e: any) {
store.log.error('Failed fo create follow', e) store.log.error('Failed to create follow', e)
Toast.show('An issue occurred, please try again.') Toast.show('An issue occurred, please try again.')
} }
} }

View File

@ -218,7 +218,7 @@ const ProfileHeaderLoaded = observer(
onRefreshAll() onRefreshAll()
Toast.show('Account unblocked') Toast.show('Account unblocked')
} catch (e: any) { } catch (e: any) {
store.log.error('Failed to block unaccount', e) store.log.error('Failed to unblock account', e)
Toast.show(`There was an issue! ${e.toString()}`) Toast.show(`There was an issue! ${e.toString()}`)
} }
}, },
@ -289,6 +289,9 @@ const ProfileHeaderLoaded = observer(
]) ])
const blockHide = !isMe && (view.viewer.blocking || view.viewer.blockedBy) const blockHide = !isMe && (view.viewer.blocking || view.viewer.blockedBy)
const following = formatCount(view.followsCount)
const followers = formatCount(view.followersCount)
const pluralizedFollowers = pluralize(view.followersCount, 'follower')
return ( return (
<View style={pal.view}> <View style={pal.view}>
@ -394,13 +397,13 @@ const ProfileHeaderLoaded = observer(
style={[s.flexRow, s.mr10]} style={[s.flexRow, s.mr10]}
onPress={onPressFollowers} onPress={onPressFollowers}
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel={`Show ${view.handle}'s followers`} accessibilityLabel={`${followers} ${pluralizedFollowers}`}
accessibilityHint={`Shows folks following ${view.handle}`}> accessibilityHint={'Opens followers list'}>
<Text type="md" style={[s.bold, s.mr2, pal.text]}> <Text type="md" style={[s.bold, s.mr2, pal.text]}>
{formatCount(view.followersCount)} {followers}
</Text> </Text>
<Text type="md" style={[pal.textLight]}> <Text type="md" style={[pal.textLight]}>
{pluralize(view.followersCount, 'follower')} {pluralizedFollowers}
</Text> </Text>
</TouchableOpacity> </TouchableOpacity>
<TouchableOpacity <TouchableOpacity
@ -408,10 +411,10 @@ const ProfileHeaderLoaded = observer(
style={[s.flexRow, s.mr10]} style={[s.flexRow, s.mr10]}
onPress={onPressFollows} onPress={onPressFollows}
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel={`Show ${view.handle}'s follows`} accessibilityLabel={`${following} following`}
accessibilityHint={`Shows folks followed by ${view.handle}`}> accessibilityHint={'Opens following list'}>
<Text type="md" style={[s.bold, s.mr2, pal.text]}> <Text type="md" style={[s.bold, s.mr2, pal.text]}>
{formatCount(view.followsCount)} {following}
</Text> </Text>
<Text type="md" style={[pal.textLight]}> <Text type="md" style={[pal.textLight]}>
following following

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