Compare commits
95 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9041b04484 | |||
| a25bc8f249 | |||
| 177a6e50bd | |||
| 338016ed5c | |||
| e2058c8ecc | |||
| 3cbded0269 | |||
| 5ea96736de | |||
| efed955003 | |||
| b8db36afb0 | |||
| 5642bc40bb | |||
| 3be1f5caa9 | |||
| 18eea81e76 | |||
| 917f099e26 | |||
| 6bfe758d2a | |||
| 18ab5d6f34 | |||
| dc3f01591f | |||
| 423eddc474 | |||
| 5c5b365ee9 | |||
| 1584c2de48 | |||
| bb6ce83198 | |||
| 3abc361800 | |||
| e6c4a539ca | |||
| 965b17ff86 | |||
| 546201c93c | |||
| b3cbb3440a | |||
| da5c356fc7 | |||
| 6f01503eac | |||
| 24dbe799dc | |||
| 3197cbcf36 | |||
| 017120b3e8 | |||
| 27d9462639 | |||
| b2c95bc35a | |||
| cbd48c855a | |||
| 421c18ea7c | |||
| 26c84399dd | |||
| 4f1d4821c5 | |||
| bfd5ed480f | |||
| d9ef02737b | |||
| 809b318fe4 | |||
| 864af57fd9 | |||
| ab98130295 | |||
| a168e97d07 | |||
| 748706daab | |||
| 45d6e50eb4 | |||
| e2a56b0191 | |||
| 1eb09b7210 | |||
| ee99320e1f | |||
| 9689a6daaa | |||
| 45735144ee | |||
| 4b86444bd8 | |||
| 9ff5b2da50 | |||
| 58f532a495 | |||
| 0babd0f475 | |||
| 2cee96da8e | |||
| 31553f0d40 | |||
| 0ac5b07bfd | |||
| d13df6c7e6 | |||
| a18f1b68e8 | |||
| b9c92d39eb | |||
| d45a2c832d | |||
| fd49349b71 | |||
| 277e985e1f | |||
| 3b2573bc56 | |||
| ae77320d81 | |||
| 72b7516d9b | |||
| 220e989f3d | |||
| 39e7132fd8 | |||
| 26605ee730 | |||
| f1c50baa4e | |||
| e49ce42a12 | |||
| fd6b8fcbf1 | |||
| 2953b3a094 | |||
| 69a765cc0d | |||
| dd7bb1bc14 | |||
| d31bc7f335 | |||
| f26ac583e6 | |||
| 2ad84d7dfc | |||
| 282b5e8460 | |||
| f82bc98d8d | |||
| 3b7806963a | |||
| 49e7a96cd9 | |||
| 3523e7ce58 | |||
| 967b3b49d9 | |||
| 97083bb55b | |||
| df89b79c2a | |||
| 6534630d16 | |||
| 25a1ed1209 | |||
| 8614e5e105 | |||
| 7da65efc08 | |||
| 4f01d4cc81 | |||
| b4f57b94aa | |||
| bd9e8244f1 | |||
| 5989bf7fad | |||
| a4f173d008 | |||
| f244afcd9c |
@@ -28,6 +28,13 @@ EXPO_PUBLIC_CHAT_PROXY_DID=
|
||||
#
|
||||
#
|
||||
|
||||
# Bluesky's metrics API
|
||||
EXPO_PUBLIC_METRICS_API_HOST=
|
||||
|
||||
# Growthbook config
|
||||
EXPO_PUBLIC_GROWTHBOOK_API_HOST=
|
||||
EXPO_PUBLIC_GROWTHBOOK_CLIENT_KEY=
|
||||
|
||||
# Sentry DSN for telemetry
|
||||
EXPO_PUBLIC_SENTRY_DSN=
|
||||
|
||||
|
||||
@@ -15,11 +15,11 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Git Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
- name: Set up Go tooling
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.25"
|
||||
go-version-file: bskyweb/go.mod
|
||||
- name: Dummy Static Files
|
||||
run: touch bskyweb/static/js/blah.js && touch bskyweb/static/css/blah.txt && touch bskyweb/static/media/blah.txt
|
||||
- name: Check
|
||||
@@ -32,11 +32,11 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Git Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
- name: Set up Go tooling
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.25"
|
||||
go-version-file: bskyweb/go.mod
|
||||
- name: Dummy Static Files
|
||||
run: touch bskyweb/static/js/blah.js && touch bskyweb/static/css/blah.txt && touch bskyweb/static/media/blah.txt
|
||||
- name: Lint
|
||||
|
||||
@@ -29,8 +29,9 @@ yarn lint # Run ESLint
|
||||
yarn typecheck # Run TypeScript type checking
|
||||
|
||||
# Internationalization
|
||||
yarn intl:extract # Extract translation strings
|
||||
yarn intl:compile # Compile translations for runtime
|
||||
# DO NOT run these commands - extraction and compilation are handled by CI
|
||||
yarn intl:extract # Extract translation strings (nightly CI job)
|
||||
yarn intl:compile # Compile translations for runtime (nightly CI job)
|
||||
|
||||
# Build
|
||||
yarn build-web # Build web version
|
||||
@@ -119,7 +120,7 @@ if (gtMobile) {
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
- Spacing: `xxs`, `xs`, `sm`, `md`, `lg`, `xl`, `xxl` (t-shirt sizes)
|
||||
- Spacing: `2xs`, `xs`, `sm`, `md`, `lg`, `xl`, `2xl` (t-shirt sizes)
|
||||
- Text: `text_xs`, `text_sm`, `text_md`, `text_lg`, `text_xl`
|
||||
- Gaps/Padding: `gap_sm`, `p_md`, `px_lg`, `py_xl`
|
||||
- Flex: `flex_row`, `flex_1`, `align_center`, `justify_between`
|
||||
@@ -144,7 +145,8 @@ function MyFeature() {
|
||||
</Button>
|
||||
|
||||
<Dialog.Outer control={control}>
|
||||
<Dialog.Handle /> {/* Native drag handle */}
|
||||
{/* Typically the inner part is in its own component */}
|
||||
<Dialog.Handle /> {/* Native-only drag handle */}
|
||||
<Dialog.ScrollableInner label={_(msg`My Dialog`)}>
|
||||
<Dialog.Header>
|
||||
<Dialog.HeaderText>Title</Dialog.HeaderText>
|
||||
@@ -152,9 +154,10 @@ function MyFeature() {
|
||||
|
||||
<Text>Dialog content here</Text>
|
||||
|
||||
<Button label="Close" onPress={() => control.close()}>
|
||||
<ButtonText>Close</ButtonText>
|
||||
<Button label="Done" onPress={() => control.close()}>
|
||||
<ButtonText>Done</ButtonText>
|
||||
</Button>
|
||||
<Dialog.Close /> {/* Web-only X button in top left */}
|
||||
</Dialog.ScrollableInner>
|
||||
</Dialog.Outer>
|
||||
</>
|
||||
@@ -215,7 +218,7 @@ import {Button, ButtonText, ButtonIcon} from '#/components/Button'
|
||||
|
||||
// Icon-only button
|
||||
<Button label="Close" onPress={handleClose} color="secondary" size="small" shape="round">
|
||||
<ButtonIcon icon={X} />
|
||||
<ButtonIcon icon={XIcon} />
|
||||
</Button>
|
||||
|
||||
// Ghost variant (deprecated - use color prop)
|
||||
@@ -225,7 +228,7 @@ import {Button, ButtonText, ButtonIcon} from '#/components/Button'
|
||||
```
|
||||
|
||||
**Button Props:**
|
||||
- `color`: `'primary'` | `'secondary'` | `'negative'` | `'primary_subtle'` | `'negative_subtle'`
|
||||
- `color`: `'primary'` | `'secondary'` | `'negative'` | `'primary_subtle'` | `'negative_subtle'` | `'secondary_inverted'`
|
||||
- `size`: `'tiny'` | `'small'` | `'large'`
|
||||
- `shape`: `'default'` (pill) | `'round'` | `'square'` | `'rectangular'`
|
||||
- `variant`: `'solid'` | `'outline'` | `'ghost'` (deprecated, use `color`)
|
||||
@@ -297,8 +300,9 @@ function MyComponent() {
|
||||
|
||||
**Commands:**
|
||||
```bash
|
||||
# DO NOT run these commands - extraction and compilation are handled by a nightly CI job
|
||||
yarn intl:extract # Extract new strings to locale files
|
||||
yarn intl:compile # Compile for runtime (required after changes)
|
||||
yarn intl:compile # Compile translations for runtime
|
||||
```
|
||||
|
||||
## State Management
|
||||
@@ -339,6 +343,16 @@ export function useUpdateProfile() {
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({queryKey: RQKEY(variables.did)})
|
||||
},
|
||||
onError: (error) => {
|
||||
if (isNetworkError(error)) {
|
||||
// don't log, but inform user
|
||||
} else if (error instanceof AppBskyExampleProcedure.ExampleError) {
|
||||
// XRPC APIs often have typed errors, allows nicer handling
|
||||
} else {
|
||||
// Log unexpected errors to Sentry
|
||||
logger.error('Error updating profile', {safeMessage: error})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
@@ -352,6 +366,26 @@ STALE.HOURS.ONE // 1 hour
|
||||
STALE.INFINITY // Never stale
|
||||
```
|
||||
|
||||
**Paginated APIs:** Many atproto APIs return paginated results with a `cursor`. Use `useInfiniteQuery` for these:
|
||||
|
||||
```tsx
|
||||
export function useDraftsQuery() {
|
||||
const agent = useAgent()
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['drafts'],
|
||||
queryFn: async ({pageParam}) => {
|
||||
const res = await agent.app.bsky.draft.getDrafts({cursor: pageParam})
|
||||
return res.data
|
||||
},
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: page => page.cursor,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
To get all items from pages: `data?.pages.flatMap(page => page.items) ?? []`
|
||||
|
||||
### Preferences (React Context)
|
||||
|
||||
```tsx
|
||||
@@ -437,7 +471,19 @@ Example from Dialog:
|
||||
- `src/components/Dialog/index.tsx` - Native (uses BottomSheet)
|
||||
- `src/components/Dialog/index.web.tsx` - Web (uses modal with Radix primitives)
|
||||
|
||||
Platform detection:
|
||||
**Important:** The bundler automatically resolves platform-specific files. Just import normally:
|
||||
|
||||
```tsx
|
||||
// CORRECT - bundler picks storage.ts or storage.web.ts automatically
|
||||
import * as storage from '#/state/drafts/storage'
|
||||
|
||||
// WRONG - don't use require() or conditional imports for platform files
|
||||
const storage = IS_NATIVE
|
||||
? require('#/state/drafts/storage')
|
||||
: require('#/state/drafts/storage.web')
|
||||
```
|
||||
|
||||
Platform detection (for runtime logic, not imports):
|
||||
```tsx
|
||||
import {IS_WEB, IS_NATIVE, IS_IOS, IS_ANDROID} from '#/env'
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright 2023–2025 Bluesky Social PBC
|
||||
Copyright 2023–2026 Bluesky Social PBC
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
// @ts-check
|
||||
const pkg = require('./package.json')
|
||||
|
||||
/**
|
||||
* @param {import('@expo/config-types').ExpoConfig} _config
|
||||
* @returns {{ expo: import('@expo/config-types').ExpoConfig }}
|
||||
*/
|
||||
module.exports = function (_config) {
|
||||
/**
|
||||
* App version number. Should be incremented as part of a release cycle.
|
||||
@@ -15,7 +20,7 @@ module.exports = function (_config) {
|
||||
|
||||
const IS_TESTFLIGHT = process.env.EXPO_PUBLIC_ENV === 'testflight'
|
||||
const IS_PRODUCTION = process.env.EXPO_PUBLIC_ENV === 'production'
|
||||
const IS_DEV = !IS_TESTFLIGHT || !IS_PRODUCTION
|
||||
const IS_DEV = !IS_TESTFLIGHT && !IS_PRODUCTION
|
||||
|
||||
const ASSOCIATED_DOMAINS = [
|
||||
'applinks:bsky.app',
|
||||
@@ -114,6 +119,7 @@ module.exports = function (_config) {
|
||||
'com.apple.developer.kernel.increased-memory-limit': true,
|
||||
'com.apple.developer.kernel.extended-virtual-addressing': true,
|
||||
'com.apple.security.application-groups': 'group.app.bsky',
|
||||
// 'com.apple.developer.device-information.user-assigned-device-name': true,
|
||||
},
|
||||
privacyManifests: {
|
||||
NSPrivacyCollectedDataTypes: [
|
||||
@@ -192,10 +198,14 @@ module.exports = function (_config) {
|
||||
scheme: 'https',
|
||||
host: 'bsky.app',
|
||||
},
|
||||
IS_DEV && {
|
||||
scheme: 'http',
|
||||
host: 'localhost:19006',
|
||||
},
|
||||
...(IS_DEV
|
||||
? [
|
||||
{
|
||||
scheme: 'http',
|
||||
host: 'localhost:19006',
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
category: ['BROWSABLE', 'DEFAULT'],
|
||||
},
|
||||
@@ -227,20 +237,25 @@ module.exports = function (_config) {
|
||||
'react-native-edge-to-edge',
|
||||
{android: {enforceNavigationBarContrast: false}},
|
||||
],
|
||||
USE_SENTRY && [
|
||||
'@sentry/react-native/expo',
|
||||
{
|
||||
organization: 'blueskyweb',
|
||||
project: 'app',
|
||||
url: 'https://sentry.io',
|
||||
},
|
||||
],
|
||||
...(USE_SENTRY
|
||||
? [
|
||||
/** @type {[string, any]} */ ([
|
||||
'@sentry/react-native/expo',
|
||||
{
|
||||
organization: 'blueskyweb',
|
||||
project: 'app',
|
||||
url: 'https://sentry.io',
|
||||
},
|
||||
]),
|
||||
]
|
||||
: []),
|
||||
[
|
||||
'expo-build-properties',
|
||||
{
|
||||
ios: {
|
||||
deploymentTarget: '15.1',
|
||||
buildReactNativeFromSource: true,
|
||||
ccacheEnabled: IS_DEV,
|
||||
},
|
||||
android: {
|
||||
compileSdkVersion: 35,
|
||||
@@ -297,25 +312,25 @@ module.exports = function (_config) {
|
||||
'expo-splash-screen',
|
||||
{
|
||||
ios: {
|
||||
enableFullScreenImage_legacy: true,
|
||||
backgroundColor: '#ffffff',
|
||||
image: './assets/splash.png',
|
||||
enableFullScreenImage_legacy: true, // iOS only
|
||||
backgroundColor: '#006AFF', // primary_500
|
||||
image: './assets/splash/splash.png',
|
||||
resizeMode: 'cover',
|
||||
dark: {
|
||||
enableFullScreenImage_legacy: true,
|
||||
backgroundColor: '#001429',
|
||||
image: './assets/splash-dark.png',
|
||||
enableFullScreenImage_legacy: true, // iOS only
|
||||
backgroundColor: '#002861', // primary_900
|
||||
image: './assets/splash/splash-dark.png',
|
||||
resizeMode: 'cover',
|
||||
},
|
||||
},
|
||||
android: {
|
||||
backgroundColor: '#0c7cff',
|
||||
image: './assets/splash-android-icon.png',
|
||||
imageWidth: 150,
|
||||
backgroundColor: '#006AFF', // primary_500
|
||||
image: './assets/splash/android-splash-logo-white.png',
|
||||
imageWidth: 102, // even division of 306px
|
||||
dark: {
|
||||
backgroundColor: '#0c2a49',
|
||||
image: './assets/splash-android-icon-dark.png',
|
||||
imageWidth: 150,
|
||||
backgroundColor: '#002861', // primary_900
|
||||
image: './assets/splash/android-splash-logo-white.png',
|
||||
imageWidth: 102,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -396,7 +411,7 @@ module.exports = function (_config) {
|
||||
'I agree to allow Bluesky to use my contacts for friend discovery until I opt out.',
|
||||
},
|
||||
],
|
||||
].filter(Boolean),
|
||||
],
|
||||
extra: {
|
||||
eas: {
|
||||
build: {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 64 64"><path fill="#000" d="M32.457 7c1.68 0 3.29.668 4.478 1.855L49.813 21.73a6.33 6.33 0 0 1 1.854 4.479v24.458A6.333 6.333 0 0 1 45.333 57H18.666a6.334 6.334 0 0 1-6.333-6.333V13.333A6.334 6.334 0 0 1 18.666 7h13.791ZM18.666 9a4.334 4.334 0 0 0-4.333 4.333v37.334A4.334 4.334 0 0 0 18.666 55h26.667a4.333 4.333 0 0 0 4.333-4.333V26.209c0-.418-.061-.829-.177-1.223a1 1 0 0 1-.155.014H40a6.334 6.334 0 0 1-6.325-6.008l-.008-.326V9.333q0-.08.013-.156A4.3 4.3 0 0 0 32.457 9H18.666Zm18.627 22.293a1 1 0 1 1 1.414 1.414L33.414 38l5.293 5.293a1 1 0 1 1-1.414 1.414L32 39.414l-5.293 5.293a1 1 0 1 1-1.414-1.414L30.586 38l-5.293-5.293a1 1 0 1 1 1.414-1.414L32 36.586l5.293-5.293Zm-1.626-12.627.006.224A4.333 4.333 0 0 0 40 23h8.253L35.667 10.414v8.252Z"/></svg>
|
||||
|
After Width: | Height: | Size: 822 B |
|
After Width: | Height: | Size: 153 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 5.2 KiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 606 KiB After Width: | Height: | Size: 606 KiB |
|
Before Width: | Height: | Size: 563 KiB After Width: | Height: | Size: 563 KiB |
@@ -30,5 +30,8 @@
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "^7.0.4",
|
||||
"vite-tsconfig-paths": "^5.1.4"
|
||||
},
|
||||
"resolutions": {
|
||||
"@types/estree": "1.0.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1330,10 +1330,10 @@
|
||||
resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.45.0.tgz#0a7eecae41f463d6591c8fecd7a5c5087345ee36"
|
||||
integrity sha512-SRf1cytG7wqcHVLrBc9VtPK4pU5wxiB/lNIkNmW2ApKXIg+RpqwHfsaEK+e7eH4A1BpI6BX/aBWXxZCIrJg3uA==
|
||||
|
||||
"@types/estree@1.0.8", "@types/estree@^1.0.6":
|
||||
version "1.0.8"
|
||||
resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.8.tgz#958b91c991b1867ced318bedea0e215ee050726e"
|
||||
integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==
|
||||
"@types/estree@1.0.6", "@types/estree@1.0.8", "@types/estree@^1.0.6":
|
||||
version "1.0.6"
|
||||
resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.6.tgz#628effeeae2064a1b4e79f78e81d87b7e5fc7b50"
|
||||
integrity sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==
|
||||
|
||||
"@types/json-schema@^7.0.15":
|
||||
version "7.0.15"
|
||||
|
||||
@@ -72,10 +72,12 @@ export default defineConfig(
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.browser,
|
||||
...globals.node,
|
||||
},
|
||||
parserOptions: {
|
||||
parser: tsParser,
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
},
|
||||
@@ -118,8 +120,8 @@ export default defineConfig(
|
||||
},
|
||||
],
|
||||
'bsky-internal/use-exact-imports': 'error',
|
||||
'bsky-internal/use-typed-gates': 'error',
|
||||
'bsky-internal/use-prefixed-imports': 'error',
|
||||
'bsky-internal/lingui-msg-rule': 'error',
|
||||
|
||||
/**
|
||||
* React & React Native
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
const {RuleTester} = require('eslint')
|
||||
const tseslint = require('typescript-eslint')
|
||||
const linguiMsgRule = require('../lingui-msg-rule')
|
||||
|
||||
const ruleTester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: tseslint.parser,
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
},
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
describe('lingui-msg-rule', () => {
|
||||
const tests = {
|
||||
valid: [
|
||||
// msg template literal
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _(msg\`Hello\`)
|
||||
`,
|
||||
},
|
||||
// msg template literal with interpolation
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const name = 'World'
|
||||
const x = _(msg\`Hello \${name}\`)
|
||||
`,
|
||||
},
|
||||
// plural macro
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const count = 5
|
||||
const x = _(plural(count, {one: '# item', other: '# items'}))
|
||||
`,
|
||||
},
|
||||
// select macro
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const gender = 'female'
|
||||
const x = _(select(gender, {male: 'He', female: 'She', other: 'They'}))
|
||||
`,
|
||||
},
|
||||
// selectOrdinal macro
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const position = 1
|
||||
const x = _(selectOrdinal(position, {one: '#st', two: '#nd', few: '#rd', other: '#th'}))
|
||||
`,
|
||||
},
|
||||
// msg function call with object (descriptor form)
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _(msg({message: 'Hello'}))
|
||||
`,
|
||||
},
|
||||
// msg function call with object and context
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _(msg({message: 'Hello', context: 'greeting'}))
|
||||
`,
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
// Plain string literal (single quotes) - with auto-fix
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _('Bad')
|
||||
`,
|
||||
output: `
|
||||
const {_} = useLingui()
|
||||
const x = _(msg\`Bad\`)
|
||||
`,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Plain string literal (double quotes) - with auto-fix
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _("Bad")
|
||||
`,
|
||||
output: `
|
||||
const {_} = useLingui()
|
||||
const x = _(msg\`Bad\`)
|
||||
`,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Template literal without msg tag - with auto-fix
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _(\`Bad\`)
|
||||
`,
|
||||
output: `
|
||||
const {_} = useLingui()
|
||||
const x = _(msg\`Bad\`)
|
||||
`,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Template literal with interpolation - with auto-fix
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const name = 'World'
|
||||
const x = _(\`Hello \${name}\`)
|
||||
`,
|
||||
output: `
|
||||
const {_} = useLingui()
|
||||
const name = 'World'
|
||||
const x = _(msg\`Hello \${name}\`)
|
||||
`,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// String with backticks that need escaping
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _('Use \\\`code\\\` here')
|
||||
`,
|
||||
output: `
|
||||
const {_} = useLingui()
|
||||
const x = _(msg\`Use \\\`code\\\` here\`)
|
||||
`,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Variable/identifier - no auto-fix possible
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const message = 'Hello'
|
||||
const x = _(message)
|
||||
`,
|
||||
output: null,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Arbitrary function call - no auto-fix possible
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _(getMessage())
|
||||
`,
|
||||
output: null,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Empty call - no auto-fix possible
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _()
|
||||
`,
|
||||
output: null,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Tagged template with wrong tag - no auto-fix (would need to replace tag)
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _(html\`Hello\`)
|
||||
`,
|
||||
output: null,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
// Number literal - no auto-fix possible
|
||||
{
|
||||
code: `
|
||||
const {_} = useLingui()
|
||||
const x = _(123)
|
||||
`,
|
||||
output: null,
|
||||
errors: [{messageId: 'missingMsg'}],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
ruleTester.run('lingui-msg-rule', linguiMsgRule, tests)
|
||||
})
|
||||
@@ -8,8 +8,8 @@ const plugin = {
|
||||
rules: {
|
||||
'avoid-unwrapped-text': require('./avoid-unwrapped-text'),
|
||||
'use-exact-imports': require('./use-exact-imports'),
|
||||
'use-typed-gates': require('./use-typed-gates'),
|
||||
'use-prefixed-imports': require('./use-prefixed-imports'),
|
||||
'lingui-msg-rule': require('./lingui-msg-rule'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* @type {import('eslint').Rule.RuleModule}
|
||||
*/
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description:
|
||||
'Enforce that Lingui _() function is called with msg`` template literal or plural/select macros',
|
||||
recommended: true,
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
missingMsg:
|
||||
'Lingui _() must be called with msg`...` or msg({...}) or plural/select/selectOrdinal. Example: _(msg`Hello`)',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
|
||||
create(context) {
|
||||
// Valid Lingui macro functions that can be passed to _()
|
||||
const VALID_MACRO_FUNCTIONS = new Set([
|
||||
'msg',
|
||||
'plural',
|
||||
'select',
|
||||
'selectOrdinal',
|
||||
])
|
||||
|
||||
/**
|
||||
* Escape backticks and backslashes for template literal
|
||||
*/
|
||||
function escapeForTemplateLiteral(str) {
|
||||
return str.replace(/\\`/g, '`').replace(/`/g, '\\`')
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to get a fixer for the given argument
|
||||
* Returns null if we can't safely fix it
|
||||
*/
|
||||
function getFixer(firstArg) {
|
||||
const sourceCode = context.sourceCode ?? context.getSourceCode()
|
||||
|
||||
// Fix string literals: _('foo') -> _(msg`foo`)
|
||||
if (firstArg.type === 'Literal' && typeof firstArg.value === 'string') {
|
||||
const escaped = escapeForTemplateLiteral(firstArg.value)
|
||||
return function (fixer) {
|
||||
return fixer.replaceText(firstArg, 'msg`' + escaped + '`')
|
||||
}
|
||||
}
|
||||
|
||||
// Fix untagged template literals: _(`foo`) -> _(msg`foo`)
|
||||
if (firstArg.type === 'TemplateLiteral') {
|
||||
const text = sourceCode.getText(firstArg)
|
||||
return function (fixer) {
|
||||
return fixer.replaceText(firstArg, 'msg' + text)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
CallExpression(node) {
|
||||
// Check if this is a call to _()
|
||||
if (node.callee.type !== 'Identifier' || node.callee.name !== '_') {
|
||||
return
|
||||
}
|
||||
|
||||
// Must have at least one argument
|
||||
if (node.arguments.length === 0) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'missingMsg',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const firstArg = node.arguments[0]
|
||||
|
||||
// Valid: _(msg`...`)
|
||||
if (
|
||||
firstArg.type === 'TaggedTemplateExpression' &&
|
||||
firstArg.tag.type === 'Identifier' &&
|
||||
firstArg.tag.name === 'msg'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Valid: _(msg(...)), _(plural(...)), _(select(...)), _(selectOrdinal(...))
|
||||
if (
|
||||
firstArg.type === 'CallExpression' &&
|
||||
firstArg.callee.type === 'Identifier' &&
|
||||
VALID_MACRO_FUNCTIONS.has(firstArg.callee.name)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Everything else is invalid
|
||||
const fix = getFixer(firstArg)
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'missingMsg',
|
||||
fix,
|
||||
})
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description:
|
||||
'Enforce using internal statsig wrapper instead of npm package',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
ImportSpecifier(node) {
|
||||
if (
|
||||
!node.local ||
|
||||
node.local.type !== 'Identifier' ||
|
||||
node.local.name !== 'useGate'
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (
|
||||
node.parent.type !== 'ImportDeclaration' ||
|
||||
!node.parent.source ||
|
||||
node.parent.source.type !== 'Literal'
|
||||
) {
|
||||
return
|
||||
}
|
||||
const source = node.parent.source.value
|
||||
if (source.startsWith('statsig') || source.startsWith('@statsig')) {
|
||||
context.report({
|
||||
node,
|
||||
message:
|
||||
"Use useGate() from '#/lib/statsig/statsig' instead of the one on npm.",
|
||||
})
|
||||
}
|
||||
// TODO: Verify gate() call results aren't stored in variables.
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -99,20 +99,9 @@ jest.mock('expo-modules-core', () => ({
|
||||
requireNativeViewManager: jest.fn().mockImplementation(_ => {
|
||||
return () => null
|
||||
}),
|
||||
createPermissionHook: () => () => [true],
|
||||
}))
|
||||
|
||||
jest.mock('expo-localization', () => ({
|
||||
getLocales: () => [],
|
||||
}))
|
||||
|
||||
jest.mock('statsig-react-native-expo', () => ({
|
||||
Statsig: {
|
||||
initialize() {},
|
||||
initializeCalled() {
|
||||
return false
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('../src/logger/bitdrift/lib', () => ({}))
|
||||
jest.mock('../src/lib/statsig/statsig', () => ({}))
|
||||
|
||||
@@ -44,6 +44,6 @@ android {
|
||||
|
||||
dependencies {
|
||||
implementation project(':expo-modules-core')
|
||||
implementation 'com.google.android.material:material:1.12.0'
|
||||
implementation 'com.google.android.material:material:1.13.0'
|
||||
implementation "com.facebook.react:react-native:+"
|
||||
}
|
||||
|
||||
@@ -5,8 +5,12 @@ import android.util.DisplayMetrics
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.ViewStructure
|
||||
import android.view.Window
|
||||
import android.view.accessibility.AccessibilityEvent
|
||||
import android.widget.FrameLayout
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import androidx.core.view.allViews
|
||||
import com.facebook.react.bridge.LifecycleEventListener
|
||||
import com.facebook.react.bridge.ReactContext
|
||||
@@ -15,6 +19,7 @@ import com.facebook.react.uimanager.UIManagerHelper
|
||||
import com.facebook.react.uimanager.events.EventDispatcher
|
||||
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.google.android.material.internal.EdgeToEdgeUtils
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
@@ -29,22 +34,26 @@ class BottomSheetView(
|
||||
|
||||
private lateinit var dialogRootViewGroup: DialogRootViewGroup
|
||||
private var eventDispatcher: EventDispatcher? = null
|
||||
private var isKeyboardVisible: Boolean = false
|
||||
|
||||
private val rawScreenHeight =
|
||||
private val screenHeight =
|
||||
context.resources.displayMetrics.heightPixels
|
||||
.toFloat()
|
||||
private val safeScreenHeight = (rawScreenHeight - getNavigationBarHeight()).toFloat()
|
||||
|
||||
private fun getNavigationBarHeight(): Int {
|
||||
val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
|
||||
return if (resourceId > 0) resources.getDimensionPixelSize(resourceId) else 0
|
||||
}
|
||||
|
||||
private fun getStatusBarHeight(): Int {
|
||||
val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
|
||||
return if (resourceId > 0) resources.getDimensionPixelSize(resourceId) else 0
|
||||
}
|
||||
|
||||
private val onAttemptDismiss by EventDispatcher()
|
||||
private val onSnapPointChange by EventDispatcher()
|
||||
private val onStateChange by EventDispatcher()
|
||||
|
||||
// Props
|
||||
var disableDrag = false
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -56,48 +65,31 @@ class BottomSheetView(
|
||||
field = value
|
||||
this.dialog?.setCancelable(!value)
|
||||
}
|
||||
|
||||
var preventExpansion = false
|
||||
|
||||
var minHeight = 0f
|
||||
set(value) {
|
||||
field =
|
||||
if (value < 0) {
|
||||
0f
|
||||
} else {
|
||||
dpToPx(value)
|
||||
}
|
||||
field = if (value < 0) 0f else dpToPx(value)
|
||||
}
|
||||
|
||||
var maxHeight = this.safeScreenHeight
|
||||
var maxHeight = this.screenHeight
|
||||
set(value) {
|
||||
val px = dpToPx(value)
|
||||
field =
|
||||
if (px > this.safeScreenHeight) {
|
||||
this.safeScreenHeight
|
||||
} else {
|
||||
px
|
||||
}
|
||||
field = if (px > this.screenHeight) this.screenHeight else px
|
||||
}
|
||||
|
||||
private var isOpen: Boolean = false
|
||||
set(value) {
|
||||
field = value
|
||||
onStateChange(
|
||||
mapOf(
|
||||
"state" to if (value) "open" else "closed",
|
||||
),
|
||||
)
|
||||
onStateChange(mapOf("state" to if (value) "open" else "closed"))
|
||||
}
|
||||
|
||||
private var isOpening: Boolean = false
|
||||
set(value) {
|
||||
field = value
|
||||
if (value) {
|
||||
onStateChange(
|
||||
mapOf(
|
||||
"state" to "opening",
|
||||
),
|
||||
)
|
||||
onStateChange(mapOf("state" to "opening"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,33 +97,21 @@ class BottomSheetView(
|
||||
set(value) {
|
||||
field = value
|
||||
if (value) {
|
||||
onStateChange(
|
||||
mapOf(
|
||||
"state" to "closing",
|
||||
),
|
||||
)
|
||||
onStateChange(mapOf("state" to "closing"))
|
||||
}
|
||||
}
|
||||
|
||||
private var selectedSnapPoint = 0
|
||||
set(value) {
|
||||
if (field == value) return
|
||||
|
||||
field = value
|
||||
onSnapPointChange(
|
||||
mapOf(
|
||||
"snapPoint" to value,
|
||||
),
|
||||
)
|
||||
onSnapPointChange(mapOf("snapPoint" to value))
|
||||
}
|
||||
|
||||
// Lifecycle
|
||||
|
||||
init {
|
||||
(appContext.reactContext as? ReactContext)?.let {
|
||||
it.addLifecycleEventListener(this)
|
||||
this.eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(it, this.id)
|
||||
|
||||
this.dialogRootViewGroup = DialogRootViewGroup(context)
|
||||
this.dialogRootViewGroup.eventDispatcher = this.eventDispatcher
|
||||
}
|
||||
@@ -161,27 +141,55 @@ class BottomSheetView(
|
||||
private fun getHalfExpandedRatio(contentHeight: Float): Float =
|
||||
when {
|
||||
// Full height sheets
|
||||
contentHeight >= safeScreenHeight -> 0.99f
|
||||
// Medium height sheets (>50% but <100%)
|
||||
contentHeight >= safeScreenHeight / 2 ->
|
||||
this.clampRatio(this.getTargetHeight() / safeScreenHeight)
|
||||
// Small height sheets (<50%)
|
||||
else ->
|
||||
this.clampRatio(this.getTargetHeight() / rawScreenHeight)
|
||||
contentHeight >= screenHeight -> 0.99f
|
||||
else -> this.clampRatio(this.getTargetHeight() / screenHeight)
|
||||
}
|
||||
|
||||
private fun present() {
|
||||
if (this.isOpen || this.isOpening || this.isClosing) return
|
||||
|
||||
val contentHeight = this.getContentHeight()
|
||||
val dialog = BottomSheetDialog(context)
|
||||
|
||||
var activityWindow: Window? = null
|
||||
var currentContext = context
|
||||
while (currentContext != null) {
|
||||
if (currentContext is android.app.Activity) {
|
||||
activityWindow = currentContext.window
|
||||
break
|
||||
}
|
||||
currentContext = (currentContext as? android.content.ContextWrapper)?.baseContext
|
||||
}
|
||||
|
||||
val originalStatusBarAppearance =
|
||||
activityWindow?.let { window ->
|
||||
WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars
|
||||
}
|
||||
val originalNavBarAppearance =
|
||||
activityWindow?.let { window ->
|
||||
WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightNavigationBars
|
||||
}
|
||||
|
||||
val dialog = BottomSheetDialog(context, R.style.EdgeToEdgeBottomSheetDialogTheme)
|
||||
dialog.setContentView(dialogRootViewGroup)
|
||||
dialog.setCancelable(!preventDismiss)
|
||||
dialog.setDismissWithAnimation(true)
|
||||
dialog.setOnDismissListener {
|
||||
this.isClosing = true
|
||||
this.destroy()
|
||||
}
|
||||
|
||||
dialog.setOnShowListener {
|
||||
dialog.window?.let { window ->
|
||||
val insetsController = WindowInsetsControllerCompat(window, window.decorView)
|
||||
if (originalNavBarAppearance != null) {
|
||||
insetsController.isAppearanceLightNavigationBars = originalNavBarAppearance
|
||||
}
|
||||
if (originalStatusBarAppearance != null) {
|
||||
EdgeToEdgeUtils.setLightStatusBar(window, originalStatusBarAppearance)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val bottomSheet = dialog.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)
|
||||
bottomSheet?.let {
|
||||
it.setBackgroundColor(0)
|
||||
@@ -194,7 +202,17 @@ class BottomSheetView(
|
||||
behavior.isDraggable = true
|
||||
behavior.isHideable = true
|
||||
|
||||
if (contentHeight >= this.safeScreenHeight || this.minHeight >= this.safeScreenHeight) {
|
||||
if (preventExpansion) {
|
||||
behavior.maxHeight = (behavior.halfExpandedRatio * screenHeight).toInt()
|
||||
} else {
|
||||
behavior.maxHeight = (screenHeight - getStatusBarHeight()).toInt()
|
||||
}
|
||||
|
||||
val targetHeight = this.getTargetHeight()
|
||||
val availableHeight = screenHeight - getStatusBarHeight() - getNavigationBarHeight()
|
||||
val shouldBeExpanded = targetHeight >= availableHeight
|
||||
|
||||
if (shouldBeExpanded) {
|
||||
behavior.state = BottomSheetBehavior.STATE_EXPANDED
|
||||
this.selectedSnapPoint = 2
|
||||
} else {
|
||||
@@ -209,18 +227,10 @@ class BottomSheetView(
|
||||
newState: Int,
|
||||
) {
|
||||
when (newState) {
|
||||
BottomSheetBehavior.STATE_EXPANDED -> {
|
||||
selectedSnapPoint = 2
|
||||
}
|
||||
BottomSheetBehavior.STATE_COLLAPSED -> {
|
||||
selectedSnapPoint = 1
|
||||
}
|
||||
BottomSheetBehavior.STATE_HALF_EXPANDED -> {
|
||||
selectedSnapPoint = 1
|
||||
}
|
||||
BottomSheetBehavior.STATE_HIDDEN -> {
|
||||
selectedSnapPoint = 0
|
||||
}
|
||||
BottomSheetBehavior.STATE_EXPANDED -> selectedSnapPoint = 2
|
||||
BottomSheetBehavior.STATE_COLLAPSED -> selectedSnapPoint = 1
|
||||
BottomSheetBehavior.STATE_HALF_EXPANDED -> selectedSnapPoint = 1
|
||||
BottomSheetBehavior.STATE_HIDDEN -> selectedSnapPoint = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,9 +241,26 @@ class BottomSheetView(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
this.isOpening = true
|
||||
dialog.show()
|
||||
this.dialog = dialog
|
||||
|
||||
ViewCompat.setOnApplyWindowInsetsListener(dialogRootViewGroup) { view, insets ->
|
||||
val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
|
||||
val bottomSheet = dialog.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)
|
||||
val behavior = bottomSheet?.let { BottomSheetBehavior.from(it) }
|
||||
|
||||
val wasKeyboardVisible = isKeyboardVisible
|
||||
isKeyboardVisible = imeVisible
|
||||
|
||||
if (imeVisible && behavior?.state == BottomSheetBehavior.STATE_HALF_EXPANDED) {
|
||||
behavior.state = BottomSheetBehavior.STATE_EXPANDED
|
||||
} else if (!imeVisible && wasKeyboardVisible) {
|
||||
updateLayout()
|
||||
}
|
||||
insets
|
||||
}
|
||||
}
|
||||
|
||||
fun updateLayout() {
|
||||
@@ -246,12 +273,24 @@ class BottomSheetView(
|
||||
val currentState = behavior.state
|
||||
|
||||
val oldRatio = behavior.halfExpandedRatio
|
||||
var newRatio = getHalfExpandedRatio(contentHeight)
|
||||
val newRatio = getHalfExpandedRatio(contentHeight)
|
||||
behavior.halfExpandedRatio = newRatio
|
||||
|
||||
if (contentHeight > this.safeScreenHeight && behavior.state != BottomSheetBehavior.STATE_EXPANDED) {
|
||||
if (preventExpansion) {
|
||||
behavior.maxHeight = (behavior.halfExpandedRatio * screenHeight).toInt()
|
||||
}
|
||||
|
||||
val targetHeight = this.getTargetHeight()
|
||||
val availableHeight = screenHeight - getStatusBarHeight() - getNavigationBarHeight()
|
||||
val shouldBeExpanded = targetHeight >= availableHeight
|
||||
|
||||
if (isKeyboardVisible) {
|
||||
if (behavior.state != BottomSheetBehavior.STATE_EXPANDED) {
|
||||
behavior.state = BottomSheetBehavior.STATE_EXPANDED
|
||||
}
|
||||
} else if (shouldBeExpanded && behavior.state != BottomSheetBehavior.STATE_EXPANDED && !preventExpansion) {
|
||||
behavior.state = BottomSheetBehavior.STATE_EXPANDED
|
||||
} else if (contentHeight < this.safeScreenHeight && behavior.state != BottomSheetBehavior.STATE_HALF_EXPANDED) {
|
||||
} else if (!shouldBeExpanded && behavior.state != BottomSheetBehavior.STATE_HALF_EXPANDED) {
|
||||
behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
|
||||
} else if (currentState == BottomSheetBehavior.STATE_HALF_EXPANDED && oldRatio != newRatio) {
|
||||
behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
|
||||
@@ -279,25 +318,19 @@ class BottomSheetView(
|
||||
|
||||
private fun getTargetHeight(): Float {
|
||||
val contentHeight = this.getContentHeight()
|
||||
val height =
|
||||
if (contentHeight > maxHeight) {
|
||||
maxHeight
|
||||
} else if (contentHeight < minHeight) {
|
||||
minHeight
|
||||
} else {
|
||||
contentHeight
|
||||
}
|
||||
return height
|
||||
return when {
|
||||
contentHeight > maxHeight -> maxHeight
|
||||
contentHeight < minHeight -> minHeight
|
||||
else -> contentHeight
|
||||
}
|
||||
}
|
||||
|
||||
private fun clampRatio(ratio: Float): Float {
|
||||
if (ratio < 0.01) {
|
||||
return 0.01f
|
||||
} else if (ratio > 0.99) {
|
||||
return 0.99f
|
||||
private fun clampRatio(ratio: Float): Float =
|
||||
when {
|
||||
ratio < 0.01 -> 0.01f
|
||||
ratio > 0.99 -> 0.99f
|
||||
else -> ratio
|
||||
}
|
||||
return ratio
|
||||
}
|
||||
|
||||
private fun setDraggable(draggable: Boolean) {
|
||||
val dialog = this.dialog ?: return
|
||||
@@ -322,9 +355,7 @@ class BottomSheetView(
|
||||
// View overrides to pass to DialogRootViewGroup instead
|
||||
|
||||
override fun dispatchProvideStructure(structure: ViewStructure?) {
|
||||
if (structure == null) {
|
||||
return
|
||||
}
|
||||
if (structure == null) return
|
||||
dialogRootViewGroup.dispatchProvideStructure(structure)
|
||||
}
|
||||
|
||||
@@ -363,7 +394,6 @@ class BottomSheetView(
|
||||
// https://stackoverflow.com/questions/11862391/getheight-px-or-dpi
|
||||
fun dpToPx(dp: Float): Float {
|
||||
val displayMetrics = context.resources.displayMetrics
|
||||
val px = dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)
|
||||
return px
|
||||
return dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,8 @@ class DialogRootViewGroup(
|
||||
if (ReactFeatureFlags.dispatchPointerEvents) {
|
||||
jSPointerDispatcher = JSPointerDispatcher(this)
|
||||
}
|
||||
|
||||
fitsSystemWindows = false
|
||||
}
|
||||
|
||||
override fun onSizeChanged(
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="EdgeToEdgeBottomSheetDialogTheme" parent="Theme.Material3.DayNight.BottomSheetDialog">
|
||||
<!-- Enable edge-to-edge -->
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:windowIsFloating">false</item>
|
||||
<item name="enableEdgeToEdge">true</item>
|
||||
|
||||
<!-- Configure bottom sheet to respect system window insets -->
|
||||
<item name="bottomSheetStyle">@style/EdgeToEdgeBottomSheet</item>
|
||||
</style>
|
||||
|
||||
<style name="EdgeToEdgeBottomSheet" parent="Widget.Material3.BottomSheet">
|
||||
<item name="paddingBottomSystemWindowInsets">false</item>
|
||||
<item name="paddingLeftSystemWindowInsets">true</item>
|
||||
<item name="paddingRightSystemWindowInsets">true</item>
|
||||
<item name="paddingTopSystemWindowInsets">false</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -175,6 +175,7 @@ function BottomSheetNativeComponentInner({
|
||||
Platform.OS === 'android' && {
|
||||
borderTopLeftRadius: cornerRadius,
|
||||
borderTopRightRadius: cornerRadius,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
extraStyles,
|
||||
]}>
|
||||
|
||||
@@ -34,12 +34,15 @@ class NotificationPrefs(
|
||||
is Boolean -> {
|
||||
putBoolean(key, value)
|
||||
}
|
||||
|
||||
is String -> {
|
||||
putString(key, value)
|
||||
}
|
||||
|
||||
is Array<*> -> {
|
||||
putStringSet(key, value.map { it.toString() }.toSet())
|
||||
}
|
||||
|
||||
is Map<*, *> -> {
|
||||
putStringSet(key, value.map { it.toString() }.toSet())
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ class ExpoReceiveAndroidIntentsModule : Module() {
|
||||
|
||||
private fun handleImageIntents(
|
||||
uris: List<Uri>,
|
||||
text: String?
|
||||
text: String?,
|
||||
) {
|
||||
var allParams = ""
|
||||
|
||||
@@ -145,7 +145,7 @@ class ExpoReceiveAndroidIntentsModule : Module() {
|
||||
|
||||
private fun handleVideoIntents(
|
||||
uris: List<Uri>,
|
||||
text: String?
|
||||
text: String?,
|
||||
) {
|
||||
val uri = uris[0]
|
||||
// If there is no extension for the file, substringAfterLast returns the original string - not
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "bsky.app",
|
||||
"version": "1.114.0",
|
||||
"version": "1.117.0",
|
||||
"private": true,
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
@@ -48,8 +48,8 @@
|
||||
"e2e:mock-server": "NODE_ENV=development ./jest/dev-infra/with-test-redis-and-db.sh ts-node --project tsconfig.e2e.json __e2e__/mock-server.ts",
|
||||
"e2e:build": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:ios",
|
||||
"e2e:build-android": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:android",
|
||||
"e2e:start": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo start",
|
||||
"e2e:run": "maestro test __e2e__",
|
||||
"e2e:start": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo start -c",
|
||||
"e2e:run": "maestro test",
|
||||
"perf:test": "NODE_ENV=test maestro test",
|
||||
"perf:test:run": "NODE_ENV=test maestro test __e2e__/perf-test.yml",
|
||||
"perf:test:measure": "NODE_ENV=test flashlight test --bundleId xyz.blueskyweb.app --testCommand \"yarn perf:test\" --duration 150000 --resultsFilePath .perf/results.json",
|
||||
@@ -73,7 +73,7 @@
|
||||
"icons:optimize": "svgo -f ./assets/icons"
|
||||
},
|
||||
"dependencies": {
|
||||
"@atproto/api": "^0.18.15",
|
||||
"@atproto/api": "^0.18.20",
|
||||
"@bitdrift/react-native": "^0.6.8",
|
||||
"@braintree/sanitize-url": "^6.0.2",
|
||||
"@bsky.app/alf": "^0.1.6",
|
||||
@@ -93,6 +93,7 @@
|
||||
"@fortawesome/free-regular-svg-icons": "^6.1.1",
|
||||
"@fortawesome/free-solid-svg-icons": "^6.1.1",
|
||||
"@fortawesome/react-native-fontawesome": "^0.3.2",
|
||||
"@growthbook/growthbook-react": "^1.6.2",
|
||||
"@haileyok/bluesky-video": "0.3.2",
|
||||
"@ipld/dag-cbor": "^9.2.0",
|
||||
"@lingui/react": "^4.14.1",
|
||||
@@ -165,11 +166,13 @@
|
||||
"expo-task-manager": "~14.0.9",
|
||||
"expo-updates": "~29.0.14",
|
||||
"expo-video": "~3.0.15",
|
||||
"expo-video-thumbnails": "^10.0.8",
|
||||
"expo-web-browser": "~15.0.10",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-text-encoding": "^1.0.6",
|
||||
"history": "^5.3.0",
|
||||
"hls.js": "^1.6.2",
|
||||
"idb-keyval": "^6.2.2",
|
||||
"js-sha256": "^0.9.0",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"lande": "^1.0.10",
|
||||
@@ -199,7 +202,7 @@
|
||||
"react-native-edge-to-edge": "^1.6.0",
|
||||
"react-native-gesture-handler": "~2.28.0",
|
||||
"react-native-get-random-values": "~1.11.0",
|
||||
"react-native-keyboard-controller": "1.18.5",
|
||||
"react-native-keyboard-controller": "^1.20.7",
|
||||
"react-native-pager-view": "6.8.0",
|
||||
"react-native-progress": "bluesky-social/react-native-progress",
|
||||
"react-native-qrcode-styled": "^0.3.3",
|
||||
@@ -219,7 +222,6 @@
|
||||
"react-textarea-autosize": "^8.5.3",
|
||||
"sonner": "^2.0.7",
|
||||
"sonner-native": "^0.21.0",
|
||||
"statsig-react-native-expo": "^4.6.1",
|
||||
"tippy.js": "^6.3.7",
|
||||
"tlds": "^1.234.0",
|
||||
"tldts": "^6.1.46",
|
||||
@@ -227,7 +229,7 @@
|
||||
"zod": "^3.20.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@atproto/dev-env": "^0.3.204",
|
||||
"@atproto/dev-env": "^0.3.208",
|
||||
"@babel/core": "^7.26.0",
|
||||
"@babel/preset-env": "^7.26.0",
|
||||
"@babel/runtime": "^7.26.0",
|
||||
@@ -240,7 +242,6 @@
|
||||
"@react-native/eslint-config": "^0.81.5",
|
||||
"@react-native/typescript-config": "^0.81.5",
|
||||
"@sentry/webpack-plugin": "^3.2.2",
|
||||
"@testing-library/jest-native": "^5.4.3",
|
||||
"@testing-library/react-native": "^13.2.0",
|
||||
"@types/jest": "29.5.14",
|
||||
"@types/lodash.chunk": "^4.2.7",
|
||||
@@ -292,7 +293,8 @@
|
||||
"**/expo-constants": "18.0.8",
|
||||
"**/expo-device": "7.1.4",
|
||||
"**/multiformats": "9.9.0",
|
||||
"unicode-segmenter": "0.14.5"
|
||||
"unicode-segmenter": "0.14.5",
|
||||
"@types/estree": "1.0.6"
|
||||
},
|
||||
"jest": {
|
||||
"preset": "jest-expo/ios",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import '#/logger/sentry/setup'
|
||||
import '#/logger/bitdrift/setup'
|
||||
import '#/view/icons'
|
||||
|
||||
import React, {useEffect, useState} from 'react'
|
||||
import {GestureHandlerRootView} from 'react-native-gesture-handler'
|
||||
import {KeyboardProvider as KeyboardControllerProvider} from 'react-native-keyboard-controller'
|
||||
import {
|
||||
initialWindowMetrics,
|
||||
SafeAreaProvider,
|
||||
@@ -15,10 +15,8 @@ import {msg} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
import * as Sentry from '@sentry/react-native'
|
||||
|
||||
import {KeyboardControllerProvider} from '#/lib/hooks/useEnableKeyboardController'
|
||||
import {Provider as HideBottomBarBorderProvider} from '#/lib/hooks/useHideBottomBarBorder'
|
||||
import {QueryProvider} from '#/lib/react-query'
|
||||
import {Provider as StatsigProvider, tryFetchGates} from '#/lib/statsig/statsig'
|
||||
import {s} from '#/lib/styles'
|
||||
import {ThemeProvider} from '#/lib/ThemeContext'
|
||||
import I18nProvider from '#/locale/i18nProvider'
|
||||
@@ -66,8 +64,16 @@ import {Provider as PolicyUpdateOverlayProvider} from '#/components/PolicyUpdate
|
||||
import {Provider as PortalProvider} from '#/components/Portal'
|
||||
import {Provider as VideoVolumeProvider} from '#/components/Post/Embed/VideoEmbed/VideoVolumeContext'
|
||||
import {ToastOutlet} from '#/components/Toast'
|
||||
import {Provider as AgeAssuranceV2Provider} from '#/ageAssurance'
|
||||
import {prefetchAgeAssuranceConfig} from '#/ageAssurance'
|
||||
import {
|
||||
prefetchAgeAssuranceConfig,
|
||||
Provider as AgeAssuranceV2Provider,
|
||||
} from '#/ageAssurance'
|
||||
import {
|
||||
AnalyticsContext,
|
||||
AnalyticsFeaturesContext,
|
||||
features,
|
||||
setupDeviceId,
|
||||
} from '#/analytics'
|
||||
import {IS_ANDROID, IS_IOS} from '#/env'
|
||||
import {
|
||||
prefetchLiveEvents,
|
||||
@@ -113,7 +119,7 @@ function InnerApp() {
|
||||
if (account) {
|
||||
await resumeSession(account)
|
||||
} else {
|
||||
await tryFetchGates(undefined, 'prefer-fresh-gates')
|
||||
await features.init
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(`session: resume failed`, {message: e})
|
||||
@@ -143,9 +149,9 @@ function InnerApp() {
|
||||
<React.Fragment
|
||||
// Resets the entire tree below when it changes:
|
||||
key={currentAccount?.did}>
|
||||
<QueryProvider currentDid={currentAccount?.did}>
|
||||
<PolicyUpdateOverlayProvider>
|
||||
<StatsigProvider>
|
||||
<AnalyticsFeaturesContext>
|
||||
<QueryProvider currentDid={currentAccount?.did}>
|
||||
<PolicyUpdateOverlayProvider>
|
||||
<LiveEventsProvider>
|
||||
<AgeAssuranceV2Provider>
|
||||
<ComposerProvider>
|
||||
@@ -191,9 +197,9 @@ function InnerApp() {
|
||||
</ComposerProvider>
|
||||
</AgeAssuranceV2Provider>
|
||||
</LiveEventsProvider>
|
||||
</StatsigProvider>
|
||||
</PolicyUpdateOverlayProvider>
|
||||
</QueryProvider>
|
||||
</PolicyUpdateOverlayProvider>
|
||||
</QueryProvider>
|
||||
</AnalyticsFeaturesContext>
|
||||
</React.Fragment>
|
||||
</VideoVolumeProvider>
|
||||
</Splash>
|
||||
@@ -207,7 +213,7 @@ function App() {
|
||||
const [isReady, setReady] = useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
Promise.all([initPersistedState(), Geo.resolve()]).then(() =>
|
||||
Promise.all([initPersistedState(), Geo.resolve(), setupDeviceId]).then(() =>
|
||||
setReady(true),
|
||||
)
|
||||
}, [])
|
||||
@@ -225,30 +231,32 @@ function App() {
|
||||
<A11yProvider>
|
||||
<KeyboardControllerProvider>
|
||||
<OnboardingProvider>
|
||||
<SessionProvider>
|
||||
<PrefsStateProvider>
|
||||
<I18nProvider>
|
||||
<ShellStateProvider>
|
||||
<ModalStateProvider>
|
||||
<DialogStateProvider>
|
||||
<LightboxStateProvider>
|
||||
<PortalProvider>
|
||||
<BottomSheetProvider>
|
||||
<StarterPackProvider>
|
||||
<SafeAreaProvider
|
||||
initialMetrics={initialWindowMetrics}>
|
||||
<InnerApp />
|
||||
</SafeAreaProvider>
|
||||
</StarterPackProvider>
|
||||
</BottomSheetProvider>
|
||||
</PortalProvider>
|
||||
</LightboxStateProvider>
|
||||
</DialogStateProvider>
|
||||
</ModalStateProvider>
|
||||
</ShellStateProvider>
|
||||
</I18nProvider>
|
||||
</PrefsStateProvider>
|
||||
</SessionProvider>
|
||||
<AnalyticsContext>
|
||||
<SessionProvider>
|
||||
<PrefsStateProvider>
|
||||
<I18nProvider>
|
||||
<ShellStateProvider>
|
||||
<ModalStateProvider>
|
||||
<DialogStateProvider>
|
||||
<LightboxStateProvider>
|
||||
<PortalProvider>
|
||||
<BottomSheetProvider>
|
||||
<StarterPackProvider>
|
||||
<SafeAreaProvider
|
||||
initialMetrics={initialWindowMetrics}>
|
||||
<InnerApp />
|
||||
</SafeAreaProvider>
|
||||
</StarterPackProvider>
|
||||
</BottomSheetProvider>
|
||||
</PortalProvider>
|
||||
</LightboxStateProvider>
|
||||
</DialogStateProvider>
|
||||
</ModalStateProvider>
|
||||
</ShellStateProvider>
|
||||
</I18nProvider>
|
||||
</PrefsStateProvider>
|
||||
</SessionProvider>
|
||||
</AnalyticsContext>
|
||||
</OnboardingProvider>
|
||||
</KeyboardControllerProvider>
|
||||
</A11yProvider>
|
||||
|
||||
@@ -9,7 +9,6 @@ import {useLingui} from '@lingui/react'
|
||||
import * as Sentry from '@sentry/react-native'
|
||||
|
||||
import {QueryProvider} from '#/lib/react-query'
|
||||
import {Provider as StatsigProvider} from '#/lib/statsig/statsig'
|
||||
import {ThemeProvider} from '#/lib/ThemeContext'
|
||||
import I18nProvider from '#/locale/i18nProvider'
|
||||
import {logger} from '#/logger'
|
||||
@@ -55,8 +54,16 @@ import {Provider as PortalProvider} from '#/components/Portal'
|
||||
import {Provider as ActiveVideoProvider} from '#/components/Post/Embed/VideoEmbed/ActiveVideoWebContext'
|
||||
import {Provider as VideoVolumeProvider} from '#/components/Post/Embed/VideoEmbed/VideoVolumeContext'
|
||||
import {ToastOutlet} from '#/components/Toast'
|
||||
import {Provider as AgeAssuranceV2Provider} from '#/ageAssurance'
|
||||
import {prefetchAgeAssuranceConfig} from '#/ageAssurance'
|
||||
import {
|
||||
prefetchAgeAssuranceConfig,
|
||||
Provider as AgeAssuranceV2Provider,
|
||||
} from '#/ageAssurance'
|
||||
import {
|
||||
AnalyticsContext,
|
||||
AnalyticsFeaturesContext,
|
||||
features,
|
||||
setupDeviceId,
|
||||
} from '#/analytics'
|
||||
import {
|
||||
prefetchLiveEvents,
|
||||
Provider as LiveEventsProvider,
|
||||
@@ -87,6 +94,8 @@ function InnerApp() {
|
||||
try {
|
||||
if (account) {
|
||||
await resumeSession(account)
|
||||
} else {
|
||||
await features.init
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(`session: resumeSession failed`, {message: e})
|
||||
@@ -119,9 +128,9 @@ function InnerApp() {
|
||||
<React.Fragment
|
||||
// Resets the entire tree below when it changes:
|
||||
key={currentAccount?.did}>
|
||||
<QueryProvider currentDid={currentAccount?.did}>
|
||||
<PolicyUpdateOverlayProvider>
|
||||
<StatsigProvider>
|
||||
<AnalyticsFeaturesContext>
|
||||
<QueryProvider currentDid={currentAccount?.did}>
|
||||
<PolicyUpdateOverlayProvider>
|
||||
<LiveEventsProvider>
|
||||
<AgeAssuranceV2Provider>
|
||||
<ComposerProvider>
|
||||
@@ -163,9 +172,9 @@ function InnerApp() {
|
||||
</ComposerProvider>
|
||||
</AgeAssuranceV2Provider>
|
||||
</LiveEventsProvider>
|
||||
</StatsigProvider>
|
||||
</PolicyUpdateOverlayProvider>
|
||||
</QueryProvider>
|
||||
</PolicyUpdateOverlayProvider>
|
||||
</QueryProvider>
|
||||
</AnalyticsFeaturesContext>
|
||||
</React.Fragment>
|
||||
</ActiveVideoProvider>
|
||||
</VideoVolumeProvider>
|
||||
@@ -179,7 +188,7 @@ function App() {
|
||||
const [isReady, setReady] = useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
Promise.all([initPersistedState(), Geo.resolve()]).then(() =>
|
||||
Promise.all([initPersistedState(), Geo.resolve(), setupDeviceId]).then(() =>
|
||||
setReady(true),
|
||||
)
|
||||
}, [])
|
||||
@@ -196,25 +205,27 @@ function App() {
|
||||
<Geo.Provider>
|
||||
<A11yProvider>
|
||||
<OnboardingProvider>
|
||||
<SessionProvider>
|
||||
<PrefsStateProvider>
|
||||
<I18nProvider>
|
||||
<ShellStateProvider>
|
||||
<ModalStateProvider>
|
||||
<DialogStateProvider>
|
||||
<LightboxStateProvider>
|
||||
<PortalProvider>
|
||||
<StarterPackProvider>
|
||||
<InnerApp />
|
||||
</StarterPackProvider>
|
||||
</PortalProvider>
|
||||
</LightboxStateProvider>
|
||||
</DialogStateProvider>
|
||||
</ModalStateProvider>
|
||||
</ShellStateProvider>
|
||||
</I18nProvider>
|
||||
</PrefsStateProvider>
|
||||
</SessionProvider>
|
||||
<AnalyticsContext>
|
||||
<SessionProvider>
|
||||
<PrefsStateProvider>
|
||||
<I18nProvider>
|
||||
<ShellStateProvider>
|
||||
<ModalStateProvider>
|
||||
<DialogStateProvider>
|
||||
<LightboxStateProvider>
|
||||
<PortalProvider>
|
||||
<StarterPackProvider>
|
||||
<InnerApp />
|
||||
</StarterPackProvider>
|
||||
</PortalProvider>
|
||||
</LightboxStateProvider>
|
||||
</DialogStateProvider>
|
||||
</ModalStateProvider>
|
||||
</ShellStateProvider>
|
||||
</I18nProvider>
|
||||
</PrefsStateProvider>
|
||||
</SessionProvider>
|
||||
</AnalyticsContext>
|
||||
</OnboardingProvider>
|
||||
</A11yProvider>
|
||||
</Geo.Provider>
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
storePayloadForAccountSwitch,
|
||||
} from '#/lib/hooks/useNotificationHandler'
|
||||
import {useWebScrollRestoration} from '#/lib/hooks/useWebScrollRestoration'
|
||||
import {logger as notyLogger} from '#/lib/notifications/util'
|
||||
import {useCallOnce} from '#/lib/once'
|
||||
import {buildStateObject} from '#/lib/routes/helpers'
|
||||
import {
|
||||
type AllNavigatorParams,
|
||||
@@ -38,12 +38,11 @@ import {
|
||||
type MessagesTabNavigatorParams,
|
||||
type MyProfileTabNavigatorParams,
|
||||
type NotificationsTabNavigatorParams,
|
||||
type RouteParams,
|
||||
type SearchTabNavigatorParams,
|
||||
type State,
|
||||
} from '#/lib/routes/types'
|
||||
import {type RouteParams, type State} from '#/lib/routes/types'
|
||||
import {attachRouteToLogEvents, logEvent} from '#/lib/statsig/statsig'
|
||||
import {bskyTitle} from '#/lib/strings/headings'
|
||||
import {logger} from '#/logger'
|
||||
import {useUnreadNotifications} from '#/state/queries/notifications/unread'
|
||||
import {useSession} from '#/state/session'
|
||||
import {useLoggedOutViewControls} from '#/state/shell/logged-out'
|
||||
@@ -137,6 +136,8 @@ import {
|
||||
EmailDialogScreenID,
|
||||
useEmailDialogControl,
|
||||
} from '#/components/dialogs/EmailDialog'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {setNavigationMetadata} from '#/analytics/metadata'
|
||||
import {IS_NATIVE, IS_WEB} from '#/env'
|
||||
import {router} from '#/routes'
|
||||
import {Referrer} from '../modules/expo-bluesky-swiss-army'
|
||||
@@ -879,11 +880,13 @@ const LINKING = {
|
||||
let lastHandledNotificationDateDedupe: number | undefined
|
||||
|
||||
function RoutesContainer({children}: React.PropsWithChildren<{}>) {
|
||||
const ax = useAnalytics()
|
||||
const notyLogger = ax.logger.useChild(ax.logger.Context.Notifications)
|
||||
const theme = useColorSchemeStyle(DefaultTheme, DarkTheme)
|
||||
const {currentAccount, accounts} = useSession()
|
||||
const {onPressSwitchAccount} = useAccountSwitcher()
|
||||
const {setShowLoggedOut} = useLoggedOutViewControls()
|
||||
const prevLoggedRouteName = useRef<string | undefined>(undefined)
|
||||
const previousScreen = useRef<string | undefined>(undefined)
|
||||
const emailDialogControl = useEmailDialogControl()
|
||||
const closeAllActiveElements = useCloseAllActiveElements()
|
||||
|
||||
@@ -945,11 +948,10 @@ function RoutesContainer({children}: React.PropsWithChildren<{}>) {
|
||||
const payload = getNotificationPayload(response.notification)
|
||||
|
||||
if (payload) {
|
||||
notyLogger.metric(
|
||||
'notifications:openApp',
|
||||
{reason: payload.reason, causedBoot: true},
|
||||
{statsig: false},
|
||||
)
|
||||
ax.metric('notifications:openApp', {
|
||||
reason: payload.reason,
|
||||
causedBoot: true,
|
||||
})
|
||||
|
||||
if (payload.reason === 'chat-message') {
|
||||
handleChatMessage(payload)
|
||||
@@ -973,47 +975,69 @@ function RoutesContainer({children}: React.PropsWithChildren<{}>) {
|
||||
}
|
||||
}
|
||||
|
||||
function onReady() {
|
||||
prevLoggedRouteName.current = getCurrentRouteName()
|
||||
const onNavigationReady = useCallOnce(() => {
|
||||
const currentScreen = getCurrentRouteName()
|
||||
setNavigationMetadata({
|
||||
previousScreen: currentScreen,
|
||||
currentScreen,
|
||||
})
|
||||
previousScreen.current = currentScreen
|
||||
|
||||
handlePushNotificationEntry()
|
||||
|
||||
ax.metric('router:navigate', {})
|
||||
|
||||
if (currentAccount && shouldRequestEmailConfirmation(currentAccount)) {
|
||||
emailDialogControl.open({
|
||||
id: EmailDialogScreenID.VerificationReminder,
|
||||
})
|
||||
snoozeEmailConfirmationPrompt()
|
||||
}
|
||||
}
|
||||
|
||||
ax.metric('init', {
|
||||
initMs: Math.round(
|
||||
// @ts-ignore Emitted by Metro in the bundle prelude
|
||||
performance.now() - global.__BUNDLE_START_TIME__,
|
||||
),
|
||||
})
|
||||
|
||||
if (IS_WEB) {
|
||||
const referrerInfo = Referrer.getReferrerInfo()
|
||||
if (referrerInfo && referrerInfo.hostname !== 'bsky.app') {
|
||||
ax.metric('deepLink:referrerReceived', {
|
||||
to: window.location.href,
|
||||
referrer: referrerInfo?.referrer,
|
||||
hostname: referrerInfo?.hostname,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<NavigationContainer
|
||||
ref={navigationRef}
|
||||
linking={LINKING}
|
||||
theme={theme}
|
||||
onStateChange={() => {
|
||||
logger.metric(
|
||||
'router:navigate',
|
||||
{from: prevLoggedRouteName.current},
|
||||
{statsig: false},
|
||||
)
|
||||
prevLoggedRouteName.current = getCurrentRouteName()
|
||||
}}
|
||||
onReady={() => {
|
||||
attachRouteToLogEvents(getCurrentRouteName)
|
||||
logModuleInitTime()
|
||||
onReady()
|
||||
logger.metric('router:navigate', {}, {statsig: false})
|
||||
handlePushNotificationEntry()
|
||||
}}
|
||||
// WARNING: Implicit navigation to nested navigators is depreciated in React Navigation 7.x
|
||||
// However, there's a fair amount of places we do that, especially in when popping to the top of stacks.
|
||||
// See BottomBar.tsx for an example of how to handle nested navigators in the tabs correctly.
|
||||
// I'm scared of missing a spot (esp. with push notifications etc) so let's enable this legacy behaviour for now.
|
||||
// We will need to confirm we handle nested navigators correctly by the time we migrate to React Navigation 8.x
|
||||
// -sfn
|
||||
navigationInChildEnabled>
|
||||
{children}
|
||||
</NavigationContainer>
|
||||
</>
|
||||
<NavigationContainer
|
||||
ref={navigationRef}
|
||||
linking={LINKING}
|
||||
theme={theme}
|
||||
onStateChange={() => {
|
||||
const currentScreen = getCurrentRouteName()
|
||||
// do this before metric
|
||||
setNavigationMetadata({
|
||||
previousScreen: previousScreen.current,
|
||||
currentScreen,
|
||||
})
|
||||
ax.metric('router:navigate', {from: previousScreen.current})
|
||||
previousScreen.current = currentScreen
|
||||
}}
|
||||
onReady={onNavigationReady}
|
||||
// WARNING: Implicit navigation to nested navigators is depreciated in React Navigation 7.x
|
||||
// However, there's a fair amount of places we do that, especially in when popping to the top of stacks.
|
||||
// See BottomBar.tsx for an example of how to handle nested navigators in the tabs correctly.
|
||||
// I'm scared of missing a spot (esp. with push notifications etc) so let's enable this legacy behaviour for now.
|
||||
// We will need to confirm we handle nested navigators correctly by the time we migrate to React Navigation 8.x
|
||||
// -sfn
|
||||
navigationInChildEnabled>
|
||||
{children}
|
||||
</NavigationContainer>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1087,44 +1111,6 @@ function reset(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
let didInit = false
|
||||
function logModuleInitTime() {
|
||||
if (didInit) {
|
||||
return
|
||||
}
|
||||
didInit = true
|
||||
|
||||
const initMs = Math.round(
|
||||
// @ts-ignore Emitted by Metro in the bundle prelude
|
||||
performance.now() - global.__BUNDLE_START_TIME__,
|
||||
)
|
||||
console.log(`Time to first paint: ${initMs} ms`)
|
||||
logEvent('init', {
|
||||
initMs,
|
||||
})
|
||||
|
||||
if (IS_WEB) {
|
||||
const referrerInfo = Referrer.getReferrerInfo()
|
||||
if (referrerInfo && referrerInfo.hostname !== 'bsky.app') {
|
||||
logEvent('deepLink:referrerReceived', {
|
||||
to: window.location.href,
|
||||
referrer: referrerInfo?.referrer,
|
||||
hostname: referrerInfo?.hostname,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
// This log is noisy, so keep false committed
|
||||
const shouldLog = false
|
||||
// Relies on our patch to polyfill.js in metro-runtime
|
||||
const initLogs = (global as any).__INIT_LOGS__
|
||||
if (shouldLog && Array.isArray(initLogs)) {
|
||||
console.log(initLogs.join('\n'))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
FlatNavigator,
|
||||
navigate,
|
||||
|
||||
@@ -21,9 +21,9 @@ import * as SplashScreen from 'expo-splash-screen'
|
||||
|
||||
import {Logotype} from '#/view/icons/Logotype'
|
||||
// @ts-ignore
|
||||
import splashImagePointer from '../assets/splash.png'
|
||||
import splashImagePointer from '../assets/splash/splash.png'
|
||||
// @ts-ignore
|
||||
import darkSplashImagePointer from '../assets/splash-dark.png'
|
||||
import darkSplashImagePointer from '../assets/splash/splash-dark.png'
|
||||
const splashImageUri = RNImage.resolveAssetSource(splashImagePointer).uri
|
||||
const darkSplashImageUri = RNImage.resolveAssetSource(
|
||||
darkSplashImagePointer,
|
||||
@@ -146,7 +146,8 @@ export function Splash(props: React.PropsWithChildren<Props>) {
|
||||
withTiming(
|
||||
1,
|
||||
{duration: 400, easing: Easing.out(Easing.cubic)},
|
||||
async () => {
|
||||
() => {
|
||||
'worklet'
|
||||
// set these values to check animation at specific point
|
||||
outroLogo.set(() =>
|
||||
withTiming(
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
useCreateSupportLink,
|
||||
} from '#/lib/hooks/useCreateSupportLink'
|
||||
import {dateDiff, useGetTimeAgo} from '#/lib/hooks/useTimeAgo'
|
||||
import {logger} from '#/logger'
|
||||
import {useIsBirthdateUpdateAllowed} from '#/state/birthdate'
|
||||
import {useSessionApi} from '#/state/session'
|
||||
import {atoms as a, useBreakpoints, useTheme, web} from '#/alf'
|
||||
@@ -36,8 +35,8 @@ import {
|
||||
isLegacyBirthdateBug,
|
||||
useAgeAssuranceRegionConfig,
|
||||
} from '#/ageAssurance/util'
|
||||
import {IS_WEB} from '#/env'
|
||||
import {IS_NATIVE} from '#/env'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_NATIVE, IS_WEB} from '#/env'
|
||||
import {useDeviceGeolocationApi} from '#/geolocation'
|
||||
|
||||
const textStyles = [a.text_md, a.leading_snug]
|
||||
@@ -45,6 +44,7 @@ const textStyles = [a.text_md, a.leading_snug]
|
||||
export function NoAccessScreen() {
|
||||
const t = useTheme()
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const {gtPhone} = useBreakpoints()
|
||||
const insets = useSafeAreaInsets()
|
||||
const birthdateControl = useDialogControl()
|
||||
@@ -63,8 +63,8 @@ export function NoAccessScreen() {
|
||||
|
||||
useEffect(() => {
|
||||
// just counting overall hits here
|
||||
logger.metric(`blockedGeoOverlay:shown`, {})
|
||||
logger.metric(`ageAssurance:noAccessScreen:shown`, {
|
||||
ax.metric(`blockedGeoOverlay:shown`, {})
|
||||
ax.metric(`ageAssurance:noAccessScreen:shown`, {
|
||||
accountCreatedAt: data?.accountCreatedAt || 'unknown',
|
||||
isAARegion,
|
||||
hasDeclaredAge,
|
||||
@@ -103,10 +103,7 @@ export function NoAccessScreen() {
|
||||
label={_(msg`Click here to update your birthdate`)}
|
||||
style={[textStyles]}
|
||||
{...createStaticClick(() => {
|
||||
logger.metric(
|
||||
'ageAssurance:noAccessScreen:openBirthdateDialog',
|
||||
{},
|
||||
)
|
||||
ax.metric('ageAssurance:noAccessScreen:openBirthdateDialog', {})
|
||||
birthdateControl.open()
|
||||
})}>
|
||||
clicking here
|
||||
@@ -272,6 +269,7 @@ export function NoAccessScreen() {
|
||||
function AccessSection() {
|
||||
const t = useTheme()
|
||||
const {_, i18n} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const control = useDialogControl()
|
||||
const appealControl = Dialog.useDialogControl()
|
||||
const locationControl = Dialog.useDialogControl()
|
||||
@@ -305,7 +303,7 @@ function AccessSection() {
|
||||
label={_(msg`Contact our moderation team`)}
|
||||
{...createStaticClick(() => {
|
||||
appealControl.open()
|
||||
logger.metric('ageAssurance:appealDialogOpen', {})
|
||||
ax.metric('ageAssurance:appealDialogOpen', {})
|
||||
})}>
|
||||
contact our moderation team
|
||||
</SimpleInlineLinkText>{' '}
|
||||
@@ -321,7 +319,7 @@ function AccessSection() {
|
||||
color={hasInitiated ? 'secondary' : 'primary'}
|
||||
onPress={() => {
|
||||
control.open()
|
||||
logger.metric('ageAssurance:initDialogOpen', {
|
||||
ax.metric('ageAssurance:initDialogOpen', {
|
||||
hasInitiatedPreviously: hasInitiated,
|
||||
})
|
||||
}}>
|
||||
|
||||
@@ -25,9 +25,8 @@ import {CircleInfo_Stroke2_Corner0_Rounded as ErrorIcon} from '#/components/icon
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {refetchAgeAssuranceServerState} from '#/ageAssurance'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {IS_WEB} from '#/env'
|
||||
import {IS_IOS} from '#/env'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_IOS, IS_WEB} from '#/env'
|
||||
|
||||
export type RedirectOverlayState = {
|
||||
result: 'success' | 'unknown'
|
||||
@@ -174,6 +173,7 @@ export function RedirectOverlay() {
|
||||
|
||||
function Inner() {
|
||||
const t = useTheme()
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const agent = useAgent()
|
||||
const polling = useRef(false)
|
||||
@@ -187,7 +187,7 @@ function Inner() {
|
||||
|
||||
polling.current = true
|
||||
|
||||
logger.metric('ageAssurance:redirectDialogOpen', {})
|
||||
ax.metric('ageAssurance:redirectDialogOpen', {})
|
||||
|
||||
wait(
|
||||
3e3,
|
||||
@@ -218,18 +218,18 @@ function Inner() {
|
||||
|
||||
setSuccess(true)
|
||||
|
||||
logger.metric('ageAssurance:redirectDialogSuccess', {})
|
||||
ax.metric('ageAssurance:redirectDialogSuccess', {})
|
||||
})
|
||||
.catch(() => {
|
||||
if (unmounted.current) return
|
||||
setError(true)
|
||||
logger.metric('ageAssurance:redirectDialogFail', {})
|
||||
ax.metric('ageAssurance:redirectDialogFail', {})
|
||||
})
|
||||
|
||||
return () => {
|
||||
unmounted.current = true
|
||||
}
|
||||
}, [agent])
|
||||
}, [ax, agent])
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
AtpAgent,
|
||||
getAgeAssuranceRegionConfig,
|
||||
} from '@atproto/api'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
import {createAsyncStoragePersister} from '@tanstack/query-async-storage-persister'
|
||||
import {focusManager, QueryClient, useQuery} from '@tanstack/react-query'
|
||||
import {persistQueryClient} from '@tanstack/react-query-persist-client'
|
||||
@@ -14,6 +13,7 @@ import debounce from 'lodash.debounce'
|
||||
|
||||
import {networkRetry} from '#/lib/async/retry'
|
||||
import {PUBLIC_BSKY_SERVICE} from '#/lib/constants'
|
||||
import {createPersistedQueryStorage} from '#/lib/persisted-query-storage'
|
||||
import {getAge} from '#/lib/strings/time'
|
||||
import {
|
||||
hasSnoozedBirthdateUpdateForDid,
|
||||
@@ -45,7 +45,7 @@ const qc = new QueryClient({
|
||||
},
|
||||
})
|
||||
const persister = createAsyncStoragePersister({
|
||||
storage: AsyncStorage,
|
||||
storage: createPersistedQueryStorage('age-assurance'),
|
||||
key: 'age-assurance-query-client',
|
||||
})
|
||||
const [, cacheHydrationPromise] = persistQueryClient({
|
||||
|
||||
@@ -12,6 +12,7 @@ import {isNetworkError} from '#/lib/hooks/useCleanError'
|
||||
import {useAgent} from '#/state/session'
|
||||
import {usePatchAgeAssuranceServerState} from '#/ageAssurance'
|
||||
import {logger} from '#/ageAssurance/logger'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {BLUESKY_PROXY_DID} from '#/env'
|
||||
import {useGeolocation} from '#/geolocation'
|
||||
|
||||
@@ -19,6 +20,7 @@ const IS_DEV_ENV = BLUESKY_PROXY_DID !== PUBLIC_APPVIEW_DID
|
||||
const APPVIEW = IS_DEV_ENV ? DEV_ENV_APPVIEW : PUBLIC_APPVIEW
|
||||
|
||||
export function useBeginAgeAssurance() {
|
||||
const ax = useAnalytics()
|
||||
const agent = useAgent()
|
||||
const geolocation = useGeolocation()
|
||||
const patchAgeAssuranceStateResponse = usePatchAgeAssuranceServerState()
|
||||
@@ -48,15 +50,11 @@ export function useBeginAgeAssurance() {
|
||||
appView.sessionManager.session.accessJwt = token
|
||||
appView.sessionManager.session.refreshJwt = ''
|
||||
|
||||
logger.metric(
|
||||
'ageAssurance:api:begin',
|
||||
{
|
||||
platform: Platform.OS,
|
||||
countryCode,
|
||||
regionCode,
|
||||
},
|
||||
{statsig: false},
|
||||
)
|
||||
ax.metric('ageAssurance:api:begin', {
|
||||
platform: Platform.OS,
|
||||
countryCode,
|
||||
regionCode,
|
||||
})
|
||||
|
||||
/*
|
||||
* 2s wait is good actually. Email sending takes a hot sec and this helps
|
||||
|
||||
@@ -5,6 +5,8 @@ import {CARD_ASPECT_RATIO} from '#/lib/constants'
|
||||
import {native, platform, web} from '#/alf/util/platform'
|
||||
import * as Layout from '#/components/Layout'
|
||||
|
||||
const EXP_CURVE = 'cubic-bezier(0.16, 1, 0.3, 1)'
|
||||
|
||||
export const atoms = {
|
||||
...baseAtoms,
|
||||
|
||||
@@ -103,7 +105,7 @@ export const atoms = {
|
||||
}),
|
||||
// special composite animation for dialogs
|
||||
zoom_fade_in: web({
|
||||
animation: 'zoomIn ease-out 0.1s, fadeIn ease-out 0.1s',
|
||||
animation: `zoomIn ${EXP_CURVE} 0.3s, fadeIn ${EXP_CURVE} 0.3s`,
|
||||
}),
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import {useEffect, useRef} from 'react'
|
||||
|
||||
import {getCurrentState, onAppStateChange} from '#/lib/appState'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
/**
|
||||
* Tracks passive analytics like app foreground/background time.
|
||||
*/
|
||||
export function PassiveAnalytics() {
|
||||
const ax = useAnalytics()
|
||||
const lastActive = useRef(
|
||||
getCurrentState() === 'active' ? performance.now() : null,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const sub = onAppStateChange(state => {
|
||||
if (state === 'active') {
|
||||
lastActive.current = performance.now()
|
||||
ax.metric('state:foreground', {})
|
||||
} else if (lastActive.current !== null) {
|
||||
ax.metric('state:background', {
|
||||
secondsActive: Math.round(
|
||||
(performance.now() - lastActive.current) / 1e3,
|
||||
),
|
||||
})
|
||||
}
|
||||
})
|
||||
return () => sub.remove()
|
||||
}, [ax])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import {MMKV} from '@bsky.app/react-native-mmkv'
|
||||
import {setPolyfills} from '@growthbook/growthbook'
|
||||
import {GrowthBook} from '@growthbook/growthbook-react'
|
||||
|
||||
import {getNavigationMetadata, type Metadata} from '#/analytics/metadata'
|
||||
import * as env from '#/env'
|
||||
|
||||
export {Features} from '#/analytics/features/types'
|
||||
|
||||
const CACHE = new MMKV({id: 'bsky_features_cache'})
|
||||
|
||||
setPolyfills({
|
||||
localStorage: {
|
||||
getItem: key => {
|
||||
const value = CACHE.getString(key)
|
||||
return value != null ? JSON.parse(value) : null
|
||||
},
|
||||
setItem: async (key, value) => {
|
||||
CACHE.set(key, value)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
/**
|
||||
* We vary the amount of time we wait for GrowthBook to fetch feature
|
||||
* gates based on the strategy specified.
|
||||
*/
|
||||
export type FeatureFetchStrategy = 'prefer-low-latency' | 'prefer-fresh-gates'
|
||||
|
||||
const TIMEOUT_INIT = 500 // TODO should base on p99 or something
|
||||
const TIMEOUT_PREFER_LOW_LATENCY = 250
|
||||
const TIMEOUT_PREFER_FRESH_GATES = 1500
|
||||
|
||||
export const features = new GrowthBook({
|
||||
apiHost: env.GROWTHBOOK_API_HOST,
|
||||
clientKey: env.GROWTHBOOK_CLIENT_KEY,
|
||||
})
|
||||
|
||||
/**
|
||||
* Initializer promise that must be awaited before using the GrowthBook
|
||||
* instance or rendering the `AnalyticsFeaturesContext`. Note: this may not be
|
||||
* fully initialized if it takes longer than `TIMEOUT_INIT` to initialize. In
|
||||
* that case, we may see a flash of uncustomized content until the
|
||||
* initialization completes.
|
||||
*/
|
||||
export const init = new Promise<void>(async y => {
|
||||
await features.init({timeout: TIMEOUT_INIT})
|
||||
y()
|
||||
})
|
||||
|
||||
/**
|
||||
* Refresh feature gates from GrowthBook. Updates attributes based on the
|
||||
* provided account, if any.
|
||||
*/
|
||||
export async function refresh({strategy}: {strategy: FeatureFetchStrategy}) {
|
||||
await features.refreshFeatures({
|
||||
timeout:
|
||||
strategy === 'prefer-low-latency'
|
||||
? TIMEOUT_PREFER_LOW_LATENCY
|
||||
: TIMEOUT_PREFER_FRESH_GATES,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts our metadata into GrowthBook attributes and sets them. GrowthBook
|
||||
* attributes are manually configured in the GrowthBook dashboard. So these
|
||||
* values need to match exactly. Therefore, let's add them here manually to and
|
||||
* not spread them to avoid mistakes.
|
||||
*/
|
||||
export function setAttributes({
|
||||
base,
|
||||
geolocation,
|
||||
session,
|
||||
preferences,
|
||||
}: Metadata) {
|
||||
features.setAttributes({
|
||||
deviceId: base.deviceId,
|
||||
sessionId: base.sessionId,
|
||||
platform: base.platform,
|
||||
appVersion: base.appVersion,
|
||||
countryCode: geolocation.countryCode,
|
||||
regionCode: geolocation.regionCode,
|
||||
did: session?.did,
|
||||
isBskyPds: session?.isBskyPds,
|
||||
appLanguage: preferences?.appLanguage,
|
||||
contentLanguages: preferences?.contentLanguages,
|
||||
currentScreen: getNavigationMetadata()?.currentScreen,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export enum Features {
|
||||
// core flags
|
||||
IsBskyTeam = 'is_bsky_team',
|
||||
|
||||
// debug flags
|
||||
DebugFeedContext = 'debug_feed_context',
|
||||
|
||||
// feature flags
|
||||
ImportContactsOnboardingDisable = 'import_contacts:onboarding:disable',
|
||||
ImportContactsSettingsDisable = 'import_contacts:settings:disable',
|
||||
LiveNowBetaDisable = 'live_now_beta:disable',
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import uuid from 'react-native-uuid'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
|
||||
import {device} from '#/storage'
|
||||
|
||||
const LEGACY_STABLE_ID = 'STATSIG_LOCAL_STORAGE_STABLE_ID'
|
||||
|
||||
export async function getAndMigrateDeviceId() {
|
||||
const migrated = getDeviceId()
|
||||
if (migrated) return migrated
|
||||
const id = (await AsyncStorage.getItem(LEGACY_STABLE_ID)) || uuid.v4()
|
||||
device.set(['deviceId'], id)
|
||||
return id
|
||||
}
|
||||
|
||||
export function getDeviceId() {
|
||||
return device.get(['deviceId'])
|
||||
}
|
||||
|
||||
export function getDeviceIdOrThrow() {
|
||||
const id = device.get(['deviceId'])
|
||||
if (!id) {
|
||||
throw new Error(`deviceId is not set, call getAndMigrateDeviceId first`)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from '#/analytics/identifiers/device'
|
||||
export * from '#/analytics/identifiers/session'
|
||||
@@ -0,0 +1,79 @@
|
||||
jest.mock('#/storage', () => ({
|
||||
device: {
|
||||
get: jest.fn(),
|
||||
set: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('#/analytics/identifiers/util', () => ({
|
||||
isSessionIdExpired: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('#/lib/appState', () => ({
|
||||
onAppStateChange: jest.fn(() => ({remove: jest.fn()})),
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetModules()
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
function getMocks() {
|
||||
const {device} = require('#/storage')
|
||||
const {isSessionIdExpired} = require('#/analytics/identifiers/util')
|
||||
return {
|
||||
device: jest.mocked(device),
|
||||
isSessionIdExpired: jest.mocked(isSessionIdExpired),
|
||||
}
|
||||
}
|
||||
|
||||
describe('session initialization', () => {
|
||||
it('creates new session and sets timestamp when none exists', () => {
|
||||
const {device, isSessionIdExpired} = getMocks()
|
||||
device.get.mockReturnValue(undefined)
|
||||
isSessionIdExpired.mockReturnValue(false)
|
||||
|
||||
const {getInitialSessionId} = require('./session')
|
||||
const id = getInitialSessionId()
|
||||
|
||||
expect(id).toBeDefined()
|
||||
expect(typeof id).toBe('string')
|
||||
expect(device.set).toHaveBeenCalledWith(['nativeSessionId'], id)
|
||||
expect(device.set).toHaveBeenCalledWith(
|
||||
['nativeSessionIdLastEventAt'],
|
||||
expect.any(Number),
|
||||
)
|
||||
})
|
||||
|
||||
it('reuses existing session when not expired', () => {
|
||||
const {device, isSessionIdExpired} = getMocks()
|
||||
const existingId = 'existing-session-id'
|
||||
device.get.mockImplementation((key: string[]) => {
|
||||
if (key[0] === 'nativeSessionId') return existingId
|
||||
if (key[0] === 'nativeSessionIdLastEventAt') return Date.now()
|
||||
return undefined
|
||||
})
|
||||
isSessionIdExpired.mockReturnValue(false)
|
||||
|
||||
const {getInitialSessionId} = require('./session')
|
||||
|
||||
expect(getInitialSessionId()).toBe(existingId)
|
||||
})
|
||||
|
||||
it('creates new session when existing is expired', () => {
|
||||
const {device, isSessionIdExpired} = getMocks()
|
||||
const existingId = 'existing-session-id'
|
||||
device.get.mockImplementation((key: string[]) => {
|
||||
if (key[0] === 'nativeSessionId') return existingId
|
||||
if (key[0] === 'nativeSessionIdLastEventAt') return Date.now() - 999999
|
||||
return undefined
|
||||
})
|
||||
isSessionIdExpired.mockReturnValue(true)
|
||||
|
||||
const {getInitialSessionId} = require('./session')
|
||||
const id = getInitialSessionId()
|
||||
|
||||
expect(id).not.toBe(existingId)
|
||||
expect(device.set).toHaveBeenCalledWith(['nativeSessionId'], id)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import {useEffect, useState} from 'react'
|
||||
import uuid from 'react-native-uuid'
|
||||
|
||||
import {onAppStateChange} from '#/lib/appState'
|
||||
import {isSessionIdExpired} from '#/analytics/identifiers/util'
|
||||
import {device} from '#/storage'
|
||||
|
||||
let sessionId = (() => {
|
||||
const existing = device.get(['nativeSessionId'])
|
||||
const lastEvent = device.get(['nativeSessionIdLastEventAt'])
|
||||
const id = existing && !isSessionIdExpired(lastEvent) ? existing : uuid.v4()
|
||||
device.set(['nativeSessionId'], id)
|
||||
device.set(['nativeSessionIdLastEventAt'], Date.now())
|
||||
return id
|
||||
})()
|
||||
|
||||
export function getInitialSessionId() {
|
||||
return sessionId
|
||||
}
|
||||
|
||||
export function useSessionId() {
|
||||
const [id, setId] = useState(() => sessionId)
|
||||
|
||||
useEffect(() => {
|
||||
const sub = onAppStateChange(state => {
|
||||
if (state === 'active') {
|
||||
const lastEvent = device.get(['nativeSessionIdLastEventAt'])
|
||||
if (isSessionIdExpired(lastEvent)) {
|
||||
sessionId = uuid.v4()
|
||||
device.set(['nativeSessionId'], sessionId)
|
||||
setId(sessionId)
|
||||
}
|
||||
}
|
||||
device.set(['nativeSessionIdLastEventAt'], Date.now())
|
||||
})
|
||||
return () => sub.remove()
|
||||
}, [])
|
||||
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import {useEffect, useState} from 'react'
|
||||
import uuid from 'react-native-uuid'
|
||||
|
||||
import {onAppStateChange} from '#/lib/appState'
|
||||
import {isSessionIdExpired} from '#/analytics/identifiers/util'
|
||||
|
||||
const SESSION_ID_KEY = 'bsky_session_id'
|
||||
const LAST_EVENT_KEY = 'bsky_session_id_last_event_at'
|
||||
|
||||
let sessionId = (() => {
|
||||
const existing = window.sessionStorage.getItem(SESSION_ID_KEY)
|
||||
const lastEventStr = window.sessionStorage.getItem(LAST_EVENT_KEY)
|
||||
const lastEvent = lastEventStr ? Number(lastEventStr) : undefined
|
||||
const id = existing && !isSessionIdExpired(lastEvent) ? existing : uuid.v4()
|
||||
window.sessionStorage.setItem(SESSION_ID_KEY, id)
|
||||
window.sessionStorage.setItem(LAST_EVENT_KEY, String(Date.now()))
|
||||
return id
|
||||
})()
|
||||
|
||||
export function getInitialSessionId() {
|
||||
return sessionId
|
||||
}
|
||||
|
||||
export function useSessionId() {
|
||||
const [id, setId] = useState(() => sessionId)
|
||||
|
||||
useEffect(() => {
|
||||
const sub = onAppStateChange(state => {
|
||||
if (state === 'active') {
|
||||
const lastEventStr = window.sessionStorage.getItem(LAST_EVENT_KEY)
|
||||
const lastEvent = lastEventStr ? Number(lastEventStr) : undefined
|
||||
if (isSessionIdExpired(lastEvent)) {
|
||||
sessionId = uuid.v4()
|
||||
window.sessionStorage.setItem(SESSION_ID_KEY, sessionId)
|
||||
setId(sessionId)
|
||||
}
|
||||
}
|
||||
window.sessionStorage.setItem(LAST_EVENT_KEY, String(Date.now()))
|
||||
})
|
||||
return () => sub.remove()
|
||||
}, [])
|
||||
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import * as env from '#/env'
|
||||
|
||||
const ONE_MIN = 60 * 1e3
|
||||
const TTL = (env.IS_NATIVE ? 5 : 30) * ONE_MIN // 5 min on native
|
||||
|
||||
export function isSessionIdExpired(since: number | undefined) {
|
||||
if (since === undefined) return false
|
||||
return Date.now() - since >= TTL
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import {createContext, useContext, useEffect, useMemo} from 'react'
|
||||
import {Platform} from 'react-native'
|
||||
|
||||
import {Logger} from '#/logger'
|
||||
import {
|
||||
Features,
|
||||
features as feats,
|
||||
init,
|
||||
refresh,
|
||||
setAttributes,
|
||||
} from '#/analytics/features'
|
||||
import {
|
||||
getAndMigrateDeviceId,
|
||||
getDeviceId,
|
||||
getInitialSessionId,
|
||||
useSessionId,
|
||||
} from '#/analytics/identifiers'
|
||||
import {
|
||||
getMetadataForLogger,
|
||||
getNavigationMetadata,
|
||||
type MergeableMetadata,
|
||||
type Metadata,
|
||||
} from '#/analytics/metadata'
|
||||
import {type Metrics, metrics} from '#/analytics/metrics'
|
||||
import * as refParams from '#/analytics/misc/refParams'
|
||||
import * as env from '#/env'
|
||||
import {useGeolocation} from '#/geolocation'
|
||||
import {device} from '#/storage'
|
||||
|
||||
export * as utils from '#/analytics/utils'
|
||||
export const features = {init, refresh}
|
||||
export {Features} from '#/analytics/features'
|
||||
export {type Metrics} from '#/analytics/metrics'
|
||||
|
||||
type LoggerType = {
|
||||
debug: Logger['debug']
|
||||
info: Logger['info']
|
||||
log: Logger['log']
|
||||
warn: Logger['warn']
|
||||
error: Logger['error']
|
||||
/**
|
||||
* Clones the existing logger and overrides the `context` value. Existing
|
||||
* metadata is inherited.
|
||||
*
|
||||
* ```ts
|
||||
* const ax = useAnalytics()
|
||||
* const logger = ax.logger.useChild(ax.logger.Context.Notifications)
|
||||
* ```
|
||||
*/
|
||||
useChild: (context: Exclude<Logger['context'], undefined>) => LoggerType
|
||||
Context: typeof Logger.Context
|
||||
}
|
||||
export type AnalyticsContextType = {
|
||||
metadata: Metadata
|
||||
logger: LoggerType
|
||||
metric: <E extends keyof Metrics>(
|
||||
event: E,
|
||||
payload: Metrics[E],
|
||||
metadata?: MergeableMetadata,
|
||||
) => void
|
||||
features: typeof Features & {
|
||||
enabled(feature: Features): boolean
|
||||
}
|
||||
}
|
||||
export type AnalyticsBaseContextType = Omit<AnalyticsContextType, 'features'>
|
||||
|
||||
function createLogger(
|
||||
context: Logger['context'],
|
||||
metadata: Partial<Metadata>,
|
||||
): LoggerType {
|
||||
const logger = Logger.create(context, metadata)
|
||||
return {
|
||||
debug: logger.debug.bind(logger),
|
||||
info: logger.info.bind(logger),
|
||||
log: logger.log.bind(logger),
|
||||
warn: logger.warn.bind(logger),
|
||||
error: logger.error.bind(logger),
|
||||
useChild: (context: Exclude<Logger['context'], undefined>) => {
|
||||
return useMemo(() => createLogger(context, metadata), [context, metadata])
|
||||
},
|
||||
Context: Logger.Context,
|
||||
}
|
||||
}
|
||||
|
||||
const Context = createContext<AnalyticsBaseContextType>({
|
||||
logger: createLogger(Logger.Context.Default, {}),
|
||||
metric: (event, payload, metadata) => {
|
||||
if (metadata && '__meta' in metadata) {
|
||||
delete metadata.__meta
|
||||
}
|
||||
metrics.track(event, payload, {
|
||||
...metadata,
|
||||
navigation: getNavigationMetadata(),
|
||||
})
|
||||
},
|
||||
metadata: {
|
||||
base: {
|
||||
deviceId: getDeviceId() ?? 'unknown',
|
||||
sessionId: getInitialSessionId(),
|
||||
platform: Platform.OS,
|
||||
appVersion: env.APP_VERSION,
|
||||
bundleIdentifier: env.BUNDLE_IDENTIFIER,
|
||||
bundleDate: env.BUNDLE_DATE,
|
||||
referrerSrc: refParams.src,
|
||||
referrerUrl: refParams.url,
|
||||
},
|
||||
geolocation: device.get(['mergedGeolocation']) || {
|
||||
countryCode: '',
|
||||
regionCode: '',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
/**
|
||||
* Ensures that deviceId is set and migrated from legacy storage. Handled on
|
||||
* startup in `App.<platform>.tsx`. This must be awaited prior to the app
|
||||
* booting up.
|
||||
*/
|
||||
export const setupDeviceId = getAndMigrateDeviceId()
|
||||
|
||||
/**
|
||||
* Analytics context provider. Decorates the parent analytics context with
|
||||
* additional metadata. Nesting should be done carefully and sparingly.
|
||||
*/
|
||||
export function AnalyticsContext({
|
||||
children,
|
||||
metadata,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
metadata?: MergeableMetadata
|
||||
}) {
|
||||
if (metadata) {
|
||||
if (!('__meta' in metadata)) {
|
||||
throw new Error(
|
||||
'Use the useMeta() helper when passing metadata to AnalyticsContext',
|
||||
)
|
||||
}
|
||||
}
|
||||
const sessionId = useSessionId()
|
||||
const geolocation = useGeolocation()
|
||||
const parentContext = useContext(Context)
|
||||
const childContext = useMemo(() => {
|
||||
const combinedMetadata = {
|
||||
...parentContext.metadata,
|
||||
...metadata,
|
||||
base: {
|
||||
...parentContext.metadata.base,
|
||||
sessionId,
|
||||
},
|
||||
geolocation,
|
||||
}
|
||||
const context: AnalyticsBaseContextType = {
|
||||
...parentContext,
|
||||
logger: createLogger(
|
||||
Logger.Context.Default,
|
||||
getMetadataForLogger(combinedMetadata),
|
||||
),
|
||||
metadata: combinedMetadata,
|
||||
metric: (event, payload, extraMetadata) => {
|
||||
parentContext.metric(event, payload, {
|
||||
...combinedMetadata,
|
||||
...extraMetadata,
|
||||
})
|
||||
},
|
||||
}
|
||||
return context
|
||||
}, [sessionId, geolocation, parentContext, metadata])
|
||||
return <Context.Provider value={childContext}>{children}</Context.Provider>
|
||||
}
|
||||
|
||||
/**
|
||||
* Feature gates provider. Decorates the parent analytics context with
|
||||
* feature gate capabilities. Should be mounted within `AnalyticsContext`,
|
||||
* and below the `<Fragment key={did} />` breaker in `App.<platform>.tsx`.
|
||||
*/
|
||||
export function AnalyticsFeaturesContext({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const parentContext = useContext(Context)
|
||||
|
||||
/**
|
||||
* Side-effect: we need to synchronously set this during the
|
||||
* same render cycle. It does not trigger a re-render, it just
|
||||
* sets properties on the singleton GrowthBook instance.
|
||||
*/
|
||||
setAttributes(parentContext.metadata)
|
||||
|
||||
useEffect(() => {
|
||||
feats.setTrackingCallback((experiment, result) => {
|
||||
parentContext.metric('experiment:viewed', {
|
||||
experimentId: experiment.key,
|
||||
variationId: result.key,
|
||||
})
|
||||
})
|
||||
}, [parentContext.metric])
|
||||
|
||||
const childContext = useMemo<AnalyticsContextType>(() => {
|
||||
return {
|
||||
...parentContext,
|
||||
features: {
|
||||
enabled: feats.isOn.bind(feats),
|
||||
...Features,
|
||||
},
|
||||
}
|
||||
}, [parentContext])
|
||||
|
||||
return <Context.Provider value={childContext}>{children}</Context.Provider>
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic analytics context without feature gates. Should really only be used
|
||||
* above the `AnalyticsFeaturesContext` provider.
|
||||
*/
|
||||
export function useAnalyticsBase() {
|
||||
return useContext(Context)
|
||||
}
|
||||
|
||||
/**
|
||||
* The main analytics context, including feature gates. Use this everywhere you
|
||||
* need metrics, features, or logging within the React tree.
|
||||
*/
|
||||
export function useAnalytics() {
|
||||
const ctx = useContext(Context)
|
||||
if (!('features' in ctx)) {
|
||||
throw new Error(
|
||||
'useAnalytics must be used within an AnalyticsFeaturesContext',
|
||||
)
|
||||
}
|
||||
return ctx as AnalyticsContextType
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import {type Geolocation} from '#/geolocation'
|
||||
|
||||
export type BaseMetadata = {
|
||||
deviceId: string
|
||||
sessionId: string
|
||||
platform: string
|
||||
appVersion: string
|
||||
bundleIdentifier: string
|
||||
bundleDate: number
|
||||
referrerSrc: string
|
||||
referrerUrl: string
|
||||
}
|
||||
|
||||
export type GeolocationMetadata = Geolocation
|
||||
|
||||
export type SessionMetadata = {
|
||||
did: string
|
||||
isBskyPds: boolean
|
||||
}
|
||||
|
||||
export type PreferencesMetadata = {
|
||||
appLanguage: string
|
||||
contentLanguages: string[]
|
||||
}
|
||||
|
||||
export type MergeableMetadata = {
|
||||
session?: SessionMetadata
|
||||
preferences?: PreferencesMetadata
|
||||
/**
|
||||
* Navigation metadata is not actually available on this object, instead it's
|
||||
* merged in at time-of-log/metric. See `#/analytics/metadata.ts` for details.
|
||||
*/
|
||||
navigation?: NavigationMetadata
|
||||
}
|
||||
|
||||
export type Metadata = {
|
||||
base: BaseMetadata
|
||||
geolocation: GeolocationMetadata
|
||||
} & MergeableMetadata
|
||||
|
||||
/*
|
||||
* Navigation metadata is handle out-of-band from React, since we don't want to
|
||||
* slow down screen transitions in any way, and there doesn't seem to be a nice
|
||||
* way to get current navigation state without an additional re-render between
|
||||
* navigations.
|
||||
*
|
||||
* So instead of this data being available on the Metadata object, it's stored
|
||||
* here and merged in at time-of-log/metric.
|
||||
*/
|
||||
export type NavigationMetadata = {
|
||||
previousScreen?: string
|
||||
currentScreen?: string
|
||||
}
|
||||
let navigationMetadata: NavigationMetadata | undefined
|
||||
export function getNavigationMetadata() {
|
||||
return navigationMetadata
|
||||
}
|
||||
export function setNavigationMetadata(meta: NavigationMetadata | undefined) {
|
||||
navigationMetadata = meta
|
||||
}
|
||||
|
||||
/**
|
||||
* We don't want or need to send all data to the logger
|
||||
*/
|
||||
export function getMetadataForLogger({
|
||||
base,
|
||||
geolocation,
|
||||
session,
|
||||
}: Metadata): Record<string, any> {
|
||||
return {
|
||||
deviceId: base.deviceId,
|
||||
sessionId: base.sessionId,
|
||||
platform: base.platform,
|
||||
appVersion: base.appVersion,
|
||||
countryCode: geolocation.countryCode,
|
||||
regionCode: geolocation.regionCode,
|
||||
isBskyPds: session?.isBskyPds || 'anonymous',
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import {MetricsClient} from './client'
|
||||
|
||||
let appStateCallback: (state: string) => void
|
||||
|
||||
jest.mock('#/lib/appState', () => ({
|
||||
onAppStateChange: jest.fn(cb => {
|
||||
appStateCallback = cb
|
||||
return {remove: jest.fn()}
|
||||
}),
|
||||
}))
|
||||
|
||||
jest.mock('#/logger', () => ({
|
||||
Logger: {
|
||||
create: () => ({
|
||||
info: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}),
|
||||
Context: {Metric: 'metric'},
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('#/env', () => ({
|
||||
METRICS_API_HOST: 'https://test.metrics.api',
|
||||
IS_WEB: false,
|
||||
}))
|
||||
|
||||
type TestEvents = {
|
||||
click: {button: string}
|
||||
view: {screen: string}
|
||||
}
|
||||
|
||||
describe('MetricsClient', () => {
|
||||
let fetchMock: jest.Mock
|
||||
let fetchRequests: {body: any}[]
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers({advanceTimers: true})
|
||||
fetchRequests = []
|
||||
fetchMock = jest.fn().mockImplementation(async (_url, options) => {
|
||||
const body = JSON.parse(options.body)
|
||||
fetchRequests.push({body})
|
||||
return {ok: true, status: 200}
|
||||
})
|
||||
global.fetch = fetchMock
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('flushes events on interval', async () => {
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
client.track('view', {screen: 'home'})
|
||||
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// Advance past the 10 second interval
|
||||
await jest.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events).toHaveLength(2)
|
||||
expect(fetchRequests[0].body.events[0].event).toBe('click')
|
||||
expect(fetchRequests[0].body.events[1].event).toBe('view')
|
||||
})
|
||||
|
||||
it('flushes when maxBatchSize is exceeded', async () => {
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.maxBatchSize = 5
|
||||
|
||||
// Add events up to maxBatchSize (should not flush yet)
|
||||
for (let i = 0; i < 5; i++) {
|
||||
client.track('click', {button: `btn-${i}`})
|
||||
}
|
||||
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// One more event should trigger flush (> maxBatchSize)
|
||||
client.track('click', {button: 'btn-trigger'})
|
||||
|
||||
// Allow microtasks to run
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events).toHaveLength(6)
|
||||
})
|
||||
|
||||
it('retries failed events once on 500 response', async () => {
|
||||
let requestCount = 0
|
||||
|
||||
fetchMock.mockImplementation(async (_url, options) => {
|
||||
requestCount++
|
||||
const body = JSON.parse(options.body)
|
||||
|
||||
if (requestCount === 1) {
|
||||
// First request fails with 500 - "Failed to fetch" triggers isNetworkError
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: async () => 'Internal Server Error',
|
||||
}
|
||||
}
|
||||
|
||||
// Retry succeeds
|
||||
fetchRequests.push({body})
|
||||
return {ok: true, status: 200}
|
||||
})
|
||||
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
|
||||
// Trigger flush via interval
|
||||
await jest.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
expect(requestCount).toBe(1)
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// Simulate app coming to foreground to trigger retry
|
||||
appStateCallback('active')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(requestCount).toBe(2)
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events).toHaveLength(1)
|
||||
expect(fetchRequests[0].body.events[0].event).toBe('click')
|
||||
})
|
||||
|
||||
it('does not retry more than once', async () => {
|
||||
let requestCount = 0
|
||||
|
||||
fetchMock.mockImplementation(async () => {
|
||||
requestCount++
|
||||
// Always fail with network-like error
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: async () => 'Internal Server Error',
|
||||
}
|
||||
})
|
||||
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
|
||||
// First flush fails
|
||||
await jest.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
expect(requestCount).toBe(1)
|
||||
|
||||
// Retry also fails
|
||||
appStateCallback('active')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(requestCount).toBe(2)
|
||||
|
||||
// Another foreground event should not retry again (events are dropped)
|
||||
appStateCallback('active')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(requestCount).toBe(2) // No additional requests
|
||||
})
|
||||
|
||||
it('flushes when app goes to background', async () => {
|
||||
const client = new MetricsClient<TestEvents>()
|
||||
client.track('click', {button: 'submit'})
|
||||
|
||||
expect(fetchRequests).toHaveLength(0)
|
||||
|
||||
// Simulate app going to background
|
||||
appStateCallback('background')
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(fetchRequests).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
import {onAppStateChange} from '#/lib/appState'
|
||||
import {isNetworkError} from '#/lib/strings/errors'
|
||||
import {Logger} from '#/logger'
|
||||
import * as env from '#/env'
|
||||
|
||||
type Event<M extends Record<string, any>> = {
|
||||
time: number
|
||||
event: keyof M
|
||||
payload: M[keyof M]
|
||||
metadata: Record<string, any>
|
||||
}
|
||||
|
||||
const TRACKING_ENDPOINT = env.METRICS_API_HOST + '/t'
|
||||
const logger = Logger.create(Logger.Context.Metric, {})
|
||||
|
||||
export class MetricsClient<M extends Record<string, any>> {
|
||||
maxBatchSize = 100
|
||||
|
||||
private started: boolean = false
|
||||
private queue: Event<M>[] = []
|
||||
private failedQueue: Event<M>[] = []
|
||||
private flushInterval: NodeJS.Timeout | null = null
|
||||
|
||||
start() {
|
||||
if (this.started) return
|
||||
this.started = true
|
||||
this.flushInterval = setInterval(() => {
|
||||
this.flush()
|
||||
}, 10_000)
|
||||
onAppStateChange(state => {
|
||||
if (state === 'active') {
|
||||
this.retryFailedLogs()
|
||||
} else {
|
||||
this.flush()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
track<E extends keyof M>(
|
||||
event: E,
|
||||
payload: M[E],
|
||||
metadata: Record<string, any> = {},
|
||||
) {
|
||||
this.start()
|
||||
|
||||
const e = {
|
||||
time: Date.now(),
|
||||
event,
|
||||
payload,
|
||||
metadata,
|
||||
}
|
||||
this.queue.push(e)
|
||||
|
||||
logger.debug(`event: ${e.event as string}`, e)
|
||||
|
||||
if (this.queue.length > this.maxBatchSize) {
|
||||
this.flush()
|
||||
}
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (!this.queue.length) return
|
||||
const events = this.queue.splice(0, this.queue.length)
|
||||
this.sendBatch(events)
|
||||
}
|
||||
|
||||
private async sendBatch(events: Event<M>[], isRetry: boolean = false) {
|
||||
logger.debug(`sendBatch: ${events.length}`, {
|
||||
isRetry,
|
||||
})
|
||||
|
||||
try {
|
||||
const body = JSON.stringify({events})
|
||||
if (env.IS_WEB && 'navigator' in globalThis && navigator.sendBeacon) {
|
||||
const success = navigator.sendBeacon(
|
||||
TRACKING_ENDPOINT,
|
||||
new Blob([body], {type: 'application/json'}),
|
||||
)
|
||||
if (!success) {
|
||||
// construct a "network error" for `isNetworkError` to work
|
||||
throw new Error(`Failed to fetch: sendBeacon returned false`)
|
||||
}
|
||||
} else {
|
||||
const res = await fetch(TRACKING_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({events}),
|
||||
keepalive: true,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.text().catch(() => 'Unknown error')
|
||||
// construct a "network error" for `isNetworkError` to work
|
||||
throw new Error(`${res.status} Failed to fetch — ${error}`)
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (isNetworkError(e)) {
|
||||
if (isRetry) return // retry once
|
||||
this.failedQueue.push(...events)
|
||||
return
|
||||
}
|
||||
logger.error(`Failed to send metrics`, {
|
||||
safeMessage: e.toString(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private retryFailedLogs() {
|
||||
if (!this.failedQueue.length) return
|
||||
const events = this.failedQueue.splice(0, this.failedQueue.length)
|
||||
this.sendBatch(events, true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import {MetricsClient} from '#/analytics/metrics/client'
|
||||
import {type Events} from '#/analytics/metrics/types'
|
||||
|
||||
export type {Events as Metrics} from '#/analytics/metrics/types'
|
||||
export * from '#/analytics/metrics/utils'
|
||||
export const metrics = new MetricsClient<Events>()
|
||||
@@ -1,12 +1,21 @@
|
||||
/*
|
||||
* Do not import runtime code into this file
|
||||
*/
|
||||
|
||||
import {type NotificationReason} from '#/lib/hooks/useNotificationHandler'
|
||||
import {type FeedDescriptor} from '#/state/queries/post-feed'
|
||||
import {type LiveEventFeedMetricContext} from '#/features/liveEvents/types'
|
||||
|
||||
export type MetricEvents = {
|
||||
export type Events = {
|
||||
// App events
|
||||
init: {
|
||||
initMs: number
|
||||
}
|
||||
'experiment:viewed': {
|
||||
experimentId: string
|
||||
variationId: string
|
||||
}
|
||||
|
||||
'account:loggedIn': {
|
||||
logContext:
|
||||
| 'LoginForm'
|
||||
@@ -139,6 +148,7 @@ export type MetricEvents = {
|
||||
feedUrl: string
|
||||
feedType: string
|
||||
index: number
|
||||
reason?: string
|
||||
}
|
||||
'feed:endReached': {
|
||||
feedUrl: string
|
||||
@@ -223,6 +233,53 @@ export type MetricEvents = {
|
||||
persist: boolean
|
||||
hasChanged: boolean
|
||||
}
|
||||
'composer:open': {
|
||||
logContext:
|
||||
| 'Fab'
|
||||
| 'PostReply'
|
||||
| 'QuotePost'
|
||||
| 'ProfileFeed'
|
||||
| 'Deeplink'
|
||||
| 'Other'
|
||||
isReply: boolean
|
||||
hasQuote: boolean
|
||||
hasDraft: boolean
|
||||
}
|
||||
'draft:save': {
|
||||
isNewDraft: boolean
|
||||
hasText: boolean
|
||||
hasImages: boolean
|
||||
hasVideo: boolean
|
||||
hasGif: boolean
|
||||
hasQuote: boolean
|
||||
hasLink: boolean
|
||||
postCount: number
|
||||
textLength: number
|
||||
}
|
||||
'draft:load': {
|
||||
draftAgeMs: number
|
||||
hasText: boolean
|
||||
hasImages: boolean
|
||||
hasVideo: boolean
|
||||
hasGif: boolean
|
||||
postCount: number
|
||||
}
|
||||
'draft:delete': {
|
||||
logContext: 'DraftsList'
|
||||
draftAgeMs: number
|
||||
}
|
||||
'draft:listOpen': {
|
||||
draftCount: number
|
||||
}
|
||||
'draft:post': {
|
||||
draftAgeMs: number
|
||||
wasEdited: boolean
|
||||
}
|
||||
'draft:discard': {
|
||||
logContext: 'ComposerClose' | 'BeforeDraftsList'
|
||||
hadContent: boolean
|
||||
textLength: number
|
||||
}
|
||||
|
||||
// Data events
|
||||
'account:create:begin': {}
|
||||
@@ -374,7 +431,6 @@ export type MetricEvents = {
|
||||
| 'AvatarButton'
|
||||
| 'StarterPackProfilesList'
|
||||
| 'FeedInterstitial'
|
||||
| 'ProfileHeaderSuggestedFollows'
|
||||
| 'PostOnboardingFindFollows'
|
||||
| 'ImmersiveVideo'
|
||||
| 'ExploreSuggestedAccounts'
|
||||
@@ -411,8 +467,8 @@ export type MetricEvents = {
|
||||
| 'InterstitialProfile'
|
||||
| 'Profile'
|
||||
| 'Onboarding'
|
||||
location: 'Card' | 'Profile'
|
||||
recId?: number
|
||||
location: 'Card' | 'Profile' | 'FollowAll'
|
||||
recId?: number | string
|
||||
position: number
|
||||
suggestedDid: string
|
||||
category: string | null
|
||||
@@ -423,7 +479,7 @@ export type MetricEvents = {
|
||||
| 'InterstitialDiscover'
|
||||
| 'InterstitialProfile'
|
||||
| 'Onboarding'
|
||||
recId?: number
|
||||
recId?: number | string
|
||||
position: number
|
||||
suggestedDid: string
|
||||
category: string | null
|
||||
@@ -436,7 +492,7 @@ export type MetricEvents = {
|
||||
| 'Profile'
|
||||
| 'Onboarding'
|
||||
| 'ProgressGuide'
|
||||
recId?: number
|
||||
recId?: number | string
|
||||
position: number
|
||||
suggestedDid: string
|
||||
category: string | null
|
||||
@@ -451,7 +507,7 @@ export type MetricEvents = {
|
||||
}
|
||||
'suggestedUser:dismiss': {
|
||||
logContext: 'InterstitialDiscover' | 'InterstitialProfile'
|
||||
recId?: number
|
||||
recId?: number | string
|
||||
position: number
|
||||
suggestedDid: string
|
||||
}
|
||||
@@ -468,7 +524,6 @@ export type MetricEvents = {
|
||||
| 'AvatarButton'
|
||||
| 'StarterPackProfilesList'
|
||||
| 'FeedInterstitial'
|
||||
| 'ProfileHeaderSuggestedFollows'
|
||||
| 'PostOnboardingFindFollows'
|
||||
| 'ImmersiveVideo'
|
||||
| 'ExploreSuggestedAccounts'
|
||||
@@ -0,0 +1,7 @@
|
||||
export function toClout(n: number | null | undefined): number | undefined {
|
||||
if (n == null) {
|
||||
return undefined
|
||||
} else {
|
||||
return Math.max(0, Math.round(Math.log(n)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* This is used for our own Bluesky post embeds, and maybe other things.
|
||||
*
|
||||
* In the case of our embeds, `ref_src=embed`. Not sure if `ref_url` is used.
|
||||
*/
|
||||
|
||||
import * as env from '#/env'
|
||||
|
||||
let refSrc = ''
|
||||
let refUrl = ''
|
||||
if (env.IS_WEB) {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
refSrc = params.get('ref_src') ?? ''
|
||||
refUrl = decodeURIComponent(params.get('ref_url') ?? '')
|
||||
}
|
||||
|
||||
export const src = refSrc
|
||||
export const url = refUrl
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useMemo} from 'react'
|
||||
|
||||
import {BSKY_SERVICE} from '#/lib/constants'
|
||||
import {type SessionAccount} from '#/state/session'
|
||||
import {
|
||||
type MergeableMetadata,
|
||||
type SessionMetadata,
|
||||
} from '#/analytics/metadata'
|
||||
|
||||
/**
|
||||
* Thin `useMemo` wrapper that marks the metadata as memoized and provides a
|
||||
* type guard.
|
||||
*/
|
||||
export function useMeta(metadata?: MergeableMetadata) {
|
||||
const m = useMemo(() => metadata, [metadata])
|
||||
if (!m) return
|
||||
// @ts-ignore
|
||||
m.__meta = true
|
||||
return m
|
||||
}
|
||||
|
||||
export function accountToSessionMetadata(
|
||||
account: SessionAccount | undefined,
|
||||
): SessionMetadata | undefined {
|
||||
if (!account) {
|
||||
return
|
||||
} else {
|
||||
return {
|
||||
did: account.did,
|
||||
isBskyPds: account.service.startsWith(BSKY_SERVICE),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from 'react-native'
|
||||
import {
|
||||
KeyboardAwareScrollView,
|
||||
type KeyboardAwareScrollViewRef,
|
||||
useKeyboardHandler,
|
||||
useReanimatedKeyboardAnimation,
|
||||
} from 'react-native-keyboard-controller'
|
||||
@@ -23,7 +24,6 @@ import {useSafeAreaInsets} from 'react-native-safe-area-context'
|
||||
import {msg} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
|
||||
import {useEnableKeyboardController} from '#/lib/hooks/useEnableKeyboardController'
|
||||
import {ScrollProvider} from '#/lib/ScrollContext'
|
||||
import {logger} from '#/logger'
|
||||
import {useA11y} from '#/state/a11y'
|
||||
@@ -209,10 +209,9 @@ export const ScrollableInner = React.forwardRef<ScrollView, DialogInnerProps>(
|
||||
const {nativeSnapPoint, disableDrag, setDisableDrag} = useDialogContext()
|
||||
const insets = useSafeAreaInsets()
|
||||
|
||||
useEnableKeyboardController(IS_IOS)
|
||||
|
||||
const [keyboardHeight, setKeyboardHeight] = React.useState(0)
|
||||
|
||||
// note: iOS-only. keyboard-controller doesn't seem to work inside the sheets on Android
|
||||
useKeyboardHandler(
|
||||
{
|
||||
onEnd: e => {
|
||||
@@ -231,7 +230,6 @@ export const ScrollableInner = React.forwardRef<ScrollView, DialogInnerProps>(
|
||||
}
|
||||
paddingBottom = Math.max(paddingBottom, tokens.space._2xl)
|
||||
} else {
|
||||
paddingBottom += keyboardHeight
|
||||
if (nativeSnapPoint === BottomSheetSnapPoint.Full) {
|
||||
paddingBottom += insets.top
|
||||
}
|
||||
@@ -259,7 +257,7 @@ export const ScrollableInner = React.forwardRef<ScrollView, DialogInnerProps>(
|
||||
{paddingBottom},
|
||||
contentContainerStyle,
|
||||
]}
|
||||
ref={ref}
|
||||
ref={ref as React.Ref<KeyboardAwareScrollViewRef>}
|
||||
showsVerticalScrollIndicator={IS_ANDROID ? false : undefined}
|
||||
{...props}
|
||||
bounces={nativeSnapPoint === BottomSheetSnapPoint.Full}
|
||||
@@ -289,8 +287,6 @@ export const InnerFlatList = React.forwardRef<
|
||||
const insets = useSafeAreaInsets()
|
||||
const {nativeSnapPoint, disableDrag, setDisableDrag} = useDialogContext()
|
||||
|
||||
useEnableKeyboardController(IS_IOS)
|
||||
|
||||
const onScroll = (e: ScrollEvent) => {
|
||||
'worklet'
|
||||
if (!IS_ANDROID) {
|
||||
@@ -409,3 +405,7 @@ export function Handle({
|
||||
export function Close() {
|
||||
return null
|
||||
}
|
||||
|
||||
export function Backdrop() {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ import {
|
||||
FlatList,
|
||||
type FlatListProps,
|
||||
type GestureResponderEvent,
|
||||
Pressable,
|
||||
type StyleProp,
|
||||
TouchableWithoutFeedback,
|
||||
View,
|
||||
type ViewStyle,
|
||||
} from 'react-native'
|
||||
@@ -113,7 +113,7 @@ export function Outer({
|
||||
<Portal>
|
||||
<Context.Provider value={context}>
|
||||
<RemoveScrollBar />
|
||||
<TouchableWithoutFeedback
|
||||
<Pressable
|
||||
accessibilityHint={undefined}
|
||||
accessibilityLabel={_(msg`Close active dialog`)}
|
||||
onPress={handleBackgroundPress}>
|
||||
@@ -146,7 +146,7 @@ export function Outer({
|
||||
{children}
|
||||
</View>
|
||||
</View>
|
||||
</TouchableWithoutFeedback>
|
||||
</Pressable>
|
||||
</Context.Provider>
|
||||
</Portal>
|
||||
)}
|
||||
@@ -304,7 +304,7 @@ export function Handle() {
|
||||
return null
|
||||
}
|
||||
|
||||
function Backdrop() {
|
||||
export function Backdrop() {
|
||||
const t = useTheme()
|
||||
const {reduceMotionEnabled} = useA11y()
|
||||
return (
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import React, {useCallback, useEffect, useRef} from 'react'
|
||||
import {useCallback, useEffect, useMemo, useRef, useState} from 'react'
|
||||
import {ScrollView, View} from 'react-native'
|
||||
import Animated, {LinearTransition} from 'react-native-reanimated'
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeIn,
|
||||
FadeOut,
|
||||
LayoutAnimationConfig,
|
||||
LinearTransition,
|
||||
} from 'react-native-reanimated'
|
||||
import {type AppBskyFeedDefs, AtUri} from '@atproto/api'
|
||||
import {msg, Trans} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
import {useNavigation} from '@react-navigation/native'
|
||||
|
||||
import {type NavigationProp} from '#/lib/routes/types'
|
||||
import {logEvent, useGate} from '#/lib/statsig/statsig'
|
||||
import {logger} from '#/logger'
|
||||
import {type MetricEvents} from '#/logger/metrics'
|
||||
import {useModerationOpts} from '#/state/preferences/moderation-opts'
|
||||
import {useGetPopularFeedsQuery} from '#/state/queries/feed'
|
||||
import {type FeedDescriptor} from '#/state/queries/post-feed'
|
||||
@@ -24,6 +27,7 @@ import {type SeenPost} from '#/state/userActionHistory'
|
||||
import {BlockDrawerGesture} from '#/view/shell/BlockDrawerGesture'
|
||||
import {
|
||||
atoms as a,
|
||||
native,
|
||||
useBreakpoints,
|
||||
useTheme,
|
||||
type ViewStyleProp,
|
||||
@@ -38,6 +42,7 @@ import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
|
||||
import {InlineLinkText} from '#/components/Link'
|
||||
import * as ProfileCard from '#/components/ProfileCard'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {type Metrics, useAnalytics} from '#/analytics'
|
||||
import {IS_IOS} from '#/env'
|
||||
import type * as bsky from '#/types/bsky'
|
||||
import {FollowDialogWithoutGuide} from './ProgressGuide/FollowDialog'
|
||||
@@ -154,7 +159,7 @@ function sortSeenPosts(postA: SeenPost, postB: SeenPost): 0 | 1 | -1 {
|
||||
function useExperimentalSuggestedUsersQuery() {
|
||||
const {currentAccount} = useSession()
|
||||
const userActionSnapshot = userActionHistory.useActionHistorySnapshot()
|
||||
const dids = React.useMemo(() => {
|
||||
const dids = useMemo(() => {
|
||||
const {likes, follows, followSuggestions, seen} = userActionSnapshot
|
||||
const likeDids = likes
|
||||
.map(l => new AtUri(l))
|
||||
@@ -227,67 +232,54 @@ export function SuggestedFollowsProfile({did}: {did: string}) {
|
||||
isFetchingNextPage,
|
||||
} = useSuggestedFollowsQuery({limit: 25})
|
||||
|
||||
const [dismissedDids, setDismissedDids] = React.useState<Set<string>>(
|
||||
new Set(),
|
||||
)
|
||||
const [dismissingDids, setDismissingDids] = React.useState<Set<string>>(
|
||||
new Set(),
|
||||
)
|
||||
const [dismissedDids, setDismissedDids] = useState<Set<string>>(new Set())
|
||||
|
||||
const onDismiss = React.useCallback((dismissedDid: string) => {
|
||||
// Start the fade animation
|
||||
setDismissingDids(prev => new Set(prev).add(dismissedDid))
|
||||
// After animation completes, actually remove from list
|
||||
setTimeout(() => {
|
||||
setDismissedDids(prev => new Set(prev).add(dismissedDid))
|
||||
setDismissingDids(prev => {
|
||||
const next = new Set(prev)
|
||||
next.delete(dismissedDid)
|
||||
return next
|
||||
})
|
||||
}, DISMISS_ANIMATION_DURATION)
|
||||
const onDismiss = useCallback((dismissedDid: string) => {
|
||||
setDismissedDids(prev => new Set(prev).add(dismissedDid))
|
||||
}, [])
|
||||
|
||||
// Combine profiles from the actor-specific query with fallback suggestions
|
||||
const allProfiles = React.useMemo(() => {
|
||||
const allProfiles = useMemo(() => {
|
||||
const actorProfiles = data?.suggestions ?? []
|
||||
const fallbackProfiles =
|
||||
moreSuggestions?.pages.flatMap(page => page.actors) ?? []
|
||||
moreSuggestions?.pages.flatMap(page =>
|
||||
page.actors.map(actor => ({actor, recId: page.recId})),
|
||||
) ?? []
|
||||
|
||||
// Dedupe by did, preferring actor-specific profiles
|
||||
const seen = new Set<string>()
|
||||
const combined: bsky.profile.AnyProfileView[] = []
|
||||
const combined: {actor: bsky.profile.AnyProfileView; recId?: number}[] = []
|
||||
|
||||
for (const profile of actorProfiles) {
|
||||
if (!seen.has(profile.did)) {
|
||||
seen.add(profile.did)
|
||||
combined.push(profile)
|
||||
combined.push({actor: profile, recId: data?.recId})
|
||||
}
|
||||
}
|
||||
|
||||
for (const profile of fallbackProfiles) {
|
||||
if (!seen.has(profile.did) && profile.did !== did) {
|
||||
seen.add(profile.did)
|
||||
if (!seen.has(profile.actor.did) && profile.actor.did !== did) {
|
||||
seen.add(profile.actor.did)
|
||||
combined.push(profile)
|
||||
}
|
||||
}
|
||||
|
||||
return combined
|
||||
}, [data?.suggestions, moreSuggestions?.pages, did])
|
||||
}, [data?.suggestions, moreSuggestions?.pages, did, data?.recId])
|
||||
|
||||
const filteredProfiles = React.useMemo(() => {
|
||||
return allProfiles.filter(p => !dismissedDids.has(p.did))
|
||||
const filteredProfiles = useMemo(() => {
|
||||
return allProfiles.filter(p => !dismissedDids.has(p.actor.did))
|
||||
}, [allProfiles, dismissedDids])
|
||||
|
||||
// Fetch more when running low
|
||||
React.useEffect(() => {
|
||||
useEffect(() => {
|
||||
if (
|
||||
moderationOpts &&
|
||||
filteredProfiles.length < maxLength &&
|
||||
hasNextPage &&
|
||||
!isFetchingNextPage
|
||||
) {
|
||||
fetchNextPage()
|
||||
void fetchNextPage()
|
||||
}
|
||||
}, [
|
||||
filteredProfiles.length,
|
||||
@@ -303,11 +295,9 @@ export function SuggestedFollowsProfile({did}: {did: string}) {
|
||||
isSuggestionsLoading={isSuggestionsLoading}
|
||||
profiles={filteredProfiles}
|
||||
totalProfileCount={allProfiles.length}
|
||||
recId={data?.recId}
|
||||
error={error}
|
||||
viewContext="profile"
|
||||
onDismiss={onDismiss}
|
||||
dismissingDids={dismissingDids}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -329,46 +319,36 @@ export function SuggestedFollowsHome() {
|
||||
error: suggestionsError,
|
||||
} = useSuggestedFollowsQuery({limit: 25})
|
||||
|
||||
const [dismissedDids, setDismissedDids] = React.useState<Set<string>>(
|
||||
new Set(),
|
||||
)
|
||||
const [dismissingDids, setDismissingDids] = React.useState<Set<string>>(
|
||||
new Set(),
|
||||
)
|
||||
const [dismissedDids, setDismissedDids] = useState<Set<string>>(new Set())
|
||||
|
||||
const onDismiss = React.useCallback((did: string) => {
|
||||
// Start the fade animation
|
||||
setDismissingDids(prev => new Set(prev).add(did))
|
||||
// After animation completes, actually remove from list
|
||||
setTimeout(() => {
|
||||
setDismissedDids(prev => new Set(prev).add(did))
|
||||
setDismissingDids(prev => {
|
||||
const next = new Set(prev)
|
||||
next.delete(did)
|
||||
return next
|
||||
})
|
||||
}, DISMISS_ANIMATION_DURATION)
|
||||
const onDismiss = useCallback((did: string) => {
|
||||
setDismissedDids(prev => new Set(prev).add(did))
|
||||
}, [])
|
||||
|
||||
// Combine profiles from experimental query with paginated suggestions
|
||||
const allProfiles = React.useMemo(() => {
|
||||
const allProfiles = useMemo(() => {
|
||||
const fallbackProfiles =
|
||||
moreSuggestions?.pages.flatMap(page => page.actors) ?? []
|
||||
moreSuggestions?.pages.flatMap(page =>
|
||||
page.actors.map(actor => ({actor, recId: page.recId})),
|
||||
) ?? []
|
||||
|
||||
// Dedupe by did, preferring experimental profiles
|
||||
const seen = new Set<string>()
|
||||
const combined: bsky.profile.AnyProfileView[] = []
|
||||
const combined: Array<{
|
||||
actor: bsky.profile.AnyProfileView
|
||||
recId?: number
|
||||
}> = []
|
||||
|
||||
for (const profile of experimentalProfiles) {
|
||||
if (!seen.has(profile.did)) {
|
||||
seen.add(profile.did)
|
||||
combined.push(profile)
|
||||
combined.push({actor: profile, recId: undefined})
|
||||
}
|
||||
}
|
||||
|
||||
for (const profile of fallbackProfiles) {
|
||||
if (!seen.has(profile.did)) {
|
||||
seen.add(profile.did)
|
||||
if (!seen.has(profile.actor.did)) {
|
||||
seen.add(profile.actor.did)
|
||||
combined.push(profile)
|
||||
}
|
||||
}
|
||||
@@ -376,19 +356,19 @@ export function SuggestedFollowsHome() {
|
||||
return combined
|
||||
}, [experimentalProfiles, moreSuggestions?.pages])
|
||||
|
||||
const filteredProfiles = React.useMemo(() => {
|
||||
return allProfiles.filter(p => !dismissedDids.has(p.did))
|
||||
const filteredProfiles = useMemo(() => {
|
||||
return allProfiles.filter(p => !dismissedDids.has(p.actor.did))
|
||||
}, [allProfiles, dismissedDids])
|
||||
|
||||
// Fetch more when running low
|
||||
React.useEffect(() => {
|
||||
useEffect(() => {
|
||||
if (
|
||||
moderationOpts &&
|
||||
filteredProfiles.length < maxLength &&
|
||||
hasNextPage &&
|
||||
!isFetchingNextPage
|
||||
) {
|
||||
fetchNextPage()
|
||||
void fetchNextPage()
|
||||
}
|
||||
}, [
|
||||
filteredProfiles.length,
|
||||
@@ -407,7 +387,6 @@ export function SuggestedFollowsHome() {
|
||||
error={experimentalError || suggestionsError}
|
||||
viewContext="feed"
|
||||
onDismiss={onDismiss}
|
||||
dismissingDids={dismissingDids}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -417,25 +396,21 @@ export function ProfileGrid({
|
||||
error,
|
||||
profiles,
|
||||
totalProfileCount,
|
||||
recId,
|
||||
viewContext = 'feed',
|
||||
onDismiss,
|
||||
dismissingDids,
|
||||
isVisible = true,
|
||||
}: {
|
||||
isSuggestionsLoading: boolean
|
||||
profiles: bsky.profile.AnyProfileView[]
|
||||
profiles: {actor: bsky.profile.AnyProfileView; recId?: number}[]
|
||||
totalProfileCount?: number
|
||||
recId?: number
|
||||
error: Error | null
|
||||
dismissingDids?: Set<string>
|
||||
viewContext: 'profile' | 'profileHeader' | 'feed'
|
||||
onDismiss?: (did: string) => void
|
||||
isVisible?: boolean
|
||||
}) {
|
||||
const t = useTheme()
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const gate = useGate()
|
||||
const moderationOpts = useModerationOpts()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
const followDialogControl = useDialogControl()
|
||||
@@ -443,7 +418,6 @@ export function ProfileGrid({
|
||||
const isLoading = isSuggestionsLoading || !moderationOpts
|
||||
const isProfileHeaderContext = viewContext === 'profileHeader'
|
||||
const isFeedContext = viewContext === 'feed'
|
||||
const showDismissButton = onDismiss && gate('suggested_users_dismiss')
|
||||
|
||||
const maxLength = gtMobile ? 3 : isProfileHeaderContext ? 12 : 6
|
||||
const minLength = gtMobile ? 3 : 4
|
||||
@@ -452,12 +426,11 @@ export function ProfileGrid({
|
||||
const seenProfilesRef = useRef<Set<string>>(new Set())
|
||||
const containerRef = useRef<View>(null)
|
||||
const hasTrackedRef = useRef(false)
|
||||
const logContext: MetricEvents['suggestedUser:seen']['logContext'] =
|
||||
isFeedContext
|
||||
? 'InterstitialDiscover'
|
||||
: isProfileHeaderContext
|
||||
? 'Profile'
|
||||
: 'InterstitialProfile'
|
||||
const logContext: Metrics['suggestedUser:seen']['logContext'] = isFeedContext
|
||||
? 'InterstitialDiscover'
|
||||
: isProfileHeaderContext
|
||||
? 'Profile'
|
||||
: 'InterstitialProfile'
|
||||
|
||||
// Callback to fire seen events
|
||||
const fireSeen = useCallback(() => {
|
||||
@@ -467,22 +440,18 @@ export function ProfileGrid({
|
||||
|
||||
const profilesToShow = profiles.slice(0, maxLength)
|
||||
profilesToShow.forEach((profile, index) => {
|
||||
if (!seenProfilesRef.current.has(profile.did)) {
|
||||
seenProfilesRef.current.add(profile.did)
|
||||
logger.metric(
|
||||
'suggestedUser:seen',
|
||||
{
|
||||
logContext,
|
||||
recId,
|
||||
position: index,
|
||||
suggestedDid: profile.did,
|
||||
category: null,
|
||||
},
|
||||
{statsig: true},
|
||||
)
|
||||
if (!seenProfilesRef.current.has(profile.actor.did)) {
|
||||
seenProfilesRef.current.add(profile.actor.did)
|
||||
ax.metric('suggestedUser:seen', {
|
||||
logContext,
|
||||
recId: profile.recId,
|
||||
position: index,
|
||||
suggestedDid: profile.actor.did,
|
||||
category: null,
|
||||
})
|
||||
}
|
||||
})
|
||||
}, [isLoading, error, profiles, maxLength, logContext, recId])
|
||||
}, [ax, isLoading, error, profiles, maxLength, logContext])
|
||||
|
||||
// For profile header, fire when isVisible becomes true
|
||||
useEffect(() => {
|
||||
@@ -548,8 +517,15 @@ export function ProfileGrid({
|
||||
? null
|
||||
: profiles.slice(0, maxLength).map((profile, index) => (
|
||||
<Animated.View
|
||||
key={profile.did}
|
||||
layout={LinearTransition.duration(DISMISS_ANIMATION_DURATION)}
|
||||
key={profile.actor.did}
|
||||
layout={native(
|
||||
LinearTransition.delay(DISMISS_ANIMATION_DURATION).easing(
|
||||
Easing.out(Easing.exp),
|
||||
),
|
||||
)}
|
||||
exiting={FadeOut.duration(DISMISS_ANIMATION_DURATION)}
|
||||
// for web, as the cards are static, not in a list
|
||||
entering={web(FadeIn.delay(DISMISS_ANIMATION_DURATION * 2))}
|
||||
style={[
|
||||
a.flex_1,
|
||||
gtMobile &&
|
||||
@@ -558,22 +534,17 @@ export function ProfileGrid({
|
||||
a.flex_grow,
|
||||
{width: `calc(30% - ${a.gap_md.gap / 2}px)`},
|
||||
]),
|
||||
{
|
||||
opacity: dismissingDids?.has(profile.did) ? 0 : 1,
|
||||
transitionProperty: 'opacity',
|
||||
transitionDuration: `${DISMISS_ANIMATION_DURATION}ms`,
|
||||
},
|
||||
]}>
|
||||
<ProfileCard.Link
|
||||
profile={profile}
|
||||
profile={profile.actor}
|
||||
onPress={() => {
|
||||
logEvent('suggestedUser:press', {
|
||||
ax.metric('suggestedUser:press', {
|
||||
logContext: isFeedContext
|
||||
? 'InterstitialDiscover'
|
||||
: 'InterstitialProfile',
|
||||
recId,
|
||||
recId: profile.recId,
|
||||
position: index,
|
||||
suggestedDid: profile.did,
|
||||
suggestedDid: profile.actor.did,
|
||||
category: null,
|
||||
})
|
||||
}}
|
||||
@@ -584,19 +555,19 @@ export function ProfileGrid({
|
||||
(hovered || pressed) && t.atoms.border_contrast_high,
|
||||
]}>
|
||||
<ProfileCard.Outer>
|
||||
{showDismissButton && (
|
||||
{onDismiss && (
|
||||
<Button
|
||||
label={_(msg`Dismiss this suggestion`)}
|
||||
onPress={e => {
|
||||
e.preventDefault()
|
||||
onDismiss!(profile.did)
|
||||
logEvent('suggestedUser:dismiss', {
|
||||
onDismiss(profile.actor.did)
|
||||
ax.metric('suggestedUser:dismiss', {
|
||||
logContext: isFeedContext
|
||||
? 'InterstitialDiscover'
|
||||
: 'InterstitialProfile',
|
||||
position: index,
|
||||
suggestedDid: profile.did,
|
||||
recId,
|
||||
suggestedDid: profile.actor.did,
|
||||
recId: profile.recId,
|
||||
})
|
||||
}}
|
||||
style={[
|
||||
@@ -629,18 +600,18 @@ export function ProfileGrid({
|
||||
a.mb_auto,
|
||||
]}>
|
||||
<ProfileCard.Avatar
|
||||
profile={profile}
|
||||
profile={profile.actor}
|
||||
moderationOpts={moderationOpts}
|
||||
disabledPreview
|
||||
size={88}
|
||||
/>
|
||||
<View style={[a.flex_col, a.align_center, a.max_w_full]}>
|
||||
<ProfileCard.Name
|
||||
profile={profile}
|
||||
profile={profile.actor}
|
||||
moderationOpts={moderationOpts}
|
||||
/>
|
||||
<ProfileCard.Description
|
||||
profile={profile}
|
||||
profile={profile.actor}
|
||||
numberOfLines={2}
|
||||
style={[
|
||||
t.atoms.text_contrast_medium,
|
||||
@@ -652,20 +623,20 @@ export function ProfileGrid({
|
||||
</View>
|
||||
|
||||
<ProfileCard.FollowButton
|
||||
profile={profile}
|
||||
profile={profile.actor}
|
||||
moderationOpts={moderationOpts}
|
||||
logContext="FeedInterstitial"
|
||||
withIcon={false}
|
||||
style={[a.rounded_sm]}
|
||||
onFollow={() => {
|
||||
logEvent('suggestedUser:follow', {
|
||||
ax.metric('suggestedUser:follow', {
|
||||
logContext: isFeedContext
|
||||
? 'InterstitialDiscover'
|
||||
: 'InterstitialProfile',
|
||||
location: 'Card',
|
||||
recId,
|
||||
recId: profile.recId,
|
||||
position: index,
|
||||
suggestedDid: profile.did,
|
||||
suggestedDid: profile.actor.did,
|
||||
category: null,
|
||||
})
|
||||
}}
|
||||
@@ -680,7 +651,7 @@ export function ProfileGrid({
|
||||
// Use totalProfileCount (before dismissals) for minLength check on initial render.
|
||||
const profileCountForMinCheck = totalProfileCount ?? profiles.length
|
||||
if (error || (!isLoading && profileCountForMinCheck < minLength)) {
|
||||
logger.debug(`Not enough profiles to show suggested follows`)
|
||||
ax.logger.debug(`Not enough profiles to show suggested follows`)
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -703,18 +674,14 @@ export function ProfileGrid({
|
||||
]}
|
||||
pointerEvents={IS_IOS ? 'auto' : 'box-none'}>
|
||||
<Text style={[a.text_sm, a.font_semi_bold, t.atoms.text]}>
|
||||
{isFeedContext ? (
|
||||
<Trans>Suggested for you</Trans>
|
||||
) : (
|
||||
<Trans>Similar accounts</Trans>
|
||||
)}
|
||||
<Trans>Suggested for you</Trans>
|
||||
</Text>
|
||||
{!isProfileHeaderContext && (
|
||||
<Button
|
||||
label={_(msg`See more suggested profiles`)}
|
||||
onPress={() => {
|
||||
followDialogControl.open()
|
||||
logEvent('suggestedUser:seeMore', {
|
||||
ax.metric('suggestedUser:seeMore', {
|
||||
logContext: isFeedContext ? 'Explore' : 'Profile',
|
||||
})
|
||||
}}>
|
||||
@@ -738,35 +705,37 @@ export function ProfileGrid({
|
||||
|
||||
<FollowDialogWithoutGuide control={followDialogControl} />
|
||||
|
||||
{gtMobile ? (
|
||||
<View style={[a.p_lg, a.pt_md]}>
|
||||
<View style={[a.flex_1, a.flex_row, a.flex_wrap, a.gap_md]}>
|
||||
{content}
|
||||
<LayoutAnimationConfig skipExiting skipEntering>
|
||||
{gtMobile ? (
|
||||
<View style={[a.p_lg, a.pt_md]}>
|
||||
<View style={[a.flex_1, a.flex_row, a.flex_wrap, a.gap_md]}>
|
||||
{content}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<BlockDrawerGesture>
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={[a.p_lg, a.pt_md, a.flex_row, a.gap_md]}
|
||||
snapToInterval={MOBILE_CARD_WIDTH + a.gap_md.gap}
|
||||
decelerationRate="fast">
|
||||
{content}
|
||||
) : (
|
||||
<BlockDrawerGesture>
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={[a.p_lg, a.pt_md, a.flex_row, a.gap_md]}
|
||||
snapToInterval={MOBILE_CARD_WIDTH + a.gap_md.gap}
|
||||
decelerationRate="fast">
|
||||
{content}
|
||||
|
||||
{!isProfileHeaderContext && (
|
||||
<SeeMoreSuggestedProfilesCard
|
||||
onPress={() => {
|
||||
followDialogControl.open()
|
||||
logger.metric('suggestedUser:seeMore', {
|
||||
logContext: 'Explore',
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</ScrollView>
|
||||
</BlockDrawerGesture>
|
||||
)}
|
||||
{!isProfileHeaderContext && (
|
||||
<SeeMoreSuggestedProfilesCard
|
||||
onPress={() => {
|
||||
followDialogControl.open()
|
||||
ax.metric('suggestedUser:seeMore', {
|
||||
logContext: 'Explore',
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</ScrollView>
|
||||
</BlockDrawerGesture>
|
||||
)}
|
||||
</LayoutAnimationConfig>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -796,9 +765,10 @@ function SeeMoreSuggestedProfilesCard({onPress}: {onPress: () => void}) {
|
||||
)
|
||||
}
|
||||
|
||||
const numFeedsToDisplay = 3
|
||||
export function SuggestedFeeds() {
|
||||
const numFeedsToDisplay = 3
|
||||
const t = useTheme()
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const {data, isLoading, error} = useGetPopularFeedsQuery({
|
||||
limit: numFeedsToDisplay,
|
||||
@@ -806,7 +776,7 @@ export function SuggestedFeeds() {
|
||||
const navigation = useNavigation<NavigationProp>()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
|
||||
const feeds = React.useMemo(() => {
|
||||
const feeds = useMemo(() => {
|
||||
const items: AppBskyFeedDefs.GeneratorView[] = []
|
||||
|
||||
if (!data) return items
|
||||
@@ -831,7 +801,7 @@ export function SuggestedFeeds() {
|
||||
key={feed.uri}
|
||||
view={feed}
|
||||
onPress={() => {
|
||||
logEvent('feed:interstitial:feedCard:press', {})
|
||||
ax.metric('feed:interstitial:feedCard:press', {})
|
||||
}}>
|
||||
{({hovered, pressed}) => (
|
||||
<CardOuter
|
||||
|
||||
@@ -157,7 +157,7 @@ export function Link({
|
||||
to={{
|
||||
screen: 'Profile',
|
||||
params: {
|
||||
name: labeler.creator.handle,
|
||||
name: labeler.creator.did,
|
||||
},
|
||||
}}
|
||||
label={_(
|
||||
|
||||
@@ -50,7 +50,11 @@ export function Embed({
|
||||
} else if (e.type === 'video') {
|
||||
return (
|
||||
<Outer style={style}>
|
||||
<VideoItem thumbnail={e.view.thumbnail} alt={e.view.alt} />
|
||||
{e.view.presentation === 'gif' ? (
|
||||
<GifItem thumbnail={e.view.thumbnail} alt={e.view.alt} />
|
||||
) : (
|
||||
<VideoItem thumbnail={e.view.thumbnail} alt={e.view.alt} />
|
||||
)}
|
||||
</Outer>
|
||||
)
|
||||
} else if (
|
||||
@@ -81,11 +85,29 @@ export function ImageItem({
|
||||
alt,
|
||||
children,
|
||||
}: {
|
||||
thumbnail: string
|
||||
thumbnail?: string
|
||||
alt?: string
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
const t = useTheme()
|
||||
|
||||
if (!thumbnail) {
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
{backgroundColor: 'black'},
|
||||
a.flex_1,
|
||||
a.aspect_square,
|
||||
{maxWidth: 100},
|
||||
a.rounded_xs,
|
||||
]}
|
||||
accessibilityLabel={alt}
|
||||
accessibilityHint="">
|
||||
{children}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={[a.relative, a.flex_1, a.aspect_square, {maxWidth: 100}]}>
|
||||
<Image
|
||||
@@ -103,7 +125,7 @@ export function ImageItem({
|
||||
)
|
||||
}
|
||||
|
||||
export function GifItem({thumbnail, alt}: {thumbnail: string; alt?: string}) {
|
||||
export function GifItem({thumbnail, alt}: {thumbnail?: string; alt?: string}) {
|
||||
return (
|
||||
<ImageItem thumbnail={thumbnail} alt={alt}>
|
||||
<View style={[a.absolute, a.inset_0, a.justify_center, a.align_center]}>
|
||||
@@ -125,21 +147,6 @@ export function VideoItem({
|
||||
thumbnail?: string
|
||||
alt?: string
|
||||
}) {
|
||||
if (!thumbnail) {
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
{backgroundColor: 'black'},
|
||||
a.flex_1,
|
||||
a.aspect_square,
|
||||
{maxWidth: 100},
|
||||
a.justify_center,
|
||||
a.align_center,
|
||||
]}>
|
||||
<PlayButtonIcon size={24} />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<ImageItem thumbnail={thumbnail} alt={alt}>
|
||||
<View style={[a.absolute, a.inset_0, a.justify_center, a.align_center]}>
|
||||
@@ -156,7 +163,7 @@ const styles = StyleSheet.create({
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 3,
|
||||
position: 'absolute',
|
||||
right: 5,
|
||||
left: 5,
|
||||
bottom: 5,
|
||||
zIndex: 2,
|
||||
},
|
||||
|
||||
@@ -1,76 +1,17 @@
|
||||
import React from 'react'
|
||||
import {
|
||||
Pressable,
|
||||
type StyleProp,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
View,
|
||||
type ViewStyle,
|
||||
} from 'react-native'
|
||||
import {msg, Trans} from '@lingui/macro'
|
||||
import {useRef, useState} from 'react'
|
||||
import {type StyleProp, View, type ViewStyle} from 'react-native'
|
||||
import {msg} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
|
||||
import {HITSLOP_20} from '#/lib/constants'
|
||||
import {clamp} from '#/lib/numbers'
|
||||
import {type EmbedPlayerParams} from '#/lib/strings/embed-player'
|
||||
import {useAutoplayDisabled} from '#/state/preferences'
|
||||
import {useLargeAltBadgeEnabled} from '#/state/preferences/large-alt-badge'
|
||||
import {atoms as a, useTheme} from '#/alf'
|
||||
import {Fill} from '#/components/Fill'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import * as Prompt from '#/components/Prompt'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {PlayButtonIcon} from '#/components/video/PlayButtonIcon'
|
||||
import {IS_WEB} from '#/env'
|
||||
import {MediaInsetBorder} from '#/components/MediaInsetBorder'
|
||||
import {GifView} from '../../../../../modules/expo-bluesky-gif-view'
|
||||
import {type GifViewStateChangeEvent} from '../../../../../modules/expo-bluesky-gif-view/src/GifView.types'
|
||||
|
||||
function PlaybackControls({
|
||||
onPress,
|
||||
isPlaying,
|
||||
isLoaded,
|
||||
}: {
|
||||
onPress: () => void
|
||||
isPlaying: boolean
|
||||
isLoaded: boolean
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const t = useTheme()
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityHint={_(msg`Plays or pauses the GIF`)}
|
||||
accessibilityLabel={isPlaying ? _(msg`Pause`) : _(msg`Play`)}
|
||||
style={[
|
||||
a.absolute,
|
||||
a.align_center,
|
||||
a.justify_center,
|
||||
!isLoaded && a.border,
|
||||
t.atoms.border_contrast_medium,
|
||||
a.inset_0,
|
||||
a.w_full,
|
||||
a.h_full,
|
||||
{
|
||||
zIndex: 2,
|
||||
backgroundColor: !isLoaded
|
||||
? t.atoms.bg_contrast_25.backgroundColor
|
||||
: undefined,
|
||||
},
|
||||
]}
|
||||
onPress={onPress}>
|
||||
{!isLoaded ? (
|
||||
<View>
|
||||
<View style={[a.align_center, a.justify_center]}>
|
||||
<Loader size="xl" />
|
||||
</View>
|
||||
</View>
|
||||
) : !isPlaying ? (
|
||||
<PlayButtonIcon />
|
||||
) : undefined}
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
import {GifPresentationControls} from '../VideoEmbed/GifPresentationControls'
|
||||
|
||||
export function GifEmbed({
|
||||
params,
|
||||
@@ -91,9 +32,9 @@ export function GifEmbed({
|
||||
const {_} = useLingui()
|
||||
const autoplayDisabled = useAutoplayDisabled()
|
||||
|
||||
const playerRef = React.useRef<GifView>(null)
|
||||
const playerRef = useRef<GifView>(null)
|
||||
|
||||
const [playerState, setPlayerState] = React.useState<{
|
||||
const [playerState, setPlayerState] = useState<{
|
||||
isPlaying: boolean
|
||||
isLoaded: boolean
|
||||
}>({
|
||||
@@ -101,24 +42,18 @@ export function GifEmbed({
|
||||
isLoaded: false,
|
||||
})
|
||||
|
||||
const onPlayerStateChange = React.useCallback(
|
||||
(e: GifViewStateChangeEvent) => {
|
||||
setPlayerState(e.nativeEvent)
|
||||
},
|
||||
[],
|
||||
)
|
||||
const onPlayerStateChange = (e: GifViewStateChangeEvent) => {
|
||||
setPlayerState(e.nativeEvent)
|
||||
}
|
||||
|
||||
const onPress = React.useCallback(() => {
|
||||
playerRef.current?.toggleAsync()
|
||||
}, [])
|
||||
const onPress = () => {
|
||||
void playerRef.current?.toggleAsync()
|
||||
}
|
||||
|
||||
let aspectRatio = 1
|
||||
if (params.dimensions) {
|
||||
aspectRatio = clamp(
|
||||
params.dimensions.width / params.dimensions.height,
|
||||
0.75,
|
||||
4,
|
||||
)
|
||||
const ratio = params.dimensions.width / params.dimensions.height
|
||||
aspectRatio = clamp(ratio, 0.75, 4)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -126,8 +61,6 @@ export function GifEmbed({
|
||||
style={[
|
||||
a.rounded_md,
|
||||
a.overflow_hidden,
|
||||
a.border,
|
||||
t.atoms.border_contrast_low,
|
||||
{backgroundColor: t.palette.black},
|
||||
{aspectRatio},
|
||||
style,
|
||||
@@ -145,10 +78,12 @@ export function GifEmbed({
|
||||
right: -2,
|
||||
},
|
||||
]}>
|
||||
<PlaybackControls
|
||||
<MediaInsetBorder />
|
||||
<GifPresentationControls
|
||||
onPress={onPress}
|
||||
isPlaying={playerState.isPlaying}
|
||||
isLoaded={playerState.isLoaded}
|
||||
isLoading={!playerState.isLoaded}
|
||||
altText={!hideAlt && isPreferredAltText ? altText : undefined}
|
||||
/>
|
||||
<GifView
|
||||
source={params.playerUri}
|
||||
@@ -170,66 +105,7 @@ export function GifEmbed({
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
{!hideAlt && isPreferredAltText && <AltText text={altText} />}
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function AltText({text}: {text: string}) {
|
||||
const control = Prompt.usePromptControl()
|
||||
const largeAltBadge = useLargeAltBadgeEnabled()
|
||||
|
||||
const {_} = useLingui()
|
||||
return (
|
||||
<>
|
||||
<TouchableOpacity
|
||||
testID="altTextButton"
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={_(msg`Show alt text`)}
|
||||
accessibilityHint=""
|
||||
hitSlop={HITSLOP_20}
|
||||
onPress={control.open}
|
||||
style={styles.altContainer}>
|
||||
<Text
|
||||
style={[styles.alt, largeAltBadge && a.text_xs]}
|
||||
accessible={false}>
|
||||
<Trans>ALT</Trans>
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
<Prompt.Outer control={control}>
|
||||
<Prompt.TitleText>
|
||||
<Trans>Alt Text</Trans>
|
||||
</Prompt.TitleText>
|
||||
<Prompt.DescriptionText selectable>{text}</Prompt.DescriptionText>
|
||||
<Prompt.Actions>
|
||||
<Prompt.Action
|
||||
onPress={() => control.close()}
|
||||
cta={_(msg`Close`)}
|
||||
color="secondary"
|
||||
/>
|
||||
</Prompt.Actions>
|
||||
</Prompt.Outer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
altContainer: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.75)',
|
||||
borderRadius: 6,
|
||||
paddingHorizontal: IS_WEB ? 8 : 6,
|
||||
paddingVertical: IS_WEB ? 6 : 3,
|
||||
position: 'absolute',
|
||||
// Related to margin/gap hack. This keeps the alt label in the same position
|
||||
// on all platforms
|
||||
right: IS_WEB ? 8 : 5,
|
||||
bottom: IS_WEB ? 8 : 5,
|
||||
zIndex: 2,
|
||||
},
|
||||
alt: {
|
||||
color: 'white',
|
||||
fontSize: IS_WEB ? 10 : 7,
|
||||
fontWeight: '600',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import {
|
||||
ActivityIndicator,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
View,
|
||||
} from 'react-native'
|
||||
import {msg, Trans} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
|
||||
import {HITSLOP_20} from '#/lib/constants'
|
||||
import {atoms as a, useTheme} from '#/alf'
|
||||
import {Button} from '#/components/Button'
|
||||
import {Fill} from '#/components/Fill'
|
||||
import * as Prompt from '#/components/Prompt'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {PlayButtonIcon} from '#/components/video/PlayButtonIcon'
|
||||
|
||||
export function GifPresentationControls({
|
||||
onPress,
|
||||
isPlaying,
|
||||
isLoading,
|
||||
altText,
|
||||
}: {
|
||||
onPress: () => void
|
||||
isPlaying: boolean
|
||||
isLoading?: boolean
|
||||
altText?: string
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const t = useTheme()
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
label={isPlaying ? _(msg`Pause GIF`) : _(msg`Play GIF`)}
|
||||
accessibilityHint={_(msg`Plays or pauses the GIF`)}
|
||||
style={[
|
||||
a.absolute,
|
||||
a.align_center,
|
||||
a.justify_center,
|
||||
a.inset_0,
|
||||
{zIndex: 2},
|
||||
]}
|
||||
onPress={onPress}>
|
||||
{isLoading ? (
|
||||
<View style={[a.align_center, a.justify_center]}>
|
||||
<ActivityIndicator size="large" color="white" />
|
||||
</View>
|
||||
) : !isPlaying ? (
|
||||
<PlayButtonIcon />
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</Button>
|
||||
{!isPlaying && (
|
||||
<Fill
|
||||
style={[
|
||||
t.name === 'light' ? t.atoms.bg_contrast_975 : t.atoms.bg,
|
||||
{
|
||||
opacity: 0.2,
|
||||
zIndex: 1,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<View style={styles.gifBadgeContainer}>
|
||||
<Text style={[{color: 'white'}, a.font_bold, a.text_xs]}>
|
||||
<Trans>GIF</Trans>
|
||||
</Text>
|
||||
</View>
|
||||
{altText && <AltBadge text={altText} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function AltBadge({text}: {text: string}) {
|
||||
const control = Prompt.usePromptControl()
|
||||
const {_} = useLingui()
|
||||
|
||||
return (
|
||||
<>
|
||||
<TouchableOpacity
|
||||
testID="altTextButton"
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={_(msg`Show alt text`)}
|
||||
accessibilityHint=""
|
||||
hitSlop={HITSLOP_20}
|
||||
onPress={control.open}
|
||||
style={styles.altBadgeContainer}>
|
||||
<Text
|
||||
style={[{color: 'white'}, a.font_bold, a.text_xs]}
|
||||
accessible={false}>
|
||||
<Trans>ALT</Trans>
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
<Prompt.Outer control={control}>
|
||||
<Prompt.Content>
|
||||
<Prompt.TitleText>
|
||||
<Trans>Alt Text</Trans>
|
||||
</Prompt.TitleText>
|
||||
<Prompt.DescriptionText selectable>{text}</Prompt.DescriptionText>
|
||||
</Prompt.Content>
|
||||
<Prompt.Actions>
|
||||
<Prompt.Action
|
||||
onPress={() => control.close()}
|
||||
cta={_(msg`Close`)}
|
||||
color="secondary"
|
||||
/>
|
||||
</Prompt.Actions>
|
||||
</Prompt.Outer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
gifBadgeContainer: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.75)',
|
||||
borderRadius: 6,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 3,
|
||||
position: 'absolute',
|
||||
left: 6,
|
||||
bottom: 6,
|
||||
zIndex: 2,
|
||||
},
|
||||
altBadgeContainer: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.75)',
|
||||
borderRadius: 6,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 3,
|
||||
position: 'absolute',
|
||||
right: 6,
|
||||
bottom: 6,
|
||||
zIndex: 2,
|
||||
},
|
||||
})
|
||||
@@ -15,6 +15,7 @@ import {Play_Filled_Corner0_Rounded as PlayIcon} from '#/components/icons/Play'
|
||||
import {SpeakerVolumeFull_Stroke2_Corner0_Rounded as UnmuteIcon} from '#/components/icons/Speaker'
|
||||
import {MediaInsetBorder} from '#/components/MediaInsetBorder'
|
||||
import {useVideoMuteState} from '#/components/Post/Embed/VideoEmbed/VideoVolumeContext'
|
||||
import {GifPresentationControls} from '../GifPresentationControls'
|
||||
import {TimeIndicator} from './TimeIndicator'
|
||||
|
||||
export function VideoEmbedInnerNative({
|
||||
@@ -50,12 +51,14 @@ export function VideoEmbedInnerNative({
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
const isGif = embed.presentation === 'gif'
|
||||
|
||||
return (
|
||||
<View style={[a.flex_1, a.relative]}>
|
||||
<BlueskyVideoView
|
||||
url={embed.playlist}
|
||||
autoplay={!autoplayDisabled && !isWithinMessage}
|
||||
beginMuted={autoplayDisabled ? false : muted}
|
||||
beginMuted={isGif || autoplayDisabled ? false : muted}
|
||||
style={[a.rounded_sm]}
|
||||
onActiveChange={e => {
|
||||
setIsActive(e.nativeEvent.isActive)
|
||||
@@ -82,25 +85,36 @@ export function VideoEmbedInnerNative({
|
||||
}
|
||||
accessibilityHint=""
|
||||
/>
|
||||
<VideoControls
|
||||
enterFullscreen={() => {
|
||||
videoRef.current?.enterFullscreen(true)
|
||||
}}
|
||||
toggleMuted={() => {
|
||||
videoRef.current?.toggleMuted()
|
||||
}}
|
||||
togglePlayback={() => {
|
||||
videoRef.current?.togglePlayback()
|
||||
}}
|
||||
isPlaying={isPlaying}
|
||||
timeRemaining={timeRemaining}
|
||||
/>
|
||||
{isGif ? (
|
||||
<GifPresentationControls
|
||||
onPress={() => {
|
||||
videoRef.current?.togglePlayback()
|
||||
}}
|
||||
isPlaying={isPlaying}
|
||||
isLoading={false}
|
||||
altText={embed.alt}
|
||||
/>
|
||||
) : (
|
||||
<VideoPresentationControls
|
||||
enterFullscreen={() => {
|
||||
videoRef.current?.enterFullscreen(true)
|
||||
}}
|
||||
toggleMuted={() => {
|
||||
videoRef.current?.toggleMuted()
|
||||
}}
|
||||
togglePlayback={() => {
|
||||
videoRef.current?.togglePlayback()
|
||||
}}
|
||||
isPlaying={isPlaying}
|
||||
timeRemaining={timeRemaining}
|
||||
/>
|
||||
)}
|
||||
<MediaInsetBorder />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function VideoControls({
|
||||
function VideoPresentationControls({
|
||||
enterFullscreen,
|
||||
toggleMuted,
|
||||
togglePlayback,
|
||||
|
||||
@@ -21,7 +21,7 @@ export function VideoEmbedInnerWeb({
|
||||
active: boolean
|
||||
setActive: () => void
|
||||
onScreen: boolean
|
||||
lastKnownTime: React.MutableRefObject<number | undefined>
|
||||
lastKnownTime: React.RefObject<number | undefined>
|
||||
}) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const videoRef = useRef<HTMLVideoElement>(null)
|
||||
@@ -37,7 +37,7 @@ export function VideoEmbedInnerWeb({
|
||||
throw error
|
||||
}
|
||||
|
||||
const hlsRef = useHLS({
|
||||
const {hlsRef, loop} = useHLS({
|
||||
playlist: embed.playlist,
|
||||
setHasSubtitleTrack,
|
||||
setError,
|
||||
@@ -64,11 +64,12 @@ export function VideoEmbedInnerWeb({
|
||||
style={{width: '100%', height: '100%', objectFit: 'contain'}}
|
||||
playsInline
|
||||
preload="none"
|
||||
muted={!focused}
|
||||
muted={embed.presentation === 'gif' || !focused}
|
||||
aria-labelledby={embed.alt ? figId : undefined}
|
||||
onTimeUpdate={e => {
|
||||
lastKnownTime.current = e.currentTarget.currentTime
|
||||
}}
|
||||
loop={loop}
|
||||
/>
|
||||
{embed.alt && (
|
||||
<figcaption
|
||||
@@ -99,6 +100,8 @@ export function VideoEmbedInnerWeb({
|
||||
onScreen={onScreen}
|
||||
fullscreenRef={containerRef}
|
||||
hasSubtitleTrack={hasSubtitleTrack}
|
||||
isGif={embed.presentation === 'gif'}
|
||||
altText={embed.alt}
|
||||
/>
|
||||
</div>
|
||||
</View>
|
||||
@@ -192,29 +195,6 @@ function useHLS({
|
||||
},
|
||||
)
|
||||
|
||||
const flushOnLoop = useNonReactiveCallback(() => {
|
||||
if (!Hls) return
|
||||
if (!hlsRef.current) return
|
||||
const hls = hlsRef.current
|
||||
// the above callback will catch most stale frags, but there's a corner case -
|
||||
// if there's only one segment in the video, it won't get flushed because it avoids
|
||||
// flushing the currently active segment. Therefore, we have to catch it when we loop
|
||||
if (
|
||||
hls.nextAutoLevel > 0 &&
|
||||
lowQualityFragments.length === 1 &&
|
||||
lowQualityFragments[0].start === 0
|
||||
) {
|
||||
const lowQualFrag = lowQualityFragments[0]
|
||||
|
||||
hls.trigger(Hls.Events.BUFFER_FLUSHING, {
|
||||
startOffset: lowQualFrag.start,
|
||||
endOffset: lowQualFrag.end,
|
||||
type: 'video',
|
||||
})
|
||||
setLowQualityFragments([])
|
||||
}
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!videoRef.current) return
|
||||
if (!Hls) return
|
||||
@@ -242,20 +222,6 @@ function useHLS({
|
||||
hls.attachMedia(videoRef.current)
|
||||
hls.loadSource(playlist)
|
||||
|
||||
// manually loop, so if we've flushed the first buffer it doesn't get confused
|
||||
const abortController = new AbortController()
|
||||
const {signal} = abortController
|
||||
const videoNode = videoRef.current
|
||||
videoNode.addEventListener(
|
||||
'ended',
|
||||
() => {
|
||||
flushOnLoop()
|
||||
videoNode.currentTime = 0
|
||||
videoNode.play()
|
||||
},
|
||||
{signal},
|
||||
)
|
||||
|
||||
hls.on(Hls.Events.FRAG_LOADED, () => {
|
||||
BandwidthEstimate.set(hls.bandwidthEstimate)
|
||||
})
|
||||
@@ -293,17 +259,65 @@ function useHLS({
|
||||
hlsRef.current = undefined
|
||||
hls.detachMedia()
|
||||
hls.destroy()
|
||||
}
|
||||
}, [playlist, setError, setHasSubtitleTrack, videoRef, handleFragChange, Hls])
|
||||
|
||||
const flushOnLoop = useNonReactiveCallback(() => {
|
||||
if (!Hls) return
|
||||
if (!hlsRef.current) return
|
||||
const hls = hlsRef.current
|
||||
// `handleFragChange` will catch most stale frags, but there's a corner case -
|
||||
// if there's only one segment in the video, it won't get flushed because it avoids
|
||||
// flushing the currently active segment. Therefore, we have to catch it when we loop
|
||||
if (
|
||||
hls.nextAutoLevel > 0 &&
|
||||
lowQualityFragments.length === 1 &&
|
||||
lowQualityFragments[0].start === 0
|
||||
) {
|
||||
const lowQualFrag = lowQualityFragments[0]
|
||||
|
||||
hls.trigger(Hls.Events.BUFFER_FLUSHING, {
|
||||
startOffset: lowQualFrag.start,
|
||||
endOffset: lowQualFrag.end,
|
||||
type: 'video',
|
||||
})
|
||||
setLowQualityFragments([])
|
||||
}
|
||||
})
|
||||
|
||||
// manually loop, so if we've flushed the first buffer it doesn't get confused
|
||||
const hasLowQualityFragmentAtStart = lowQualityFragments.some(
|
||||
frag => frag.start === 0,
|
||||
)
|
||||
useEffect(() => {
|
||||
if (!videoRef.current) return
|
||||
|
||||
// use `loop` prop on `<video>` element if the starting frag is high quality.
|
||||
// otherwise, we need to do it with an event listener as we may need to manually flush the frag
|
||||
if (!hasLowQualityFragmentAtStart) return
|
||||
|
||||
const abortController = new AbortController()
|
||||
const {signal} = abortController
|
||||
const videoNode = videoRef.current
|
||||
videoNode.addEventListener(
|
||||
'ended',
|
||||
() => {
|
||||
flushOnLoop()
|
||||
videoNode.currentTime = 0
|
||||
const maybePromise = videoNode.play() as Promise<void> | undefined
|
||||
if (maybePromise) {
|
||||
maybePromise.catch(() => {})
|
||||
}
|
||||
},
|
||||
{signal},
|
||||
)
|
||||
return () => {
|
||||
abortController.abort()
|
||||
}
|
||||
}, [
|
||||
playlist,
|
||||
setError,
|
||||
setHasSubtitleTrack,
|
||||
videoRef,
|
||||
handleFragChange,
|
||||
flushOnLoop,
|
||||
Hls,
|
||||
])
|
||||
}, [videoRef, flushOnLoop, hasLowQualityFragmentAtStart])
|
||||
|
||||
return hlsRef
|
||||
return {
|
||||
hlsRef,
|
||||
loop: !hasLowQualityFragmentAtStart,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import {Play_Filled_Corner0_Rounded as PlayIcon} from '#/components/icons/Play'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {IS_WEB_MOBILE_IOS, IS_WEB_TOUCH_DEVICE} from '#/env'
|
||||
import {GifPresentationControls} from '../../GifPresentationControls'
|
||||
import {TimeIndicator} from '../TimeIndicator'
|
||||
import {ControlButton} from './ControlButton'
|
||||
import {Scrubber} from './Scrubber'
|
||||
@@ -44,6 +45,8 @@ export function Controls({
|
||||
fullscreenRef,
|
||||
hlsLoading,
|
||||
hasSubtitleTrack,
|
||||
isGif,
|
||||
altText,
|
||||
}: {
|
||||
videoRef: React.RefObject<HTMLVideoElement | null>
|
||||
hlsRef: React.RefObject<Hls | undefined | null>
|
||||
@@ -55,6 +58,8 @@ export function Controls({
|
||||
fullscreenRef: React.RefObject<HTMLDivElement | null>
|
||||
hlsLoading: boolean
|
||||
hasSubtitleTrack: boolean
|
||||
isGif: boolean
|
||||
altText?: string
|
||||
}) {
|
||||
const {
|
||||
play,
|
||||
@@ -125,13 +130,14 @@ export function Controls({
|
||||
const autoplayDisabled = useAutoplayDisabled() || isWithinMessage
|
||||
useEffect(() => {
|
||||
if (active) {
|
||||
if (onScreen) {
|
||||
// GIFs play immediately, videos wait until onScreen
|
||||
if (onScreen || isGif) {
|
||||
if (!autoplayDisabled) play()
|
||||
} else {
|
||||
pause()
|
||||
}
|
||||
}
|
||||
}, [onScreen, pause, active, play, autoplayDisabled])
|
||||
}, [onScreen, pause, active, play, autoplayDisabled, isGif])
|
||||
|
||||
// use minimal quality when not focused
|
||||
useEffect(() => {
|
||||
@@ -287,6 +293,17 @@ export function Controls({
|
||||
((focused || autoplayDisabled) && !playing) ||
|
||||
(interactingViaKeypress ? hasFocus : hovered)
|
||||
|
||||
if (isGif) {
|
||||
return (
|
||||
<GifPresentationControls
|
||||
isPlaying={playing}
|
||||
isLoading={showSpinner}
|
||||
onPress={onPressPlayPause}
|
||||
altText={altText}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -312,13 +329,13 @@ export function Controls({
|
||||
onPointerEnter={onPointerMoveEmptySpace}
|
||||
onPointerMove={onPointerMoveEmptySpace}
|
||||
onPointerLeave={onPointerLeaveEmptySpace}
|
||||
accessibilityLabel={_(
|
||||
accessibilityLabel={
|
||||
!focused
|
||||
? msg`Unmute video`
|
||||
? _(msg`Unmute video`)
|
||||
: playing
|
||||
? msg`Pause video`
|
||||
: msg`Play video`,
|
||||
)}
|
||||
? _(msg`Pause video`)
|
||||
: _(msg`Play video`)
|
||||
}
|
||||
accessibilityHint=""
|
||||
style={[
|
||||
a.flex_1,
|
||||
|
||||
@@ -6,11 +6,12 @@ import {msg, Trans} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
|
||||
import {ErrorBoundary} from '#/view/com/util/ErrorBoundary'
|
||||
import {atoms as a} from '#/alf'
|
||||
import {atoms as a, platform} from '#/alf'
|
||||
import {Button} from '#/components/Button'
|
||||
import {useThrottledValue} from '#/components/hooks/useThrottledValue'
|
||||
import {ConstrainedImage} from '#/components/images/AutoSizedImage'
|
||||
import {PlayButtonIcon} from '#/components/video/PlayButtonIcon'
|
||||
import {GifPresentationControls} from './GifPresentationControls'
|
||||
import {VideoEmbedInnerNative} from './VideoEmbedInner/VideoEmbedInnerNative'
|
||||
import * as VideoFallback from './VideoEmbedInner/VideoFallback'
|
||||
|
||||
@@ -101,33 +102,40 @@ function InnerWrapper({embed}: Props) {
|
||||
{
|
||||
backgroundColor: 'transparent', // If you don't add `backgroundColor` to the styles here,
|
||||
// the play button won't show up on the first render on android 🥴😮💨
|
||||
display: showOverlay ? 'flex' : 'none',
|
||||
},
|
||||
platform({
|
||||
android: {display: showOverlay ? 'flex' : 'none'},
|
||||
ios: {zIndex: showOverlay ? 1 : -1},
|
||||
}),
|
||||
]}
|
||||
cachePolicy="memory-disk" // Preferring memory cache helps to avoid flicker when re-displaying on android
|
||||
>
|
||||
{showOverlay && (
|
||||
<Button
|
||||
style={[a.flex_1, a.align_center, a.justify_center]}
|
||||
onPress={() => {
|
||||
ref.current?.togglePlayback()
|
||||
}}
|
||||
label={_(msg`Play video`)}>
|
||||
{showSpinner ? (
|
||||
<View
|
||||
style={[
|
||||
a.rounded_full,
|
||||
a.p_xs,
|
||||
a.align_center,
|
||||
a.justify_center,
|
||||
]}>
|
||||
<ActivityIndicator size="large" color="white" />
|
||||
</View>
|
||||
) : (
|
||||
<PlayButtonIcon />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{showOverlay &&
|
||||
(embed.presentation === 'gif' ? (
|
||||
<GifPresentationControls
|
||||
isPlaying={false}
|
||||
isLoading={showSpinner}
|
||||
onPress={() => {
|
||||
ref.current?.togglePlayback()
|
||||
}}
|
||||
altText={embed.alt}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
style={[a.flex_1, a.align_center, a.justify_center]}
|
||||
onPress={() => {
|
||||
ref.current?.togglePlayback()
|
||||
}}
|
||||
label={_(msg`Play video`)}>
|
||||
{showSpinner ? (
|
||||
<View style={[a.align_center, a.justify_center]}>
|
||||
<ActivityIndicator size="large" color="white" />
|
||||
</View>
|
||||
) : (
|
||||
<PlayButtonIcon />
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</ImageBackground>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -26,15 +26,25 @@ import {IS_WEB_FIREFOX} from '#/env'
|
||||
import {useActiveVideoWeb} from './ActiveVideoWebContext'
|
||||
import * as VideoFallback from './VideoEmbedInner/VideoFallback'
|
||||
|
||||
const noop = () => {}
|
||||
|
||||
export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
|
||||
const t = useTheme()
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const {active, setActive, sendPosition, currentActiveView} =
|
||||
useActiveVideoWeb()
|
||||
const {
|
||||
active: activeFromContext,
|
||||
setActive,
|
||||
sendPosition,
|
||||
currentActiveView,
|
||||
} = useActiveVideoWeb()
|
||||
const [onScreen, setOnScreen] = useState(false)
|
||||
const [isFullscreen] = useFullscreen()
|
||||
const lastKnownTime = useRef<number | undefined>(undefined)
|
||||
|
||||
const isGif = embed.presentation === 'gif'
|
||||
// GIFs don't participate in the "one video at a time" system
|
||||
const active = isGif || activeFromContext
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref.current) return
|
||||
if (isFullscreen && !IS_WEB_FIREFOX) return
|
||||
@@ -43,15 +53,18 @@ export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
|
||||
const entry = entries[0]
|
||||
if (!entry) return
|
||||
setOnScreen(entry.isIntersecting)
|
||||
sendPosition(
|
||||
entry.boundingClientRect.y + entry.boundingClientRect.height / 2,
|
||||
)
|
||||
// GIFs don't send position - they don't compete to be the active video
|
||||
if (!isGif) {
|
||||
sendPosition(
|
||||
entry.boundingClientRect.y + entry.boundingClientRect.height / 2,
|
||||
)
|
||||
}
|
||||
},
|
||||
{threshold: 0.5},
|
||||
)
|
||||
observer.observe(ref.current)
|
||||
return () => observer.disconnect()
|
||||
}, [sendPosition, isFullscreen])
|
||||
}, [sendPosition, isFullscreen, isGif])
|
||||
|
||||
const [key, setKey] = useState(0)
|
||||
const renderError = useCallback(
|
||||
@@ -107,7 +120,7 @@ export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
|
||||
return (
|
||||
<View style={[a.pt_xs]}>
|
||||
<ViewportObserver
|
||||
sendPosition={sendPosition}
|
||||
sendPosition={isGif ? noop : sendPosition}
|
||||
isAnyViewActive={currentActiveView !== null}>
|
||||
<ConstrainedImage
|
||||
fullBleed
|
||||
|
||||
@@ -6,7 +6,6 @@ import {useLingui} from '@lingui/react'
|
||||
import type React from 'react'
|
||||
|
||||
import {useCleanError} from '#/lib/hooks/useCleanError'
|
||||
import {logger} from '#/logger'
|
||||
import {type Shadow} from '#/state/cache/post-shadow'
|
||||
import {useFeedFeedbackContext} from '#/state/feed-feedback'
|
||||
import {useBookmarkMutation} from '#/state/queries/bookmarks/useBookmarkMutation'
|
||||
@@ -15,6 +14,7 @@ import {useTheme} from '#/alf'
|
||||
import {Bookmark, BookmarkFilled} from '#/components/icons/Bookmark'
|
||||
import {Trash_Stroke2_Corner0_Rounded as TrashIcon} from '#/components/icons/Trash'
|
||||
import * as toast from '#/components/Toast'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {PostControlButton, PostControlButtonIcon} from './PostControlButton'
|
||||
|
||||
export const BookmarkButton = memo(function BookmarkButton({
|
||||
@@ -29,6 +29,7 @@ export const BookmarkButton = memo(function BookmarkButton({
|
||||
hitSlop?: Insets
|
||||
}): React.ReactNode {
|
||||
const t = useTheme()
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const {mutateAsync: bookmark} = useBookmarkMutation()
|
||||
const cleanError = useCleanError()
|
||||
@@ -52,7 +53,7 @@ export const BookmarkButton = memo(function BookmarkButton({
|
||||
post,
|
||||
})
|
||||
|
||||
logger.metric('post:bookmark', {
|
||||
ax.metric('post:bookmark', {
|
||||
uri: post.uri,
|
||||
authorDid: post.author.did,
|
||||
logContext,
|
||||
@@ -92,7 +93,7 @@ export const BookmarkButton = memo(function BookmarkButton({
|
||||
uri: post.uri,
|
||||
})
|
||||
|
||||
logger.metric('post:unbookmark', {
|
||||
ax.metric('post:unbookmark', {
|
||||
uri: post.uri,
|
||||
authorDid: post.author.did,
|
||||
logContext,
|
||||
|
||||
@@ -3,11 +3,11 @@ import * as Clipboard from 'expo-clipboard'
|
||||
import {t} from '@lingui/macro'
|
||||
|
||||
import {DISCOVER_DEBUG_DIDS} from '#/lib/constants'
|
||||
import {useGate} from '#/lib/statsig/statsig'
|
||||
import {useSession} from '#/state/session'
|
||||
import {atoms as a, useTheme} from '#/alf'
|
||||
import * as Toast from '#/components/Toast'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_INTERNAL} from '#/env'
|
||||
|
||||
export function DiscoverDebug({
|
||||
@@ -15,12 +15,12 @@ export function DiscoverDebug({
|
||||
}: {
|
||||
feedContext: string | undefined
|
||||
}) {
|
||||
const ax = useAnalytics()
|
||||
const {currentAccount} = useSession()
|
||||
const gate = useGate()
|
||||
const isDiscoverDebugUser =
|
||||
IS_INTERNAL ||
|
||||
DISCOVER_DEBUG_DIDS[currentAccount?.did || ''] ||
|
||||
gate('debug_show_feedcontext')
|
||||
ax.features.enabled(ax.features.DebugFeedContext)
|
||||
const theme = useTheme()
|
||||
|
||||
return (
|
||||
|
||||
@@ -26,15 +26,17 @@ import {
|
||||
type CommonNavigatorParams,
|
||||
type NavigationProp,
|
||||
} from '#/lib/routes/types'
|
||||
import {logEvent, useGate} from '#/lib/statsig/statsig'
|
||||
import {richTextToString} from '#/lib/strings/rich-text-helpers'
|
||||
import {toShareUrl} from '#/lib/strings/url-helpers'
|
||||
import {logger} from '#/logger'
|
||||
import {type Shadow} from '#/state/cache/post-shadow'
|
||||
import {useProfileShadow} from '#/state/cache/profile-shadow'
|
||||
import {useFeedFeedbackContext} from '#/state/feed-feedback'
|
||||
import {useLanguagePrefs} from '#/state/preferences'
|
||||
import {useHiddenPosts, useHiddenPostsApi} from '#/state/preferences'
|
||||
import {
|
||||
useHiddenPosts,
|
||||
useHiddenPostsApi,
|
||||
useLanguagePrefs,
|
||||
} from '#/state/preferences'
|
||||
import {usePinnedPostMutation} from '#/state/queries/pinned-post'
|
||||
import {
|
||||
usePostDeleteMutation,
|
||||
@@ -71,13 +73,17 @@ import {
|
||||
import {Eye_Stroke2_Corner0_Rounded as Eye} from '#/components/icons/Eye'
|
||||
import {EyeSlash_Stroke2_Corner0_Rounded as EyeSlash} from '#/components/icons/EyeSlash'
|
||||
import {Filter_Stroke2_Corner0_Rounded as Filter} from '#/components/icons/Filter'
|
||||
import {Mute_Stroke2_Corner0_Rounded as MuteIcon} from '#/components/icons/Mute'
|
||||
import {Mute_Stroke2_Corner0_Rounded as Mute} from '#/components/icons/Mute'
|
||||
import {
|
||||
Mute_Stroke2_Corner0_Rounded as Mute,
|
||||
Mute_Stroke2_Corner0_Rounded as MuteIcon,
|
||||
} from '#/components/icons/Mute'
|
||||
import {PersonX_Stroke2_Corner0_Rounded as PersonX} from '#/components/icons/Person'
|
||||
import {Pin_Stroke2_Corner0_Rounded as PinIcon} from '#/components/icons/Pin'
|
||||
import {SettingsGear2_Stroke2_Corner0_Rounded as Gear} from '#/components/icons/SettingsGear2'
|
||||
import {SpeakerVolumeFull_Stroke2_Corner0_Rounded as UnmuteIcon} from '#/components/icons/Speaker'
|
||||
import {SpeakerVolumeFull_Stroke2_Corner0_Rounded as Unmute} from '#/components/icons/Speaker'
|
||||
import {
|
||||
SpeakerVolumeFull_Stroke2_Corner0_Rounded as Unmute,
|
||||
SpeakerVolumeFull_Stroke2_Corner0_Rounded as UnmuteIcon,
|
||||
} from '#/components/icons/Speaker'
|
||||
import {Trash_Stroke2_Corner0_Rounded as Trash} from '#/components/icons/Trash'
|
||||
import {Warning_Stroke2_Corner0_Rounded as Warning} from '#/components/icons/Warning'
|
||||
import {Loader} from '#/components/Loader'
|
||||
@@ -87,6 +93,7 @@ import {
|
||||
useReportDialogControl,
|
||||
} from '#/components/moderation/ReportDialog'
|
||||
import * as Prompt from '#/components/Prompt'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_INTERNAL} from '#/env'
|
||||
import * as bsky from '#/types/bsky'
|
||||
|
||||
@@ -116,6 +123,7 @@ let PostMenuItems = ({
|
||||
}): React.ReactNode => {
|
||||
const {hasSession, currentAccount} = useSession()
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const langPrefs = useLanguagePrefs()
|
||||
const {mutateAsync: deletePostMutate} = usePostDeleteMutation()
|
||||
const {mutateAsync: pinPostMutate, isPending: isPinPending} =
|
||||
@@ -212,7 +220,7 @@ let PostMenuItems = ({
|
||||
try {
|
||||
if (isThreadMuted) {
|
||||
unmuteThread()
|
||||
logger.metric('post:unmute', {
|
||||
ax.metric('post:unmute', {
|
||||
uri: postUri,
|
||||
authorDid: postAuthor.did,
|
||||
logContext,
|
||||
@@ -221,7 +229,7 @@ let PostMenuItems = ({
|
||||
Toast.show(_(msg`You will now receive notifications for this thread`))
|
||||
} else {
|
||||
muteThread()
|
||||
logger.metric('post:mute', {
|
||||
ax.metric('post:mute', {
|
||||
uri: postUri,
|
||||
authorDid: postAuthor.did,
|
||||
logContext,
|
||||
@@ -258,21 +266,17 @@ let PostMenuItems = ({
|
||||
AppBskyFeedPost.isRecord,
|
||||
)
|
||||
) {
|
||||
logger.metric(
|
||||
'translate',
|
||||
{
|
||||
sourceLanguages: post.record.langs ?? [],
|
||||
targetLanguage: langPrefs.primaryLanguage,
|
||||
textLength: post.record.text.length,
|
||||
},
|
||||
{statsig: false},
|
||||
)
|
||||
ax.metric('translate', {
|
||||
sourceLanguages: post.record.langs ?? [],
|
||||
targetLanguage: langPrefs.primaryLanguage,
|
||||
textLength: post.record.text.length,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const onHidePost = () => {
|
||||
hidePost({uri: postUri})
|
||||
logEvent('thread:click:hideReplyForMe', {})
|
||||
ax.metric('thread:click:hideReplyForMe', {})
|
||||
}
|
||||
|
||||
const hideInPWI = !!postAuthor.labels?.find(
|
||||
@@ -286,7 +290,7 @@ let PostMenuItems = ({
|
||||
feedContext: postFeedContext,
|
||||
reqId: postReqId,
|
||||
})
|
||||
logger.metric('post:showMore', {
|
||||
ax.metric('post:showMore', {
|
||||
uri: postUri,
|
||||
authorDid: postAuthor.did,
|
||||
logContext,
|
||||
@@ -304,7 +308,7 @@ let PostMenuItems = ({
|
||||
feedContext: postFeedContext,
|
||||
reqId: postReqId,
|
||||
})
|
||||
logger.metric('post:showLess', {
|
||||
ax.metric('post:showLess', {
|
||||
uri: postUri,
|
||||
authorDid: postAuthor.did,
|
||||
logContext,
|
||||
@@ -368,7 +372,7 @@ let PostMenuItems = ({
|
||||
|
||||
// Log metric only when hiding (not when showing)
|
||||
if (isHide) {
|
||||
logEvent('thread:click:hideReplyForEveryone', {})
|
||||
ax.metric('thread:click:hideReplyForEveryone', {})
|
||||
}
|
||||
|
||||
Toast.show(
|
||||
@@ -405,7 +409,7 @@ let PostMenuItems = ({
|
||||
}
|
||||
|
||||
const onPressPin = () => {
|
||||
logEvent(isPinned ? 'post:unpin' : 'post:pin', {})
|
||||
ax.metric(isPinned ? 'post:unpin' : 'post:pin', {})
|
||||
pinPostMutate({
|
||||
postUri,
|
||||
postCid,
|
||||
@@ -458,11 +462,10 @@ let PostMenuItems = ({
|
||||
|
||||
const onSignIn = () => requireSignIn(() => {})
|
||||
|
||||
const gate = useGate()
|
||||
const isDiscoverDebugUser =
|
||||
IS_INTERNAL ||
|
||||
DISCOVER_DEBUG_DIDS[currentAccount?.did || ''] ||
|
||||
gate('debug_show_feedcontext')
|
||||
ax.features.enabled(ax.features.DebugFeedContext)
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -8,7 +8,6 @@ import {isBlockedOrBlocking, isMuted} from '#/lib/moderation/blocked-and-muted'
|
||||
import {type NavigationProp} from '#/lib/routes/types'
|
||||
import {sanitizeDisplayName} from '#/lib/strings/display-names'
|
||||
import {sanitizeHandle} from '#/lib/strings/handles'
|
||||
import {logger} from '#/logger'
|
||||
import {useProfileShadow} from '#/state/cache/profile-shadow'
|
||||
import {useModerationOpts} from '#/state/preferences/moderation-opts'
|
||||
import {useListConvosQuery} from '#/state/queries/messages/list-conversations'
|
||||
@@ -20,9 +19,11 @@ import {useDialogContext} from '#/components/Dialog'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useSimpleVerificationState} from '#/components/verification'
|
||||
import {VerificationCheck} from '#/components/verification/VerificationCheck'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import type * as bsky from '#/types/bsky'
|
||||
|
||||
export function RecentChats({postUri}: {postUri: string}) {
|
||||
const ax = useAnalytics()
|
||||
const control = useDialogContext()
|
||||
const {currentAccount} = useSession()
|
||||
const {data} = useListConvosQuery({status: 'accepted'})
|
||||
@@ -32,7 +33,7 @@ export function RecentChats({postUri}: {postUri: string}) {
|
||||
|
||||
const onSelectChat = (convoId: string) => {
|
||||
control.close(() => {
|
||||
logger.metric('share:press:recentDm', {}, {statsig: true})
|
||||
ax.metric('share:press:recentDm', {})
|
||||
navigation.navigate('MessagesConversation', {
|
||||
conversation: convoId,
|
||||
embed: postUri,
|
||||
|
||||
@@ -9,7 +9,6 @@ import {makeProfileLink} from '#/lib/routes/links'
|
||||
import {type NavigationProp} from '#/lib/routes/types'
|
||||
import {shareText, shareUrl} from '#/lib/sharing'
|
||||
import {toShareUrl} from '#/lib/strings/url-helpers'
|
||||
import {logger} from '#/logger'
|
||||
import {useProfileShadow} from '#/state/cache/profile-shadow'
|
||||
import {useSession} from '#/state/session'
|
||||
import * as Toast from '#/view/com/util/Toast'
|
||||
@@ -23,6 +22,7 @@ import {Clipboard_Stroke2_Corner2_Rounded as ClipboardIcon} from '#/components/i
|
||||
import {PaperPlane_Stroke2_Corner0_Rounded as PaperPlaneIcon} from '#/components/icons/PaperPlane'
|
||||
import * as Menu from '#/components/Menu'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_IOS} from '#/env'
|
||||
import {useDevMode} from '#/storage/hooks/dev-mode'
|
||||
import {RecentChats} from './RecentChats'
|
||||
@@ -32,6 +32,7 @@ let ShareMenuItems = ({
|
||||
post,
|
||||
onShare: onShareProp,
|
||||
}: ShareMenuItemsProps): React.ReactNode => {
|
||||
const ax = useAnalytics()
|
||||
const {hasSession} = useSession()
|
||||
const {_} = useLingui()
|
||||
const navigation = useNavigation<NavigationProp>()
|
||||
@@ -54,14 +55,14 @@ let ShareMenuItems = ({
|
||||
}, [postAuthor])
|
||||
|
||||
const onSharePost = () => {
|
||||
logger.metric('share:press:nativeShare', {}, {statsig: true})
|
||||
ax.metric('share:press:nativeShare', {})
|
||||
const url = toShareUrl(href)
|
||||
shareUrl(url)
|
||||
onShareProp()
|
||||
}
|
||||
|
||||
const onCopyLink = async () => {
|
||||
logger.metric('share:press:copyLink', {}, {statsig: true})
|
||||
ax.metric('share:press:copyLink', {})
|
||||
const url = toShareUrl(href)
|
||||
if (IS_IOS) {
|
||||
// iOS only
|
||||
@@ -100,7 +101,7 @@ let ShareMenuItems = ({
|
||||
testID="postDropdownSendViaDMBtn"
|
||||
label={_(msg`Send via direct message`)}
|
||||
onPress={() => {
|
||||
logger.metric('share:press:openDmSearch', {}, {statsig: true})
|
||||
ax.metric('share:press:openDmSearch', {})
|
||||
sendViaChatControl.open()
|
||||
}}>
|
||||
<Menu.ItemText>
|
||||
|
||||
@@ -8,7 +8,6 @@ import {makeProfileLink} from '#/lib/routes/links'
|
||||
import {type NavigationProp} from '#/lib/routes/types'
|
||||
import {shareText, shareUrl} from '#/lib/sharing'
|
||||
import {toShareUrl} from '#/lib/strings/url-helpers'
|
||||
import {logger} from '#/logger'
|
||||
import {useProfileShadow} from '#/state/cache/profile-shadow'
|
||||
import {useSession} from '#/state/session'
|
||||
import {useBreakpoints} from '#/alf'
|
||||
@@ -21,6 +20,7 @@ import {CodeBrackets_Stroke2_Corner0_Rounded as CodeBracketsIcon} from '#/compon
|
||||
import {PaperPlane_Stroke2_Corner0_Rounded as Send} from '#/components/icons/PaperPlane'
|
||||
import * as Menu from '#/components/Menu'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_WEB} from '#/env'
|
||||
import {useDevMode} from '#/storage/hooks/dev-mode'
|
||||
import {type ShareMenuItemsProps} from './ShareMenuItems.types'
|
||||
@@ -31,6 +31,7 @@ let ShareMenuItems = ({
|
||||
timestamp,
|
||||
onShare: onShareProp,
|
||||
}: ShareMenuItemsProps): React.ReactNode => {
|
||||
const ax = useAnalytics()
|
||||
const {hasSession} = useSession()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
const {_} = useLingui()
|
||||
@@ -56,14 +57,14 @@ let ShareMenuItems = ({
|
||||
}, [postAuthor])
|
||||
|
||||
const onCopyLink = () => {
|
||||
logger.metric('share:press:copyLink', {}, {statsig: true})
|
||||
ax.metric('share:press:copyLink', {})
|
||||
const url = toShareUrl(href)
|
||||
shareUrl(url)
|
||||
onShareProp()
|
||||
}
|
||||
|
||||
const onSelectChatToShareTo = (conversation: string) => {
|
||||
logger.metric('share:press:dmSelected', {}, {statsig: true})
|
||||
ax.metric('share:press:dmSelected', {})
|
||||
navigation.navigate('MessagesConversation', {
|
||||
conversation,
|
||||
embed: postUri,
|
||||
@@ -102,7 +103,7 @@ let ShareMenuItems = ({
|
||||
testID="postDropdownSendViaDMBtn"
|
||||
label={_(msg`Send via direct message`)}
|
||||
onPress={() => {
|
||||
logger.metric('share:press:openDmSearch', {}, {statsig: true})
|
||||
ax.metric('share:press:openDmSearch', {})
|
||||
sendViaChatControl.open()
|
||||
}}>
|
||||
<Menu.ItemText>
|
||||
@@ -117,7 +118,7 @@ let ShareMenuItems = ({
|
||||
testID="postDropdownEmbedBtn"
|
||||
label={_(msg`Embed post`)}
|
||||
onPress={() => {
|
||||
logger.metric('share:press:embed', {}, {statsig: true})
|
||||
ax.metric('share:press:embed', {})
|
||||
embedPostControl.open()
|
||||
}}>
|
||||
<Menu.ItemText>{_(msg`Embed post`)}</Menu.ItemText>
|
||||
|
||||
@@ -12,17 +12,15 @@ import {useLingui} from '@lingui/react'
|
||||
|
||||
import {makeProfileLink} from '#/lib/routes/links'
|
||||
import {shareUrl} from '#/lib/sharing'
|
||||
import {useGate} from '#/lib/statsig/statsig'
|
||||
import {toShareUrl} from '#/lib/strings/url-helpers'
|
||||
import {logger} from '#/logger'
|
||||
import {type Shadow} from '#/state/cache/post-shadow'
|
||||
import {useFeedFeedbackContext} from '#/state/feed-feedback'
|
||||
import {EventStopper} from '#/view/com/util/EventStopper'
|
||||
import {native} from '#/alf'
|
||||
import {ArrowOutOfBoxModified_Stroke2_Corner2_Rounded as ArrowOutOfBoxIcon} from '#/components/icons/ArrowOutOfBox'
|
||||
import {ArrowShareRight_Stroke2_Corner2_Rounded as ArrowShareRightIcon} from '#/components/icons/ArrowShareRight'
|
||||
import {useMenuControl} from '#/components/Menu'
|
||||
import * as Menu from '#/components/Menu'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {PostControlButton, PostControlButtonIcon} from '../PostControlButton'
|
||||
import {ShareMenuItems} from './ShareMenuItems'
|
||||
|
||||
@@ -49,14 +47,10 @@ let ShareMenuButton = ({
|
||||
hitSlop?: Insets
|
||||
logContext: 'FeedItem' | 'PostThreadItem' | 'Post' | 'ImmersiveVideo'
|
||||
}): React.ReactNode => {
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const gate = useGate()
|
||||
const {feedDescriptor} = useFeedFeedbackContext()
|
||||
|
||||
const ShareIcon = gate('alt_share_icon')
|
||||
? ArrowShareRightIcon
|
||||
: ArrowOutOfBoxIcon
|
||||
|
||||
const menuControl = useMenuControl()
|
||||
const [hasBeenOpen, setHasBeenOpen] = useState(false)
|
||||
const lazyMenuControl = useMemo(
|
||||
@@ -68,20 +62,17 @@ let ShareMenuButton = ({
|
||||
// menuControl.open() fires but RN doesn't expose flushSync.
|
||||
setTimeout(menuControl.open)
|
||||
|
||||
logger.metric(
|
||||
'post:share',
|
||||
{
|
||||
uri: post.uri,
|
||||
authorDid: post.author.did,
|
||||
logContext,
|
||||
feedDescriptor,
|
||||
postContext: big ? 'thread' : 'feed',
|
||||
},
|
||||
{statsig: true},
|
||||
)
|
||||
ax.metric('post:share', {
|
||||
uri: post.uri,
|
||||
authorDid: post.author.did,
|
||||
logContext,
|
||||
feedDescriptor,
|
||||
postContext: big ? 'thread' : 'feed',
|
||||
})
|
||||
},
|
||||
}),
|
||||
[
|
||||
ax,
|
||||
menuControl,
|
||||
setHasBeenOpen,
|
||||
big,
|
||||
@@ -93,7 +84,7 @@ let ShareMenuButton = ({
|
||||
)
|
||||
|
||||
const onNativeLongPress = () => {
|
||||
logger.metric('share:press:nativeShare', {}, {statsig: true})
|
||||
ax.metric('share:press:nativeShare', {})
|
||||
const urip = new AtUri(post.uri)
|
||||
const href = makeProfileLink(post.author, 'post', urip.rkey)
|
||||
const url = toShareUrl(href)
|
||||
@@ -114,7 +105,7 @@ let ShareMenuButton = ({
|
||||
{...props}
|
||||
onLongPress={native(onNativeLongPress)}
|
||||
hitSlop={hitSlop}>
|
||||
<PostControlButtonIcon icon={ShareIcon} />
|
||||
<PostControlButtonIcon icon={ArrowShareRightIcon} />
|
||||
</PostControlButton>
|
||||
)
|
||||
}}
|
||||
|
||||
@@ -13,7 +13,6 @@ import {CountWheel} from '#/lib/custom-animations/CountWheel'
|
||||
import {AnimatedLikeIcon} from '#/lib/custom-animations/LikeIcon'
|
||||
import {useHaptics} from '#/lib/haptics'
|
||||
import {useOpenComposer} from '#/lib/hooks/useOpenComposer'
|
||||
import {logger} from '#/logger'
|
||||
import {type Shadow} from '#/state/cache/types'
|
||||
import {useFeedFeedbackContext} from '#/state/feed-feedback'
|
||||
import {
|
||||
@@ -30,6 +29,7 @@ import {atoms as a, useBreakpoints} from '#/alf'
|
||||
import {Reply as Bubble} from '#/components/icons/Reply'
|
||||
import {useFormatPostStatCount} from '#/components/PostControls/util'
|
||||
import * as Skele from '#/components/Skeleton'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {BookmarkButton} from './BookmarkButton'
|
||||
import {
|
||||
PostControlButton,
|
||||
@@ -71,6 +71,7 @@ let PostControls = ({
|
||||
viaRepost?: {uri: string; cid: string}
|
||||
variant?: 'compact' | 'normal' | 'large'
|
||||
}): React.ReactNode => {
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const {openComposer} = useOpenComposer()
|
||||
const {feedDescriptor} = useFeedFeedbackContext()
|
||||
@@ -175,7 +176,7 @@ let PostControls = ({
|
||||
feedContext,
|
||||
reqId,
|
||||
})
|
||||
logger.metric('post:clickQuotePost', {
|
||||
ax.metric('post:clickQuotePost', {
|
||||
uri: post.uri,
|
||||
authorDid: post.author.did,
|
||||
logContext,
|
||||
@@ -184,6 +185,7 @@ let PostControls = ({
|
||||
openComposer({
|
||||
quote: post,
|
||||
onPost: onPostReply,
|
||||
logContext: 'QuotePost',
|
||||
})
|
||||
}
|
||||
|
||||
@@ -226,7 +228,7 @@ let PostControls = ({
|
||||
!replyDisabled
|
||||
? () =>
|
||||
requireAuth(() => {
|
||||
logger.metric('post:clickReply', {
|
||||
ax.metric('post:clickReply', {
|
||||
uri: post.uri,
|
||||
authorDid: post.author.did,
|
||||
logContext,
|
||||
|
||||
@@ -16,7 +16,6 @@ import {useLingui} from '@lingui/react'
|
||||
|
||||
import {useActorStatus} from '#/lib/actor-status'
|
||||
import {getModerationCauseKey} from '#/lib/moderation'
|
||||
import {type LogEvents} from '#/lib/statsig/statsig'
|
||||
import {forceLTR} from '#/lib/strings/bidi'
|
||||
import {NON_BREAKING_SPACE} from '#/lib/strings/constants'
|
||||
import {sanitizeDisplayName} from '#/lib/strings/display-names'
|
||||
@@ -47,6 +46,7 @@ import {RichText} from '#/components/RichText'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useSimpleVerificationState} from '#/components/verification'
|
||||
import {VerificationCheck} from '#/components/verification/VerificationCheck'
|
||||
import {type Metrics} from '#/analytics'
|
||||
import type * as bsky from '#/types/bsky'
|
||||
|
||||
export function Default({
|
||||
@@ -461,8 +461,8 @@ export function DescriptionPlaceholder({
|
||||
export type FollowButtonProps = {
|
||||
profile: bsky.profile.AnyProfileView
|
||||
moderationOpts: ModerationOpts
|
||||
logContext: LogEvents['profile:follow']['logContext'] &
|
||||
LogEvents['profile:unfollow']['logContext']
|
||||
logContext: Metrics['profile:follow']['logContext'] &
|
||||
Metrics['profile:unfollow']['logContext']
|
||||
colorInverted?: boolean
|
||||
onFollow?: () => void
|
||||
withIcon?: boolean
|
||||
|
||||
@@ -9,9 +9,8 @@ import {type ModerationOpts} from '@atproto/api'
|
||||
import {msg, Trans} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
|
||||
import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
|
||||
import {popularInterests, useInterestsDisplayNames} from '#/lib/interests'
|
||||
import {logEvent} from '#/lib/statsig/statsig'
|
||||
import {logger} from '#/logger'
|
||||
import {useModerationOpts} from '#/state/preferences/moderation-opts'
|
||||
import {useActorSearch} from '#/state/queries/actor-search'
|
||||
import {usePreferencesQuery} from '#/state/queries/preferences'
|
||||
@@ -36,6 +35,7 @@ import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
|
||||
import {boostInterests, InterestTabs} from '#/components/InterestTabs'
|
||||
import * as ProfileCard from '#/components/ProfileCard'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_WEB} from '#/env'
|
||||
import type * as bsky from '#/types/bsky'
|
||||
import {ProgressGuideTask} from './Task'
|
||||
@@ -67,6 +67,7 @@ export function FollowDialog({
|
||||
guide: Follow10ProgressGuide
|
||||
showArrow?: boolean
|
||||
}) {
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const control = Dialog.useDialogControl()
|
||||
const {gtPhone} = useBreakpoints()
|
||||
@@ -78,7 +79,7 @@ export function FollowDialog({
|
||||
label={_(msg`Find people to follow`)}
|
||||
onPress={() => {
|
||||
control.open()
|
||||
logEvent('progressGuide:followDialog:open', {})
|
||||
ax.metric('progressGuide:followDialog:open', {})
|
||||
}}
|
||||
size={gtPhone ? 'small' : 'large'}
|
||||
color="primary">
|
||||
@@ -118,6 +119,7 @@ let lastSearchText = ''
|
||||
|
||||
function DialogInner({guide}: {guide?: Follow10ProgressGuide}) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const interestsDisplayNames = useInterestsDisplayNames()
|
||||
const {data: preferences} = usePreferencesQuery()
|
||||
const personalizedInterests = preferences?.interests?.tags
|
||||
@@ -206,6 +208,15 @@ function DialogInner({guide}: {guide?: Follow10ProgressGuide}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
hasSearchText &&
|
||||
!isFetchingSearchResults &&
|
||||
!_items.length &&
|
||||
!isSearchResultsError
|
||||
) {
|
||||
_items.push({type: 'empty', key: 'empty', message: _(msg`No results`)})
|
||||
}
|
||||
|
||||
return _items
|
||||
}, [
|
||||
_,
|
||||
@@ -218,17 +229,9 @@ function DialogInner({guide}: {guide?: Follow10ProgressGuide}) {
|
||||
currentAccount?.did,
|
||||
hasSearchText,
|
||||
resultsKey,
|
||||
isSearchResultsError,
|
||||
])
|
||||
|
||||
if (
|
||||
searchText &&
|
||||
!isFetchingSearchResults &&
|
||||
!items.length &&
|
||||
!isSearchResultsError
|
||||
) {
|
||||
items.push({type: 'empty', key: 'empty', message: _(msg`No results`)})
|
||||
}
|
||||
|
||||
const renderItems = useCallback(
|
||||
({item, index}: {item: Item; index: number}) => {
|
||||
switch (item.type) {
|
||||
@@ -261,7 +264,7 @@ function DialogInner({guide}: {guide?: Follow10ProgressGuide}) {
|
||||
const selectedInterestRef = useRef(selectedInterest)
|
||||
selectedInterestRef.current = selectedInterest
|
||||
|
||||
const onViewableItemsChanged = useRef(
|
||||
const onViewableItemsChanged = useNonReactiveCallback(
|
||||
({viewableItems}: {viewableItems: ViewToken[]}) => {
|
||||
for (const viewableItem of viewableItems) {
|
||||
const item = viewableItem.item as Item
|
||||
@@ -271,25 +274,24 @@ function DialogInner({guide}: {guide?: Follow10ProgressGuide}) {
|
||||
const position = itemsRef.current.findIndex(
|
||||
i => i.type === 'profile' && i.profile.did === item.profile.did,
|
||||
)
|
||||
logger.metric(
|
||||
'suggestedUser:seen',
|
||||
{
|
||||
logContext: 'ProgressGuide',
|
||||
recId: undefined,
|
||||
position: position !== -1 ? position : 0,
|
||||
suggestedDid: item.profile.did,
|
||||
category: selectedInterestRef.current,
|
||||
},
|
||||
{statsig: true},
|
||||
)
|
||||
ax.metric('suggestedUser:seen', {
|
||||
logContext: 'ProgressGuide',
|
||||
recId: hasSearchText ? undefined : suggestions?.recId,
|
||||
position: position !== -1 ? position : 0,
|
||||
suggestedDid: item.profile.did,
|
||||
category: selectedInterestRef.current,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
).current
|
||||
const viewabilityConfig = useRef({
|
||||
itemVisiblePercentThreshold: 50,
|
||||
}).current
|
||||
)
|
||||
const viewabilityConfig = useMemo(
|
||||
() => ({
|
||||
itemVisiblePercentThreshold: 50,
|
||||
}),
|
||||
[],
|
||||
)
|
||||
|
||||
const onSelectTab = useCallback(
|
||||
(interest: string) => {
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import React from 'react'
|
||||
import {createContext, useCallback, useContext, useId, useMemo} from 'react'
|
||||
import {type GestureResponderEvent, View} from 'react-native'
|
||||
import {msg} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
|
||||
import {
|
||||
atoms as a,
|
||||
useBreakpoints,
|
||||
useTheme,
|
||||
type ViewStyleProp,
|
||||
web,
|
||||
} from '#/alf'
|
||||
import {atoms as a, useTheme, type ViewStyleProp, web} from '#/alf'
|
||||
import {Button, type ButtonColor, ButtonText} from '#/components/Button'
|
||||
import * as Dialog from '#/components/Dialog'
|
||||
import {Text} from '#/components/Typography'
|
||||
@@ -20,7 +14,7 @@ export {
|
||||
useDialogControl as usePromptControl,
|
||||
} from '#/components/Dialog'
|
||||
|
||||
const Context = React.createContext<{
|
||||
const Context = createContext<{
|
||||
titleId: string
|
||||
descriptionId: string
|
||||
}>({
|
||||
@@ -37,12 +31,15 @@ export function Outer({
|
||||
}: React.PropsWithChildren<{
|
||||
control: Dialog.DialogControlProps
|
||||
testID?: string
|
||||
/**
|
||||
* Native-specific options for the prompt. Extends `BottomSheetViewProps`
|
||||
*/
|
||||
nativeOptions?: Omit<BottomSheetViewProps, 'children'>
|
||||
}>) {
|
||||
const titleId = React.useId()
|
||||
const descriptionId = React.useId()
|
||||
const titleId = useId()
|
||||
const descriptionId = useId()
|
||||
|
||||
const context = React.useMemo(
|
||||
const context = useMemo(
|
||||
() => ({titleId, descriptionId}),
|
||||
[titleId, descriptionId],
|
||||
)
|
||||
@@ -58,7 +55,7 @@ export function Outer({
|
||||
<Dialog.ScrollableInner
|
||||
accessibilityLabelledBy={titleId}
|
||||
accessibilityDescribedBy={descriptionId}
|
||||
style={web({maxWidth: 400})}>
|
||||
style={web([{maxWidth: 320, borderRadius: 36}])}>
|
||||
{children}
|
||||
</Dialog.ScrollableInner>
|
||||
</Context.Provider>
|
||||
@@ -70,7 +67,7 @@ export function TitleText({
|
||||
children,
|
||||
style,
|
||||
}: React.PropsWithChildren<ViewStyleProp>) {
|
||||
const {titleId} = React.useContext(Context)
|
||||
const {titleId} = useContext(Context)
|
||||
return (
|
||||
<Text
|
||||
nativeID={titleId}
|
||||
@@ -78,7 +75,7 @@ export function TitleText({
|
||||
a.flex_1,
|
||||
a.text_2xl,
|
||||
a.font_semi_bold,
|
||||
a.pb_sm,
|
||||
a.pb_xs,
|
||||
a.leading_snug,
|
||||
style,
|
||||
]}>
|
||||
@@ -92,7 +89,7 @@ export function DescriptionText({
|
||||
selectable,
|
||||
}: React.PropsWithChildren<{selectable?: boolean}>) {
|
||||
const t = useTheme()
|
||||
const {descriptionId} = React.useContext(Context)
|
||||
const {descriptionId} = useContext(Context)
|
||||
return (
|
||||
<Text
|
||||
nativeID={descriptionId}
|
||||
@@ -103,22 +100,12 @@ export function DescriptionText({
|
||||
)
|
||||
}
|
||||
|
||||
export function Actions({children}: React.PropsWithChildren<{}>) {
|
||||
const {gtMobile} = useBreakpoints()
|
||||
export function Actions({children}: {children: React.ReactNode}) {
|
||||
return <View style={[a.w_full, a.gap_sm, a.justify_end]}>{children}</View>
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
a.w_full,
|
||||
a.gap_md,
|
||||
a.justify_end,
|
||||
gtMobile
|
||||
? [a.flex_row, a.flex_row_reverse, a.justify_start]
|
||||
: [a.flex_col],
|
||||
]}>
|
||||
{children}
|
||||
</View>
|
||||
)
|
||||
export function Content({children}: {children: React.ReactNode}) {
|
||||
return <View style={[a.pb_sm]}>{children}</View>
|
||||
}
|
||||
|
||||
export function Cancel({
|
||||
@@ -130,9 +117,8 @@ export function Cancel({
|
||||
cta?: string
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
const {close} = Dialog.useDialogContext()
|
||||
const onPress = React.useCallback(() => {
|
||||
const onPress = useCallback(() => {
|
||||
close()
|
||||
}, [close])
|
||||
|
||||
@@ -140,7 +126,7 @@ export function Cancel({
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size={gtMobile ? 'small' : 'large'}
|
||||
size={'large'}
|
||||
label={cta || _(msg`Cancel`)}
|
||||
onPress={onPress}>
|
||||
<ButtonText>{cta || _(msg`Cancel`)}</ButtonText>
|
||||
@@ -170,9 +156,8 @@ export function Action({
|
||||
testID?: string
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
const {close} = Dialog.useDialogContext()
|
||||
const handleOnPress = React.useCallback(
|
||||
const handleOnPress = useCallback(
|
||||
(e: GestureResponderEvent) => {
|
||||
close(() => onPress?.(e))
|
||||
},
|
||||
@@ -181,9 +166,8 @@ export function Action({
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="solid"
|
||||
color={color}
|
||||
size={gtMobile ? 'small' : 'large'}
|
||||
size={'large'}
|
||||
label={cta || _(msg`Confirm`)}
|
||||
onPress={handleOnPress}
|
||||
testID={testID}>
|
||||
@@ -220,8 +204,10 @@ export function Basic({
|
||||
}>) {
|
||||
return (
|
||||
<Outer control={control} testID="confirmModal">
|
||||
<TitleText>{title}</TitleText>
|
||||
{description && <DescriptionText>{description}</DescriptionText>}
|
||||
<Content>
|
||||
<TitleText>{title}</TitleText>
|
||||
{description && <DescriptionText>{description}</DescriptionText>}
|
||||
</Content>
|
||||
<Actions>
|
||||
<Action
|
||||
cta={confirmButtonCta}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react'
|
||||
import {useMemo} from 'react'
|
||||
import {type StyleProp, type TextStyle} from 'react-native'
|
||||
import {AppBskyRichtextFacet, RichText as RichTextAPI} from '@atproto/api'
|
||||
|
||||
@@ -27,6 +27,16 @@ export type RichTextProps = TextStyleProp &
|
||||
interactiveStyle?: StyleProp<TextStyle>
|
||||
emojiMultiplier?: number
|
||||
shouldProxyLinks?: boolean
|
||||
/**
|
||||
* DANGEROUS: Disable facet lexicon validation
|
||||
*
|
||||
* `detectFacetsWithoutResolution()` generates technically invalid facets,
|
||||
* with a handle in place of the DID. This means that RichText that uses it
|
||||
* won't be able to render links.
|
||||
*
|
||||
* Use with care - only use if you're rendering facets you're generating yourself.
|
||||
*/
|
||||
disableMentionFacetValidation?: true
|
||||
}
|
||||
|
||||
export function RichText({
|
||||
@@ -44,12 +54,17 @@ export function RichText({
|
||||
onLayout,
|
||||
onTextLayout,
|
||||
shouldProxyLinks,
|
||||
disableMentionFacetValidation,
|
||||
}: RichTextProps) {
|
||||
const richText = React.useMemo(
|
||||
() =>
|
||||
value instanceof RichTextAPI ? value : new RichTextAPI({text: value}),
|
||||
[value],
|
||||
)
|
||||
const richText = useMemo(() => {
|
||||
if (value instanceof RichTextAPI) {
|
||||
return value
|
||||
} else {
|
||||
const rt = new RichTextAPI({text: value})
|
||||
rt.detectFacetsWithoutResolution()
|
||||
return rt
|
||||
}
|
||||
}, [value])
|
||||
|
||||
const plainStyles = [a.leading_snug, style]
|
||||
const interactiveStyles = [plainStyles, interactiveStyle]
|
||||
@@ -98,9 +113,11 @@ export function RichText({
|
||||
const link = segment.link
|
||||
const mention = segment.mention
|
||||
const tag = segment.tag
|
||||
|
||||
if (
|
||||
mention &&
|
||||
AppBskyRichtextFacet.validateMention(mention).success &&
|
||||
(disableMentionFacetValidation ||
|
||||
AppBskyRichtextFacet.validateMention(mention).success) &&
|
||||
!disableLinks
|
||||
) {
|
||||
els.push(
|
||||
|
||||
@@ -101,7 +101,7 @@ export function ProfileStarterPacks({
|
||||
message={
|
||||
emptyStateMessage ??
|
||||
_(
|
||||
'Starter packs let you share your favorite feeds and people with your friends.',
|
||||
msg`Starter packs let you share your favorite feeds and people with your friends.`,
|
||||
)
|
||||
}
|
||||
button={emptyStateButton}
|
||||
@@ -331,15 +331,17 @@ function Empty() {
|
||||
</View>
|
||||
|
||||
<Prompt.Outer control={confirmDialogControl}>
|
||||
<Prompt.TitleText>
|
||||
<Trans>Generate a starter pack</Trans>
|
||||
</Prompt.TitleText>
|
||||
<Prompt.DescriptionText>
|
||||
<Trans>
|
||||
Bluesky will choose a set of recommended accounts from people in
|
||||
your network.
|
||||
</Trans>
|
||||
</Prompt.DescriptionText>
|
||||
<Prompt.Content>
|
||||
<Prompt.TitleText>
|
||||
<Trans>Generate a starter pack</Trans>
|
||||
</Prompt.TitleText>
|
||||
<Prompt.DescriptionText>
|
||||
<Trans>
|
||||
Bluesky will choose a set of recommended accounts from people in
|
||||
your network.
|
||||
</Trans>
|
||||
</Prompt.DescriptionText>
|
||||
</Prompt.Content>
|
||||
<Prompt.Actions>
|
||||
<Prompt.Action
|
||||
color="primary"
|
||||
|
||||
@@ -19,6 +19,7 @@ import {FloppyDisk_Stroke2_Corner0_Rounded as FloppyDiskIcon} from '#/components
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {QrCode} from '#/components/StarterPack/QrCode'
|
||||
import * as Toast from '#/components/Toast'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_NATIVE, IS_WEB} from '#/env'
|
||||
import * as bsky from '#/types/bsky'
|
||||
|
||||
@@ -32,6 +33,7 @@ export function QrCodeDialog({
|
||||
control: DialogControlProps
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
const [isSaveProcessing, setIsSaveProcessing] = useState(false)
|
||||
const [isCopyProcessing, setIsCopyProcessing] = useState(false)
|
||||
@@ -104,7 +106,7 @@ export function QrCodeDialog({
|
||||
link.click()
|
||||
}
|
||||
|
||||
logger.metric('starterPack:share', {
|
||||
ax.metric('starterPack:share', {
|
||||
starterPack: starterPack.uri,
|
||||
shareType: 'qrcode',
|
||||
qrShareType: 'save',
|
||||
@@ -129,7 +131,7 @@ export function QrCodeDialog({
|
||||
navigator.clipboard.write([item])
|
||||
})
|
||||
|
||||
logger.metric('starterPack:share', {
|
||||
ax.metric('starterPack:share', {
|
||||
starterPack: starterPack.uri,
|
||||
shareType: 'qrcode',
|
||||
qrShareType: 'copy',
|
||||
@@ -145,7 +147,7 @@ export function QrCodeDialog({
|
||||
control.close(() => {
|
||||
Sharing.shareAsync(uri, {mimeType: 'image/png', UTI: 'image/png'}).then(
|
||||
() => {
|
||||
logger.metric('starterPack:share', {
|
||||
ax.metric('starterPack:share', {
|
||||
starterPack: starterPack.uri,
|
||||
shareType: 'qrcode',
|
||||
qrShareType: 'share',
|
||||
|
||||
@@ -7,7 +7,6 @@ import {useLingui} from '@lingui/react'
|
||||
import {useSaveImageToMediaLibrary} from '#/lib/media/save-image'
|
||||
import {shareUrl} from '#/lib/sharing'
|
||||
import {getStarterPackOgCard} from '#/lib/strings/starter-pack'
|
||||
import {logger} from '#/logger'
|
||||
import {atoms as a, useBreakpoints, useTheme} from '#/alf'
|
||||
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
|
||||
import {type DialogControlProps} from '#/components/Dialog'
|
||||
@@ -17,6 +16,7 @@ import {Download_Stroke2_Corner0_Rounded as DownloadIcon} from '#/components/ico
|
||||
import {QrCode_Stroke2_Corner0_Rounded as QrCodeIcon} from '#/components/icons/QrCode'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_NATIVE, IS_WEB} from '#/env'
|
||||
|
||||
interface Props {
|
||||
@@ -46,6 +46,7 @@ function ShareDialogInner({
|
||||
control,
|
||||
}: Props) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const t = useTheme()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
|
||||
@@ -54,7 +55,7 @@ function ShareDialogInner({
|
||||
const onShareLink = async () => {
|
||||
if (!link) return
|
||||
shareUrl(link)
|
||||
logger.metric('starterPack:share', {
|
||||
ax.metric('starterPack:share', {
|
||||
starterPack: starterPack.uri,
|
||||
shareType: 'link',
|
||||
})
|
||||
|
||||
@@ -13,7 +13,6 @@ import {useLingui} from '@lingui/react'
|
||||
import {DISCOVER_FEED_URI, STARTER_PACK_MAX_SIZE} from '#/lib/constants'
|
||||
import {sanitizeDisplayName} from '#/lib/strings/display-names'
|
||||
import {sanitizeHandle} from '#/lib/strings/handles'
|
||||
import {logger} from '#/logger'
|
||||
import {useSession} from '#/state/session'
|
||||
import {UserAvatar} from '#/view/com/util/UserAvatar'
|
||||
import {
|
||||
@@ -25,6 +24,7 @@ import {Button, ButtonText} from '#/components/Button'
|
||||
import * as Toggle from '#/components/forms/Toggle'
|
||||
import {Checkbox} from '#/components/forms/Toggle'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import type * as bsky from '#/types/bsky'
|
||||
|
||||
function WizardListCard({
|
||||
@@ -130,6 +130,7 @@ export function WizardProfileCard({
|
||||
profile: bsky.profile.AnyProfileView
|
||||
moderationOpts: ModerationOpts
|
||||
}) {
|
||||
const ax = useAnalytics()
|
||||
const {currentAccount} = useSession()
|
||||
|
||||
// Determine the "main" profile for this starter pack - either targetDid or current account
|
||||
@@ -151,10 +152,10 @@ export function WizardProfileCard({
|
||||
if (profile.did === targetProfileDid) return
|
||||
|
||||
if (!included) {
|
||||
logger.metric('starterPack:addUser', {})
|
||||
ax.metric('starterPack:addUser', {})
|
||||
dispatch({type: 'AddProfile', profile})
|
||||
} else {
|
||||
logger.metric('starterPack:removeUser', {})
|
||||
ax.metric('starterPack:removeUser', {})
|
||||
dispatch({type: 'RemoveProfile', profileDid: profile.did})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,13 @@ import {msg, Trans} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
import {FocusGuards, FocusScope} from 'radix-ui/internal'
|
||||
|
||||
import {logger} from '#/logger'
|
||||
import {useLoggedOutViewControls} from '#/state/shell/logged-out'
|
||||
import {Logo} from '#/view/icons/Logo'
|
||||
import {atoms as a, flatten, useBreakpoints, web} from '#/alf'
|
||||
import {Button, ButtonText} from '#/components/Button'
|
||||
import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/Times'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
const welcomeModalBg = require('../../assets/images/welcome-modal-bg.jpg')
|
||||
|
||||
@@ -25,6 +25,7 @@ interface WelcomeModalProps {
|
||||
|
||||
export function WelcomeModal({control}: WelcomeModalProps) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const {requestSwitchToAccount} = useLoggedOutViewControls()
|
||||
const {gtMobile} = useBreakpoints()
|
||||
const [isExiting, setIsExiting] = useState(false)
|
||||
@@ -40,23 +41,24 @@ export function WelcomeModal({control}: WelcomeModalProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (control.isOpen) {
|
||||
logger.metric('welcomeModal:presented', {})
|
||||
ax.metric('welcomeModal:presented', {})
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [control.isOpen])
|
||||
|
||||
const onPressCreateAccount = () => {
|
||||
logger.metric('welcomeModal:signupClicked', {})
|
||||
ax.metric('welcomeModal:signupClicked', {})
|
||||
control.close()
|
||||
requestSwitchToAccount({requestedAccount: 'new'})
|
||||
}
|
||||
|
||||
const onPressExplore = () => {
|
||||
logger.metric('welcomeModal:exploreClicked', {})
|
||||
ax.metric('welcomeModal:exploreClicked', {})
|
||||
fadeOutAndClose()
|
||||
}
|
||||
|
||||
const onPressSignIn = () => {
|
||||
logger.metric('welcomeModal:signinClicked', {})
|
||||
ax.metric('welcomeModal:signinClicked', {})
|
||||
control.close()
|
||||
requestSwitchToAccount({requestedAccount: 'existing'})
|
||||
}
|
||||
@@ -222,7 +224,7 @@ export function WelcomeModal({control}: WelcomeModalProps) {
|
||||
]}
|
||||
hoverStyle={[a.bg_transparent]}
|
||||
onPress={() => {
|
||||
logger.metric('welcomeModal:dismissed', {})
|
||||
ax.metric('welcomeModal:dismissed', {})
|
||||
fadeOutAndClose()
|
||||
}}
|
||||
color="secondary"
|
||||
|
||||
@@ -17,7 +17,6 @@ import {useLingui} from '@lingui/react'
|
||||
|
||||
import {HITSLOP_10} from '#/lib/constants'
|
||||
import {makeListLink, makeProfileLink} from '#/lib/routes/links'
|
||||
import {logger} from '#/logger'
|
||||
import {
|
||||
type ThreadgateAllowUISetting,
|
||||
threadgateViewToAllowUISetting,
|
||||
@@ -36,6 +35,7 @@ import {Earth_Stroke2_Corner0_Rounded as EarthIcon} from '#/components/icons/Glo
|
||||
import {Group3_Stroke2_Corner0_Rounded as GroupIcon} from '#/components/icons/Group'
|
||||
import {InlineLinkText} from '#/components/Link'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_NATIVE} from '#/env'
|
||||
import * as bsky from '#/types/bsky'
|
||||
|
||||
@@ -46,8 +46,9 @@ interface WhoCanReplyProps {
|
||||
}
|
||||
|
||||
export function WhoCanReply({post, isThreadAuthor, style}: WhoCanReplyProps) {
|
||||
const {_} = useLingui()
|
||||
const t = useTheme()
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const infoDialogControl = useDialogControl()
|
||||
const editDialogControl = useDialogControl()
|
||||
|
||||
@@ -90,7 +91,7 @@ export function WhoCanReply({post, isThreadAuthor, style}: WhoCanReplyProps) {
|
||||
Keyboard.dismiss()
|
||||
}
|
||||
if (isThreadAuthor) {
|
||||
logger.metric('thread:click:editOwnThreadgate', {})
|
||||
ax.metric('thread:click:editOwnThreadgate', {})
|
||||
|
||||
// wait on prefetch if it manages to resolve in under 200ms
|
||||
// otherwise, proceed immediately and show the spinner -sfn
|
||||
@@ -101,7 +102,7 @@ export function WhoCanReply({post, isThreadAuthor, style}: WhoCanReplyProps) {
|
||||
editDialogControl.open()
|
||||
})
|
||||
} else {
|
||||
logger.metric('thread:click:viewSomeoneElsesThreadgate', {})
|
||||
ax.metric('thread:click:viewSomeoneElsesThreadgate', {})
|
||||
|
||||
infoDialogControl.open()
|
||||
}
|
||||
|
||||
@@ -17,13 +17,11 @@ import {
|
||||
import {createSanitizedDisplayName} from '#/lib/moderation/create-sanitized-display-name'
|
||||
import {cleanError} from '#/lib/strings/errors'
|
||||
import {sanitizeHandle} from '#/lib/strings/handles'
|
||||
import {logger} from '#/logger'
|
||||
import {updateProfileShadow} from '#/state/cache/profile-shadow'
|
||||
import {RQKEY_getActivitySubscriptions} from '#/state/queries/activity-subscriptions'
|
||||
import {useAgent} from '#/state/session'
|
||||
import * as Toast from '#/view/com/util/Toast'
|
||||
import {platform, useTheme, web} from '#/alf'
|
||||
import {atoms as a} from '#/alf'
|
||||
import {atoms as a, platform, useTheme, web} from '#/alf'
|
||||
import {Admonition} from '#/components/Admonition'
|
||||
import {
|
||||
Button,
|
||||
@@ -36,6 +34,7 @@ import * as Toggle from '#/components/forms/Toggle'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import * as ProfileCard from '#/components/ProfileCard'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_WEB} from '#/env'
|
||||
import type * as bsky from '#/types/bsky'
|
||||
|
||||
@@ -71,6 +70,7 @@ function DialogInner({
|
||||
moderationOpts: ModerationOpts
|
||||
includeProfile?: boolean
|
||||
}) {
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const t = useTheme()
|
||||
const agent = useAgent()
|
||||
@@ -133,7 +133,7 @@ function DialogInner({
|
||||
})
|
||||
|
||||
if (!activitySubscription.post && !activitySubscription.reply) {
|
||||
logger.metric('activitySubscription:disable', {})
|
||||
ax.metric('activitySubscription:disable', {})
|
||||
Toast.show(
|
||||
_(
|
||||
msg`You will no longer receive notifications for ${sanitizeHandle(profile.handle, '@')}`,
|
||||
@@ -160,7 +160,7 @@ function DialogInner({
|
||||
},
|
||||
)
|
||||
} else {
|
||||
logger.metric('activitySubscription:enable', {
|
||||
ax.metric('activitySubscription:enable', {
|
||||
setting: activitySubscription.reply ? 'posts_and_replies' : 'posts',
|
||||
})
|
||||
if (!initialState.post && !initialState.reply) {
|
||||
@@ -177,7 +177,7 @@ function DialogInner({
|
||||
})
|
||||
},
|
||||
onError: err => {
|
||||
logger.error('Could not save activity subscription', {message: err})
|
||||
ax.logger.error('Could not save activity subscription', {message: err})
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -20,8 +20,9 @@ import {Divider} from '#/components/Divider'
|
||||
import {createStaticClick, InlineLinkText} from '#/components/Link'
|
||||
import * as Toast from '#/components/Toast'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {logger, useAgeAssurance} from '#/ageAssurance'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {useComputeAgeAssuranceRegionAccess} from '#/ageAssurance/useComputeAgeAssuranceRegionAccess'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_NATIVE} from '#/env'
|
||||
import {useDeviceGeolocationApi} from '#/geolocation'
|
||||
|
||||
@@ -41,6 +42,7 @@ export function AgeAssuranceAccountCard({style}: ViewStyleProp & {}) {
|
||||
function Inner({style}: ViewStyleProp & {}) {
|
||||
const t = useTheme()
|
||||
const {_, i18n} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const control = useDialogControl()
|
||||
const appealControl = Dialog.useDialogControl()
|
||||
const locationControl = Dialog.useDialogControl()
|
||||
@@ -138,7 +140,7 @@ function Inner({style}: ViewStyleProp & {}) {
|
||||
label={_(msg`Contact our moderation team`)}
|
||||
{...createStaticClick(() => {
|
||||
appealControl.open()
|
||||
logger.metric('ageAssurance:appealDialogOpen', {})
|
||||
ax.metric('ageAssurance:appealDialogOpen', {})
|
||||
})}>
|
||||
contact our moderation team
|
||||
</InlineLinkText>{' '}
|
||||
@@ -167,7 +169,7 @@ function Inner({style}: ViewStyleProp & {}) {
|
||||
color={hasInitiated ? 'secondary' : 'primary'}
|
||||
onPress={() => {
|
||||
control.open()
|
||||
logger.metric('ageAssurance:initDialogOpen', {
|
||||
ax.metric('ageAssurance:initDialogOpen', {
|
||||
hasInitiatedPreviously: hasInitiated,
|
||||
})
|
||||
}}>
|
||||
|
||||
@@ -10,7 +10,7 @@ import {ShieldCheck_Stroke2_Corner0_Rounded as Shield} from '#/components/icons/
|
||||
import {InlineLinkText} from '#/components/Link'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
export function AgeAssuranceAdmonition({
|
||||
children,
|
||||
@@ -40,6 +40,7 @@ function Inner({
|
||||
}) {
|
||||
const t = useTheme()
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -92,7 +93,7 @@ function Inner({
|
||||
to={'/settings/account'}
|
||||
style={[a.text_sm, a.leading_snug, a.font_semi_bold]}
|
||||
onPress={() => {
|
||||
logger.metric('ageAssurance:navigateToSettings', {})
|
||||
ax.metric('ageAssurance:navigateToSettings', {})
|
||||
}}>
|
||||
account settings.
|
||||
</InlineLinkText>
|
||||
|
||||
@@ -15,6 +15,7 @@ import * as Dialog from '#/components/Dialog'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
export function AgeAssuranceAppealDialog({
|
||||
control,
|
||||
@@ -37,6 +38,7 @@ export function AgeAssuranceAppealDialog({
|
||||
|
||||
function Inner({control}: {control: Dialog.DialogControlProps}) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const {currentAccount} = useSession()
|
||||
const {gtPhone} = useBreakpoints()
|
||||
const agent = useAgent()
|
||||
@@ -46,7 +48,7 @@ function Inner({control}: {control: Dialog.DialogControlProps}) {
|
||||
|
||||
const {mutate, isPending} = useMutation({
|
||||
mutationFn: async () => {
|
||||
logger.metric('ageAssurance:appealDialogSubmit', {})
|
||||
ax.metric('ageAssurance:appealDialogSubmit', {})
|
||||
|
||||
await agent.createModerationReport(
|
||||
{
|
||||
|
||||
@@ -12,7 +12,7 @@ import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
|
||||
import {Link} from '#/components/Link'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
export function useInternalState() {
|
||||
const aa = useAgeAssurance()
|
||||
@@ -42,6 +42,7 @@ export function useInternalState() {
|
||||
|
||||
export function AgeAssuranceDismissibleFeedBanner() {
|
||||
const t = useTheme()
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const {visible, close} = useInternalState()
|
||||
const copy = useAgeAssuranceCopy()
|
||||
@@ -66,7 +67,7 @@ export function AgeAssuranceDismissibleFeedBanner() {
|
||||
to="/settings/account"
|
||||
onPress={() => {
|
||||
close()
|
||||
logger.metric('ageAssurance:navigateToSettings', {})
|
||||
ax.metric('ageAssurance:navigateToSettings', {})
|
||||
}}
|
||||
style={[a.w_full, a.justify_between, a.align_center, a.gap_md]}>
|
||||
<View
|
||||
@@ -105,7 +106,7 @@ export function AgeAssuranceDismissibleFeedBanner() {
|
||||
size="small"
|
||||
onPress={() => {
|
||||
close()
|
||||
logger.metric('ageAssurance:dismissFeedBanner', {})
|
||||
ax.metric('ageAssurance:dismissFeedBanner', {})
|
||||
}}
|
||||
style={[
|
||||
a.absolute,
|
||||
|
||||
@@ -10,10 +10,11 @@ import {useAgeAssuranceCopy} from '#/components/ageAssurance/useAgeAssuranceCopy
|
||||
import {Button, ButtonIcon} from '#/components/Button'
|
||||
import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
export function AgeAssuranceDismissibleNotice({style}: ViewStyleProp & {}) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const aa = useAgeAssurance()
|
||||
const {nux} = useNux(Nux.AgeAssuranceDismissibleNotice)
|
||||
const copy = useAgeAssuranceCopy()
|
||||
@@ -45,7 +46,7 @@ export function AgeAssuranceDismissibleNotice({style}: ViewStyleProp & {}) {
|
||||
completed: true,
|
||||
data: undefined,
|
||||
})
|
||||
logger.metric('ageAssurance:dismissSettingsNotice', {})
|
||||
ax.metric('ageAssurance:dismissSettingsNotice', {})
|
||||
}}
|
||||
style={[
|
||||
a.absolute,
|
||||
|
||||
@@ -19,8 +19,7 @@ import {useSession} from '#/state/session'
|
||||
import {atoms as a, web} from '#/alf'
|
||||
import {Admonition} from '#/components/Admonition'
|
||||
import {AgeAssuranceBadge} from '#/components/ageAssurance/AgeAssuranceBadge'
|
||||
import {urls} from '#/components/ageAssurance/const'
|
||||
import {KWS_SUPPORTED_LANGS} from '#/components/ageAssurance/const'
|
||||
import {KWS_SUPPORTED_LANGS, urls} from '#/components/ageAssurance/const'
|
||||
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
|
||||
import * as Dialog from '#/components/Dialog'
|
||||
import {Divider} from '#/components/Divider'
|
||||
@@ -30,9 +29,9 @@ import {LanguageSelect} from '#/components/LanguageSelect'
|
||||
import {SimpleInlineLinkText} from '#/components/Link'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {useBeginAgeAssurance} from '#/ageAssurance/useBeginAgeAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
export {useDialogControl} from '#/components/Dialog/context'
|
||||
|
||||
@@ -64,6 +63,7 @@ export function AgeAssuranceInitDialog({
|
||||
|
||||
function Inner() {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const {currentAccount} = useSession()
|
||||
const langPrefs = useLanguagePrefs()
|
||||
const cleanError = useCleanError()
|
||||
@@ -116,7 +116,7 @@ function Inner() {
|
||||
const onSubmit = async () => {
|
||||
setLanguageError(false)
|
||||
|
||||
logger.metric('ageAssurance:initDialogSubmit', {})
|
||||
ax.metric('ageAssurance:initDialogSubmit', {})
|
||||
|
||||
try {
|
||||
const {status} = runEmailValidation()
|
||||
@@ -143,7 +143,7 @@ function Inner() {
|
||||
error = _(
|
||||
msg`Please enter a valid, non-temporary email address. You may need to access this email in the future.`,
|
||||
)
|
||||
logger.metric('ageAssurance:initDialogError', {code: 'InvalidEmail'})
|
||||
ax.metric('ageAssurance:initDialogError', {code: 'InvalidEmail'})
|
||||
} else if (e.error === 'DidTooLong') {
|
||||
error = (
|
||||
<>
|
||||
@@ -159,14 +159,14 @@ function Inner() {
|
||||
</Trans>
|
||||
</>
|
||||
)
|
||||
logger.metric('ageAssurance:initDialogError', {code: 'DidTooLong'})
|
||||
ax.metric('ageAssurance:initDialogError', {code: 'DidTooLong'})
|
||||
} else {
|
||||
logger.metric('ageAssurance:initDialogError', {code: 'other'})
|
||||
ax.metric('ageAssurance:initDialogError', {code: 'other'})
|
||||
}
|
||||
} else {
|
||||
const {clean, raw} = cleanError(e)
|
||||
error = clean || raw || error
|
||||
logger.metric('ageAssurance:initDialogError', {code: 'other'})
|
||||
ax.metric('ageAssurance:initDialogError', {code: 'other'})
|
||||
}
|
||||
|
||||
setError(error)
|
||||
|
||||
@@ -16,7 +16,7 @@ import {CircleInfo_Stroke2_Corner0_Rounded as ErrorIcon} from '#/components/icon
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {refetchAgeAssuranceServerState} from '#/ageAssurance'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_NATIVE} from '#/env'
|
||||
|
||||
export type AgeAssuranceRedirectDialogState = {
|
||||
@@ -81,6 +81,7 @@ export function AgeAssuranceRedirectDialog() {
|
||||
|
||||
export function Inner({}: {optimisticState?: AgeAssuranceRedirectDialogState}) {
|
||||
const t = useTheme()
|
||||
const ax = useAnalytics()
|
||||
const {_} = useLingui()
|
||||
const agent = useAgent()
|
||||
const polling = useRef(false)
|
||||
@@ -94,7 +95,7 @@ export function Inner({}: {optimisticState?: AgeAssuranceRedirectDialogState}) {
|
||||
|
||||
polling.current = true
|
||||
|
||||
logger.metric('ageAssurance:redirectDialogOpen', {})
|
||||
ax.metric('ageAssurance:redirectDialogOpen', {})
|
||||
|
||||
wait(
|
||||
3e3,
|
||||
@@ -125,18 +126,18 @@ export function Inner({}: {optimisticState?: AgeAssuranceRedirectDialogState}) {
|
||||
|
||||
setSuccess(true)
|
||||
|
||||
logger.metric('ageAssurance:redirectDialogSuccess', {})
|
||||
ax.metric('ageAssurance:redirectDialogSuccess', {})
|
||||
})
|
||||
.catch(() => {
|
||||
if (unmounted.current) return
|
||||
setError(true)
|
||||
logger.metric('ageAssurance:redirectDialogFail', {})
|
||||
ax.metric('ageAssurance:redirectDialogFail', {})
|
||||
})
|
||||
|
||||
return () => {
|
||||
unmounted.current = true
|
||||
}
|
||||
}, [agent, control])
|
||||
}, [ax, agent, control])
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
|
||||
@@ -13,7 +13,7 @@ import * as Layout from '#/components/Layout'
|
||||
import {Link} from '#/components/Link'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAgeAssurance} from '#/ageAssurance'
|
||||
import {logger} from '#/ageAssurance'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
|
||||
export function AgeRestrictedScreen({
|
||||
children,
|
||||
@@ -27,6 +27,7 @@ export function AgeRestrictedScreen({
|
||||
rightHeaderSlot?: React.ReactNode
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const copy = useAgeAssuranceCopy()
|
||||
const aa = useAgeAssurance()
|
||||
|
||||
@@ -74,7 +75,7 @@ export function AgeRestrictedScreen({
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onPress={() => {
|
||||
logger.metric('ageAssurance:navigateToSettings', {})
|
||||
ax.metric('ageAssurance:navigateToSettings', {})
|
||||
}}>
|
||||
<ButtonText>
|
||||
<Trans>Go to account settings</Trans>
|
||||
|
||||
@@ -6,13 +6,12 @@ import {msg, Trans} from '@lingui/macro'
|
||||
import {useLingui} from '@lingui/react'
|
||||
|
||||
import {HITSLOP_10} from '#/lib/constants'
|
||||
import {useGate} from '#/lib/statsig/statsig'
|
||||
import {logger} from '#/logger'
|
||||
import {Nux, useNux, useSaveNux} from '#/state/queries/nuxs'
|
||||
import {atoms as a, useTheme} from '#/alf'
|
||||
import {Button} from '#/components/Button'
|
||||
import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/Times'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {IS_WEB} from '#/env'
|
||||
import {Link} from '../Link'
|
||||
import {useIsFindContactsFeatureEnabledBasedOnGeolocation} from './country-allowlist'
|
||||
@@ -20,6 +19,7 @@ import {useIsFindContactsFeatureEnabledBasedOnGeolocation} from './country-allow
|
||||
export function FindContactsBannerNUX() {
|
||||
const t = useTheme()
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const {visible, close} = useInternalState()
|
||||
|
||||
if (!visible) return null
|
||||
@@ -31,7 +31,7 @@ export function FindContactsBannerNUX() {
|
||||
to={{screen: 'FindContactsFlow'}}
|
||||
label={_(msg`Import contacts to find your friends`)}
|
||||
onPress={() => {
|
||||
logger.metric('contacts:nux:bannerPressed', {})
|
||||
ax.metric('contacts:nux:bannerPressed', {})
|
||||
}}
|
||||
style={[
|
||||
a.w_full,
|
||||
@@ -85,20 +85,19 @@ export function FindContactsBannerNUX() {
|
||||
)
|
||||
}
|
||||
function useInternalState() {
|
||||
const ax = useAnalytics()
|
||||
const {nux} = useNux(Nux.FindContactsDismissibleBanner)
|
||||
const {mutate: save, variables} = useSaveNux()
|
||||
const hidden = !!variables
|
||||
const isFeatureEnabled = useIsFindContactsFeatureEnabledBasedOnGeolocation()
|
||||
const gate = useGate()
|
||||
|
||||
const visible = useMemo(() => {
|
||||
if (IS_WEB) return false
|
||||
if (hidden) return false
|
||||
if (nux && nux.completed) return false
|
||||
if (!isFeatureEnabled) return false
|
||||
if (gate('disable_settings_find_contacts')) return false
|
||||
return true
|
||||
}, [hidden, nux, isFeatureEnabled, gate])
|
||||
}, [hidden, nux, isFeatureEnabled])
|
||||
|
||||
const close = () => {
|
||||
save({
|
||||
@@ -106,7 +105,7 @@ function useInternalState() {
|
||||
completed: true,
|
||||
data: undefined,
|
||||
})
|
||||
logger.metric('contacts:nux:bannerDismissed', {})
|
||||
ax.metric('contacts:nux:bannerDismissed', {})
|
||||
}
|
||||
|
||||
return {visible, close}
|
||||
|
||||
@@ -28,6 +28,7 @@ import * as Layout from '#/components/Layout'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import * as Toast from '#/components/Toast'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {
|
||||
contactsWithPhoneNumbersOnly,
|
||||
filterMatchedNumbers,
|
||||
@@ -51,6 +52,7 @@ export function GetContacts({
|
||||
context: 'Onboarding' | 'Standalone'
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const agent = useAgent()
|
||||
const insets = useSafeAreaInsets()
|
||||
const gutters = useGutters([0, 'wide'])
|
||||
@@ -100,16 +102,16 @@ export function GetContacts({
|
||||
},
|
||||
onSuccess: (result, contacts) => {
|
||||
if (context === 'Onboarding') {
|
||||
logger.metric('onboarding:contacts:contactsShared', {})
|
||||
ax.metric('onboarding:contacts:contactsShared', {})
|
||||
}
|
||||
if (result.matches.length > 0) {
|
||||
logger.metric('contacts:import:success', {
|
||||
ax.metric('contacts:import:success', {
|
||||
contactCount: contacts.length,
|
||||
matchCount: result.matches.length,
|
||||
entryPoint: context,
|
||||
})
|
||||
} else {
|
||||
logger.metric('contacts:import:failure', {
|
||||
ax.metric('contacts:import:failure', {
|
||||
reason: 'noValidNumbers',
|
||||
entryPoint: context,
|
||||
})
|
||||
@@ -134,7 +136,7 @@ export function GetContacts({
|
||||
})
|
||||
},
|
||||
onError: err => {
|
||||
logger.metric('contacts:import:failure', {
|
||||
ax.metric('contacts:import:failure', {
|
||||
reason: isNetworkError(err) ? 'networkError' : 'unknown',
|
||||
entryPoint: context,
|
||||
})
|
||||
@@ -180,7 +182,7 @@ export function GetContacts({
|
||||
permissions = await Contacts.requestPermissionsAsync()
|
||||
}
|
||||
|
||||
logger.metric('contacts:permission:request', {
|
||||
ax.metric('contacts:permission:request', {
|
||||
status: permissions.granted ? 'granted' : 'denied',
|
||||
accessLevelIOS: ios(permissions.accessPrivileges),
|
||||
})
|
||||
|
||||
@@ -31,6 +31,7 @@ import * as Layout from '#/components/Layout'
|
||||
import {InlineLinkText} from '#/components/Link'
|
||||
import {Loader} from '#/components/Loader'
|
||||
import {Text} from '#/components/Typography'
|
||||
import {useAnalytics} from '#/analytics'
|
||||
import {useGeolocation} from '#/geolocation'
|
||||
import {isFindContactsFeatureEnabled} from '../country-allowlist'
|
||||
import {
|
||||
@@ -52,6 +53,7 @@ export function PhoneInput({
|
||||
onSkip: () => void
|
||||
}) {
|
||||
const {_} = useLingui()
|
||||
const ax = useAnalytics()
|
||||
const t = useTheme()
|
||||
const agent = useAgent()
|
||||
const location = useGeolocation()
|
||||
@@ -85,7 +87,7 @@ export function PhoneInput({
|
||||
payload: {phoneCountryCode, phoneNumber},
|
||||
})
|
||||
|
||||
logger.metric('contacts:phone:phoneEntered', {entryPoint: context})
|
||||
ax.metric('contacts:phone:phoneEntered', {entryPoint: context})
|
||||
},
|
||||
onMutate: () => {
|
||||
Keyboard.dismiss()
|
||||
|
||||