diff --git a/app.config.js b/app.config.js
index 8ba9a9e37..47b1d5304 100644
--- a/app.config.js
+++ b/app.config.js
@@ -281,6 +281,8 @@ module.exports = function (_config) {
],
'expo-web-browser',
'expo-background-task',
+ // edits expo-widgets' output, and mods run in reverse order
+ './plugins/withTrendingWidget.js',
[
'expo-widgets',
{
diff --git a/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_background.xml b/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_background.xml
new file mode 100644
index 000000000..9905ddd72
--- /dev/null
+++ b/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_background.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
diff --git a/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_description_bar.xml b/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_description_bar.xml
new file mode 100644
index 000000000..3636b5523
--- /dev/null
+++ b/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_description_bar.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
diff --git a/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_title_bar.xml b/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_title_bar.xml
new file mode 100644
index 000000000..0b42c0918
--- /dev/null
+++ b/modules/TrendingTopicsWidget/android/res/drawable/trending_topics_widget_preview_title_bar.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
diff --git a/modules/TrendingTopicsWidget/android/res/layout/trending_topics_widget_preview.xml b/modules/TrendingTopicsWidget/android/res/layout/trending_topics_widget_preview.xml
new file mode 100644
index 000000000..65cb5a9eb
--- /dev/null
+++ b/modules/TrendingTopicsWidget/android/res/layout/trending_topics_widget_preview.xml
@@ -0,0 +1,244 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/modules/TrendingTopicsWidget/android/res/values-night/trending_topics_widget_preview.xml b/modules/TrendingTopicsWidget/android/res/values-night/trending_topics_widget_preview.xml
new file mode 100644
index 000000000..ddbd6b02f
--- /dev/null
+++ b/modules/TrendingTopicsWidget/android/res/values-night/trending_topics_widget_preview.xml
@@ -0,0 +1,10 @@
+
+
+
+ #10161F
+ #F1F3F5
+ #AEBBC9
+ #2E4052
+ #2E4052
+ #1E2A37
+
diff --git a/modules/TrendingTopicsWidget/android/res/values/trending_topics_widget_preview.xml b/modules/TrendingTopicsWidget/android/res/values/trending_topics_widget_preview.xml
new file mode 100644
index 000000000..baeec57c1
--- /dev/null
+++ b/modules/TrendingTopicsWidget/android/res/values/trending_topics_widget_preview.xml
@@ -0,0 +1,12 @@
+
+
+
+ #FFFFFF
+ #0A0A0A
+ #536471
+ #E5E7EB
+ #D4DBE3
+ #EBEEF2
+ #0085FF
+ Trending on Bluesky
+
diff --git a/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/BlueskyButterfly.imageset/Contents.json b/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/BlueskyButterfly.imageset/Contents.json
new file mode 100644
index 000000000..d687fcf6d
--- /dev/null
+++ b/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/BlueskyButterfly.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "butterfly.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/BlueskyButterfly.imageset/butterfly.svg b/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/BlueskyButterfly.imageset/butterfly.svg
new file mode 100644
index 000000000..5c41669bb
--- /dev/null
+++ b/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/BlueskyButterfly.imageset/butterfly.svg
@@ -0,0 +1,2 @@
+
+
diff --git a/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/Contents.json b/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/Contents.json
new file mode 100644
index 000000000..73c00596a
--- /dev/null
+++ b/modules/TrendingTopicsWidget/ios/WidgetAssets.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/plugins/withTrendingWidget.js b/plugins/withTrendingWidget.js
new file mode 100644
index 000000000..bd373b59e
--- /dev/null
+++ b/plugins/withTrendingWidget.js
@@ -0,0 +1,126 @@
+const {withDangerousMod, withXcodeProject} = require('expo/config-plugins')
+const fs = require('fs')
+const path = require('path')
+
+const SOURCE_DIRECTORY = 'modules/TrendingTopicsWidget'
+const ANDROID_WIDGET_INFO_FILE = 'trending_topics_widget_info.xml'
+const ANDROID_PREVIEW_LAYOUT = '@layout/trending_topics_widget_preview'
+const IOS_TARGET = 'ExpoWidgetsTarget'
+const IOS_ASSET_CATALOG = 'WidgetAssets.xcassets'
+
+/**
+ * Native extras for the trending topics widget that expo-widgets has no
+ * options for: a widget picker preview on Android, and an asset catalog (for
+ * the butterfly) in the iOS widget extension.
+ *
+ * Both edit what expo-widgets generates, and mods run in reverse order of
+ * registration, so this plugin must be listed before `expo-widgets`.
+ */
+module.exports = function withTrendingWidget(config) {
+ config = withAndroidPreview(config)
+ config = withIosAssetCatalog(config)
+ return config
+}
+
+/**
+ * Copies our preview resources into the project and adds
+ * `android:previewLayout` to the widget info.
+ */
+function withAndroidPreview(config) {
+ return withDangerousMod(config, [
+ 'android',
+ config => {
+ const resDirectory = path.join(
+ config.modRequest.platformProjectRoot,
+ 'app/src/main/res',
+ )
+ fs.cpSync(
+ path.join(
+ config.modRequest.projectRoot,
+ SOURCE_DIRECTORY,
+ 'android/res',
+ ),
+ resDirectory,
+ {recursive: true},
+ )
+
+ const widgetInfoPath = path.join(
+ resDirectory,
+ 'xml',
+ ANDROID_WIDGET_INFO_FILE,
+ )
+ if (!fs.existsSync(widgetInfoPath)) {
+ throw new Error(
+ `withTrendingWidget: ${ANDROID_WIDGET_INFO_FILE} not found. Is this plugin listed before expo-widgets?`,
+ )
+ }
+ const widgetInfo = fs.readFileSync(widgetInfoPath, 'utf8')
+ if (!widgetInfo.includes('android:previewLayout')) {
+ fs.writeFileSync(
+ widgetInfoPath,
+ widgetInfo.replace(
+ ' {
+ const project = config.modResults
+ fs.cpSync(
+ path.join(
+ config.modRequest.projectRoot,
+ SOURCE_DIRECTORY,
+ 'ios',
+ IOS_ASSET_CATALOG,
+ ),
+ path.join(
+ config.modRequest.platformProjectRoot,
+ IOS_TARGET,
+ IOS_ASSET_CATALOG,
+ ),
+ {recursive: true},
+ )
+
+ const targetKey = project.findTargetKey(IOS_TARGET)
+ const groupKey = project.findPBXGroupKey({name: IOS_TARGET})
+ if (!targetKey || !groupKey) {
+ throw new Error(
+ `withTrendingWidget: the ${IOS_TARGET} target was not found. Is this plugin listed before expo-widgets?`,
+ )
+ }
+
+ // null if the catalog was already added by an earlier prebuild
+ const file = project.addFile(IOS_ASSET_CATALOG, groupKey)
+ if (!file) {
+ return config
+ }
+ file.uuid = project.generateUuid()
+ file.target = targetKey
+ project.addToPbxBuildFileSection(file)
+ /*
+ * expo-widgets only gives the target a resources phase when the app has
+ * locales. Check the target itself: `pbxResourcesBuildPhaseObj` falls back
+ * to the main app's phase when the target has none.
+ */
+ if (!project.buildPhase('Resources', targetKey)) {
+ project.addBuildPhase(
+ [],
+ 'PBXResourcesBuildPhase',
+ 'Resources',
+ targetKey,
+ )
+ }
+ project.addToPbxResourcesBuildPhase(file)
+ return config
+ })
+}
diff --git a/src/Navigation.tsx b/src/Navigation.tsx
index b1b23f892..ec62e60f2 100644
--- a/src/Navigation.tsx
+++ b/src/Navigation.tsx
@@ -160,6 +160,7 @@ import {setNavigationMetadata} from '#/analytics/metadata'
import {IS_LIQUID_GLASS, IS_NATIVE, IS_WEB} from '#/env'
import {HomeScreen} from '#/features/followingV2/home'
import {InviteScannerScreen} from '#/features/inviteFriends'
+import {stripWidgetTopicParams} from '#/features/trendingWidget/links'
import {router} from '#/routes'
const navigationRef = createNavigationContainerRef()
@@ -985,7 +986,9 @@ const LINKING = {
return route.build((node.params || {}) as RouteParams)
},
- getStateFromPath(path: string) {
+ getStateFromPath(rawPath: string) {
+ // `useIntentHandler` has already logged a click from the widget
+ const path = stripWidgetTopicParams(rawPath)
const [name, params] = router.matchPath(path)
// Any time we receive a url that starts with `intent/` we want to ignore it here. It will be handled in the
diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts
index f24d4ee09..3b4cd6fc2 100644
--- a/src/analytics/metrics/types.ts
+++ b/src/analytics/metrics/types.ts
@@ -944,12 +944,17 @@ export type Events = {
feedSliceIndex?: number
}
'trendingTopic:click': {
- context: 'sidebar' | 'interstitial' | 'explore'
+ context: 'sidebar' | 'interstitial' | 'explore' | 'widget'
feedUri?: string
recId?: string
rank: number
feedSliceIndex?: number
}
+ /**
+ * The trending topics home screen widget was seen installed on this device
+ * for the first time.
+ */
+ 'trendingWidget:installed': {}
'trendingVideos:show': {
context: 'settings'
}
diff --git a/src/components/TrendingTopics.tsx b/src/components/TrendingTopics.tsx
index b6866f2a6..35e9a9cf3 100644
--- a/src/components/TrendingTopics.tsx
+++ b/src/components/TrendingTopics.tsx
@@ -110,7 +110,7 @@ export function useTrendingTopicSeen(
}
export function getTrendingTopicFeedUri(
- topic: app.bsky.unspecced.defs.TrendView,
+ topic: Pick,
): string | undefined {
const match = topic.link.match(/^\/profile\/([^/]+)\/feed\/([^/?#]+)/)
diff --git a/src/features/trendingWidget/BackgroundTask.native.ts b/src/features/trendingWidget/BackgroundTask.native.ts
index 8de4168c1..fb6935629 100644
--- a/src/features/trendingWidget/BackgroundTask.native.ts
+++ b/src/features/trendingWidget/BackgroundTask.native.ts
@@ -5,7 +5,10 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
import {createBskyTopicsHeader} from '#/lib/api/feed/utils'
import {logger} from '#/logger'
-import {filterTrends} from '#/state/queries/trending/useGetTrendsQuery'
+import {
+ DEFAULT_FETCH_LIMIT,
+ filterTrends,
+} from '#/state/queries/trending/useGetTrendsQuery'
import {getPublicAppviewClient} from '#/state/session/clients'
import {
type TrendingWidgetCopy,
@@ -15,8 +18,7 @@ import {app} from '#/lexicons'
const TASK_NAME = 'bluesky-trending-widget-refresh'
const CONFIG_KEY = 'bluesky-trending-widget-background-config'
-const FETCH_LIMIT = 10
-const DISPLAY_LIMIT = 5
+const TOPIC_LIMIT = 10
const MINIMUM_INTERVAL_MINUTES = 60
type BackgroundConfig = {
@@ -41,7 +43,7 @@ TaskManager.defineTask(TASK_NAME, async () => {
const config: BackgroundConfig = JSON.parse(storedConfig)
const data = await getPublicAppviewClient().call(
app.bsky.unspecced.getTrends,
- {limit: FETCH_LIMIT},
+ {limit: DEFAULT_FETCH_LIMIT},
{
headers: {
...createBskyTopicsHeader(config.interests),
@@ -52,10 +54,10 @@ TaskManager.defineTask(TASK_NAME, async () => {
const trends = filterTrends(
data.trends ?? [],
config.mutedWords,
- DISPLAY_LIMIT,
+ TOPIC_LIMIT,
)
- updateTrendingWidgetSnapshot(trends, config.copy)
+ updateTrendingWidgetSnapshot(trends, config.copy, data.recIdStr)
return BackgroundTask.BackgroundTaskResult.Success
} catch (error) {
logger.error('Failed to refresh the trending widget in the background', {
diff --git a/src/features/trendingWidget/Snapshot.native.ts b/src/features/trendingWidget/Snapshot.native.ts
index e9f961586..a52595462 100644
--- a/src/features/trendingWidget/Snapshot.native.ts
+++ b/src/features/trendingWidget/Snapshot.native.ts
@@ -1,3 +1,4 @@
+import {createWidgetTopicUrl} from '#/features/trendingWidget/links'
import TrendingTopicsWidget from '#/features/trendingWidget/TrendingTopicsWidget'
import {type app} from '#/lexicons'
@@ -11,16 +12,15 @@ type Trend = app.bsky.unspecced.getTrends.$OutputBody['trends'][number]
export function updateTrendingWidgetSnapshot(
trends: Trend[],
copy: TrendingWidgetCopy,
+ recId?: string,
) {
TrendingTopicsWidget.updateSnapshot({
emptyMessage: copy.emptyMessage,
title: copy.title,
- topics: trends.map(trend => ({
+ topics: trends.map((trend, index) => ({
displayName: trend.displayName,
description: trend.description,
- destination: trend.link.startsWith('http')
- ? trend.link
- : `https://bsky.app${trend.link.startsWith('/') ? '' : '/'}${trend.link}`,
+ destination: createWidgetTopicUrl(trend.link, {rank: index + 1, recId}),
})),
})
}
diff --git a/src/features/trendingWidget/Snapshot.ts b/src/features/trendingWidget/Snapshot.ts
index 8870b8b31..9f4dcaa3d 100644
--- a/src/features/trendingWidget/Snapshot.ts
+++ b/src/features/trendingWidget/Snapshot.ts
@@ -10,4 +10,5 @@ type Trend = app.bsky.unspecced.getTrends.$OutputBody['trends'][number]
export function updateTrendingWidgetSnapshot(
_trends: Trend[],
_copy: TrendingWidgetCopy,
+ _recId?: string,
) {}
diff --git a/src/features/trendingWidget/Sync.native.tsx b/src/features/trendingWidget/Sync.native.tsx
index 7597ae965..17d175fe6 100644
--- a/src/features/trendingWidget/Sync.native.tsx
+++ b/src/features/trendingWidget/Sync.native.tsx
@@ -8,6 +8,7 @@ import {logger} from '#/logger'
import {useLanguagePrefs} from '#/state/preferences'
import {usePreferencesQuery} from '#/state/queries/preferences'
import {useGetTrendsQuery} from '#/state/queries/trending/useGetTrendsQuery'
+import {useAnalytics} from '#/analytics'
import {
clearTrendingWidgetBackgroundConfig,
registerTrendingWidgetBackgroundTask,
@@ -15,17 +16,22 @@ import {
unregisterTrendingWidgetBackgroundTask,
} from '#/features/trendingWidget/BackgroundTask'
import {updateTrendingWidgetSnapshot} from '#/features/trendingWidget/Snapshot'
+import {device} from '#/storage'
export function TrendingTopicsWidgetSync() {
const {t: l} = useLingui()
+ const ax = useAnalytics()
/**
* `undefined` until the first check finishes.
*/
const [isWidgetInstalled, setIsWidgetInstalled] = useState()
+ /*
+ * Fetched whether or not the widget is installed, so it has data as soon as
+ * it's added. The default fetch limit shares the cache with the feed's
+ * trending topics.
+ */
const {data} = useGetTrendsQuery({
- enabled: isWidgetInstalled === true,
- fetchLimit: 10,
- limit: 5,
+ limit: 10,
refetchOnWindowFocus: true,
})
const {data: preferences} = usePreferencesQuery()
@@ -41,8 +47,11 @@ export function TrendingTopicsWidgetSync() {
const updateInstalledState = async () => {
try {
const isInstalled = await WidgetInfo.isInstalled('TrendingTopicsWidget')
- if (!cancelled) {
- setIsWidgetInstalled(isInstalled)
+ if (cancelled) return
+ setIsWidgetInstalled(isInstalled)
+ if (isInstalled && !device.get(['trendingWidgetInstalled'])) {
+ device.set(['trendingWidgetInstalled'], true)
+ ax.metric('trendingWidget:installed', {})
}
} catch (error) {
logger.error(
@@ -65,7 +74,7 @@ export function TrendingTopicsWidgetSync() {
cancelled = true
subscription.remove()
}
- }, [])
+ }, [ax])
// keep the background refresh registered only while the widget is installed
useEffect(() => {
@@ -107,16 +116,38 @@ export function TrendingTopicsWidgetSync() {
})
}, [copy, languagePrefs.contentLanguages, preferences])
+ /*
+ * The widget is only visible while the app isn't, so sync it whenever the
+ * app leaves the foreground. That also re-renders it, which picks up things
+ * like a light/dark mode change. If the trends arrive after the app has
+ * already left, sync straight away.
+ */
useEffect(() => {
if (!data) return
- try {
- updateTrendingWidgetSnapshot(data.trends, copy)
- } catch (error) {
- logger.error('Failed to update the trending topics widget', {
- safeMessage: error,
- })
+ const sync = () => {
+ try {
+ updateTrendingWidgetSnapshot(data.trends, copy, data.recId)
+ } catch (error) {
+ logger.error('Failed to update the trending topics widget', {
+ safeMessage: error,
+ })
+ }
+ }
+
+ let isActive = AppState.currentState === 'active'
+ if (!isActive) {
+ sync()
}
+ // iOS goes through `inactive` on the way to `background`
+ const subscription = AppState.addEventListener('change', state => {
+ if (isActive && state !== 'active') {
+ sync()
+ }
+ isActive = state === 'active'
+ })
+
+ return () => subscription.remove()
}, [copy, data])
return null
diff --git a/src/features/trendingWidget/TrendingTopicsWidget.android.tsx b/src/features/trendingWidget/TrendingTopicsWidget.android.tsx
index 23618b9d6..47a615bfc 100644
--- a/src/features/trendingWidget/TrendingTopicsWidget.android.tsx
+++ b/src/features/trendingWidget/TrendingTopicsWidget.android.tsx
@@ -45,7 +45,7 @@ function TrendingTopicsWidget(
'widget'
const isDark = environment.colorScheme === 'dark'
- const topics = (props.topics ?? []).slice(0, 5)
+ const topics = props.topics ?? []
const backgroundColor = isDark ? '#10161F' : '#FFFFFF'
const textColor = isDark ? '#F1F3F5' : '#0A0A0A'
const secondaryTextColor = isDark ? '#AEBBC9' : '#536471'
@@ -84,18 +84,17 @@ function TrendingTopicsWidget(
{topics.map((topic, index) => (
)}
diff --git a/src/features/trendingWidget/TrendingTopicsWidget.ios.tsx b/src/features/trendingWidget/TrendingTopicsWidget.ios.tsx
index c45566b20..ead54d362 100644
--- a/src/features/trendingWidget/TrendingTopicsWidget.ios.tsx
+++ b/src/features/trendingWidget/TrendingTopicsWidget.ios.tsx
@@ -9,6 +9,8 @@ import {
VStack,
} from '@expo/ui/swift-ui'
import {
+ background,
+ clipShape,
containerBackground,
font,
foregroundStyle,
@@ -16,6 +18,7 @@ import {
lineLimit,
minimumScaleFactor,
padding,
+ resizable,
widgetURL,
} from '@expo/ui/swift-ui/modifiers'
@@ -135,10 +138,11 @@ function TrendingTopicsWidget(
]}>
{!isSmall ? (
+ {/* from the extension's asset catalog, see plugins/withTrendingWidget.js */}
{props.emptyMessage ?? 'Open Bluesky to load trending topics.'}
+ {/* the whole widget opens the app, this just makes that obvious */}
+ {props.topics ? null : (
+
+ Open Bluesky
+
+ )}
)}
diff --git a/src/features/trendingWidget/links.test.ts b/src/features/trendingWidget/links.test.ts
new file mode 100644
index 000000000..42e53b14a
--- /dev/null
+++ b/src/features/trendingWidget/links.test.ts
@@ -0,0 +1,76 @@
+import {describe, expect, it} from '@jest/globals'
+
+import {
+ createWidgetTopicUrl,
+ parseWidgetTopicClick,
+ stripWidgetTopicParams,
+} from './links'
+
+describe('createWidgetTopicUrl', () => {
+ it('tags a relative topic link', () => {
+ expect(
+ createWidgetTopicUrl('/profile/trending.bsky.app/feed/abc', {
+ rank: 2,
+ recId: '123',
+ }),
+ ).toBe(
+ 'https://bsky.app/profile/trending.bsky.app/feed/abc?ref_src=widget&ref_rank=2&ref_rec_id=123',
+ )
+ })
+
+ it('keeps an existing query and omits a missing recId', () => {
+ expect(createWidgetTopicUrl('/search?q=bluesky', {rank: 1})).toBe(
+ 'https://bsky.app/search?q=bluesky&ref_src=widget&ref_rank=1',
+ )
+ })
+})
+
+describe('parseWidgetTopicClick', () => {
+ it('reads back a tagged link', () => {
+ const url = createWidgetTopicUrl('/profile/trending.bsky.app/feed/abc', {
+ rank: 3,
+ recId: '123',
+ })
+ expect(parseWidgetTopicClick(new URL(url))).toEqual({
+ path: '/profile/trending.bsky.app/feed/abc',
+ rank: 3,
+ recId: '123',
+ })
+ })
+
+ it('ignores other links', () => {
+ expect(
+ parseWidgetTopicClick(new URL('https://bsky.app/search?ref_src=embed')),
+ ).toBeUndefined()
+ expect(
+ parseWidgetTopicClick(
+ new URL('https://bsky.app/search?ref_src=widget&ref_rank=nope'),
+ ),
+ ).toBeUndefined()
+ })
+})
+
+describe('stripWidgetTopicParams', () => {
+ it('removes the widget params from native paths', () => {
+ expect(
+ stripWidgetTopicParams(
+ 'profile/trending.bsky.app/feed/abc?ref_src=widget&ref_rank=1&ref_rec_id=123',
+ ),
+ ).toBe('profile/trending.bsky.app/feed/abc')
+ })
+
+ it('keeps other params', () => {
+ expect(
+ stripWidgetTopicParams('/search?q=bluesky&ref_src=widget&ref_rank=1'),
+ ).toBe('/search?q=bluesky')
+ })
+
+ it('leaves other paths alone', () => {
+ expect(stripWidgetTopicParams('/search?q=bluesky&ref_src=embed')).toBe(
+ '/search?q=bluesky&ref_src=embed',
+ )
+ expect(stripWidgetTopicParams('/profile/alice.bsky.social')).toBe(
+ '/profile/alice.bsky.social',
+ )
+ })
+})
diff --git a/src/features/trendingWidget/links.ts b/src/features/trendingWidget/links.ts
new file mode 100644
index 000000000..7eeb0c424
--- /dev/null
+++ b/src/features/trendingWidget/links.ts
@@ -0,0 +1,60 @@
+/*
+ * Topic links in the widget carry these params so the app can log a
+ * `trendingTopic:click` when it opens from one. They are stripped again before
+ * the link is routed.
+ */
+const REF_SRC = 'widget'
+const PARAMS = {
+ src: 'ref_src',
+ rank: 'ref_rank',
+ recId: 'ref_rec_id',
+}
+
+/**
+ * Builds the URL the widget opens for a trending topic.
+ */
+export function createWidgetTopicUrl(
+ link: string,
+ {rank, recId}: {rank: number; recId?: string},
+): string {
+ const url = new URL(link, 'https://bsky.app')
+ url.searchParams.set(PARAMS.src, REF_SRC)
+ url.searchParams.set(PARAMS.rank, String(rank))
+ if (recId) {
+ url.searchParams.set(PARAMS.recId, recId)
+ }
+ return url.toString()
+}
+
+/**
+ * Returns the topic's path, rank, and recommendation ID if the URL was opened
+ * from a topic in the widget.
+ */
+export function parseWidgetTopicClick(
+ url: URL,
+): {path: string; rank: number; recId?: string} | undefined {
+ if (url.searchParams.get(PARAMS.src) !== REF_SRC) return
+ const rank = Number(url.searchParams.get(PARAMS.rank))
+ if (!Number.isInteger(rank) || rank < 1) return
+ return {
+ path: url.pathname,
+ rank,
+ recId: url.searchParams.get(PARAMS.recId) ?? undefined,
+ }
+}
+
+/**
+ * Removes the widget's params from a path (with or without a leading slash).
+ * Other paths are returned unchanged.
+ */
+export function stripWidgetTopicParams(path: string): string {
+ const queryStart = path.indexOf('?')
+ if (queryStart === -1) return path
+ const params = new URLSearchParams(path.slice(queryStart + 1))
+ if (params.get(PARAMS.src) !== REF_SRC) return path
+ for (const param of Object.values(PARAMS)) {
+ params.delete(param)
+ }
+ const query = params.toString()
+ return path.slice(0, queryStart) + (query ? `?${query}` : '')
+}
diff --git a/src/lib/hooks/useIntentHandler.ts b/src/lib/hooks/useIntentHandler.ts
index 42e866b15..dd9170a90 100644
--- a/src/lib/hooks/useIntentHandler.ts
+++ b/src/lib/hooks/useIntentHandler.ts
@@ -13,8 +13,10 @@ import {useSetActiveLanding} from '#/state/shell/landing'
import {useLoggedOutViewControls} from '#/state/shell/logged-out'
import {useCloseAllActiveElements} from '#/state/util'
import {useIntentDialogs} from '#/components/intents/IntentDialogs'
+import {getTrendingTopicFeedUri} from '#/components/TrendingTopics'
import {useAnalytics} from '#/analytics'
import {IS_IOS, IS_NATIVE} from '#/env'
+import {parseWidgetTopicClick} from '#/features/trendingWidget/links'
import {useApplyPullRequestOTAUpdate} from './useOTAUpdates'
type IntentType = 'compose' | 'verify-email' | 'age-assurance' | 'apply-ota'
@@ -49,6 +51,15 @@ export function useIntentHandler() {
})
}
const urlp = parseLinkingUrl(url)
+ const widgetTopicClick = parseWidgetTopicClick(urlp)
+ if (widgetTopicClick) {
+ ax.metric('trendingTopic:click', {
+ context: 'widget',
+ feedUri: getTrendingTopicFeedUri({link: widgetTopicClick.path}),
+ rank: widgetTopicClick.rank,
+ recId: widgetTopicClick.recId,
+ })
+ }
const chatInviteMatch = urlp.pathname.match(CHAT_INVITE_CODE_REGEX)
if (chatInviteMatch) {
groupChatJoinIntent(chatInviteMatch[1], url)
diff --git a/src/state/queries/trending/useGetTrendsQuery.ts b/src/state/queries/trending/useGetTrendsQuery.ts
index 0a0dd3c5d..444fc424b 100644
--- a/src/state/queries/trending/useGetTrendsQuery.ts
+++ b/src/state/queries/trending/useGetTrendsQuery.ts
@@ -17,7 +17,6 @@ export const DEFAULT_LIMIT = 10
export const DEFAULT_FETCH_LIMIT = 20
type QueryProps = {
- enabled?: boolean
fetchLimit?: number
limit?: number
refetchOnWindowFocus?: boolean
@@ -60,7 +59,7 @@ export function useGetTrendsQuery(props: QueryProps = {}) {
}, [preferences?.moderationPrefs])
return useQuery({
- enabled: props.enabled !== false && !!preferences,
+ enabled: !!preferences,
refetchOnWindowFocus: props.refetchOnWindowFocus,
staleTime: STALE.MINUTES.THREE,
queryKey: createGetTrendsQueryKey(fetchLimit),
diff --git a/src/storage/schema.ts b/src/storage/schema.ts
index 9e29d36f5..0e3f0ab0a 100644
--- a/src/storage/schema.ts
+++ b/src/storage/schema.ts
@@ -61,6 +61,11 @@ export type Device = {
activitySubscriptionsNudged?: boolean
threadgateNudged?: boolean
inviteFriendsFollowersPromoDismissed?: boolean
+ /**
+ * Whether the trending topics widget has ever been seen installed on this
+ * device, so `trendingWidget:installed` is only logged once.
+ */
+ trendingWidgetInstalled?: boolean
pendingOTAUpdate?: {
attemptedAt: number
channel: string